broderboy + stackoverflow   209

UIActivityViewController customize text based on selected activity
I want to customize text for the same information but when I am sharing it on Facebook I don't want to use the twitter hash tags or @username scheme...

How can I diversify text for sharing based on which sharing service would be used?

Ofcourse I'm using UIActivityViewController:

UIActivityViewController *activityVC = [[UIActivityViewController alloc] initWithActivityItems:@[shareText, shareURL] applicationActivities:nil];
stackoverflow 
6 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 
15 days ago by broderboy
for each loop in objective c for accessing NSMutable dictionary
I am finding some difficulty in accessing mutable dictionary keys and values in Objective-C.

Suppose I have this:

NSMutableDictionary *xyz=[[NSMutableDictionary alloc] init];

I can set keys and values. Now, I just want to access each key and value, but I don't know the number of keys set.

In PHP it is very easy, something as follows:

foreach ($xyz as $key => $value)

How is it possible in Objective-C?
stackoverflow 
19 days ago by broderboy
UIActivityViewController UIActivityViewControllerCompletionWithItemsHandler
List item

Using Swift for an app that runs in iOS 8, I need to write a completion handler for the UIActivityViewController to capture the results of which "share" method a user selected.

This is a snippet of the code I have so far. My question is how to I set the avc.completionWithItemsHandler ? I'm sure it's simple, but I don't see it.

var activityItems = NSMutableArray()

activityItems.addObject("Email or text for 'share' goes here")

var avc = UIActivityViewController(activityItems: activityItems, applicationActivities: nil)

avc.setValue("Subject for Email", forKey: "Subject")

avc.completionWithItemsHandler = //Here is where I dont know what to do.

self.navigationController?.presentViewController(avc, animated: true, completion: nil)
stackoverflow 
5 weeks ago by broderboy
How to temporarily disable a foreign key constraint in MySQL?
Is it possible to temporarily disable constraints in MySQL?

I have two Django models, each with a ForeignKey to the other one. Deleting instances of a model returns an error because of the ForeignKey constraint:

cursor.execute("DELETE FROM myapp_item WHERE n = %s", n)

transaction.commit_unless_managed() #a foreign key constraint fails here

cursor.execute("DELETE FROM myapp_style WHERE n = %s", n)

transaction.commit_unless_managed()

Is it possible to temporarily disable constraints and delete anyway?
stackoverflow 
5 weeks ago by broderboy
How can iOS7 untethered energy/network recordings be accessed?
iOS7 has a preference under " Preferences | Developer | Instruments / Logging | Untethered Recording" to record the energy and network usage data.

How do I extract this from the device to view in Xcode or Instruments?
stackoverflow 
5 weeks ago by broderboy
The application bundle does not contain a valid identifier
I try to run my project but i get the following error "The application bundle does not contain a valid identifier."

here my info.plist

I followed other answer on the question. I don't have any "Ressources" folder inside my project.

Thanks for your help
stackoverflow 
6 weeks ago by broderboy
KissXML not returning strings
I have an example XML like this:

<rss version="2.0">

<channel>

<title></title>

<link></link>

<description></description>

<item>

<title></title>

<link></link>

<description></description>

<pubDate></pubDate>

<guid></guid>

</item>

and so on… And my obj-c syntax is looking like this:

NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

DDXMLDocument *ddDoc = [[DDXMLDocument alloc] initWithData:data options:0 error:&error];

NSArray *xmlItems = [ddDoc nodesForXPath:@"//item" error:&error]; // where ddDoc is your DDXMLDocument

NSMutableArray *returnArray = [[NSMutableArray alloc] initWithCapacity:[xmlItems count]];

for(DDXMLElement* itemElement in xmlItems)

{

ActiveActivity *activity = [[ActiveActivity alloc] init];

NSString *itemValueAsString = [[itemElement attributeForName:@"link"]stringValue];

[returnArray addObject:activity];

}

It's returning no value, can anyone say me why?
stackoverflow 
7 weeks ago by broderboy
How to configure Travis-CI to build pull requests & merges to master w/o redundancy
To put it in "BDD" terms:

Background:

Given I'm contributing to a GH repo

When I create a pull request

Then Travis should build the latest commit

When I push to an existing pull request

Then Travis should build the latest commit

When I merge a pull request to master

Then Travis should build master

I was confused by Travis-CI's "build pushes" and "build PRs" settings, as:

Enabling both causes each Pull Request to be build twice by Travis

once for the commit on that branch

