I save data with CoreData. I have an Array and the last occurrence is 'nil' value. I do not want to save the 'nil' value in CoreData. I try to check the 'nil' value but I can not achieve. My code:
for (NSManagedObject *category in array)
{
//if (![category isEqual:nil]) { <- FAILED ATTEMPT
//if (![category isFault]) { <- FAILED ATTEMPT
//if (category != NULL) { <- FAILED ATTEMPT
[ more Objective-C code ...]
// Insert Objects in the Core Data
theLine = [NSEntityDescription insertNewObjectForEntityForName:entName
inManagedObjectContext:context];
//}
}
I can not understand why is so hard to check a NSManagedObject 'nil value'.
In my code, 'category' is a NSManagedObject. I want to know when it has 'nil' value:
(NSManagedObject) isEqual
(NSManagedObject) isFault
(NSManagedObject) = NULL
Any of these options does not run. Can anyone help me?
Thanks a lot in advance.
I think if you just use if(category) or if(category == nil) they should check if it is equal to nil.
Failing this you could do a for loop like:
for (int cycle =0 ; cycle < [array count]; cycle++){
if ([[array objectAtIndex:cycle]isKindOfClass[NSNull class]]){
////Do some code here
}
}
This will check is the value of the object is not Null because your loop will only look at NSManagedObjects
Related
I'm trying to have a variable-sized array based on a Module Paramete (example below). When the size PARAM is non-zero, the code works as intended.
class HWModule (PARAM : Int) extends Module{
val my_Vec = RegInit(Vec(Seq.fill(PARAM)(0.U(32.W))))
if (PARAM > 0){
for (i <- 0 until PARAM -1){
my_Vec(i) := i.U //Example Code
}
}
}
However, when I try to have PARAM = 0, it stops working. I've tried using Patter Matching (How do I write to a conditional output) to solve the problem, but I get the following error messages (and similar ones):
Equals does not take parameters
Expression does not convert to assignment because receiver is not assignable.
My goal is to be able to remove certain portions of code when PARAM = 0, while also allowing to variable-sized instantiation of Vecs, Regs, Wires, etc.
If anyone could point me to a good solution or information about it, I would appreciate it.
Thank you,
Miguel Silva
Maybe you can use Option like this :
val my_Vec_or_none = if(PARAM > 0) Some(RegInit(Vec(Seq.fill(PARAM))(0.U(32.W)))) else None
Then get register with get method :
if (PARAM > 0){
val my_Vec = my_Vec_or_none.get
for (i <- 0 until PARAM -1){
my_Vec(i) := i.U //Example Code
}
}
Also you can use indexed value directly (without intermediate val) :
val my_Vec = if(PARAM > 0) Some(RegInit(Vec(Seq.fill(PARAM))(0.U(32.W)))) else None
if (PARAM > 0){
for (i <- 0 until PARAM -1){
my_Vec.get(i) := i.U //Example Code
}
}
And use this variable in another part of the code.
I am parsing a heavily nested JSON in VBA, using scriptcontrol/jscript.
The resulting JSON object is super nested, and has recurring 'useless' levels / layers called 'buckets'.
Is there a way I can remove these collectively from either my json string or the parsed json object?
Imagine it something like this:
responses.0.buckets.0.aggregations.0.10.buckets.0.5.buckets.0.9.buckets.0.20.buckets.0.8.buckets.0.13.buckets.0.14.buckets.0.15.buckets.0.16.buckets.0.19.buckets.0.18.buckets.0.21.doc_count_error_upper_bound
I'd only need the 'doc_count_error_upper_bound' value, and could essentially do without all the 0s and without all the buckets, making it less nested into:
responses.aggregations.10.5.9.20.8.13.14.15.16.19.18.21.doc_count_error_upper_bound
This would still be pretty heavily nested, but saves me a lot of headaches already.
I just do not know how I could do this with jscript/scriptcontrol in VBA (es3).
The source data is coming from a Kibana dashboard (examples on http://demo.elastic.co/ )
Thanks for any help!
Jasper
UPDATE:
Question regarding VBA code - the VBA code I have is irrelevant, as it's the standard way of loading a json string into an object via scriptcontrol.
I do not use EVAL, but for example purposes, it would be something like the below:
Dim Scr as Object, Json as Object
Set Scr = CreateObject("Scriptcontrol")
Scr.Language = "Jscript"
Set Json = Scr.Eval("(" & WinHTTP.ResponseText & ")")
I cannot share an example of the JSON string, as it contains sensitive data.
But ultimately, that's beside the question.
Consider example https://adobe.github.io/Spry/data/json/donuts.js
On the top there, is "batter" as key in between "batters" and the different IDs. If I'd want to remove that key, but keep the underlying ID data - how would I do that, through a js scrip that works in scriptcontrol in VBA?
UPDATE:
omegastripes answer worked very well, however, I failed to realize that a number of the keys I wanted to remove (the 'buckets' and '0' etc) had keys and values under them.
Let's take the example of the donuts, just altered a bit - see here:
https://pastebin.com/WxYir7vK
now I would want to remove the '0', '1', '2' etc keys without losing the underlying sub-keys.
However, for omegastripes code to work, I'd have to delete keys 'sequence', 'variant', 'name', and 'ppu' from all layers / throughout the json.
I can do that for one of them, for one layer with the function below:
function unseat(obj, prop) { for(var k in obj[prop]) obj[k] = obj[prop][k]; delete obj[prop]; return obj; }
And then calling the functio 'unseat (JSONObj, "variant")' - this works, but only for one of the four variables at a time and only for one layer.
How can I alter this so that I can remove it throughout the object, for all four at once, so that afterwards I can use omegastripes code to unwrap.
Summary
1) I take this json string: https://pastebin.com/WxYir7vK
2) parse it into script control into VBA
3) loop through it and remove all 'sequence', 'variant', 'name' and 'ppu' key/value pairs
4) unwrap it via omegastripes code.
Step 1 / 2 and 4 are taken care of - but how to do 3?
Thanks!
Using ScriptControl for parsing JSON has the following shortcomings (check this answer for details):
System environment is exposed to malware code injections received within response.
ScriptControl is not available on 64-bit MS Office.
Anyway if you are confident that operating in JScript environment is the only way, you may unwrap excessive nesting of objects and arrays structure using the below functions:
function gParse(sample) {
return eval('(' + sample + ')');
};
function gUnwrap(sample) {
for (var key in sample) {
sample[key] = gUnwrap(sample[key]);
};
var count = 0;
for (var key in sample) {
count++;
if (count == 2) break;
};
if (count == 1) {
var type = gGetType(sample);
if (type == 'Array' || type == 'Object') {
var type = gGetType(sample[key]);
if (type == 'Array' || type == 'Object') {
return sample[key];
}
}
};
return sample;
};
function gGetType(sample) {
return {}.toString.call(sample).slice(8, -1);
};
That could be done in VBA as shown below:
Option Explicit
Sub Test()
Dim sJSON As String
Dim ParseJSON As Object
Dim UnwrapJSON As Object
Dim oJSON As Object
With CreateObject("MSXML2.XMLHTTP")
.Open "GET", "https://adobe.github.io/Spry/data/json/donuts.js", False
.send
sJSON = .responseText
End With
With CreateObject("htmlfile")
With .parentWindow
.execScript "function gParse(sample) {return eval('(' + sample + ')')};"
.execScript "function gUnwrap(sample) {for (var key in sample) {sample[key] = gUnwrap(sample[key]);}; var count = 0; for (var key in sample) {count++; if (count == 2) break;}; if (count == 1) {var type = gGetType(sample); if (type == 'Array' || type == 'Object') {var type = gGetType(sample[key]); if (type == 'Array' || type == 'Object') {return sample[key];}}}; return sample;};"
.execScript "function gGetType(sample) {return {}.toString.call(sample).slice(8, -1)};"
Set ParseJSON = .gParse
Set UnwrapJSON = .gUnwrap
End With
End With
Set oJSON = UnwrapJSON(ParseJSON(sJSON))
End Sub
The locals window shows JSON object for the sample you provided as follows:
And unwrapped JSON object:
I am using Connector C to connect to my MySQL database. A modification that I have made to the database recently now allows the data in my url field to be NULL. Connector C does not appear to have any problems reading the NULL value, but when I try and pass the value to my array structure using strcpy, the program crashes. Here is a simplified version of my code:
mysql_real_connect(conn, server,user,password,database, port, NULL, 0);
mysql_query(conn, "SELECT * FROM main WHERE propType IN ('Single Family', 'Condominium')");
res = mysql_use_result(conn);
while (((row = mysql_fetch_row(res)) != NULL) && (row[0] != NULL)) {
props[count].uniqueID = atol(row[0]);
strcpy(props[count].address, row[1]);
.
.
.
strcpy(props[count].url, row[55]);
count++;
}
By tracing out output of the rows, I have determined that it is this line of code that is failing, and it is ONLY failing when row[55] is (null):
strcpy(props[count].url, row[55]);
I am fairly new to C, and I assume that the problem lies in trying to use strcpy with a null string.
Any suggestions?
As is suggested above in the comment the problem is that row[55] has the value NULL and so strcpy() will crash. Maybe you want to try the following:
if (row[55] != NULL)
strcpy(props[count].url, row[55]);
else
props[count].url[0] = '\0';
Here is another example code which use a bit to store if the database contains NULL or a empty value:
if (row[55] != NULL)
{
strcpy(props[count].url, row[55]);
props[count].urlEmpty = false;
}
else
{
props[count].url = '\0'; // Maybe you can skip this
props[count].urlEmpty = true;
}
In this case you need to expand your structure.
I have an assignment:
Define the co-author graph G of the dblp-excerpt to be the undirected graph that has all authors as nodes, such that there is an edge between author a and author b in G if and only if a and b have written a publication together.
Define the distance between two authors a and b to be the length of the shortest path between a and b in G. Hence, authors that have published together have distance 1.
Moreover, if a and b have not published together but they have both published together with c, then the distance between a and b is two. Write an XQuery program that computes, for each pair of authors x and y 6= x the distance
between x and y using the following output format.
I wrote a code, but it doesn't work. I'm sure, it is very simple mistake, but I can't find it.
I have an error: Error:
Stopped at C:/Users/Zhanna/Desktop/Test/test_3.xq, 28/44: [XPST0017]
Unknown function 'local:getAvailablePathSizes'.
It underlines the beginning of the list of arguments in line 28, which is:
return
local:getAvailablePathSizes($graph,$current,$target,$visitedList,$count+1)
I validate the query with the Saxon as well and it also give a msg like this:
Error XPST0008: Unresolved reference to variable $count Static
error(s) in query
Help me, please, to fix it.
<ee>
let $graph:=(
<graph>{
for $a in distinct-values(//author)
let $publications:=/dblp/*[author=$a]
order by $a
return
<node name="{$a}">
{
let $co:=$publications/author[(.)!=$a] return
for $distinctCo in distinct-values($co) return
<edge from="{$a}" to="{$distinctCo}"/>
}
</node>
}</graph>
) return
declare function local:getAvailablePathSizes
($graph, $start, $target, $visitedList, $count)
{
let $cos:=$graph/node[#name=$start]/edge/#to return
let $listOfDistances:=(
for $current in $cos
return
if($current=$target) then $count+1 else
if (empty(visitedList[.=$current])) then(
let $visitedList:=insert-before(data($current), 0, $visitedList)
return local:getAvailablePathSizes($graph,$current,$target,$visitedList,$count+1)
) else()
)
return $listOfDistances
};
<distances>
{
for $node in $graph/node return
for $to in $graph/node[#name!=$node/#name]
let $dist:=min(local:getAvailablePathSizes($graph, $node/#name, $to/#name, null, 0))
return
if($dist>0) then(
<distance
author1="{$node/#name}"
author2="{$to/#name}"
distance="{$dist}"/>)
else()
}
</distances>
</ee>
This is the XML file
http://www.filedropper.com/dblp
The first problem is, that you did omit curly braces around the XQuery code inside the <ee> element, so large parts of your code haven't been evaluated (but interpreted as text instead). This resulted in a barely helpful error message indicating the second problem: you must define functions in the so-called prolog before the "normal" XQuery statements (in the query body).
declare function local:getAvailablePathSizes
($graph, $start, $target, $visitedList, $count)
{
let $cos:=$graph/node[#name=$start]/edge/#to return
let $listOfDistances:=(
for $current in $cos
return
if($current=$target) then $count+1 else
if (empty(visitedList[.=$current])) then(
let $visitedList:=insert-before(data($current), 0, $visitedList)
return local:getAvailablePathSizes($graph,$current,$target,$visitedList,$count+1)
) else()
)
return $listOfDistances
};
<ee>{
let $graph:=(
<graph>{
for $a in distinct-values(//author)
let $publications:=/dblp/*[author=$a]
order by $a
return
<node name="{$a}">
{
let $co:=$publications/author[(.)!=$a] return
for $distinctCo in distinct-values($co) return
<edge from="{$a}" to="{$distinctCo}"/>
}
</node>
}</graph>
) return
<distances>
{
for $node in $graph/node return
for $to in $graph/node[#name!=$node/#name]
let $dist:=min(local:getAvailablePathSizes($graph, $node/#name, $to/#name, null, 0))
return
if($dist>0) then(
<distance
author1="{$node/#name}"
author2="{$to/#name}"
distance="{$dist}"/>)
else()
}
</distances>
}
</ee>
In Linq to SQL asp.net, I want to fetch a specific image from database and display on an aspx page. I declared returned type as "var" on the code. So after fetching the image, it assigns image to var type.
Here is the code:
var db = from c in context.Images
where c.imageId == iID
select c.imageData;
return new MemoryStream((byte[])db); ---->> this line of code gives error
It gives this compile error: Cannot convert type 'system.linq.iqueryable' to 'byte[]'.
How can I convert 'system.linq.iqueryable type to byte[] ?
Your problem is that you're selecting a collection of byte[] rather than a single byte[].
Depending on the behavior you want for your application, you can use Single, SingleOrDefault, First, or FirstOrDeault:
var image = context.Images.FirstOrDefault(i => i.imageId == ID);
if(image == null)
{
// Handle the case where no image was found.
//
// First or Single would throw Exceptions in this case
// if that's what you want.
}
else
{
return new MemoryStream(image.imageData);
}
try below line this work for me
var db = (context.Images.FirstOrDefault(i => i.imageId == ID).ImageData