Intro
I have an objective-C file (.m) in which I'm trying to query local users (through CSGetLocalIdentityAuthority and then print each user via printf (intentionally using C).
What do I expect?
get local users with objective c, print them with C pritnf.
Here's my attempt:
main.m
int main(){
// Query Local Identity Authority
CSIdentityAuthorityRef defaultAuthority = CSGetLocalIdentityAuthority();
CSIdentityClass identityClass = kCSIdentityClassUser;
CSIdentityQueryRef query = CSIdentityQueryCreate(NULL, identityClass, defaultAuthority);
CFErrorRef error = NULL;
CSIdentityQueryExecute(query, 0, &error);
// get query results
CFArrayRef users_queried = CSIdentityQueryCopyResults(query);
//iterate over users
// Create a users array
NSMutableArray * users_list = [NSMutableArray array];
// // number of users
int users_queried_count = CFArrayGetCount(users_queried);
// // iterate users and save to users array
for (int i = 0; i < users_queried_count; ++i) {
CSIdentityRef identity = (CSIdentityRef)CFArrayGetValueAtIndex(users_queried, i);
CBIdentity * identityObject = [CBIdentity identityWithCSIdentity:identity];
[users_list addObject:identityObject];
}
for (NSString *user in users_list) {
// NSLog(#"%#", user);
const char *c_user = [user UTF8String];
printf("%s", c_user);
}
// release
CFRelease(users_queried);
CFRelease(query);
return 0;
}
However, this yeilds the following error:
*** Terminating app due to uncaught exception
'NSInvalidArgumentException', reason: '-[CBUserIdentity UTF8String]:
unrecognized selector sent to instance 0x7fac024161f0'
You can see I'm trying to convert the NSString to a UTF8 String and print it, but it fails (however, NSLogging' it works).
CBIdentity is not a NSString - its a CBIdentity!
If you print it using NSLog it gets converted to a string (through description), but if you message it with UTF8String as you do it does not work.
You've commented out NSLog(#"%#", user);
If that actually gives you what you want then change the add part to
[users_list addObject:[identityObject description]];
Otherwise, note that you are looping CBIdentity and not NSString so change the loop e.g. like so or similar.
for ( CBIdentity * user in users_list ) {
const char *c_user = [[user posixName] UTF8String];
printf("%s", c_user);
}
There is a -fullName property for the class
Related
Json string : "{\n\t"tag": "Value",\n\t"attributes": {\n\t\t"rfid": "2"\n\t},\n\t"dat": "1"\n}
I am receiving the Json string from web server part by part i.e 8bytes at a time
When i am trying to collect the data in one buffer with the below logic in C
static char *jsonString ;
bool found_json = false;
jsonString = (char*)malloc (1024, sizeof(char));
while(data[i] != "}")
{
found_json = true;
for( i = 0; i< len; i++)
{
memcpy(jsonString, data, len);
}
}
can someday throw some light that how to detect end of the string of Json as there will be two closing Json object
I think you have two proper ways: either fully parse the JSON (you can use some libraries for that) or somehow receive the length of the string (if this is a HTTP request then there should be Content-Length header which indicates the length). Things like messing with curly braces is not reliable because even a simple number like 1233 or boolean values like true are valid JSON strings.
Here is some pseudo code for finding the end of your string:
open = 0;
close = 0;
while ( visit each character in your buffer )
{
if (new character == '{')
open++;
else if (new character == '}')
close++;
if (open == 0) // Did we even start the JSON string yet?
discard character
else if (open == close) // Matching number of { and } found. We are done.
{
process JSON string
open = close = 0; // Prepare for next incoming JSON string.
}
}
Here is my code:
var emoji = "⭐";
var query = myContext.Products.Where(x => x.Name.Contains(emoji));
var queryString = query.ToQueryString();
var list = query.ToList();
Query returns all table records. If I replace contains to equal works great, but I have to search something like this:
"this is my emoji ⭐"
This is the SQL query:
DECLARE #__emoji_0 nvarchar(4000) = N'⭐'
SELECT [p].[Id], [p].[Name], [p].[Quantity]
FROM [Products] AS [p]
WHERE (#__emoji_0 LIKE N'') OR (CHARINDEX(#__emoji_0, [p].[Name]) > 0)
Is any way to do this in EF Core or raw SQL?
Your main issue is the fact that emojis and strings are represented differently.
Before you can search the emojis you will need to decide how are you gonna unify them both in search query and db.
First of all emojis are a pair of chars.What does that mean? Here as a quote from the Microsoft docs:
"🐂".Length = 2
s[0] = '�' ('\ud83d')
s[1] = '�' ('\udc02')
These examples show that the value of string.Length, which indicates the number of char instances, doesn't necessarily indicate the number of displayed characters. A single char instance by itself doesn't necessarily represent a character.
The char pairs that map to a single character are called surrogate pairs. To understand how they work, you need to understand Unicode and UTF-16 encoding.
Having this in mind I would go as follows:
Define a method which will convert emojis to a UTF16 string[] which will keep the two surrogate chars representation.
internal static string[] EmojiToUtf16Pair(string emoji)
{
string[] arr = new string[2];
for (int i = 0; i < emoji.Length; i++)
{
arr[i] = emoji[i].ToString();
}
return arr;
}
This could be use when you persist emojis in DB. Depending on how you decide to persist the emojis in DB some modification could be done for that method e.g. to return concatenated string or something like that.
I am not sure when, but for some reason you could use another method to do the reverse operation -> UTF16 to Emoji
internal static string UTF16PairToEmoji(string[] codes)
{
var test = string.Empty;
foreach (var i in codes)
{
test += i;
}
var result = test.ToString();
return result;
}
Here is all the code example:
class Program
{
static void Main()
{
var str = "🚴";
var utf16 = string.Join("",EmojiToUtf16Pair(str));
Console.WriteLine(utf16);
var testEmpoji = UTF16PairToEmoji(EmojiToUtf16Pair(str));
Console.WriteLine(testEmpoji);
}
internal static string[] EmojiToUtf16Pair(string emoji)
{
string[] arr = new string[2];
for (int i = 0; i < emoji.Length; i++)
{
arr[i] = emoji[i].ToString();
}
return arr;
}
internal static string UTF16PairToEmoji(string[] codes)
{
var test = string.Empty;
foreach (var i in codes)
{
test += i;
}
var result = test.ToString();
return result;
}
}
emoji ef-core db-query
You have to use like command
SELECT * FROM emoticon where emoji_utf like '👨🏫';
with EF in .net core
Emoticon emoticon=db_context.Emoticons.Where(a=>EF.Functions.Like(a.EmojiUtf,"%"+item.emojiString+"%" ) ).FirstOrDefault();
I am attempting to use the cJSON library, written by Dave Gamble, to read in the following JSON request:
{"id":"8358441244995838759","jsonrpc":"2.0","method":"addext",
"params":["<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>
<trunks id=\"0\"><end_ch>3</end_ch>
<gateway>172.20.222.52</gateway>
<interface_type>E231</interface_type>
<name>Mumbai_Avaya</name>
<start_ch>12</start_ch>
<sub_type>E1PRI</sub_type></trunks>"]}
I am able to retrieve the "id" and "method" by using below code, but not able to retrieve or print the values inside "params" which is an XML string.
I want to print whatever inside the "params".
cJSON *cjson, *method_obj;
char *methodname;
char *params;
cjson = cJSON_Parse(buf);
method_obj = cJSON_GetObjectItem(cjson, "method");
methodname = method_obj->valuestring;
printf("method name %s\n", methodname);
method_obj = cJSON_GetObjectItem(cjson, "id");
id = method_obj->valueint;
char *str = method_obj->valuestring;
printf("id %s\n", str);
method_obj = cJSON_GetObjectItem(cjson, "params");
params=method_obj->valuestring;
printf("Params [ ] %s\n", params);
Please provide any suggestion.
Thanks in Advance.
Either change method_obj->valuestring to method_obj->child->valuestring (after checking that child != NULL), or have the service, that generates the JSON request, not use an array if none is needed.
params of field type is JSON Array.
use cJSON_GetArrayItem (and cJSON_GetArraySize) API like this:
method_obj = cJSON_GetObjectItem(cjson, "params");
int size = cJSON_GetArraySize(method_obj);
for(int i = 0; i < size; ++i){
params = cJSON_GetArrayItem(method_obj, i)->valuestring;
printf("Params [ ] %s\n", params);
}
So I have a program that sends emails. The user has a list of emails that cannot be sent to. These are in arrays and I need to use a if statement to determine if what the user entered in is in the array of emails. I tried the in function which didnt work but Im probably just using it wrong. I tried for loops and if statements inside. But that didnt work either. Here is a snapshot of the code Im using to help you get the idea of what im trying to do.
function test2(){
var safe = [1]
safe[1] = "lol"
safe[2] = "yay"
var entry = "lol"
Logger.log("entry: " + entry)
for(i = 0; i < safe.length; i++){
if(entry == safe[i]){
Logger.log("positive")
}else{
Logger.log("negative")
}
}
}
Here is what I tried with the in function to show you if I did it wrong
function test(){
var safe = [1]
safe[1] = "lol"
safe[2] = "yay"
var entry = "losl"
Logger.log("entry: " + entry)
if(entry in safe){
Logger.log("came positive")
}else{
Logger.log("came negative")
}
Logger.log(safe)
}
array.indexOf(element) > -1 usually does the trick for these situations!
To expand upon this:
if (array.indexOf(emailToSendTo) < 0) {
// send
}
Alternatively, check this cool thing out:
emailsToSend = emailsToSend.filter(function(x) {
// basically, this returns "yes" if it's not found in that other array.
return arrayOfBadEmails.indexOf(x) < 0;
})
What this does is it filters the list of emailsToSend, making sure that it's not a bad email. There's probably an even more elegant solution, but this is neat.
I am using the following code to check for values of 1 or 0 stored in a dictionary file called 'myDict'. At position 'block003stored' is the value 1 and at all the other positions it's 0. If I use the following code I always get 0 returned for all positions:
for (int i = 1 ; i < 100 ; i++) {
if(myDict)
{
UIImageView *imageV = (UIImageView *)[self.view viewWithTag:i];
int myInt = [[myDict objectForKey:#"block%.3istored"] intValue];
NSLog (#"value of i %d", i);
NSLog (#"myInt %d", myInt);
if (myInt == 1) imageV.hidden = FALSE;
}
}
}
However if I change the objectForKey to specifically #"block003stored":
int myInt = [[myDict objectForKey:#"block003stored"] intValue];
I get the correct value of 1 returned. I can't see why the code isn't working when I use the %.3i instead of 001, 002, 003 etc?
Try in a separate line:
NSString *indexStr = [NSString stringWithFormat:#"block%.3dstored", i]; Then use the objectForKey:indexStr];
You were asking the dictionary to get the object with the key of "block%.3istored", which didn't exist. You need to apply formatting to get i in there.
The code in the loop is using #"block%.3istored" as a literal string. There's nothing in what you've written to format the string with the i variable. Look at NSString's stringWithFormat: as a way of dynamically building the key.