and once again for the merge commit of that branch into its destination

Enabling just "build PRs" causes PRs to be built, but doesn't result in post-merge builds (i.e. on master).

Enabling "pushes" brute-force satisfies the above criteria by building all pushes to the repo. You can try to finagle things by white- & black-listing branches, but that will probably bite you unless you're rigorously disciplined with branch names.

This is explained more in Travis-CI docs and GH issue #3241 .

Anyone know a configuration that satisfies the above criteria?
stackoverflow 
10 weeks ago by broderboy
SecItemAdd and SecItemCopyMatching returns error code -34018 (errSecMissingEntitlement)
Sometimes when I run an application on device from Xcode I would try to access the keychain but fail due to error -34018. This doesn't match any of the documented keychain error codes and can't be consistently reproduced. (happens maybe 30% of the time, and it's not clear to me why it happens). What makes debugging this problem very difficult is the total lack of documentation. Any idea what causes this and how to fix it? I'm using Xcode 5 and running iOS 7.0.4 on device.

There is an open issue about this here: https://github.com/soffes/sskeychain/issues/52

EDIT: Adding keychain access code per request

I'm using the SSKeychain library for interfacing with keychain. Here's the snippet.

#define SERVICE @"default"

@implementation SSKeychain (EXT)

+ (void)setValue:(NSString *)value forKey:(NSString *)key {

NSError *error = nil;

BOOL success = NO;

if (value) {

success = [self setPassword:value forService:SERVICE account:key error:&error];

} else {

success = [self deletePasswordForService:SERVICE account:key error:&error];

}

NSAssert(success, @"Unable to set keychain value %@ for key %@ error %@", value, key, error);

if (!success) {

LogError(@"Unable to set value to keychain %@", error);

}

LogTrace(@"Will set keychain account %@. is to nil? %d", key, value == nil);

if (value == nil)

LogWarn(@"Setting keychain %@ to nil!!!", key);

}

+ (NSString *)valueForKey:(NSString *)key {

NSError *error = nil;

NSString *value = [self passwordForService:SERVICE account:key error:&error];

if (error && error.code != errSecItemNotFound) {

NSAssert(!error, @"Unable to retrieve keychain value for key %@ error %@", key, error);

LogError(@"Unable to retrieve keychain value for key %@ error %@", key, error);

}

return value;

}

+ (BOOL)removeAllValues {

LogInfo(@"Completely Reseting Keychain");

return [[self accountsForService:SERVICE] all:^BOOL(NSDictionary *accountInfo) {

return [self deletePasswordForService:SERVICE account:accountInfo[@"acct"]];

}];

}

@end

Vast majority of the time it's just fine. Sometimes I'll hit the assertion failures where I'm unable to either write to or read from keychain, causing critical assertion failure.
stackoverflow 
11 weeks ago by broderboy
Properly Create and Serve PDF Blob via HTML5 File and URL APIs
Ok, Let's say I have document data stored somewhere, let's arbitrarily take this pdf .

Issue #1. What I want to do is make an AJAX call to this URL (because I need to pass some authentication headers and it is cross domain). Then take the returned data, create a blob url for it, append an iFrame to the DOM, and direct the src to the blob url.

Currently my code looks like this:

$.ajax({

url:'http://www.grida.no/climate/ipcc_tar/wg1/pdf/tar-01.pdf'

}).done(function(data){

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

url = URL.createObjectURL(file),

_iFrame = document.createElement('iframe');

_iFrame.setAttribute('src', url);

_iFrame.setAttribute('style', 'visibility:hidden;');

$('#someDiv').append(_iFrame);

});

Unfortunately, I am getting a 'Failed to Render PDF' in the iFrame.

Issue #2. I'd like this to result in a file download prompt. Not sure how to guarantee this given that PDF's will naturally just display in the iFrame.
stackoverflow 
november 2017 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 
november 2017 by broderboy
How do you create a "reverse pivot" in Google Sheets?
I am trying to produce a "reverse pivot" function. I have searched long and hard for such a function, but cannot find one that is already out there.

I have a summary table with anywhere upto 20 columns and hundreds of row, however I would like to convert it into a flat list so I can import to a database (or even use the flat data to create more pivot tables from!)

So, I have data in this format:

Summary Table http://www.joietrade.co.uk/summary.png

And need to convert it to this format:

Summary Table http://www.joietrade.co.uk/list.png

I have created a function that will read the range from sheet1 and append the re-formatted rows at the bottom of the same sheet, however I am trying to get it working so I can have the function on sheet2 that will read the whole range from sheet1.

No matter what I try, I can't seem to get it to work, and was wondering if anybody could give me any pointers?

Here is what I have so far:

function readRows() {

var sheet = SpreadsheetApp.getActiveSheet();

var rows = sheet.getDataRange();

var numRows = rows.getNumRows();

var values = rows.getValues();

heads = values[0]

for (var i = 1; i <= numRows - 1; i++) {

for (var j = 1; j <= values[0].length - 1; j++) {

var row = [values[i][0], values[0][j], values[i][j]];

sheet.appendRow(row)

}

}

};
stackoverflow 
november 2017 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 
november 2017 by broderboy
Convert string to DATE type in swift 3
I have this structure:

struct message {

var id: String = "0"

var text: String = ""

var date: Date!

var status: String = ""

}

I have to load this structure from dbase, that it export in String format also 'date'.

So I write this code to convert String to Date type:

let dateFormatter = DateFormatter()

dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"

dateFormatter.timeZone = NSTimeZone(abbreviation: "UTC") as TimeZone!

let dataDate = dateFormatter.date(from: elemMessage["date"] as! String)!

And I load it in structure:

message(id: elemMessage["id"] as! String, text: elemMessage["text"] as! String, date: dataDate as! Date, status: elemMessage["status"] as! String)

But I have this warning: "Cast from 'Date' to unrelated type 'Date' always fails"

So if I run app it will fails.

How Can I fix this, the 'date' var in structure have to be Date type.

Thank you.
stackoverflow 
november 2017 by broderboy
throwing an exception in objective-c/cocoa
What's the best way to throw an exception in objective-c/cocoa?
stackoverflow 
november 2017 by broderboy
Add badge to app icon in iOS 8 with Swift
I'd like to set a badge on the icon of my app like in apple's mail app (number on top of the icon).

How can I do this in Swift (iOS8)?
stackoverflow 
november 2017 by broderboy
How to implement re-ordering of CoreData records?
I am using CoreData for my iPhone app, but CoreData doesn't provide an automatic way of allowing you to reorder the records. I thought of using another column to store the order info, but using contiguous numbers for ordering index has a problem. if I am dealing with lots of data, reordering a record potentially involves updating a lot of records on the ordering info (it's sorta like changing the order of an array element)

