broderboy + stackoverflow   99

How can i run Laravel Queue only once?
I used laravel 5.1 Queue for my background function with async.

But i want to run that function for only 1 time. If that function fail, i want to do other process.

How can i detect my job is failed or not?

Am i doing right or wrong ? What should i change?

ps: I'm beginner. I used like this in my controller.

$job = new myjob($var1, $var2);

$this->dispatch($job);

$job->release();

if ($job->attempts() >= 1)

{

$job->delete();

//will do other process

}
stackoverflow 
16 hours ago by broderboy
How do I convert NSMutableArray to NSArray?
How do I convert NSMutableArray to NSArray in objective-c ?
stackoverflow 
3 days ago by broderboy
What is "Constrain to margin" in Storyboard in Xcode 6
I am Working with autolayout and constraints and found there is a Constrain to margins option in XCode 6 which was not present in XCode 5 and is checked by default.

I created a test project then I added a UITableView on a ViewController with the frame set to the same size as view and added constraints

XCode 6

You can see here even though tableview has the same frame as view XCode suggests to add -16 as constraint whereas XCode 5 would suggest adding spacing 0.

Now when you uncheck "Constrain to margin" option it behaves same as XCode 5 and would suggest adding 0 as constraint

Also, I found that once I add constraint with Constrain to margin checked, I am no longer able to open the storyboard file in XCode 5 so it's definitely something new in XCode 6

Hopefully, I am able to explain my question properly. I would like to understand what "Constrain to margin" actually does and when I should and should not use it. I do apologize if it's something very simple and obvious.

EDIT

I found something about layout margins in discussion here , I wonder if it's related to this.
stackoverflow 
3 days ago by broderboy
NSPhotoLibraryUsageDescription key must be present in Info.plist to use camera roll
Recently I started to get this error:

NSPhotoLibraryUsageDescription key must be present in Info.plist to

use camera roll.

I am using React Native to build my app (I am not familiar with ios native development) and I don't know how to add this key to Info.plist

Can you post an example? Thanks

I am using npm package "react-native-camera-roll-picker": "^1.1.7"
stackoverflow 
5 days ago by broderboy
swift case falling through
Does swift have fall through statement? e.g if I do the following

var testVar = "hello"

var result = 0

switch(testVal)

{

case "one":

result = 1

case "two":

result = 1

default:

result = 3

}

is it possible to have the same code executed for case "one" and case "two"?
stackoverflow 
6 days ago by broderboy
dyld: Library not loaded: @rpath/libswift_stdlib_core.dylib
I get this error after adding a Swift class to an old Xcode project.

dyld: Library not loaded: @rpath/libswift_stdlib_core.dylib

How can I make the project run again?
stackoverflow 
7 days ago by broderboy
XCODE 7.1 Swift 2 Unknown class in Interface Builder file
I've created new Cocoa Touch File. Named it SwipingViewController.

Then try to add Custom Class to ViewController.

And when I run the app i receive an error

2015-10-09 10:53:25.054 ParseStarterProject[5369:389307] Unknown class SwipingViewController in Interface Builder file.

I've tried to find in Google by myself.

I've found some solutions

Xcode 6 Strange Bug: Unknown class in Interface Builder file

But they all did not help to fix the problem.

Any idea how to fix it?

here is my projects files
stackoverflow 
8 days ago by broderboy
How can I use mySQL replace() to replace strings in multiple records?
We have a database that has a bunch of records with some bad data in one column, in which an embedded editor escaped some stuff that shouldn't have been escaped and it's breaking generated links.

I want to run a query to replace the bad characters in all the records, but can't figure out how to do it. I found the replace() function in MySQL, but how can I use it inside a query?

For example, what would be the correct syntax if I wanted to replace the string &lt; with an actual less-than angle bracket (< ) in all records that have &lt; in the articleItem column? Can it be done in a single query (i.e. select and replace all in one swoop), or do I have to do multiple queries? Even if it's multiple queries, how do I use replace() to do the replace on the value of a field on more than one record?
stackoverflow 
15 days ago by broderboy
What is the swift equivalent of respondsToSelector?
I've googled but not been able to find out what the swift equivalent to respondsToSelector: is.

This is the only thing I could find (Swift alternative to respondsToSelector: ) but isn't too relevant in my case as its checking the existence of the delegate, I don't have a delegate I just want to check if a new API exists or not when running on the device and if not fall back to a previous version of the api.
stackoverflow 
18 days ago by broderboy
How to Support Dynamic Type in Labels in iOS 7
How do I support Dynamic Type in UILabel and UITextView in iOS 7? I'm adapting one of our projects for iOS 7 and would like to support this accessibility feature. I can't find the specific how to tutorial on it on Apple's iOS Developer site. Any links or sample code would be appreciated.
stackoverflow 
22 days ago by broderboy
Error while installing Nokogiri (1.6.7) on El Capitan
One of my developers have updated Nokogiri, and when pulling the updated Gemfile my bundle install fails.

➜ my-project git:(master) bundle install

Fetching source index from https://rubygems.org/

Using rake 10.4.2

Using i18n 0.7.0

Using json 1.8.3

Using minitest 5.8.3

Using thread_safe 0.3.5

Using tzinfo 1.2.2

Using activesupport 4.2.3

Using builder 3.2.2

Using erubis 2.7.0

Using mini_portile2 2.0.0

Gem::Ext::BuildError: ERROR: Failed to build gem native extension.

/Users/me/.rvm/rubies/ruby-2.1.2/bin/ruby extconf.rb --use-system-libraries

checking if the C compiler accepts ... yes

