Consider the following program (http://play.golang.org/p/IbAstvudtE):
package main
import (
"fmt"
)
func changeStringValueNotOK(dest *string, src string) {
dest = &src
}
func changeStringValueOK(dest *string, src string) {
*dest = src
}
func main() {
a := "Hello"
b := "World"
changeStringValueNotOK(&a, b)
fmt.Println(a) // still "Hello"
changeStringValueOK(&a, b)
fmt.Println(a) // now "World"
}
My goal is to call a function and change the value of string. Works fine with the second function, but not with the first.
Question: what is the meaning of *dest = src compared to dest = &src? I guess the former is "the contents of dest is now src" and the latter is "change the dest variable so that it now points to the address of src" which discards the previous value, but not the contents of a. But even if I am right, I don't understand how the *dest = src works.
I hope my question isn't too fuzzy.
*dest = src
is: Set the value pointed at by dest to the value in src. So it's effective.
dest = &src
is: Set the value of dest to the address of src. As dest is a formal parameter of changeStringValueNotOK the change (to the pointer only, not to the pointee) is visible only locally. As the changed value is not really used, it's total effect is a no operation.
Just to help visualize it graphically, in your main function you have this:
Data Variables
| ... |
-------
| Hello |<----- <a string>
-------
| World |<----- <b string>
-------
| ... |
When you provide the parameters to either of these functions, it becomes:
Data Parameters
| ... |
-------
| Hello |<----- <a string> <----- <dest *string>
-------
| World |<----------------------- <src string>
-------
| ... |
With that scenario, when you do *dest = src, you get:
Data Parameters
| ... |
-------
| Hello | ,- <a string> <---- <dest *string>
------- |
| World |<--/
| |<---------------------- <src string>
-------
| ... |
Note that this effectively changes a itself, so when you return to the prior scope, you'll observe the change.
On the other hand, if you do dest = &src, you'd instead get:
Data Parameters
| ... |
-------
| Hello | <dest *string> ----,
------- |
| World |<---------------------- <src string> <---/
-------
| ... |
Which doesn't solve your problem, because both dest and src are local to the functions they're in.
As a side note, this kind of parameter passing is a common C idiom, but in Go you'd generally change such a string by returning the new value instead.
Related
I am trying to create a Stream using a camera with a blocking capture method. The blocking call is wrapped with blocking::unblock.
use futures::stream;
use rscam::{Camera, Config};
fn frame_stream() -> impl stream::Stream {
let mut camera = Camera::new("/dev/video0").unwrap();
camera.start(&Config {
interval: (1, 30),
resolution: (1280, 720),
format: b"H264",
..Default::default()
}).unwrap();
stream::unfold(camera, |c| async move {
let frame = blocking::unblock(|| c.capture().unwrap()).await;
Some((frame, c))
})
}
Compiling gives this error message:
error[E0373]: closure may outlive the current function, but it borrows `c`, which is owned by the current function
--> src/lib.rs:15:39
|
15 | let frame = blocking::unblock(|| c.capture().unwrap()).await;
| ^^ - `c` is borrowed here
| |
| may outlive borrowed value `c`
|
note: function requires argument type to outlive `'static`
--> src/lib.rs:15:21
|
15 | let frame = blocking::unblock(|| c.capture().unwrap()).await;
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
help: to force the closure to take ownership of `c` (and any other referenced variables), use the `move` keyword
|
15 | let frame = blocking::unblock(move || c.capture().unwrap()).await;
| ++++
error[E0505]: cannot move out of `c` because it is borrowed
--> src/lib.rs:17:22
|
15 | let frame = blocking::unblock(|| c.capture().unwrap()).await;
| ------------------------------------------
| | | |
| | | borrow occurs due to use in closure
| | borrow of `c` occurs here
| argument requires that `c` is borrowed for `'static`
16 |
17 | Some((frame, c))
| ^ move out of `c` occurs here
How can I guarantee to the compiler that the reference to c taken in the closure will still be valid? I assume it will be, since execution of the closure is awaited before c is returned.
Solution
stream::unfold(camera, |c| async move {
Some(
blocking::unblock(|| {
(c.capture().unwrap(), c)
}).await
)
})
You could move the camera into the inner closure, then return it once the frame capture is complete:
stream::unfold(camera, |c| async move {
Some(blocking::unblock(|| move {
let frame = c.capture().unwrap()).await;
(frame,c)
})
})
.await does not guarantee liveness. This is the general problem of scoped async tasks. Futures can be canceled at any time. Consider:
let future = async {
let local = 123;
blocking::unblock(|| local).await;
};
// Poll `future`, but only once.
futures::block_on(async move { futures::poll!(future) });
We started a task using local data, then dropped the future. The task continues executing but the local data is gone. For this reason, there is currently no sound way to expose an async API allowing using local data similar to scoped threads. You have to use 'static data, for example by wrapping in Arc.
See also blocking issue #4.
i' have created label schema using graph.OpenManagement() as described in https://docs.janusgraph.org/basics/schema/#schema-constraints
mgmt = graph.openManagement()
person = mgmt.makeVertexLabel('person').make()
name = mgmt.makePropertyKey('name').dataType(String.class).cardinality(Cardinality.SET).make()
birthDate = mgmt.makePropertyKey('birthDate').dataType(Long.class).cardinality(Cardinality.SINGLE).make()
mgmt.addProperties(person, name, birthDate)
mgmt.commit()
How can I get the person label schema. What is the gremlin query to get the properties list along with the datatype and cardinality info for a label.
Im using the following query to get the properties list with the data type, but there is no map for property to the label
gremlin> mgmt.printPropertyKeys()
==>------------------------------------------------------------------------------------------------
Property Key Name | Cardinality | Data Type |
---------------------------------------------------------------------------------------------------
name2 | SINGLE | class java.lang.String |
age2 | SINGLE | class java.lang.Integer |
name3 | SET | class java.lang.String |
birthDate3 | SINGLE | class java.lang.Long |
name4 | SET | class java.lang.String |
birthDate4 | SINGLE | class java.lang.Long |
name6 | SINGLE | class java.lang.String |
age6 | SINGLE | class java.lang.Integer |
name5 | SINGLE | class java.lang.String |
age5 | SINGLE | class java.lang.Integer |
mean_radius | SINGLE | class java.lang.Integer |
distance_in_kms | SINGLE | class java.lang.Integer |
new_field | SINGLE | class java.lang.String |
radius_in_kms | SINGLE | class java.lang.Integer |
name | SINGLE | class java.lang.String |
---------------------------------------------------------------------------------------------------
Getting vertex labels and their basic information:
mgmt.getVertexLabels().forEach(vertexLabel -> {
System.out.println("Vertex label: "+vertexLabel.name()+" isPartitioned: "+vertexLabel.isPartitioned()+" isStatic: "+vertexLabel.isStatic());
});
Getting edge labels and their basic information:
mgmt.getRelationTypes(EdgeLabel.class).forEach(edgeLabel ->{
System.out.println("Edge label: "+edgeLabel.name()+" Multiplicity: "+edgeLabel.multiplicity().name()+" isUnidirected:"+edgeLabel.isUnidirected());
});
Getting properties and their basic information:
mgmt.getRelationTypes(PropertyKey.class).forEach(propertyKey -> {
System.out.println("Property key: "+propertyKey.name()+" Cardinality: "+propertyKey.cardinality().name()+" Datatype: "+propertyKey.dataType().getName());
});
Now, when you got a specific Vertex label or a specific Edge label (as shown above), you can ask for the schema constraints information as shown below. Same methods are available for both VertexLabel and EdgeLabel.
Getting vertex label properties:
VertexLabel vertexLabel = mgmt.getVertexLabel("myVertexLabel");
vertexLabel.mappedProperties().forEach(propertyKey -> {
// get information about `propertyKey` as shown above in `Getting properties and their basic information` section
});
Getting vertex label connections:
VertexLabel vertexLabel = mgmt.getVertexLabel("myVertexLabel");
vertexLabel.mappedConnections().forEach(connection -> {
// connection.getEdgeLabel() - return the label of the edge. You can use it to access the edge itself if needed like:
EdgeLabel edgeLabel = mgmt.getEdgeLabel(connection.getEdgeLabel());
// You can access JanusGraphEdge via:
JanusGraphEdge janusGraphEdge = connection.getConnectionEdge();
// Having JanusGraphEdge you can access EdgeLabel directly via:
edgeLabel = janusGraphEdge.edgeLabel();
// You can also access incoming or outgoing vertices of this connection via: connection.getIncomingVertexLabel() or connection.getOutgoingVertexLabel()
});
Flow defines so called "Maybe types". I.e. ?string is similar to string | null | void (void is a type of value undefined).
Is there something like general type that can be of any value but null and undefined? Basically something like $Diff<$Diff<any, null>, void> if $Diff operator was able to operate on non-object types.
There is no some "magic" type for this, but something like this should work: string | number | boolean | {} | []
It is possible using the NonMaybeType Flow utility type: see $NonMaybeType
$NonMaybeType<T> converts a type T to a non-maybe type. In other words, the values of $NonMaybeType<T> are the values of T except for null and undefined.
// #flow
type MaybeName = ?string;
type Name = $NonMaybeType<MaybeName>;
('Gabriel': MaybeName); // Ok
(null: MaybeName); // Ok
('Gabriel': Name); // Ok
(null: Name); // Error! null can't be annotated as Name because Name is not a maybe type
If you need only a "shallow" type that does not allow null or undefined:
export type NotNullOrUndefined =
| string
| number
| bigint
| []
| {}
Now, in case you want to propagate the not null and not undefined requirement in values nested under objects and arrays you will need the following:
export type NotNullOrUndefined =
| string
| number
| bigint
| NotNullOrUndefined[]
| { [k: string]: NotNullOrUndefined }
I have a very simple LibreOffice Calc spreadsheet with column headers and columns (cell can be multiline), someting like:
| id | Prio | Domain | Comment | ... |
|----|------|--------|----------------|-----|
| 1 | A | Foo | Something | |
|----|------|--------|----------------|-----|
| 2 | A | Bar | Something else | |
| | | | Possibly on | |
| | | | multiple lines | |
|----|------|--------|----------------|-----|
| 1 | C | Baz | Something else | |
I would like to obtain, in a (semi) automated way a plain text file containing something like:
id: 1
Prio: A
Domain: Foo
Comment: Something
...
id: 2
Prio: A
Domain: Bar
Comment: Something else
Possibly on
multiple lines
...
id: 3
Prio: C
Domain: Baz
Comment: Something else
...
Is this possible somehow?
I am aware of LO macro capabilities (e.g.: this ), so the trivial answer is probably "yes", but I never used them so I would need some guidance (I don't even know how to use such a thing).
There are a lot of different ways this could be done. One idea is to go to File -> Save As and save as type CSV. In the filter settings, check Quote all text cells to make it easier to handle newlines.
Then write a script that uses the python csv module, for example:
import csv
with open('Untitled 1.csv') as csvfile:
spamreader = csv.reader(csvfile, dialect='excel',)
for row in spamreader:
print("row: ", end="")
print(', '.join(row))
To avoid the Save As step, you could write a macro instead. It might be easier to write it in python rather than Basic, because file handling and string manipulation can be difficult in Basic.
I have an Entity which in turn refers to same table which is its parent. Below is the table which describes it more better.
| ID | Source_ID |
+----+----------+
| 1 | null |
| 2 | 1 |
| 3 | 1 |
| 4 | 2 |
| 5 | 4 |
Now, when I am at ID = 5, I need to fetch its ultimate parent, which is ID = 1.
I tried writing a function which is as below:
<entity> ultimateparententity;
internal <entity> FetchParentComponentRecursive(<entity> entity)
{
if (component.ParentEntity!= null)
{
FetchParentComponentRecursive(entity.ParentEntity);
}
else
{
ultimateparententity = entity;
return component;
}
return entity;
}
I am using variable declared at class level to know the ultimate parent. I am returning variable "Entity" which is never used later, but ultimateparententity is what is used. This approach works, but I am not too happy with this. Any directions will be helpful.
I'm not too familiar with C#, but the general structure of your recursive function looks off.
Try something along the lines of:
internal <entity> FetchParentComponentRecursive(<entity> entity)
{
if (component.ParentEntity == null)
{
return component;
}
else
{
return FetchParentComponentRecursive(entity.ParentEntity);
}
}
By the way, this very much depends on there being no circular references in your data set.