I am trying to read data from UDP socket. I am using Xcode 9.2 and Swift and I want to implement communication without external libraries. I can send the data (testing using Packet Sender), but the problem is when I send the packet back and try to read data. My socket callback function gets called and callback type matches data callback. If I try to load CFData from memory using the pointer, the operation doesn't crash. Then when I try to use a CFDataGetLength or similar function on that object, the app crashes.
func socketCallback(socket: CFSocket?, callbackType: CFSocketCallBackType, address: CFData?, data: UnsafeRawPointer?, info: UnsafeMutableRawPointer?) {
if callbackType == CFSocketCallBackType.dataCallBack {
print("dataCallback called.")
let cf = data!.load(as: CFData.self)
print(cf) // prints __NSCFData
print(CFDataGetLength(cf)) // crashes
}
}
The exception being thrown:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '+[__NSCFData length]: unrecognized selector sent to class 0x10ca08348'
Same exception for other CFData functions, not just CFDataGetLength, for example
var bytes = [UInt8]()
print(CFDataGetBytes(cf, CFRange(location: 0, length: 3), &bytes))
I have tried to read some data from memory as unsigned bytes, at pointer (data) and with offset:
var array = [UInt8]()
for i in 0...55 {
let pointer = data! + i
array.append(pointer.load(as: UInt8.self))
}
print(array, separator: ", ", terminator: "\n")
It prints the following:
[72, 67, 103, 5, 1, 0, 0, 0, 132, 20, 0, 0, 1, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 97, 97, 97, 0, 0, 0, 0, 0]
I noticed that the number 3 is the length of the message, and bytes 48, 49 and 50 are the data (I have send "aaa", 97 is "a" in ascii).
Socket initialization code:
var socket = CFSocketCreate(nil, PF_INET, SOCK_DGRAM, IPPROTO_UDP, CFSocketCallBackType.dataCallBack.rawValue, socketCallback, nil)
let runLoopSource = CFSocketCreateRunLoopSource(nil, socket, 0)
CFRunLoopAddSource(CFRunLoopGetMain(), runLoopSource, CFRunLoopMode.defaultMode)
Most information that I found was for ObjC and I am not very familiar with ObjC.
What could I have done wrong?
Related
I have a text file.
each block parameter is separated by a colon
WoodBlock : 0.886275, 0.607843, 0.25098 : 2, 2, 2 : true : -75.5656891, -11.899992, -416.506866, 1, 0, 0, 0, 1, 0, 0, 0, 1 : 0, 0, 0 : 0, 0, 0
RustedBlock : 0.639216, 0.635294, 0.647059 : 2, 2, 2 : true : -35.5656891, -11.899992, -424.506866, 1, 0, 0, 0, 1, 0, 0, 0, 1 : 0, 0, 0 : 0, 0, 0
StoneBlock : 0.639216, 0.635294, 0.647059 : 2, 2, 2 : true : -50.5656891, -11.899992, -425.506866, 1, 0, 0, 0, 1, 0, 0, 0, 1 : 0, 0, 0 : 0, 0, 0
MetalRod : 0.388235, 0.372549, 0.384314 : 1, 3, 1 : true : -51.5656891, -11.399992, -412.506866, 1, 0, 0, 0, 1, 0, 0, 0, 1 : 0, 0, 0 : 0, 0, 0
Each line contains information about a block. I want to make an algorithm that will work like this:
the first line is selected
the second parameter of the line is selected - the script does something with this parameter
the third parameter of the line is selected - the script does something with this parameter
the fourth parameter of the line is selected - the script does something with this parameter
select the fifth parameter of the line - the script does something with this parameter
etc.
I tried using gsub but I don't know how I can select a certain line or parameter in it
You can use string.gmatch to match all parameters in the colon-delimited string. The pattern used to indicate the separator is [^:]+, which translates to "match everything but : (a colon)".
Here's an example script that loops over each line, then prints each parameter.
for line in io.lines("blocks.txt") do
for param in string.gmatch(line, "[^:]+") do
print(param)
end
end
I created a LSTM RNN model for text classification on tensorflow and exported the savedModel successfully. I tested the model using savedModel CLI and everything seems to be working fine. However I am trying to create a client that can make a request and get a result. I have been following this tensorflow serving inception example (more specifically inception_client.py) for reference. This works well with the inception model but I am not sure how to change the request for my own model. How exactly should I change the request?
My signature and saving the model:
# Build the signature_def_map.
classification_signature = signature_def_utils.build_signature_def(
inputs={signature_constants.CLASSIFY_INPUTS: classification_inputs},
outputs={
signature_constants.CLASSIFY_OUTPUT_CLASSES:
classification_outputs_classes,
},
method_name=signature_constants.CLASSIFY_METHOD_NAME)
legacy_init_op = tf.group(
tf.tables_initializer(), name='legacy_init_op')
#add the sigs to the servable
builder.add_meta_graph_and_variables(
sess, [tag_constants.SERVING],
signature_def_map={
signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY:
classification_signature
},
assets_collection=tf.get_collection(tf.GraphKeys.ASSET_FILEPATHS),
legacy_init_op=tf.group(assign_filename_op))
print ("added meta graph and variables")
builder.save()
print("model saved")
The model takes in inputs_ as the input which is a list of list of numbers ( [[1,3,4,5,2]] ).
inputs_ = tf.placeholder(tf.int32, [None, None], name="input_ints")
How I am using the savedModel CLI (returns right results):
$ saved_model_cli run --dir ./python2_SavedModelFinalInputInts --tag_set serve --signature_def 'serving_default' --input_exprs inputs='[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2634, 758, 938, 579, 1868, 1894, 24, 651, 572, 32, 1847, 232]]'
More information about the savedModel:
$ saved_model_cli show --dir ./python2_prediction_SavedModelFinalInputInts --all
MetaGraphDef with tag-set: 'serve' contains the following SignatureDefs:
signature_def['serving_default']:
The given SavedModel SignatureDef contains the following input(s):
inputs['inputs'] tensor_info:
dtype: DT_INT32
shape: (-1, -1)
name: inputs/input_ints:0
The given SavedModel SignatureDef contains the following output(s):
outputs['outputs'] tensor_info:
dtype: DT_FLOAT
shape: (1, 1)
name: predictions/fully_connected/Sigmoid:0
Method name is: tensorflow/serving/predict
How I am trying to create a request in the client code:
request1 = predict_pb2.PredictRequest()
request1.model_spec.name = 'mnist'
request1.model_spec.signature_name = signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY
request1.inputs[signature_constants.PREDICT_INPUTS].CopyFrom(tf.contrib.util.make_tensor_proto(input_nums, shape=[1,100],dtype=tf.int32))
response = stub.Predict(request1,1.0)
result_dict = { 'Analyst Rating': str(response.message) }
return jsonify(result_dict)
I am getting the following error:
[2017-11-29 19:03:29,318] ERROR in app: Exception on /analyst_rating [POST]
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1612, in full_dispatch_request
rv = self.dispatch_request()
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1598, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/usr/local/lib/python2.7/dist-packages/flask_restful/__init__.py", line 480, in wrapper
resp = resource(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/flask/views.py", line 84, in view
return self.dispatch_request(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/flask_restful/__init__.py", line 595, in dispatch_request
resp = meth(*args, **kwargs)
File "restApi.py", line 91, in post
response = stub.Predict(request,1)
File "/usr/local/lib/python2.7/dist-packages/grpc/beta/_client_adaptations.py", line 309, in __call__
self._request_serializer, self._response_deserializer)
File "/usr/local/lib/python2.7/dist-packages/grpc/beta/_client_adaptations.py", line 195, in _blocking_unary_unary
raise _abortion_error(rpc_error_call)
AbortionError: AbortionError(code=StatusCode.FAILED_PRECONDITION, details="Attempting to use uninitialized value fully_connected/biases
[[Node: fully_connected/biases/read = Identity[T=DT_FLOAT, _class=["loc:#fully_connected/biases"], _output_shapes=[[1]], _device="/job:localhost/replica:0/task:0/cpu:0"](fully_connected/biases)]]")
127.0.0.1 - - [29/Nov/2017 19:03:29] "POST /analyst_rating HTTP/1.1" 500 -
{"message": "Internal Server Error"}
Update:
Changing the signature of the model from a classification signature to a prediction signature seemed to work. I also changed the legacy_init_op to legacy_init_op as defined from assign_filename_op which I was using for Assets organization initially.
Changing the model signature from classification to a prediction signature seemed to return results.
prediction_signature = (tf.saved_model.signature_def_utils.build_signature_def(
inputs={signature_constants.PREDICT_INPUTS: prediction_inputs},
outputs={signature_constants.PREDICT_OUTPUTS: prediction_outputs},
method_name=tf.saved_model.signature_constants.PREDICT_METHOD_NAME))
legacy_init_op = tf.group(tf.tables_initializer(), name='legacy_init_op')
#add the sigs to the servable
builder.add_meta_graph_and_variables(
sess, [tag_constants.SERVING],
signature_def_map={
signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY:
prediction_signature
},
# assets_collection=tf.get_collection(tf.GraphKeys.ASSET_FILEPATHS),
legacy_init_op=legacy_init_op)
I am not entirely sure how the client request should be for a model with classification signature or why it was not working.
(If anyone has an explanation, I will select that as the correct answer.)
I have no prior experience of working with bluetooth sensors and parsing raw values. I am trying to parse the characteristic value but I am not really sure how to actually read and parse it. Data description of the characteristic I am trying to parse is here: https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.characteristic.csc_measurement.xml
Here is following code
func peripheral(peripheral: CBPeripheral, didUpdateNotificationStateForCharacteristic characteristic: CBCharacteristic, error: NSError?) {
parseData(characteristic.value)
}
private func parseData(data: NSData?) {
if let data = data {
var values = [UInt8](count:data.length, repeatedValue:0)
data.getBytes(&values, length:data.length)
print(values)
}
}
The output looks something like this
[2, 14, 0, 16, 56]
[2, 16, 0, 249, 62]
[2, 18, 0, 175, 191]
[2, 23, 0, 90, 195]
[1, 2, 0, 0, 0, 251, 206]
[1, 3, 0, 0, 0, 145, 208]
[1, 4, 0, 0, 0, 5, 212]
[1, 5, 0, 0, 0, 25, 217]
Now first, I am not really sure if I have to parse this into UInt8, that's the part which is not clear and I cannot understand what bluetooth website says coz there are UInt32 and UInt16 variables. How would I parse that from a single raw data. I think I am getting this whole thing wrong but thats what I am trying to understand. Thanks in advance.
I want to add a line break (\n) in front of the 5th element on every other line:
2, 0, 0, 0, 2
4, 0, 0, 0, 4
6, 0, 0, 0, 6
8, 0, 0, 0, 8
... in order to get:
2, 0, 0, 0, 2
4, 0, 0, 0, \n4
6, 0, 0, 0, 6
8, 0, 0, 0, \n8
What I have so far in gawk doesn't work:
gawk '{if (NR % 2) {$5=\n$5; print} else print}'
You could say:
awk '{NR%2 || $5="\\n"$5 }1' filename
Note that you'll need to escape the \ in order to get a literal \.
For your input, it'd produce:
2, 0, 0, 0, 2
4, 0, 0, 0, \n4
6, 0, 0, 0, 6
8, 0, 0, 0, \n8
Alternatively, (as pointed out by #WilliamPursell), you could say:
awk '!(NR%2) {$5="\\n"$5 }1' filename
OK this is the case, I have the following query
INSERT INTO 'FoodListTBL' ('AutoNo','CHOCals','PrtCals', 'FatCals','CHOgram','PrtGram','FatGram','CatId', 'TimeTypeId','TotalCals','Visibl', 'IsActive','NameAr','NameEn','CountryId', 'TotalPerUnit','UnitId','PreferedBread1', 'PreferedMilk1','PreferedVeg1','PreferedFat1', 'PreferedFruit1','CauseAllergy','AllergyCatId', 'TotalLikes','NameDescEn','NameDescAr','ChoPerUnit','PrtPerUnit','FatPerUnit','Quantity','PreferedBread2','PreferedMilk2', 'PreferedVeg2','PreferedFat2', 'PreferedFruit2','IV','UV','InsertDate','InsertUser') VALUES (818,0,0, 45, 0, 0, 5, 17, 1, 45,1, 1, 'زبدة قليلة الدسم', 'Butter reduced fat', 0, 45, 14, 0, 0, 0, 0, 0, 0, 0, 0, 'Butter reduced fat', 'زبدة قليلة الدسم', 0, 0, 45, 1, 0, 0, 0, 0, 0, 492, 0, '-', '-' ),(819,0,0, 45, 0, 0, 5, 17, 1, 45,1, 1, 'زبدة', 'Butter regular', 0, 45, 4, 0, 0, 0, 0, 0, 0, 0, 0, 'Butter regular', 'زبدة', 0, 0, 45, 1, 0, 0, 0, 0, 0, 493, 1475, '-', '-')
this query executed successfully on iOS 6.X and failed on any iOS less than 5.X taking into consideration that any other insert query on other tables finished successfully on any iOS
and I've tried two codes for insert this is one of them
if(sqlite3_prepare_v2(database, [query UTF8String], -1, &compiledStatement, NULL) == SQLITE_OK)
{
if(SQLITE_DONE != sqlite3_step(compiledStatement))
NSLog( #"Error while inserting data: '%s'", sqlite3_errmsg(database));
else NSLog(#"New data inserted");
sqlite3_reset(compiledStatement);
}else
{
NSLog( #"Error while inserting '%s'", sqlite3_errmsg(database));
}
sqlite3_finalize(compiledStatement)
and the result in the two cases is
Error while inserting 'near ",":syntax error'
aging this query is functional on every thing except iOS < 6.0
any clues are appreciated
SQLite before version 3.7.11 does not support the multi-record INSERT syntax.
Use multiple INSERT commands, or insert the records with INSERT ... SELECT ... UNION ALL ....