What's the best way to implement an efficient ordering scheme?
stackoverflow 
november 2017 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 
october 2017 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 
october 2017 by broderboy
How to use break or continue with Laravel Eloquent Collection's each method?
How to use break or continue with Laravel Eloquent Collection's each method.

My code is this:

$objectives->each(function($objective) {

Collection::make($objective)->each(function($action) {

Collection::make($action)->each(function($success_indicator) {

Collection::make($success_indicator)->each(function($success_indicator) {

echo 'hi';

continue;

});

});

});

});
stackoverflow 
october 2017 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 2017 by broderboy
UIFont fontWithName returns nil
In my info.plist, I added a key "Fonts provided by application" and added EdwardianScriptITCStd.otf

But, when I try to get that font, it returns nil:

NSLog(@"%@", [UIFont fontWithName:@"EdwardianScriptITCStd"

size:16.0f]);

I printed the font families using [UIFont familyNames] and it's not there either:

(

Thonburi,

"Snell Roundhand",

"Academy Engraved LET",

"Marker Felt",

"Geeza Pro",

"Arial Rounded MT Bold",

"Trebuchet MS",

Arial,

Marion,

"Gurmukhi MN",

"Malayalam Sangam MN",

"Bradley Hand",

"Kannada Sangam MN",

"Bodoni 72 Oldstyle",

Cochin,

"Sinhala Sangam MN",

"Hiragino Kaku Gothic ProN",

Papyrus,

Verdana,

"Zapf Dingbats",

Courier,

"Hoefler Text",

"Euphemia UCAS",

Helvetica,

"Hiragino Mincho ProN",

"Bodoni Ornaments",

"Apple Color Emoji",

Optima,

"Gujarati Sangam MN",

"Devanagari Sangam MN",

"Times New Roman",

Kailasa,

"Telugu Sangam MN",

"Heiti SC",

"Apple SD Gothic Neo",

Futura,

"Bodoni 72",

Baskerville,

"Chalkboard SE",

"Heiti TC",

Copperplate,

"Party LET",

"American Typewriter",

"Bangla Sangam MN",

Noteworthy,

Zapfino,

"Tamil Sangam MN",

"DB LCD Temp",

"Arial Hebrew",

Chalkduster,

Georgia,

"Helvetica Neue",

"Gill Sans",

Palatino,

"Courier New",

"Oriya Sangam MN",

Didot,

"Bodoni 72 Smallcaps"

)