checking if the C compiler accepts -Wno-error=unused-command-line-argument-hard-error-in-future... no

Building nokogiri using system libraries.

libxml2 version 2.6.21 or later is required!

*** extconf.rb failed ***

Could not create Makefile due to some reason, probably lack of necessary

libraries and/or headers. Check the mkmf.log file for more details. You may

need configuration options.

Provided configuration options:

--with-opt-dir

--without-opt-dir

--with-opt-include

--without-opt-include=${opt-dir}/include

--with-opt-lib

--without-opt-lib=${opt-dir}/lib

--with-make-prog

--without-make-prog

--srcdir=.

--curdir

--ruby=/Users/me/.rvm/rubies/ruby-2.1.2/bin/ruby

--help

--clean

--use-system-libraries

--with-zlib-dir

--without-zlib-dir

--with-zlib-include

--without-zlib-include=${zlib-dir}/include

--with-zlib-lib

--without-zlib-lib=${zlib-dir}/lib

--with-xml2-dir

--without-xml2-dir

--with-xml2-include

--without-xml2-include=${xml2-dir}/include

--with-xml2-lib

--without-xml2-lib=${xml2-dir}/lib

--with-libxml-2.0-config

--without-libxml-2.0-config

--with-pkg-config

--without-pkg-config

--with-xslt-dir

--without-xslt-dir

--with-xslt-include

--without-xslt-include=${xslt-dir}/include

--with-xslt-lib

--without-xslt-lib=${xslt-dir}/lib

--with-libxslt-config

--without-libxslt-config

--with-exslt-dir

--without-exslt-dir

--with-exslt-include

--without-exslt-include=${exslt-dir}/include

--with-exslt-lib

--without-exslt-lib=${exslt-dir}/lib

--with-libexslt-config

--without-libexslt-config

extconf failed, exit code 1

Gem files will remain installed in /Users/me/.rvm/gems/ruby-2.1.2@my-project/gems/nokogiri-1.6.7 for inspection.

Results logged to /Users/me/.rvm/gems/ruby-2.1.2@my-project/extensions/x86_64-darwin-13/2.1.0-static/nokogiri-1.6.7/gem_make.out

An error occurred while installing nokogiri (1.6.7), and Bundler cannot continue.

Make sure that `gem install nokogiri -v '1.6.7'` succeeds before bundling.

As suggested in "Failing to install Nokogiri gem " I have unsuccessfully tried to run:

bundle config build.nokogiri --use-system-libraries

bundle install

As suggested in "Failing to install Nokogiri gem " I also tried:

gem install nokogiri -- --use-system-libraries

and:

gem install nokogiri -v 1.6.5 -- --use-system-libraries

My OS version is El Capitan 10.11.2, and I have checked that the Xcode licence agreement has been accepted.

Any ideas how to get the Nokogiri installation to succeed?
stackoverflow 
22 days ago by broderboy
Removing MySQL 5.5 Completely
I am trying to uninstall mysql from my ubuntu 12.04 completely. But not able to.

I tried a lot of commands. But nothing is working. Can anyone help out here!

sudo apt-get remove mysql-server mysql-client mysql-common

sudo apt-get autoremove

I am not able to understand what to do.

I want to remove everything regarding MySQL. Whenever I am trying to locate it. I am getting that.

I want everything to be removed. mysql-server, mysql-client, mysql-libraries and even configuration.

Please help me!!!
stackoverflow 
26 days ago by broderboy
dealloc in Swift
I would like to perform some cleanup at the end of a view controller's life, namely to remove an NSNotificationCenter notification. Implementing dealloc results in a Swift compiler error:

Cannot override 'dealloc' which has been marked unavailable

What is the preferred way to perform some cleanup at the end of an object's life in Swift?
stackoverflow 
28 days ago by broderboy
AngularJS: Display blob (.pdf) in an angular app
I have been trying to display pdf file which I am getting as a blob from a $http.post response. The pdf must be displayed within the app using <embed src> for example.

I came across couple of stack posts but some how my example doesnt seem to work.

JS:

according to this doc , I went on and tried...

$http.post('/postUrlHere',{myParams}).success(function (response) {

var file = new Blob([response], {type: 'application/pdf'});

var fileURL = URL.createObjectURL(file);

$scope.content = fileURL;

});

Now from what I understand, fileURL creates a temporary url that the blog can use as refference.

HTML:

<embed src="" width="200" height="200"></embed>

I am not sure how to handle this in angular, the ideal situation would be to (1) assign it to a scope, (2) 'prepare/rebuild' the blob to a pdf (3) pass it to the HTML using <embed> cause I want to display it within the app.

I have been researching for more than a day now but some how I cant seem to understand how this works in angular.. and lets just assume the pdf viewer libraries out there weren't an option.
stackoverflow 
29 days ago by broderboy
Installing Apples Network Link Conditioner Tool
I have installed xcode 4.3.1 on my machine running Lion.

I can't find the Network Link Conditioner tool anywhere.

I have checked the utilities folder, also the xcode/contents/developer/* directories.. no such luck.

Do I need to install specific components or has this tool been removed or renamed recently?
stackoverflow 
5 weeks ago by broderboy
Xcode 8 Beta 3 Use Legacy Swift issue
I have an Objective-C project in Xcode 8 Beta 3. Since updating, whenever I try to build I receive the following error:

“Use Legacy Swift Language Version” (SWIFT_VERSION) is required to be configured correctly for targets which use Swift. Use the [Edit > Convert > To Current Swift Syntax…] menu to choose a Swift version or use the Build Settings editor to configure the build setting directly.

Has anyone encountered this? Since it's an Objective-C project there's no build setting to configure Swift. I have also made sure none of the project dependencies or CocoaPods are using Swift. The only solution I have is to use Beta 2. Any ideas how I might fix this issue?

I should also mention I'm running OSX 10.12 Beta 2.
stackoverflow 
5 weeks ago by broderboy
Using a dispatch_once singleton model in Swift
I'm trying to work out an appropriate singleton model for usage in Swift. So far, I've been able to get a non-thread safe model working as:

class var sharedInstance:TPScopeManager {

get {

struct Static {

static var instance : TPScopeManager? = nil

}

if !Static.instance {

Static.instance = TPScopeManager()

}

return Static.instance!

}

}

Wrapping the singleton instance in the Static struct should allow a single instance that doesn't collide with singleton instances without complex naming schemings, and it should make things fairly private. Obviously though, this model isn't thread safe, so I tried to add dispatch_once to the whole thing:

class var sharedInstance:TPScopeManager {

get {

struct Static {

static var instance : TPScopeManager? = nil

static var token : dispatch_once_t = 0

}

dispatch_once(Static.token) { Static.instance = TPScopeManager() }

return Static.instance!

}

}

But I get a compiler error on the dispatch_once line:

Cannot convert the expression's type 'Void' to type '()'

I've tried several different variants of the syntax, but they all seem to have the same results:

dispatch_once(Static.token, { Static.instance = TPScopeManager() })

What is the proper usage of dispatch_once using Swift? I initially thought the problem was with the block due to the () in the error message, but the more I look at it, the more I think it may be a matter of getting the dispatch_once_t correctly defined.
stackoverflow 
5 weeks ago by broderboy
How can I tell AngularJS to "refresh"
I have a click event that happens outside the scope of my custom directive, so instead of using the "ng-click" attribute, I am using a jQuery.click() listener and calling a function inside my scope like so:

$('html').click(function(e) {

scope.close();

);

close() is a simple function that looks like this:

scope.close = function() {

scope.isOpen = false;

}

In my view, I have an element with "ng-show" bound to isOpen like this:

<div ng-show="isOpen">My Div</div>

When debugging, I am finding that close() is being called, isOpen is being updated to false, but the AngularJS view is not updating. Is there a way I can manually tell Angular to update the view? Or is there a more "Angular" approach to solving this problem that I am not seeing?
stackoverflow 
5 weeks ago by broderboy
How to override trait function and call it from the overridden function?
Scenario:

trait A {

function calc($v) {

return $v+1;

}

}

class MyClass {

use A;

function calc($v) {

$v++;

return A::calc($v);

}

}

print (new MyClass())->calc(2); // should print 4

This code doesn't work, and I cannot find a way to call a trait function like it was inherited. I tried calling self::calc($v) , static::calc($v) , parent::calc($v) , A::calc($v) and the following:

trait A {

function calc($v) {

return $v+1;

}

}

class MyClass {

use A {

calc as traitcalc;

}

function calc($v) {

$v++;

return traitcalc($v);

}

}

Nothing works.

Is there a way to make it work or must I override completely the trait function which is much more complex than this :)
stackoverflow 
5 weeks ago by broderboy
Angular JS update input field after change
I'm trying to build a simple calculator in Angular in which I can override the total if I want. I have this part working but when I then go back to enter in a number in fields one or two the total isn't updated in the field.

Here is my jsfiddle http://jsfiddle.net/YUza7/2/

The form

<div ng-app>

<h2>Calculate</h2>

<div ng-controller="TodoCtrl">

<form>

<li>Number 1: <input type="text" ng-model="one">

<li>Number 2: <input type="text" ng-model="two">

<li>Total <input type="text" value="">

</form>

</div>

</div>

The javascript

function TodoCtrl($scope) {

$scope.total = function(){

return $scope.one * $scope.two;

};

}
stackoverflow 
5 weeks ago by broderboy
How do I check if a string contains a specific word in PHP?
Consider:

$a = 'How are you?';

if ($a contains 'are')

echo 'true';

Suppose I have the code above, what is the correct way to write the statement if ($a contains 'are') ?
stackoverflow 
6 weeks ago by broderboy
cURL error 60: SSL certificate: unable to get local issuer certificate
I use wamp on a local development environment and am trying to charge a credit card but get the error message:

cURL error 60: SSL certificate problem: unable to get local issuer certificate

I googled a lot and lots of people are suggesting, that I download this file: cacert.pem

Put it somewhere and point through my php.ini to it. This is the part in my php.ini

curl.cainfo = "C:\Windows\cacert.pem"

Yet, even after restarting my server several times and changing the path, I get the same error message.

I use wamp from the Apache Modules and have the ssl_module enabled. And from the php extensions I have php_curl enabled.

Still the same error message. Wtf.

Now I am following this fix: How to fix PHP CURL Error 60 SSL

Which suggests that I add these lines to my cURL options:

curl_setopt($process, CURLOPT_CAINFO, dirname(__FILE__) . '/cacert.pem');

curl_setopt($process, CURLOPT_SSL_VERIFYPEER, true);

Where do I add options to my cURL? Apparently not through the command line, since my CLI doesn't find the command "curl_setopt"

EDIT

This is the code I am running:

public function chargeStripe()

{

$stripe = new Stripe;

$stripe = Stripe::make(env('STRIPE_PUBLIC_KEY'));

$charge = $stripe->charges()->create([

'amount' => 2900,

'customer' => Input::get('stripeEmail'),

'currency' => 'EUR',

]);

dd($charge);

// echo $charge[Input::get('stripeToken')];

return Redirect::route('step1');

}
stackoverflow 
7 weeks ago by broderboy
How to set a mail Subject in UIActivityViewController?
I want to set subject for email sharing in UIActivityViewController and also want to share in Twitter. I know in Twitter if we want to share — we need compress text to 140 chars. I checked many SO solutions, but nothing is working.

Is this issue fixed in latest iOS releases? Any other "working solutions"?
stackoverflow 
7 weeks ago by broderboy
NSUserDefaults and KVO issues
I'm using NSUserDefaults in my app and I would like to be notified when a particular value is changed. For that, I added the following lines in viewDidLoad:

NSUserDefaults *settings = [NSUserDefaults standardUserDefaults];

[settings synchronize];

[settings addObserver:self forKeyPath:@"pref_server" options:NSKeyValueObservingOptionNew context:NULL];

And the method to be notified:

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context

{

NSLog(@"Change");

NSUserDefaults *settings = [NSUserDefaults standardUserDefaults];

if (object == settings && [keyPath isEqualToString:@"pref_server"])

{

NSLog(@"Server did change");

}

}

Unfortunately, the latter is never called...@"pref_server" is the item identifier I have set in Root.plist, in Settings.bundle. What am I doing wrong?
stackoverflow 
8 weeks ago by broderboy
Getting error "No such module" using Xcode, but the framework is there
I'm currently coding in Swift, and I've got an error:

No such module Social

But I don't understand, because the module is in my project, declared in "Linked frameworks and Libraries" and in "Embedded Binaries".

The frameworks is in Objective-C, so I wrote a Bridge Header for it.

Please, how can I make Xcode recognize the framework?
stackoverflow 
8 weeks ago by broderboy
How to log a method's execution time exactly in milliseconds?
Is there a way to determine how much time a method needs to execute (in milliseconds)?
stackoverflow 
8 weeks ago by broderboy
Xcode process launch failed: Security
I have been developing an app for 1 or 2 weeks now and just yesterday I have updated my iPhone 5S to the iOS 8 GM. Everything worked fine and I could test on my device as well until I deleted the app from my phone and wanted to build again. The following error appeared:

Could not launch "My App"

process launch failed: Security

When I test with the simulator it works fine.

Is this because of the iOS 8 GM update and how can I fix this launch problem?

I want to be able to test on my iPhone and in the simulator.
stackoverflow 
8 weeks ago by broderboy
dyld: Library not loaded: @rpath/libswiftCore.dylib
I am trying to run a Swift app on my iPhone 4s. It works fine on the simulator, and my friend can successfully run it on his iPhone 4s. I have iOS 8 and the official release of Xcode 6.

I have tried

Restarting Xcode, iPhone, computer

Cleaning & rebuilding

Revoking and creating new certificate/provision profile

Runpath Search Paths is $(inherited) @executable_path/Frameworks

Embedded Content Contains Swift Code is 'Yes'

Code Signing Identity is developer

Below is the error in entirety

dyld: Library not loaded: @rpath/libswiftCore.dylib

Referenced from: /private/var/mobile/Containers/Bundle/Application/LONGSERIALNUMBER/AppName.app/AppName

Reason: no suitable image found. Did find:

/private/var/mobile/Containers/Bundle/Application/LONGSERIALNUMBER/AppName.app/Frameworks/libswiftCore.dylib: mmap() error 1 at

address=0x008A1000, size=0x001A4000 segment=__TEXT in Segment::map() mapping

/private/var/mobile/Containers/Bundle/Application/LONGSERIALNUMBER/APPLICATION_NAME/Frameworks/libswiftCore.dylib
stackoverflow 
11 weeks ago by broderboy
How to override trait function and call it from the overriden function?
Scenario:

trait A {

function calc($v) {

return $v+1;

}

}

class MyClass {

use A;

function calc($v) {

$v++;

return A::calc($v);

}

}

print (new MyClass())->calc(2); // should print 4

This code doesn't work, and I cannot find a way to call a trait function like it was inherited. I tried calling self::calc($v) , static::calc($v) , parent::calc($v) , A::calc($v) and the following:

trait A {

function calc($v) {

return $v+1;

}

}

class MyClass {

use A {

calc as traitcalc;

}

function calc($v) {

$v++;

return traitcalc($v);

}

}

Nothing works.

Is there a way to make it work or must I override completely the trait function which is much more complex than this :)
stackoverflow 
11 weeks ago by broderboy
How to check if a string contains a specific word in PHP?
Consider:

$a = 'How are you?';

if ($a contains 'are')

echo 'true';

Suppose I have the code above, what is the correct way to write the statement if ($a contains 'are') ?
stackoverflow 
11 weeks ago by broderboy
Set a border for UIButton in Storyboard
I can't get a border onto my buttons in XCode 5 without setting them directly in the code. Is it possible that there's no way to do this on the storyboard without making a custom background image?
stackoverflow 
12 weeks ago by broderboy
Disable UITextField Predictive Text
With the release of iOS 8 I would like to disable the predictive text section of the keyboard when I begin typing in a UITextField. Not sure how this is done, any help would be appreciated!
stackoverflow 
12 weeks ago by broderboy
Xcode : "No such module" error, but the framework is there
I'm currently coding in Swift, and I've got an error "No such module Social".

But I don't understand, because the module is in my project, declared in "Linked frameworks and Libraries" and in "Embedded Binaries".

The frameworks is in Objective C, so I wrote a Bridge Header for it.

Please, how can I make Xcode recognize the framework ? Thanks a lot !
stackoverflow 
12 weeks ago by broderboy
Controlling which view controller loads after receiving a push notification in SWIFT
Once I receive a push notification and swipe to open it, it just opens my app and not the VC I want.

So my question is how do I load the VC I want? I know if the app is open I would move the VC over to another inside the didReceiveRemoteNotification but how do I do it if the app isn't open? or if it is in background mode?

Also I have TWO different push notifications, so therefore I need it to move ONE of TWO different VCs. How can I tell the difference between different push notifactions?

Thanks.
stackoverflow 
12 weeks ago by broderboy
json_decode returns NULL after webservice call
There is a strange behaviour with json_encode and json_decode and I can't find a solution:

My php application calls a php web service. The webservice returns json that looks like this:

var_dump($foo):

string(62) "{"action":"set","user":"123123123123","status":"OK"}"

now I like to decode the json in my application:

$data = json_decode($foo, true)

but it returns NULL :

var_dump($data):

NULL

I use php5.

The Content-Type of the response from the webservice: "text/html; charset=utf-8" (also tried to use "application/json; charset=utf-8" )

What could be the reason?
stackoverflow 
november 2016 by broderboy
How do I set adaptive multiline UILabel text?
I have a UILabel named titleLabel in my storyboard nib set to its default height. I want it to programatically expand in height to fit it's content. Here is what I have tried so far:

// just setting content

titleLabel.text = "You don't always know what you are getting with mass-market cloud computing services. But with SimpliCompute, the picture is clear. SimpliCompute gives you powerful virtual servers you can deploy using just your web browser. That’s enterprise grade technology you can deploy and control on-the-fly."

titleLabel.numberOfLines = 0

titleLabel.preferredMaxLayoutWidth = 700

titleLabel.lineBreakMode = NSLineBreakMode.ByWordWrapping

titleLabel.sizeToFit()

None of this works for me in any combination! I always only see one line of text in my UILabel . What am I doing wrong?

I absolutely need the text content to be variable.
stackoverflow 
november 2016 by broderboy
Call to a member function associate() on a non-object
Error Message: http://puu.sh/d4l0F/5b0ac07e68.png

I've even saved the $transportation object before trying to create associations. I've verified that both $transporation, $from and $to are all their respective objects and they are.

I'm sure I'm missing something stupid here but I'm out of ideas.

My code:

class RideBuilder implements RideBuilderInterface

{

public function create(Advance $advance)

{

$ride = new Ride;

if($ride->validate(Input::all())) {

$ride->save();

$to = Location::find(Input::get('dropoffLocation'));

$from = Location::find(Input::get('pickupLocation'));

$transportation = new Transportation;

$transportation->save();

$transportation->transportable()->associate($ride);

$transportation->to()->associate($to);

$transportation->from()->associate($from);

$event = new Event;

$event->start = Input::get('ridePickUpTime');

$event->save();

$event->eventable->save($transportation);

$event->subjectable->save($advance);

}

return $ride;

}

}

Location Model:

class Location extends Elegant

{

protected $table = 'locations';

public $rules = array(

'label' => 'required|min:2',

'street' => 'required',

'city' => 'required',

'state' => 'required',

'type' => 'required',

);

public function advance()

{

return $this->belongsTo('Booksmart\Booking\Advance\Model\Advance');

}

public function locationable()

{

return $this->morphTo();

}

}

Transportation Model:

class Transportation extends Elegant

{

protected $table = 'transportations';

public function event()

{

$this->morphOne('Booksmart\Component\Event\Model\Event');

}

public function start_location()

{

$this->belongsTo('Booksmart\Component\Location\Model\Location', 'start_location');

}

public function end_location()

{

$this->belongsTo('Booksmart\Component\Location\Model\Location', 'end_location');

}

}
stackoverflow 
november 2016 by broderboy
#pragma mark in Swift?
In Objective C, I can use #pragma mark to mark sections of my code in the symbol navigator. Since this is a C preprocessor command, it's not available in Swift. Is there a stand-in for this in Swift, or do I have to use ugly comments?
stackoverflow 
november 2016 by broderboy
OpenUrl freezes app for over 10 seconds
I'm currently developing an App, that needs to open a browser to display a webpage.

To do that i use the [UIApplication sharedApplication] openURL method with an url.

In iOS 6 this works perfectly, but in iOS 7 it freezes the app for 10+ seconds, then opens the browser and all is good.

This happens using ad hoc provisioning. Someone on the internet commented that this was a known problem, however, that one comment was all i could find regarding this problem.
stackoverflow 
november 2016 by broderboy
Detect if app is being built for device or simulator in Swift
In Objective-C we can know if an app is being built for device or simulator using macros:

#if TARGET_IPHONE_SIMULATOR

// Simulator

#else

// Device

#endif

These are compile time macros and not available at runtime.

How can I achieve the same in Swift? I searched stack overflow, had a look into the docs and cannot figure it out.
stackoverflow 
november 2016 by broderboy
Xcode debugger doesn't print objects and shows nil, when they aren't
Xcode shows an error when trying to print an object with po <objectName> , but only for one project.

error: Couldn't materialize struct: size of variable <varName> disagrees with the ValueObject's size

Errored out in Execute, couldn't PrepareToExecuteJITExpression

The Xcode debugger also shows ALL objects as nil (self excluded), when they aren't (NSLog shows correct output, as seen in the image).

I don't know what's wrong with the project. Every other project works fine.

Any idea what it could be? (Cleaning the project had no effect.)
stackoverflow 
november 2016 by broderboy
Adding observer for KVO without pointers using Swift
In Objective-C, I would normally use something like this:

static NSString *kViewTransformChanged = @"view transform changed";

// or

static const void *kViewTransformChanged = &kViewTransformChanged;

[clearContentView addObserver:self

forKeyPath:@"transform"

options:NSKeyValueObservingOptionNew

context:&kViewTransformChanged];

I have two overloaded methods to choose from to add an observer for KVO with the only difference being the context argument:

clearContentView.addObserver(observer: NSObject?, forKeyPath: String?, options: NSKeyValueObservingOptions, context: CMutableVoidPointer)

clearContentView.addObserver(observer: NSObject?, forKeyPath: String?, options: NSKeyValueObservingOptions, kvoContext: KVOContext)

With Swift not using pointers, I'm not sure how to dereference a pointer to use the first method.

If I create my own KVOContext constant for use with the second method, I wind up with it asking for this:

let test:KVOContext = KVOContext.fromVoidContext(context: CMutableVoidPointer)

EDIT: What is the difference between CMutableVoidPointer and KVOContext? Can someone give me an example how how to use them both and when I would use one over the other?

EDIT #2: A dev at Apple just posted this to the forums: KVOContext is going away; using a global reference as your context is the way to go right now.
stackoverflow 
november 2016 by broderboy
ng-click not firing in AngularJS while onclick does
I am trying to use AngularJS in my application and have been successful to some extent.

I am able to fetch data and display it to the user. And I have a button in ng-repeat via which I want to post DELETE request. Below is my code which does it.

<div class="navbar-collapse collapse">

<table class="table table-striped" ng-controller="FetchViewData">

<tr>

<td>Name</td>

<td>ID</td>

<td>Department</td>

<td></td>

</tr>

<tr ng-repeat="d in viewData">

<td></td>

<td></td>

<td></td>

<td>

<button class="trashButton" type="button"

name="view:_id1:_id2:_id14:_id24:btnDelete"

id="view:_id1:_id2:_id14:_id24:btnDelete"

ng-click="deleteRecord('')">

<img src="/trashicon.gif"></button>

</td>

</tr>

</table>

</div>

This is the FetchViewData function which fetches the information and displays it to the user.

function FetchViewData($scope, $http) {

var test_link = "<MY LINK>";

$http.get(test_link).success( function(data) {

$scope.viewData = data;

});

}

The data is fetched and properly displayed.

But the code in ng-click="deleteRecord('')" does not fire when delete button is clicked. In Google Chrome's developer tools I can see valid values are generated for code but the code deleteRecord does not get fired. From this question I tried removing the braces and writing only d['@link'].href but it didn't work for me.

When I replace ng-click with onclick the deleteRecord function gets fired.

function deleteRecord(docURL) {

console.log(docURL);

$http.delete(docURL);

}

But then I receive the below error.

Uncaught ReferenceError: $http is not defined

deleteRecord

onclick

I am using jQuery 1.10.2 and AngularJS v1.0.8.
stackoverflow 
november 2016 by broderboy
How to calculate UILabel height dynamically?
I want to calculate number of lines and height of UILabel dynamically from given text for same.
stackoverflow 
november 2016 by broderboy
How to find max value for Double and Float in Swift
Current learning Swift, there are ways to find max and min value for different kind of Integer like Int.max and Int.min .

Is there a way to find max value for Double and Float? Moreover, which document should I refer for this kind of question? I am currently reading Apple's The Swift Programming Language .
stackoverflow 
november 2016 by broderboy
Create tap-able "links" in the NSAttributedText of a UILabel?
I have been searching this for hours but I've failed. I probably don't even know what I should be looking for.

Many applications have text and in this text are web hyperlinks in rounded rect. When I click them UIWebView opens. What puzzles me is that they often have custom links, for example if words starts with # it is also clickable and the application responds by opening another view. How can I do that? Is it possible with UILabel or do I need UITextView or something else?
stackoverflow 
november 2016 by broderboy
CocoaPods and Swift 3.0
I just wanna try Swift 3.0 in one of my projects. Xcode open the migration window to update my project to use Swift 3.0.

The problem is, I just wanna to update my project, and leave the Pods project untouched because any changes will be discard after I run the pod install again.

Anyone already have a solution for that?
stackoverflow 
november 2016 by broderboy
Alamofire : How to handle errors globally
My question is quite similar to this one, but for Alamofire : AFNetworking: Handle error globally and repeat request

How to be able to catch globally an error (typically a 401) and handle it before other requests are made (and eventually failed if not managed) ?

I was thinking of chaining a custom response handler, but that's silly to do it on each request of the app.

Maybe subclassing, but which class should i subclass to handle that ?
stackoverflow 
november 2016 by broderboy
How to Correctly handle Weak Self in Swift Blocks with Arguments
In my TextViewTableViewCell, I have a variable to keep track of a block and a configure method where the block is passed in and assigned. Here is my TextViewTableViewCell class:

//

// TextViewTableViewCell.swift

//

import UIKit

class TextViewTableViewCell: UITableViewCell, UITextViewDelegate {

@IBOutlet var textView : UITextView

var onTextViewEditClosure : ((text : String) -> Void)?

func configure(#text: String?, onTextEdit : ((text : String) -> Void)) {

onTextViewEditClosure = onTextEdit

textView.delegate = self

textView.text = text

}

// #pragma mark - Text View Delegate

func textViewDidEndEditing(textView: UITextView!) {

if onTextViewEditClosure {

onTextViewEditClosure!(text: textView.text)

}

}

}

When I use the configure method in my cellForRowAtIndexPath method, how do I properly use weak self in the block that I pass in. Here is what I have without the weak self:

let myCell = tableView.dequeueReusableCellWithIdentifier(textViewCellIdenfitier) as TextViewTableViewCell

myCell.configure(text: body, onTextEdit: {(text: String) in

// THIS SELF NEEDS TO BE WEAK

self.body = text

})

cell = bodyCell

UPDATE : I got the following to work using [weak self]:

let myCell = tableView.dequeueReusableCellWithIdentifier(textViewCellIdenfitier) as TextViewTableViewCell

myCell.configure(text: body, onTextEdit: {[weak self] (text: String) in

if let strongSelf = self {

strongSelf.body = text

}

})

cell = myCell

When I do [unowned self] instead of [weak self] and take out the if statement, the app crashes. Any ideas on how this should work with [unowned self]?
stackoverflow 
november 2016 by broderboy
Using an Encrypted Realm in a background or notification processes?
Realm has a great write up and sample code for encrypting your database. This documentation and sample work as intended, until you try to decrypt realm when:

A user has a password on their phone

The device is locked

Your app is trying to do work with Realm when a remote notification comes in

This happens because we can't access the keychain to get (or create) the key to en/decrypt the Realm. The default kSecAttrAccessible value is kSecAttrAccessibleWhenUnlocked

There are a few options as I see them:

Change kSecAttrAccessible to kSecAttrAccessibleAlways . I don't like this because it's a) too open and b) it was slated to be deprecated in iOS 9

Change kSecAttrAccessible to kSecAttrAccessibleAfterFirstUnlock or kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly . This is better but still feels too open to me, even though the docs state: This is recommended for items that need to be accessed by background applications

Create a second, non-encrypted Realm to use as a staging database. Store notification data here, then when the app wakes up from user interaction (the device would be unlocked), move the data from the staging Realm into the encrypted real one. This doesn't feel right either, as we'll have data temporarily not encrypted

Combine 2 and 3 and encrypt the staging Realm, and protect it's key with kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly

??

I'm currently trying to decide if #2, if #3 is worth putting the time into, or if I can come up with a #5

Is there an approach here that I clearly should use or one I've missed?

Thanks
stackoverflow 
november 2016 by broderboy
PHPDoc type hinting for array of objects?
So, in PHPDoc one can specify @var above the member variable declaration to hint at its type. Then an IDE, for ex. PHPEd, will know what type of object it's working with and will be able to provide a code insight for that variable.

<?php

class Test

{

/** @var SomeObj */

private $someObjInstance;

}

?>

This works great until I need to do the same to an array of objects to be able to get a proper hint when I iterate through those objects later on.

So, is there a way to declare a PHPDoc tag to specify that the member variable is an array of SomeObj s? @var array is not enough, and @var array(SomeObj) doesn't seem to be valid, for example.
stackoverflow 
october 2016 by broderboy
dispatch_after - GCD in swift?
I've gone through the iBook from Apple, and couldn't find any definition of it :

Can someone explain the structure of dispatch_after ?

dispatch_after(<#when: dispatch_time_t#>, <#queue: dispatch_queue_t?#>, <#block: dispatch_block_t?#>)
stackoverflow 
october 2016 by broderboy
Precision String Format Specifier In Swift
Below is how I would have previously truncated a float to two decimal places

NSLog(@" %.02f %.02f %.02f", r, g, b);

I checked the docs and the eBook but haven't been able to figure it out. Thanks!
stackoverflow 
october 2016 by broderboy
Send JSON data via POST (ajax) and receive json response from Controller (MVC)
I created a function in javascript like that:

function addNewManufacturer() {

var name = $("#id-manuf-name").val();

var address = $("#id-manuf-address").val();

var phone = $("#id-manuf-phone").val();

var sendInfo = {

Name: name,

Address: address,

Phone: phone

};

$.ajax({

type: "POST",

url: "/Home/Add",

dataType: "json",

success: function (msg) {

if (msg) {

alert("Somebody" + name + " was added in list !");

location.reload(true);

} else {

alert("Cannot add to list !");

}

},

data: sendInfo

});

}

I called jquery.json-2.3.min.js script file and I used it for toJSON(array) method.

In controller, I have this Add action

[HttpPost]

public ActionResult Add(PersonSheets sendInfo) {

bool success = _addSomethingInList.AddNewSomething( sendInfo );

return this.Json( new {

msg = success

});

}

But sendInfo as method parameter becomes null.

The model:

public struct PersonSheets

{

public int Id;

public string Name;

public string Address;

public string Phone;

}

public class PersonModel

{

private List<PersonSheets> _list;

public PersonModel() {

_list= GetFakeData();

}

public bool AddNewSomething(PersonSheets info) {

if ( (info as object) == null ) {

throw new ArgumentException( "Person list cannot be empty", "info" );

}

PersonSheets item= new PersonSheets();

item.Id = GetMaximumIdValueFromList( _list) + 1;

item.Name = info.Name;

item.Address = info.Address;

item.Phone = info.Phone;

_list.Add(item);

return true;

}

}

How could I do in action method when the data was sent with POST ?

I don't know how to use.

Also, it is possible to send back the response (to ajax) via JSON ?

Thank you
stackoverflow 
october 2016 by broderboy
Swift: delete all array elements
I am trying to delete all array elements with a for loop like this:

for index 1...myArray.count {

myArray.removeAtIndex(index)

}

But it doesn't work, I get this error before bulding:

Expected ';' in 'for' statement
stackoverflow 
october 2016 by broderboy
How to print call stack in Swift?
In Objective-C, you can print the call stack by doing the following:

NSLog(@"%@", [NSThread callStackSymbols]);

How do you do this in Swift without using Foundation class?
stackoverflow 
october 2016 by broderboy
How do I change timing for NSTimer?
I have the following code:

timer = [[NSTimer scheduledTimerWithTimeInterval:0.50 target:self selector:@selector(onTimer) userInfo:nil repeats:YES] retain];

-(void) onTimer

{

}

After every 0.50 seconds the OnTimer method is called.

But now I want to increment the time-interval.

That means:

OnTimer calls after 0.55

OnTimer calls after 0.60

OnTimer calls after 0.65

OnTimer calls after 0.70

OnTimer calls after 0.75

& so on.

Is there any solution for this?? I have tried lot but its not working.
stackoverflow 
october 2016 by broderboy
Can I embed a custom font in an iPhone application?
This question relates to iOS pre-3.2. As of 3.2 this functionality is easily achievable using samvermette's answer below, and I have changed the Accepted Answer (from commanda to samvermette) to reflect this. I can't give credit to both answers (besides upvotes) but they are both good.

I would like to have an app include a custom font for rendering text, load it, and then use it with standard UIKit elements like UILabel . Is this possible?

I found these links:

http://discussions.apple.com/thread.jspa?messageID=8304744

http://forums.macrumors.com/showthread.php?t=569311

but these would require me to render each glyph myself, which is a bit too much like hard work, especially for multi-line text.

I've also found posts that say straight out that it's not possible, but without justification, so I'm looking for a definitive answer.

EDIT - failed -[UIFont fontWithName:size:] experiment

I downloaded Harrowprint.tff (downloaded from here ) and added it to my Resources directory and to the project. I then tried this code:

UIFont* font = [UIFont fontWithName:@"Harrowprint" size:20];

which resulted in an exception being thrown. Looking at the TTF file in Finder confirmed that the font name was Harrowprint.

EDIT - there have been a number of replies so far which tell me to read the documentation on X or Y. I've experimented extensively with all of these, and got nowhere. In one case, X turned out to be relevant only on OS X, not on iPhone. Consequently I am setting a bounty for this question, and I will award the bounty to the first person who provides an answer (using only documented APIs) who responds with sufficient information to get this working on the device. Working on the simulator too would be a bonus.

EDIT - It appears that the bounty auto-awards to the answer with the highest number of votes. Interesting. No one actually provided an answer that solved the question as asked - the solution that involves coding your own UILabel subclass doesn't support word-wrap, which is an essential feature for me - though I guess I could extend it to do so.
stackoverflow 
october 2016 by broderboy
Laravel daily log created with wrong permissions
I have a script that I run using php artisan (with root user), and sometimes it causes the daily log file to be created before the apache www-data user does - which means that when a real user uses my web application, I get the folder permission error:

Failed to open stream: Permission denied

I change the permissions back to www-data everytime but I want to solve this by having the log file always created with the correct permissions.

I've considered creating a cron job that creates the file or touches it to make sure it has the right permission everyday, but I'm looking for a better solution that doesn't rely on another script.

We've also considered wrapping php artisan in another script to make sure that it is always run with the www-data credentials, but somethings that we want to do are actually root procedures that apache should not be allowed to do.

Any more suggestions?
stackoverflow 
october 2016 by broderboy
Assign xib to the UIView in Swift
in objective c it can be done in init method by

-(id)init{

self = [[[NSBundle mainBundle] loadNibNamed:@"ViewBtnWishList" owner:0 options:nil] objectAtIndex:0];

return self;

}

but when i do this in swift

init(frame: CGRect) {

self = NSBundle.mainBundle().loadNibNamed("ViewDetailMenu", owner: 0, options: nil)[0] as? UIView

}

cannot assign to self in a method error is shown.

now my approach is to create a view, and add the view loaded from nib to it.

anyone have a better idea?
stackoverflow 
october 2016 by broderboy
Object moved
How to set focus in AngularJS?
IFTTT  stackoverflow 
may 2014 by broderboy
Object moved
An issue with AVSpeechSynthesizer, Any workarounds?
IFTTT  stackoverflow 
march 2014 by broderboy
Object moved
How to log a method's execution time exactly in milliseconds?
IFTTT  stackoverflow 
february 2014 by broderboy
stackoverflow.com
how to connect UIview outlets to a custom subview
IFTTT  stackoverflow 
january 2014 by broderboy
stackoverflow.com
How can I update my NSTimer as I change the value of the time interval
IFTTT  stackoverflow 
january 2014 by broderboy
stackoverflow.com
NSCharacterSet: How do I add "_" to alphanumericCharacterSet text restriction?
IFTTT  stackoverflow 
january 2014 by broderboy
stackoverflow.com
How do I convert NSMutableArray to NSArray?
IFTTT  stackoverflow 
january 2014 by broderboy
stackoverflow.com
Change NSTimer interval for repeating timer
IFTTT  stackoverflow 
january 2014 by broderboy
stackoverflow.com
Ordered Sets and Core Data (NSOrderedSet)
IFTTT  stackoverflow 
january 2014 by broderboy
stackoverflow.com
Exception thrown in NSOrderedSet generated accessors
IFTTT  stackoverflow 
january 2014 by broderboy
stackoverflow.com
JSON and Core Data on the iPhone
IFTTT  stackoverflow 
january 2014 by broderboy
stackoverflow.com
How to use core data's add & remove (NSSet) accessor methods?
IFTTT  stackoverflow 
january 2014 by broderboy
« earlier      
per page:    204080120160

Copy this bookmark:



description:


tags: