For a project I'm working on I'm using core data to store the application's data. The application loads XML from the internet and tries to store the objects generated from the parsed results in the data model. This used to work fine, until a few days ago. I changed the data model (added one property on an object), so I made a new version and ran mogenerator to generate new stub classes for the objects in the model. Most of it still works fine, but there are some odd errors in code that used to work perfectly.
During the parsing of the XML an object is created and values on it are filled in. One of the values is an URL for an image. In the data model this value may not be NIL, but in the XML it occasionaly is. I use validateForInsert on the item to check if I can commit it. This is the part that used to work fine, but now fails, complaining about the NIL value.
A bit of code from the parser:
...
currentItem = [[[MyItem alloc] initWithEntity:[self.dataModel entityByName:#"MyItem"] insertIntoManagedObjectContext:self.dataModel.managedObjectContext] autorelease];
currentItem.label = [attributeDict objectForKey:LABEL];
currentItem.paramString = [attributeDict objectForKey:QUERY_STRING];
[currentItem setSortOrderValue:[[currentRootItem items] count]];
[currentRootItem addItemsObject:currentItem];
} else if ([elementName isEqualToString:IMAGE]) {
currentItem.imageLocation = [attributeDict objectForKey:IMAGE_URL];
...
Then, when the document is parsed, I do the check:
...
{
NSArray *Items = [[myRootItem items] allObjects];
for (MyItem *item in Items) {
NSLog(#"%#", item);
NSLog(#"before");
NSLog(#"%d", [item validateForInsert:&validationError]);
NSLog(#"after");
if (![item validateForInsert:&validationError]) {
[[self.dataModel managedObjectContext] deleteObject:item];
}
}
}
...
This used to work just fine, but now it crashes in validateForInsert:
2011-03-30 13:38:32.951 xx[915:207] before
2011-03-30 13:38:33.130 xx[915:207] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFDictionary setObject:forKey:]: attempt to insert nil value (key: Property/imageLocation/Entity/Item)'
Stacktrace:
0 CoreFoundation 0x022fc5a9 __exceptionPreprocess + 185
1 libobjc.A.dylib 0x02450313 objc_exception_throw + 44
2 CoreFoundation 0x022b4ef8 +[NSException raise:format:arguments:] + 136
3 CoreFoundation 0x022b4e6a +[NSException raise:format:] + 58
4 CoreFoundation 0x022fae15 -[__NSCFDictionary setObject:forKey:] + 293
5 CoreData 0x013fa87c -[NSValidationErrorLocalizationPolicy _cachedObjectForKey:value:] + 172
6 CoreData 0x013fa629 -[NSValidationErrorLocalizationPolicy _localizedPropertyNameForProperty:entity:] + 201
7 CoreData 0x013fa4e7 -[NSValidationErrorLocalizationPolicy localizedPropertyNameForProperty:] + 71
8 CoreData 0x013a844e -[NSManagedObject(_NSInternalMethods) _substituteEntityAndProperty:inString:] + 142
9 CoreData 0x013a572e -[NSManagedObject(_NSInternalMethods) _generateErrorWithCode:andMessage:forKey:andValue:additionalDetail:] + 254
10 CoreData 0x013598f1 -[NSPropertyDescription(_NSInternalMethods) _nonPredicateValidateValue:forKey:inObject:error:] + 161
11 CoreData 0x01359485 -[NSAttributeDescription(_NSInternalMethods) _nonPredicateValidateValue:forKey:inObject:error:] + 85
12 CoreData 0x01358b22 -[NSManagedObject(_NSInternalMethods) _validateValue:forProperty:andKey:withIndex:error:] + 386
13 CoreData 0x01358847 -[NSManagedObject(_NSInternalMethods) _validatePropertiesWithError:] + 263
14 CoreData 0x013586e1 -[NSManagedObject(_NSInternalMethods) _validateForSave:] + 81
15 xx 0x001af8bf -[MyParser parserDidEndDocument:] + 1039
16 Foundation 0x00742717 _endDocument + 95
I can't figure out what went wrong. As far as I know making a new version of the data model went right (using XCode), setting it to the current version etc, all went right. I didn't have these problems the last time I did all this...
The only thing different is that now I upgraded to XCode 3.2.6, from 3.2.5 or 3.2.4, I don't remember.
My target is iPhone, and I'm using the 4.3 iOS SDK that came with this version of XCode.
I had this problem and I fixed it by checking my data length. If your model has a string field, you must validate that the String you're passing doesn't exceed the field length.
Well, to answer my own question...
The problem is not there in 3.2.5, nor is it there in 4.0.1. Looks like apple has some bugfixing to do on 3.2.6...
Related
im experimenting with Swift for TensorFlow to do some image segmentations, lets first look at some code:
let (loss, grad) = model.valueWithGradient { (model: UNet) -> Tensor<Float> in
let logits = model(batch.images)
print(logits.shape)
print(batch.corners.shape)
return softmaxCrossEntropy(logits: logits, probabilities: batch.corners)
}
Each batch contains some tensors of images of tickets, and some tensors of images of the corners, hence the two references: batch.images and batch.corners
You will see, that I also print their shapes, which both come out to be: [32, 324, 324, 4]
32 being the batch size, 324*324 being the size of the images, and 4 channels for each image.
The goal is to extract the position of the corners on the images.
I wanna use softmaxCrossEntropy as the loss function, but it gives be the following error:
Fatal error: logits and labels must be either 2-dimensional, or broadcasted to be 2-dimensional: file /swift-base/tensorflow-swift-apis/Sources/TensorFlow/Bindings/EagerExecution.swift, line 300
Current stack trace:
0 libswiftCore.so 0x00007f51ab60b940 swift_reportError + 50
1 libswiftCore.so 0x00007f51ab67ccf0 _swift_stdlib_reportFatalErrorInFile + 115
2 libswiftCore.so 0x00007f51ab5a6b48 <unavailable> + 3722056
3 libswiftCore.so 0x00007f51ab5a6cd7 <unavailable> + 3722455
4 libswiftCore.so 0x00007f51ab3794e8 <unavailable> + 1438952
5 libswiftCore.so 0x00007f51ab57a5ce <unavailable> + 3540430
6 libswiftCore.so 0x00007f51ab378c09 <unavailable> + 1436681
7 libswiftTensorFlow.so 0x00007f51a79b5f50 <unavailable> + 2899792
8 libswiftTensorFlow.so 0x00007f51a7809d10 checkOk(_:file:line:) + 434
9 libswiftTensorFlow.so 0x00007f51a7810ce0 TFE_Op.evaluateUnsafe() + 506
10 libswiftTensorFlow.so 0x00007f51a7811550 TFE_Op.execute<A, B>(_:_:) + 323
11 libswiftTensorFlow.so 0x00007f51a781a0c2 <unavailable> + 1212610
12 libswiftTensorFlow.so 0x00007f51a792fee0 static Raw.softmaxCrossEntropyWithLogits<A>(features:labels:) + 821
13 libswiftTensorFlow.so 0x00007f51a7a6f5b0 _vjpSoftmaxCrossEntropyHelper<A>(logits:probabilities:) + 84
14 libswiftTensorFlow.so 0x00007f51a7a6f6b0 AD__$s10TensorFlow25softmaxCrossEntropyHelper6logits13probabilitiesAA0A0VyxGAG_AGtAA0aB13FloatingPointRzlF__vjp_src_0_wrt_0 + 9
15 libswiftTensorFlow.so 0x00007f51a7ac9e10 AD__$s10TensorFlow19softmaxCrossEntropy6logits13probabilities9reductionAA0A0VyxGAH_A3HXFtAA0aB13FloatingPointRzlF__vjp_src_0_wrt_0 + 444
16 libswiftTensorFlow.so 0x00007f51a7b48f64 <unavailable> + 4550500
17 libswiftTensorFlow.so 0x00007f51a7ac9a60 AD__$s10TensorFlow19softmaxCrossEntropy6logits13probabilitiesAA0A0VyxGAG_AGtAA0aB13FloatingPointRzlF__vjp_src_0_wrt_0 + 616
Current stack trace:
frame #14: 0x00007f516f9a3c45 $__lldb_expr162`AD__$s15__lldb_expr_16110TensorFlow0C0VySfG02__a1_B4_1354UNetVcfU___vjp_src_0_wrt_0(model=<unavailable>, batch=<unavailable>) at <Cell 25>:17
frame #21: 0x00007f516f99b941 $__lldb_expr162`main at <Cell 25>:13:34
I understand that the inputs needs to be 2D, but I dont know how to handle that. I cant help but notice, that the Python version of the same function has a parameter alongAxis and wonder what I would do in S4TF to set a specific axis.
Hey #magnuskahr I can suggest you get in touch at /tensorflow/swift-apis under
Issues and the development team can look at it as soon as they can.
Also, I searched through closed and open Issues for softmaxCrossEntropy and came across a discussion here under /swift-apis/issues/422 which you may find interesting.
You can also post your questions in the official Swift for TensorFlow Google Group here.
I have a function that takes as input some of the values in a table and returns a tuple if you will - three separate return values, which I want to transpose into the output of a query. Here's a simplified example of what I want to achieve:
multiplier:{(x*2;x*3;x*3)};
select twoX:multiplier[price][0]; threeX:multiplier[price][1]; fourX:multiplier[price][2] from data;
The above basically works (I think I've got the syntax right for the simplified example - if not then hopefully my intention is clear), but is inefficient because I'm calling the function three times and throwing away most of the output each time. I want to rewrite the query to only call the function once, and I'm struggling.
Update
I think I missed a crucial piece of information in my explanation of the problem which affects the outcome - I need to get other data in the query alongside the output of my function. Here's a hopefully more realistic example:
multiplier:{(x*2;x*3;x*4)};
select average:avg price, total:sum price, twoX:multiplier[sum price][0]; threeX:multiplier[sum price][1]; fourX:multiplier[sum price][2] by category from data;
I'll have a go at adapting your answers to fit this requirement anyway, and apologies for missing this bit of information. The real function if a proprietary and fairly complex algorithm and the real query has about 30 output columns, hence the attempt at simplifying the example :)
If you're just looking for the results themselves you can extract (exec) as lists, create dictionary and then flip the dictionary into a table:
q)exec flip`twoX`threeX`fourX!multiplier[price] from ([]price:til 10)
twoX threeX fourX
-----------------
0 0 0
2 3 4
4 6 8
6 9 12
8 12 16
10 15 20
12 18 24
14 21 28
16 24 32
18 27 36
If you need other columns from the original table too then its trickier but you could join the tables sideways using ,'
q)t:([]price:til 10)
q)t,'exec flip`twoX`threeX`fourX!multiplier[price] from t
An apply # can also achieve what you want. Here data is just a table with 10 random prices. # is then used to apply the multiplier function to the price column while also assigning a column name to each of the three resulting lists:
q)data:([] price:10?100)
q)multiplier:{(x*2;x*3;x*3)}
q)#[data;`twoX`threeX`fourX;:;multiplier data`price]
price twoX threeX fourX
-----------------------
80 160 240 240
24 48 72 72
41 82 123 123
0 0 0 0
81 162 243 243
10 20 30 30
36 72 108 108
36 72 108 108
16 32 48 48
17 34 51 51
I'm trying to set the fill color of individual features in a Mapbox map layer using the MGL_MATCH expression, but I keep getting:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFString mgl_color]: unrecognized selector sent to instance ...
func mapViewDidFinishLoadingMap(_ mapView: MGLMapView) {
let layer = mapView.style!.layer(withIdentifier: "powiaty-1") as! MGLFillStyleLayer
let source = mapView.style!.source(withIdentifier: "composite") as! MGLVectorTileSource
let features = source.features(sourceLayerIdentifiers: NSSet(object: "powiaty") as! Set<String>, predicate: nil);
let query = NSMutableString(format: "MGL_MATCH(jpt_kod_je, ");
for feature in features {
let code = feature.attribute(forKey: "jpt_kod_je") as! String
let color = code.prefix(2) == "06" ? UIColor.red : UIColor.white;
query.appendFormat("%#, %#, ", code, color)
}
query.appendFormat("%#)", UIColor.white);
print(query);
layer.fillColor = NSExpression(format: "%#", query);
}
The expected results:
Features whose 4-digit code (jpt_kod_je : String property) starts with "06" to be filled with red, all others with white.
Actual results:
Crash with the stack:
0 CoreFoundation 0x0000000106f456fb __exceptionPreprocess + 331
1 libobjc.A.dylib 0x00000001064e9ac5 objc_exception_throw + 48
2 CoreFoundation 0x0000000106f63ab4 -[NSObject(NSObject) doesNotRecognizeSelector:] + 132
3 CoreFoundation 0x0000000106f4a443 ___forwarding___ + 1443
4 CoreFoundation 0x0000000106f4c238 _CF_forwarding_prep_0 + 120
5 Mapbox 0x000000010575d629 _ZN24MGLStyleValueTransformerIN4mbgl5ColorEU8__strongP7UIColorS1_S4_E15toPropertyValueINS0_5style13PropertyValueIS1_EEEENSt3__19enable_ifIXntsr3std7is_sameIT_NS7_22ColorRampPropertyValueEEE5valueESC_E4typeEP12NSExpressionb + 257
6 Mapbox 0x000000010582845e -[MGLFillStyleLayer setFillColor:] + 123
7 MapboxExpressions 0x0000000105443eb3 $s17MapboxExpressions14ViewControllerC03mapC19DidFinishLoadingMapyySo06MGLMapC0CF + 4867 ...
Currently, I am converting the hardware decoding Obj-C code to Swift version. (Xcode 8, Swift 3).
I don't know how to set up a dictionary to set up an output option on the screen, also, I don't know how to use it.
The following code works fine in Obj-C project:
// set some values of the sample buffer's attachments
CFArrayRef attachments = CMSampleBufferGetSampleAttachmentsArray(sampleBuffer, YES);
CFMutableDictionaryRef dict = (CFMutableDictionaryRef)CFArrayGetValueAtIndex(attachments, 0);
CFDictionarySetValue(dict, kCMSampleAttachmentKey_DisplayImmediately, kCFBooleanTrue);
I tried the following Swift code, but there was a runtime error:
// i got run-time error
let attachments = CMSampleBufferGetSampleAttachmentsArray(sampleBuffer!, true)
let dict = unsafeBitCast(attachments, to: CFMutableDictionary.self)
CFDictionarySetValue(dict, unsafeBitCast(kCMSampleAttachmentKey_DisplayImmediately, to: UnsafeRawPointer.self), unsafeBitCast(kCFBooleanTrue, to: UnsafeRawPointer.self))
Is it wrong to convert the CFString to UnsafeRawPointer? or Is it wrong to use the CFDictionarySetValue method?
this is my error log.
2016-11-24 16:50:44.458 MyApp[35288:3519253] -[__NSSingleObjectArrayI __setObject:forKey:]: unrecognized selector sent to instance 0x6000002045a0
2016-11-24 16:50:44.466 MyApp[35288:3519253] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSSingleObjectArrayI __setObject:forKey:]: unrecognized selector sent to instance 0x6000002045a0'
*** First throw call stack:
(
0 CoreFoundation 0x000000010b02734b __exceptionPreprocess + 171
1 libobjc.A.dylib 0x000000010a0e421e objc_exception_throw + 48
2 CoreFoundation 0x000000010b096f34 -[NSObject(NSObject) doesNotRecognizeSelector:] + 132
3 CoreFoundation 0x000000010afacc15 ___forwarding___ + 1013
4 CoreFoundation 0x000000010afac798 _CF_forwarding_prep_0 + 120
5 MyApp 0x000000010937ac7a _TFC14MyApp16ViewerController21receivedRawVideoFramefT5frameGSaVs5UInt8_4withVs5Int32_T_ + 4890
6 MyApp 0x000000010937d8e2 _TFC14MyApp16ViewerController12MainCallBackfTVs5Int3212callbackCodeS1_8argumentGSqSv_7argSizeS1__T_ + 4242
7 MyApp 0x000000010937daed _TToFC14MyApp16ViewerController12MainCallBackfTVs5Int3212callbackCodeS1_8argumentGSqSv_7argSizeS1__T_ + 61
8 MyApp 0x000000010937dd56 _TTDFC14MyApp16ViewerController12MainCallBackfTVs5Int3212callbackCodeS1_8argumentGSqSv_7argSizeS1__T_ + 70
9 MyApp 0x000000010937dcfe _TTWC14MyApp16ViewerControllerS_18IJCallbackProtocolS_FS1_12MainCallBackfTVs5Int3212callbackCodeS2_8argumentGSqSv_7argSizeS2__T_ + 62
10 MyApp 0x00000001093b22b2 _TFC14MyApp11AppDelegate19MainCallBack_StreamfTVs5Int32S1_GSqSv_S1__T_ + 258
11 MyApp 0x00000001093d26d3 _TFZFC14MyApp19IJStreamCoreWrapper6AttachFTSv2ipSS4portSi_T_U_FTVs5Int32S1_GSqSv_S1_GSqSv__T_ + 355
12 MyApp 0x00000001093d2719 _TToFZFC14MyApp19IJStreamCoreWrapper6AttachFTSv2ipSS4portSi_T_U_FTVs5Int32S1_GSqSv_S1_GSqSv__T_ + 9
13 MyApp 0x00000001093ee176 _ZL8CallbackPN14CStreamManager9Session_TEiPvi + 70
14 MyApp 0x00000001093f09d3 _Z25StreamManagerThread_VideoPv + 3155
15 libsystem_pthread.dylib 0x000000010e494aab _pthread_body + 180
16 libsystem_pthread.dylib 0x000000010e4949f7 _pthread_body + 0
17 libsystem_pthread.dylib 0x000000010e494221 thread_start + 13
)
libc++abi.dylib: terminating with uncaught exception of type NSException
I was only able to get this working with the following:
let attachments = CMSampleBufferGetSampleAttachmentsArray(buf!, createIfNecessary: true)
let dict = unsafeBitCast(CFArrayGetValueAtIndex(attachments, 0), to: CFMutableDictionary.self)
CFDictionarySetValue(dict,
unsafeBitCast(kCMSampleAttachmentKey_DisplayImmediately, to: UnsafeRawPointer.self),
unsafeBitCast(kCFBooleanTrue, to: UnsafeRawPointer.self))
I tried #Alexander's suggestion, and although it compiles and executes, the underlying CFDictionary is not mutated and the desired result is not achieved.
// let attachments = CMSampleBufferGetSampleAttachmentsArray(buf!, createIfNecessary: true) as! Array<Dictionary<String, Any>>
// var dict = attachments[0]
// dict[kCMSampleAttachmentKey_DisplayImmediately as String] = true
In the first code snippet, you have a call to CFArrayGetValueAtIndex, which returns a dictionary that you pass to CFDictionarySetValue.
In the second code snippet, you don't call CFArrayGetValueAtIndex. You just pass the array to CFDictionarySetValue. Since an array is not a dictionary, you get a fatal error.
When you convert code to Swift, it's much best to understand the semantic of the program, and rewrite Swift code that matches. Don't try to just convert the syntax bit by bit.
CMSampleBufferGetSampleAttachmentsArray returns you a reference to a CFArray of CFDictionary instances. Casting this CFArrayRef to CFMutableDictionaryRef has the effect of just making a reference to the first instance.
It's best to just use Swift's native types. I can't provide an exact implementation because I'm not to sure of the types in play, but here's a start
//TODO: give me a better name
let array = CMSampleBufferGetSampleAttachmentsArray(sampleBuffer!, true) as [[String: Bool]] //TODO:
//TODO: give me a better name
var firstDict = array[0]
firstDict[kCMSampleAttachmentKey_DisplayImmediately as String] = true
any one have any idea why application crash on this place
In code I am doing something like this
RequestOperation* requestOperation = [[[RequestOperation alloc]initWithItem:item delegate:self] autorelease];
[operationQueue addOperation:requestOperation];
Error Code
OS Version: iPhone OS 4.2.1
Report Version: 104
Exception Type: SIGBUS
Exception Codes: BUS_ADRALN at 0x7c
Crashed Thread: 0
Thread 0 Crashed:
0 libSystem.B.dylib 0x000053e4 OSAtomicCompareAndSwap32 + 0
1 Foundation 0x00023235 ____addOperations_block_invoke_1 + 37
2 Foundation 0x00022d91 __addOperations + 229
3 Foundation 0x00022cab -[NSOperationQueue addOperation:] + 11
BUS_ADRALN means that there is an address alignment problem.
I would check if the NSOperation object that is passed to [NSOperationQueue addOperation:] is valid.