What am I missing?

Thanks!
stackoverflow 
october 2017 by broderboy
Why are there 2 ways to unstage a file in git?
Sometimes git suggests git rm --cached to unstage a file, sometimes git reset HEAD file . When should I use which?

EDIT:

D:\code\gt2>git init

Initialized empty Git repository in D:/code/gt2/.git/

D:\code\gt2>touch a

D:\code\gt2>git status

# On branch master

#

# Initial commit

#

# Untracked files:

# (use "git add <file>..." to include in what will be committed)

#

# a

nothing added to commit but untracked files present (use "git add" to track)

D:\code\gt2>git add a

D:\code\gt2>git status

# On branch master

#

# Initial commit

#

# Changes to be committed:

# (use "git rm --cached <file>..." to unstage)

#

# new file: a

#

D:\code\gt2>git commit -m a

[master (root-commit) c271e05] a

0 files changed, 0 insertions(+), 0 deletions(-)

create mode 100644 a

D:\code\gt2>touch b

D:\code\gt2>git status

# On branch master

# Untracked files:

# (use "git add <file>..." to include in what will be committed)

#

# b

nothing added to commit but untracked files present (use "git add" to track)

D:\code\gt2>git add b

D:\code\gt2>git status

# On branch master

# Changes to be committed:

# (use "git reset HEAD <file>..." to unstage)

#

# new file: b

#
stackoverflow 
september 2017 by broderboy
How to disable json output from specific ansible commands?
Some ansible commands produce json output that's barely readable for humans. It distracts people when they need to check if playbook executed correctly and causes confusion.

Example commands are shell and replace - they generate a lot of useless noise. How can I prevent this? Simple ok | changed | failed is enough. I don't need the whole JSON.
stackoverflow 
september 2017 by broderboy
Run R script from command line
I have a file, called a.r , it has a chmod of 755,

sayHello <- function(){

print('hello')

}

sayHello()

How can I run this via command-line?
stackoverflow 
september 2017 by broderboy
How do I make my debug app version receive production push notifications on iOS?
My server is sporting only one version of sending push notifications, and it has my production (release) push certificate.

How do I test the notifications on my debug device and debug builds, using the same production certificate?

My device is sending the token, but when I attempt to send a real push notification Apple servers return status 8 error, that means that device token is incorrect.
stackoverflow 
september 2017 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 
september 2017 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 
august 2017 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 
august 2017 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 
august 2017 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 
august 2017 by broderboy
Core Data: Query objectIDs in a predicate?
I am fetching a set of objects from a Core Data persistent store using a fetch request and a predicate. My current predicate simply checks whether an attribute is >= a certain value. This all works great, except that I want to finally exclude any objects that are currently held in an array.

I basically need to be able to exclude a set of objects, and the only way I think I can do this is to be able to get a list of objectID from my managed objects array, and create another expression in my predicate to ensure that any objects returned don't have the same objectID . I.E.@"ANY records.objectID NOT IN %@", arrayOfObjectID .

How can I do this?
stackoverflow 
july 2017 by broderboy
How to Determine if PHPUnit Tests are Running?
I currently have a problem that I have to work around in legacy code to get our interaction with a PHP Extension to work properly (Singleton Testing Question ).

As such, I do not want to execute this code when running our normal production code with the application. Therefore, I need to check in regular PHP code if the code being executed is being executed as part of a test or not.

Any suggestions on how to determine this? I thought about a defined variable tied to the presence of the test files themselves (we do not ship the tests to customers) but our developers need the Extension to work normally, while the CI server needs to run the tests.

Would a Global set in the PHPUnit.xml file be recommended? Other thoughts?
stackoverflow 
july 2017 by broderboy
Prevent nginx 504 Gateway timeout using PHP set_time_limit()
I am getting 504 timeouts message from nginx when my PHP script is running longer than usual. set_time_limit(0) does not seem to prevent that! Does it not work when running php5-fpm on nginx? If so, whats the proper way of setting the time limit?

Error:

504 Gateway Time-out

nginx/1.2.7
stackoverflow 
july 2017 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 
july 2017 by broderboy
How do I check if a string contains a specific word?
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 
july 2017 by broderboy
How to present UIAlertController when not in a view controller?
Scenario: The user taps on a button on a view controller. The view controller is the topmost (obviously) in the navigation stack. The tap invokes a utility class method called on another class. A bad thing happens there and I want to display an alert right there before control returns to the view controller.

+ (void)myUtilityMethod {

// do stuff

// something bad happened, display an alert.

}

This was possible with UIAlertView (but perhaps not quite proper).

In this case, how do you present a UIAlertController , right there in myUtilityMethod ?
stackoverflow 
july 2017 by broderboy
Fire a method from a Static Cell in a Table view Controller
In my code i have a table with static cell inside storyboards. I'm trying to fire a method upon clicking the last static cell.

What should i write in the code to make this happen. How can i refer static cells inside the code without firing error.
stackoverflow 
july 2017 by broderboy
Make column not nullable in a Laravel migration
I'm writing a migration to make certain columns in a table nullable right now. For the down function, I of course want to make those columns not nullable again. I looked through the schema builder docs , but couldn't see a way to do this.

Any help would be appreciated.
stackoverflow 
july 2017 by broderboy
How to update pods to Swift 3.0
Currently in the process of migrating to Swift 3.0. This is my first time doing anything like this and I am not entirely sure how to deal with the various pods I am using. For example I am using the pod SwiftDate: https://github.com/malcommac/SwiftDate . The Swift 3.0 branch isn't on the master so I assume running pod update won't pull the Swift 3.0 version. Am I correct in putting pod:

'SwiftDate', :git => 'https://github.com/malcommac/SwiftDate.git', :branch => 'feature/swift-3.0'

into my podfile and then running the update? Checking the github page seems this is the correct branch. Do branches only need to be specified like this when the Swift 3.0 version isn't on the master? Any tips and pointers on this would be greatly appreciated! Thanks!
stackoverflow 
july 2017 by broderboy
CocoaPods and Swift 3.0
I just want to 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 want to 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 
july 2017 by broderboy
Swift, could not cast value of type
I created a subclass of UICollectionViewController and called it LibraryCollectionViewController , and marked both checkboxes for the project and test. Also it's storyboard id is LibraryCollectionViewController and set its corresponding class on interface builder.

Being new to Swift and iOS Testing I went and attempted to instantiate said view controller inside my test case as follows:

let storyboard = UIStoryboard(name: "Main", bundle: nil)

let libraryCollectionVC = storyboard.instantiateViewControllerWithIdentifier("LibraryCollectionViewController") as! LibraryCollectionViewController

And I'm getting the following error:

Could not cast value of type 'MyApp.LibraryCollectionViewController' (0x1010b01f0) to 'MyAppTests.LibraryCollectionViewController' (0x10bd7f580).

So it is clear that it isn't casting, but as I'm still new to Swift, I find myself unable to determine if the error itself is being caused by:

I did something wrong when creating the subclass and I'm referencing a different one (Ergo the MyApp.[vc] vs MyAppTests.[vc])

The casting using as! is incorrect

Any other reason

Any help would be appreciate, thanks in advance.

Update 1: When I was creating the view controller, the last step shows 2 checkboxes under a Target header, I enabled both of them, could that be the cause?
stackoverflow 
july 2017 by broderboy
How do I get a PHP class constructor to call its parent's parent's constructor
I need to have a class constructor in PHP call its parent's parent's (grandparent?) constructor without calling the parent constructor.

// main class that everything inherits

class Grandpa

{

public function __construct()

{

}

}

class Papa extends Grandpa

{

public function __construct()

{

// call Grandpa's constructor

parent::__construct();

}

}

class Kiddo extends Papa

{

public function __construct()

{

// THIS IS WHERE I NEED TO CALL GRANDPA'S

// CONSTRUCTOR AND NOT PAPA'S

}

}

I know this is a bizarre thing to do and I'm attempting to find a means that doesn't smell bad but nonetheless, I'm curious if it's possible.

EDIT

I thought I should post the rationale for the chosen answer. The reason being; it most elegant solutionto the problem of wanting to call the "grandparent's" constructor while retaining all the values. It's certainly not the best approach nor is it OOP friendly, but that's not what the question was asking.

For anyone coming across this question at a later date - Please find another solution . I was able to find a much better approach that didn't wreak havoc on the class structure. So should you.
stackoverflow 
july 2017 by broderboy
Does PHPUnit have some inbuilt recursive array comparison function?
Some of the testing I will need to do will require comparing a known array with the result I am getting from the functions I will be running.

For comparing arrays recursively:

Does PHPUnit have an inbuilt function?

Does someone here have some code they have constructed to share?

Will this be something I will have to construct on my own?
stackoverflow 
july 2017 by broderboy
Navigation bar with multiple buttons
I have a navigation bar with a left and right button, and I need to put another button next to the right button. Does anyone know how I can go about this? Here is some code to help:

- (id)init {

self = [super initWithStyle:UITableViewStyleGrouped];

if (self) {

_pinArray = [[NSArray alloc]init];

_pinArray = [Data singleton].annotations;

UIBarButtonItem *right = [[UIBarButtonItem alloc]initWithTitle:@"Map"

style:UIBarButtonItemStylePlain

target:self

action:@selector(goToMap:)];

self.navigationItem.rightBarButtonItem = right;

UIBarButtonItem *left = [[UIBarButtonItem alloc]initWithTitle:@"Menu"

style:UIBarButtonItemStylePlain

target:self

action:@selector(goToMenu:)];

self.navigationItem.leftBarButtonItem = left;

self.navigationItem.title = @"My Homes";

}

return self;

}
stackoverflow 
july 2017 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 
june 2017 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 
june 2017 by broderboy
Entitlements file do not match those specified in your provisioning profile.(0xE8008016)
The executable was signed with invalid entitlements.

The entitlements specified in your application’s Code Signing Entitlements file do not match those specified in your provisioning profile.(0xE8008016).

I am getting this error. please help me.

I have create the provisioning profile and change the bundle id. I have enable the keychain sharing from Target->Capabilities and generate the new .entitlement file. and i have also change the bundle id in that.
stackoverflow 
june 2017 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 
june 2017 by broderboy
JSON and Core Data on the iPhone
I have a core data object graph (consisting of two entities linked by a to-many relationship).

I was curious, as a relatively inexperienced iPhone developer, whether anyone could recommend an approach, and a suitable JSON implementation for the iPhone, which would allow me to:

1) convert the core data records into a JSON string (whilst maintaining the relationship between the entities); and

2) convert the JSON string back into core data objects (again preserving the relationship between entities).

I have searched, unsuccessfully, for a tutorial/code sample on this point so any assistance would be gratefully received.
stackoverflow 
june 2017 by broderboy
Exception thrown in NSOrderedSet generated accessors
On my Lion app, I have this data model:

The relationship subitems inside Item is ordered .

Xcode 4.1 (build 4B110) has created for me the file Item.h , Item.m , SubItem.h and SubItem.h .

Here is the content (autogenerated) of Item.h :

#import <Foundation/Foundation.h>

#import <CoreData/CoreData.h>

@class SubItem;

@interface Item : NSManagedObject {

@private

}

@property (nonatomic, retain) NSString * name;

@property (nonatomic, retain) NSOrderedSet *subitems;

@end

@interface Item (CoreDataGeneratedAccessors)

- (void)insertObject:(SubItem *)value inSubitemsAtIndex:(NSUInteger)idx;

- (void)removeObjectFromSubitemsAtIndex:(NSUInteger)idx;

- (void)insertSubitems:(NSArray *)value atIndexes:(NSIndexSet *)indexes;

- (void)removeSubitemsAtIndexes:(NSIndexSet *)indexes;

- (void)replaceObjectInSubitemsAtIndex:(NSUInteger)idx withObject:(SubItem *)value;

- (void)replaceSubitemsAtIndexes:(NSIndexSet *)indexes withSubitems:(NSArray *)values;

- (void)addSubitemsObject:(SubItem *)value;

- (void)removeSubitemsObject:(SubItem *)value;

- (void)addSubitems:(NSOrderedSet *)values;

- (void)removeSubitems:(NSOrderedSet *)values;

@end

And here is the content (autogenerated) of Item.m :

#import "Item.h"

#import "SubItem.h"

@implementation Item

@dynamic name;

@dynamic subitems;

@end

As you can see, the class Item offers a method called addSubitemsObject: . Unfortunately, when trying to use it in this way:

Item *item = [NSEntityDescription insertNewObjectForEntityForName:@"Item" inManagedObjectContext:self.managedObjectContext];

item.name = @"FirstItem";

SubItem *subItem = [NSEntityDescription insertNewObjectForEntityForName:@"SubItem" inManagedObjectContext:self.managedObjectContext];

[item addSubitemsObject:subItem];

this error appear:

2011-09-12 10:28:45.236 Test[2002:707] *** -[NSSet intersectsSet:]: set argument is not an NSSet

Can you help me?

Update:

After just 1,787 days from my bug report, today (August 1, 2016) Apple wrote me this: "Please verify this issue with the latest iOS 10 beta build and update your bug report at bugreport.apple.com with your results." . Let's hope this is the right time :)
stackoverflow 
june 2017 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 
june 2017 by broderboy
How to set focus on input field?
What is the 'Angular way' to set focus on input field in AngularJS?

More specific requirements:

When a Modal is opened, set focus on a predefined <input> inside this Modal.

Everytime <input> becomes visible (e.g. by clicking some button), set focus on it.

I tried to achieve the first requirement with autofocus , but this works only when the Modal is opened for the first time, and only in certain browsers (e.g. in Firefox it doesn't work).

Any help will be appreciated.
stackoverflow 
june 2017 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 
june 2017 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 
june 2017 by broderboy
What does "fatal error: unexpectedly found nil while unwrapping an Optional value" mean?
My Swift program is crashing with EXC_BAD_INSTRUCTION and this error. What does it mean, and how do I fix it?

fatal error: unexpectedly found nil while unwrapping an Optional value

This post is intended to collect answers to "unexpectedly found nil" issues, so they are not scattered and hard to find. Feel free to add your own answer or edit the existing wiki answer.
stackoverflow 
june 2017 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 
june 2017 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 
june 2017 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 
june 2017 by broderboy
How do you check "if not null" with Eloquent?
How do you check if a field is not null with Eloquent?

I tried Model::where('sent_at', 'IS NOT', DB::raw('null'))->... but it gives IS NOT as a binding instead of a comparison.

This is what DB::getQueryLog() says about it:

'query' => string 'select * from my_table where sent_at = ? and profile_id in (?, ?) order by created_at desc' (length=101)

'bindings' =>

array (size=3)

0 => string 'IS NOT' (length=6)

1 => int 1

2 => int 4
stackoverflow 
may 2017 by broderboy
OpenURL in iOS10
So apparently OpenURL has been depreciated in iOS 10. Does anyone have any documentation on why or can explain what to do next? I looked on the Apple site already and found a few things pertaining to OpenURL and this is what they say to use now:

UIApplication.shared().open(url: URL, options: [String: AnyObject], completionHandler: ((Bool) -> Void)?)

Does anyone have any evidence that this is the new way to use OpenURL in Swift 3.0? In addition what values are to be used in the options: and completionHandler: parameters respectively?
stackoverflow 
may 2017 by broderboy
How to "set a breakpoint in malloc_error_break to debug"
I'm getting lots of console outputs like this without my application crashing:

malloc: * error for object 0xc6a3970: pointer being freed was not

allocated * set a breakpoint in malloc_error_break to debug

How can I find out which object or variable is affected?

I tried setting a symbolic breakpoint like this but it never halts:
stackoverflow 
may 2017 by broderboy
Update Angular model after setting input value with jQuery
I have this simple scenario:

Input element which value is changed by jQuery's val() method.

I am trying to update the angular model with the value that jQuery set. I tried to write a simple directive, but it's not doing what I want.

Here's the directive:

var myApp = angular.module('myApp', []);

myApp.directive('testChange', function() {

return function(scope, element, attrs) {

element.bind('change', function() {

console.log('value changed');

})

}

})

this is the jQuery part:

$(function(){

$('button').click(function(){

$('input').val('xxx');

})

})

and html:

<div ng-app="myApp">

<div ng-controller="MyCtrl">

<input test-change ng-model="foo" />

<span></span>

</div>

</div>

<button>clickme</button>

Here is the fiddle with my try:

http://jsfiddle.net/U3pVM/743/

Can someone please point me in the right direction?
stackoverflow 
may 2017 by broderboy
Correct way to retrieve a single object from Realm database
I am absolutely loving Realm (0.92) in combination with Swift but have a question about reading an object from the database. My goal is to retrieve a single object with a known, unique ID (which also happens to be the primary key.

All the documentation appears to be oriented around queries for multiple objects which are then filtered. In this case I know the object ID and, since it is known to be unique, would like to retrieve it directly.

My current approach is as follows:

Realm().objects(Book).filter("id == %@", prevBook.nextID).first

This seems heavy-handed. Documentation from prior versions suggest that there is a more direct way but I can't seem to locate it in the documentation.

The problem with my current approach is that it is crashing with an exception on the following function:

public func filter(predicateFormat: String, _ args: CVarArgType...) -> Results<T>

The exception is mysteriously reported as:

EXC_BAD_ACCESS (code=1, address=0xedf)

Any suggestions are very welcome.

Anticipating one line of questioning: I have confirmed that replacing prevBook.nextID with a known, good ID does not solve the problem
stackoverflow 
may 2017 by broderboy
Create tap-able "links" in the NSAttributedString 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 
may 2017 by broderboy
iOS 7 and button and border
I am making my app ready for iOS7. I did conversion and was working with a user. The button in the app does not look like button. Looks very flat. Is there someway to put border or make it stand like a button?
stackoverflow 
may 2017 by broderboy
UIFont with custom font fails with Nil
I'm trying to add a custom font to my project in Xcode 4.2, but whenever I try to use it, I get a error that the object is nil.

I have done the following:

1) Added a row to my .plist 'Fonts provided by application' value: "LCDMono2 Ultra.ttf"

2) Added the font to my Supporting Files and showed it in XCode to verify it was added.

3) Verified using Get Info that the Full Name is "LCDMono2 Ultra"

4) Created the font in my project with:

UIFont *myFont = [UIFont fontWithName:@"LCDMono2 Ultra" size:16];

and I've tried this variant:

UIFont *myFont = [UIFont fontWithName:@"LCDMono2 Ultra" size:16.f];

5) Tried to use the font name (addObject:myFont.fontName) , generating the 'nil' error.

What could be causing the error? Could it be something like the space in the name?
stackoverflow 
may 2017 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 
may 2017 by broderboy
Swift 2: guard in for loop?
what is the correct way to use guard inside a for loop?

for (index,user) in myUsersArray.enumerate() {

guard user.id != nil else {

print("no userId")

//neither break / return will keep running the for loop

}

if user.id == myUser.id {

//do stuff

}

}
stackoverflow 
may 2017 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 
may 2017 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 
may 2017 by broderboy
Best architecture for many asynchronous Realm writes
I'm getting crashes from Realm writes already being in a transaction, due to Realm data being updated from several asynchronous network callbacks. I understand why Realm is crashing, but I'm wondering what the right architecture is here.

So far, I can minimize the crashes by moving the individual write transactions to background threads, but is this the recommended best practice? It relies on me remembering to do this every time. Or should the network requests all be run through some central clearing house, which then moves callbacks (and therefore writes) onto background threads? Or are background threads not even the right way to do this?
stackoverflow 
may 2017 by broderboy
Convert String to float in Apple's Swift
I'm trying to convert numbers taken from a UITextField, which I presume, are actually strings, and convert them to float, so I can multiply them.

I have two UITextfield s which are declared as follows:

@IBOutlet var wage: UITextField

@IBOutlet var hour: UITextField

When the user presses a UIButton I want to calculate the wages the user earns, but I can't, as I need to convert them to floats first, before I can use them.

I know how to convert them to an integer by doing this:

var wageConversion:Int = 0

wageConversion = wage.text.toInt()!

However, I have no idea how to convert them to floats.
stackoverflow 
may 2017 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 
may 2017 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 
may 2017 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 
may 2017 by broderboy
Installing Apple's 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 
may 2017 by broderboy
Is there a way to 'uniq' by column?
I have a .csv file like this:

stack2@example.com,2009-11-27 01:05:47.893000000,example.net,127.0.0.1

overflow@example.com,2009-11-27 00:58:29.793000000,example.net,255.255.255.0

overflow@example.com,2009-11-27 00:58:29.646465785,example.net,256.255.255.0

...

I have to remove duplicate e-mails (the entire line) from the file (i.e. one of the lines containing overflow@example.com in the above example). How do I use uniq on only field 1 (separated by commas)? According to man , uniq doesn't have options for columns.

I tried something with sort | uniq but it doesn't work.
stackoverflow 
may 2017 by broderboy
Opening Realm file in browser always requires an encryption key
I'm using Realm Browser 0.9.85 and using the examples in https://github.com/realm/realm-cocoa .

I'm a total Realm newbie so go easy on me. Every time I try to open up a Realm file from the example from GitHub, I get a request to enter in the encryption key. It seems like the default configuration in Realm is to not have it's db be encrypted, so I don't know what gives. Any help would be greatly appreciated. Thanks.
stackoverflow 
may 2017 by broderboy
« earlier      
per page:    204080120160

Copy this bookmark:



description:


tags: