问:
cocos2d/box2d trouble
I have just started working with cocos2d and box2d for iOS SDK, and have a few problems. I got the templates working, and got the test app (the one where you click the screen and a box with a random letter appears) to compile.

My first problem is that I can't figure out how to get a blank template. Is there a quick way to do this when I begin a new app?

My second problem is that I can't figure out how to just simply change the color of an object. I can define something like this:

```<code>b2BodyDef bodyDef;
bodyDef.type = b2_dynamicBody;

bodyDef.position.Set(p.x/PTM_RATIO, p.y/PTM_RATIO);
b2Body *body = world->CreateBody(&bodyDef);

b2CircleShape circle;
circle.m_radius = .5f;//These are mid points for our 1m box

b2FixtureDef fixtureDef;
fixtureDef.shape = &circle;
fixtureDef.density = 1.0f;
fixtureDef.friction = 0.1f;
fixtureDef.restitution = 0.3f;
body->CreateFixture(&fixtureDef);
</code>```

But is there a simple way to make something a certain color?

Final question: does this sample app have the accelerometer-gravity enabled?

Thanks!

答:
For making blank template do the following

Remove these lines from -(id) init

```
CCSpriteBatchNode *batch = [CCSpriteBatchNode batchNodeWithFile:@"blocks.png" capacity:150];
[self addChild:batch z:0 tag:kTagBatchNode];
[self addNewSpriteWithCoords:ccp(screenSize.width/2, screenSize.height/2)];

CCLabelTTF *label = [CCLabelTTF labelWithString:@"Tap screen" fontName:@"Marker Felt" fontSize:32];
[self addChild:label z:0];
[label setColor:ccc3(0,0,255)];
label.position = ccp( screenSize.width/2, screenSize.height-50);
```

Remove the function

```-(void) addNewSpriteWithCoords:(CGPoint)p```

Remove the following line from - (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event

```[self addNewSpriteWithCoords: location];```

Try it out. :)

Title: cocos2d/box2d trouble

Body:
I have just started working with cocos2d and box2d for iOS SDK, and have a few problems. I got the templates working, and got the test app (the one where you click the screen and a box with a random letter appears) to compile.

My first problem is that I can't figure out how to get a blank template. Is there a quick way to do this when I begin a new app?

My second problem is that I can't figure out how to just simply change the color of an object. I can define something like this:

b2BodyDef bodyDef;
bodyDef.type = b2_dynamicBody;

bodyDef.position.Set(p.x/PTM_RATIO, p.y/PTM_RATIO);
b2Body *body = world->CreateBody(&bodyDef);

b2CircleShape circle;
circle.m_radius = .5f;//These are mid points for our 1m box

b2FixtureDef fixtureDef;
fixtureDef.shape = &circle;
fixtureDef.density = 1.0f;
fixtureDef.friction = 0.1f;
fixtureDef.restitution = 0.3f;
body->CreateFixture(&fixtureDef);

But is there a simple way to make something a certain color?

Final question: does this sample app have the accelerometer-gravity enabled?

Thanks!

Body:
For making blank template do the following

Remove these lines from -(id) init

CCSpriteBatchNode *batch = [CCSpriteBatchNode batchNodeWithFile:@"blocks.png" capacity:150];
[self addChild:batch z:0 tag:kTagBatchNode];
[self addNewSpriteWithCoords:ccp(screenSize.width/2, screenSize.height/2)];

CCLabelTTF *label = [CCLabelTTF labelWithString:@"Tap screen" fontName:@"Marker Felt" fontSize:32];
[self addChild:label z:0];
[label setColor:ccc3(0,0,255)];
label.position = ccp( screenSize.width/2, screenSize.height-50);

Remove the function

-(void) addNewSpriteWithCoords:(CGPoint)p

Remove the following line from - (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event

[self addNewSpriteWithCoords: location];

Try it out. :)


来源: stackexchange

问:
How to conditionally WHERE populated foreign keys with OneToMany Entity?
I am assuming a setup as described in: https://howtodoinjava.com/hibernate/hibernate-one-to-many-mapping-using-annotations/

Employee:

```<code>@JoinColumn(name="EMPLOYEE_ID")
private Set<AccountEntity> accounts;
</code>```

Account:

```<code>@ManyToOne
private EmployeeEntity employee;
</code>```

Using JPA/Hibernate, how can I fetch results using a WHERE condition that applies to Account. In other words, query something like Select all employees with accounts with sales > 0 or similar.

答:
I'm assuming sales column as INT in account table.

you can write a query like following:

```<code>TypedQuery<Employee> query = em.createQuery("SELECT e FROM Employee e JOIN Account a ON e.id = a.accounts.employee_id WHERE a.sales > :sales", Employee.class);
query.setParameter("sales", salesInput);
List<Employee> items = query.getResultList();
</code>```

I would recommend you to go through this tutorial to learn about CRUD operations in Hibernate Associations
https://www.dineshonjava.com/spring-crud-example-using-many-to-one/

ContentLicense: CC BY-SA 4.0

Body:
I am assuming a setup as described in: https://howtodoinjava.com/hibernate/hibernate-one-to-many-mapping-using-annotations/

Employee:

@JoinColumn(name="EMPLOYEE_ID")
private Set<AccountEntity> accounts;

Account:

@ManyToOne
private EmployeeEntity employee;

Using JPA/Hibernate, how can I fetch results using a WHERE condition that applies to Account. In other words, query something like Select all employees with accounts with sales > 0 or similar.

Body:
I'm assuming sales column as INT in account table.

you can write a query like following:

TypedQuery<Employee> query = em.createQuery("SELECT e FROM Employee e JOIN Account a ON e.id = a.accounts.employee_id WHERE a.sales > :sales", Employee.class);
query.setParameter("sales", salesInput);
List<Employee> items = query.getResultList();

I would recommend you to go through this tutorial to learn about CRUD operations in Hibernate Associations
https://www.dineshonjava.com/spring-crud-example-using-many-to-one/


问:
Error installing bcrypt with npm
I'm unable to install bcrypt using npm on my machine because I encounter the following errors. I have been troubleshooting the issue without much luck. Can you recommend any steps to diagnose or fix the problem so I can run npm install bcrypt successfully?

```<code>Someones-Macbook:node_modules Cody$ npm install bcrypt
npm WARN package.json grunt-contrib-htmlmin@0.1.3 No README data
|
> bcrypt@0.7.7 install /Applications/MAMP/htdocs/richintime/ultimate-seed/node_modules/bcrypt
> node-gyp rebuild

child_process: customFds option is deprecated, use stdio instead.
  CXX(target) Release/obj.target/bcrypt_lib/src/blowfish.o
  CXX(target) Release/obj.target/bcrypt_lib/src/bcrypt.o
  CXX(target) Release/obj.target/bcrypt_lib/src/bcrypt_node.o
../src/bcrypt_node.cc:118:18: error: no member named 'Dispose' in 'v8::Persistent<v8::Function, v8::NonCopyablePersistentTraits<v8::Function>
      >'
        callback.Dispose();
        ~~~~~~~~ ^
../src/bcrypt_node.cc:202:19: error: unknown type name 'uv_work_t'
void GenSaltAsync(uv_work_t* req) {
                  ^
../src/bcrypt_node.cc:219:24: error: unknown type name 'uv_work_t'
void GenSaltAsyncAfter(uv_work_t* req) {
                       ^
../src/bcrypt_node.cc:220:17: error: calling a protected constructor of class 'v8::HandleScope'
    HandleScope scope;
                ^
/Users/Cody/.node-gyp/0.12.0/deps/v8/include/v8.h:816:13: note: declared protected here
  V8_INLINE HandleScope() {}
            ^
../src/bcrypt_node.cc:228:44: error: no member named 'New' in 'v8::String'
        argv[0] = Exception::Error(String::New(baton->error.c_str()));
                                   ~~~~~~~~^
../src/bcrypt_node.cc:229:19: error: no matching function for call to 'Undefined'
        argv[1] = Undefined();
                  ^~~~~~~~~
/Users/Cody/.node-gyp/0.12.0/deps/v8/include/v8.h:305:28: note: candidate function not viable: requires single argument 'isolate', but no
      arguments were provided
  friend Handle<Primitive> Undefined(Isolate* isolate);
                           ^
../src/bcrypt_node.cc:232:19: error: no matching function for call to 'Undefined'
        argv[0] = Undefined();
                  ^~~~~~~~~
/Users/Cody/.node-gyp/0.12.0/deps/v8/include/v8.h:305:28: note: candidate function not viable: requires single argument 'isolate', but no
      arguments were provided
  friend Handle<Primitive> Undefined(Isolate* isolate);
                           ^
../src/bcrypt_node.cc:238:20: error: member reference type 'v8::Persistent<v8::Function>' is not a pointer; maybe you meant to use '.'?
    baton->callback->Call(Context::GetCurrent()->Global(), 2, argv);
    ~~~~~~~~~~~~~~~^~
                   .
../src/bcrypt_node.cc:238:22: error: no member named 'Call' in 'v8::Persistent<v8::Function, v8::NonCopyablePersistentTraits<v8::Function> >'
    baton->callback->Call(Context::GetCurrent()->Global(), 2, argv);
    ~~~~~~~~~~~~~~~  ^
../src/bcrypt_node.cc:238:36: error: no member named 'GetCurrent' in 'v8::Context'
    baton->callback->Call(Context::GetCurrent()->Global(), 2, argv);
                          ~~~~~~~~~^
../src/bcrypt_node.cc:246:34: error: unknown type name 'Arguments'; did you mean 'v8::internal::Arguments'?
Handle<Value> GenerateSalt(const Arguments &args) {
                                 ^~~~~~~~~
                                 v8::internal::Arguments
/Users/Cody/.node-gyp/0.12.0/deps/v8/include/v8.h:127:7: note: 'v8::internal::Arguments' declared here
class Arguments;
      ^
../src/bcrypt_node.cc:247:17: error: calling a protected constructor of class 'v8::HandleScope'
    HandleScope scope;
                ^
/Users/Cody/.node-gyp/0.12.0/deps/v8/include/v8.h:816:13: note: declared protected here
  V8_INLINE HandleScope() {}
            ^
../src/bcrypt_node.cc:249:32: error: type 'const v8::internal::Arguments' does not provide a subscript operator
    const ssize_t rounds = args[0]->Int32Value();
                           ~~~~^~
../src/bcrypt_node.cc:250:30: error: type 'const v8::internal::Arguments' does not provide a subscript operator
    const int rand_len = args[1]->Int32Value();
                         ~~~~^~
../src/bcrypt_node.cc:251:58: error: type 'const v8::internal::Arguments' does not provide a subscript operator
    Local<Function> callback = Local<Function>::Cast(args[2]);
                                                     ~~~~^~
../src/bcrypt_node.cc:255:45: error: 'New' is a private member of 'v8::PersistentBase<v8::Function>'
    baton->callback = Persistent<Function>::New(callback);
                                            ^
/Users/Cody/.node-gyp/0.12.0/deps/v8/include/v8.h:572:23: note: declared private here
  V8_INLINE static T* New(Isolate* isolate, T* that);
                      ^
../src/bcrypt_node.cc:255:57: error: too few arguments to function call, expected 2, have 1
    baton->callback = Persistent<Function>::New(callback);
                      ~~~~~~~~~~~~~~~~~~~~~~~~~         ^
/Users/Cody/.node-gyp/0.12.0/deps/v8/include/v8.h:572:3: note: 'New' declared here
  V8_INLINE static T* New(Isolate* isolate, T* that);
  ^
/Users/Cody/.node-gyp/0.12.0/deps/v8/include/v8config.h:289:20: note: expanded from macro 'V8_INLINE'
# define V8_INLINE inline __attribute__((always_inline))
                   ^
../src/bcrypt_node.cc:259:5: error: unknown type name 'uv_work_t'
    uv_work_t* req = new uv_work_t;
    ^
../src/bcrypt_node.cc:259:26: error: unknown type name 'uv_work_t'
    uv_work_t* req = new uv_work_t;
                         ^
fatal error: too many errors emitted, stopping now [-ferror-limit=]
20 errors generated.
make: *** [Release/obj.target/bcrypt_lib/src/bcrypt_node.o] Error 1
gyp ERR! build error
gyp ERR! stack Error: `make` failed with exit code: 2
gyp ERR! stack     at ChildProcess.onExit (/usr/local/lib/node_modules/npm/node_modules/node-gyp/lib/build.js:267:23)
gyp ERR! stack     at ChildProcess.emit (events.js:110:17)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (child_process.js:1067:12)
gyp ERR! System Darwin 13.4.0
gyp ERR! command "node" "/usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"
gyp ERR! cwd /Applications/MAMP/htdocs/richintime/ultimate-seed/node_modules/bcrypt
gyp ERR! node -v v0.12.0
gyp ERR! node-gyp -v v1.0.2
gyp ERR! not ok
npm ERR! Darwin 13.4.0
npm ERR! argv "node" "/usr/local/bin/npm" "install" "bcrypt"
npm ERR! node v0.12.0
npm ERR! npm  v2.7.1
npm ERR! code ELIFECYCLE

npm ERR! bcrypt@0.7.7 install: `node-gyp rebuild`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the bcrypt@0.7.7 install script 'node-gyp rebuild'.
npm ERR! This is most likely a problem with the bcrypt package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     node-gyp rebuild
</code>```

答:
If you are on windows run powershell as administrator and use these commands.

```<code>npm install --g --production windows-build-tools
</code>```

and then install bcrypt using

```<code>npm install --save bcrypt
</code>```

ContentLicense: CC BY-SA 3.0

Title: Error installing bcrypt with npm

Body:
I'm unable to install bcrypt using npm on my machine because I encounter the following errors. I have been troubleshooting the issue without much luck. Can you recommend any steps to diagnose or fix the problem so I can run npm install bcrypt successfully?

Someones-Macbook:node_modules Cody$ npm install bcrypt
npm WARN package.json grunt-contrib-htmlmin@0.1.3 No README data
|
> bcrypt@0.7.7 install /Applications/MAMP/htdocs/richintime/ultimate-seed/node_modules/bcrypt
> node-gyp rebuild

child_process: customFds option is deprecated, use stdio instead.
  CXX(target) Release/obj.target/bcrypt_lib/src/blowfish.o
  CXX(target) Release/obj.target/bcrypt_lib/src/bcrypt.o
  CXX(target) Release/obj.target/bcrypt_lib/src/bcrypt_node.o
../src/bcrypt_node.cc:118:18: error: no member named 'Dispose' in 'v8::Persistent<v8::Function, v8::NonCopyablePersistentTraits<v8::Function>
      >'
        callback.Dispose();
        ~~~~~~~~ ^
../src/bcrypt_node.cc:202:19: error: unknown type name 'uv_work_t'
void GenSaltAsync(uv_work_t* req) {
                  ^
../src/bcrypt_node.cc:219:24: error: unknown type name 'uv_work_t'
void GenSaltAsyncAfter(uv_work_t* req) {
                       ^
../src/bcrypt_node.cc:220:17: error: calling a protected constructor of class 'v8::HandleScope'
    HandleScope scope;
                ^
/Users/Cody/.node-gyp/0.12.0/deps/v8/include/v8.h:816:13: note: declared protected here
  V8_INLINE HandleScope() {}
            ^
../src/bcrypt_node.cc:228:44: error: no member named 'New' in 'v8::String'
        argv[0] = Exception::Error(String::New(baton->error.c_str()));
                                   ~~~~~~~~^
../src/bcrypt_node.cc:229:19: error: no matching function for call to 'Undefined'
        argv[1] = Undefined();
                  ^~~~~~~~~
/Users/Cody/.node-gyp/0.12.0/deps/v8/include/v8.h:305:28: note: candidate function not viable: requires single argument 'isolate', but no
      arguments were provided
  friend Handle<Primitive> Undefined(Isolate* isolate);
                           ^
../src/bcrypt_node.cc:232:19: error: no matching function for call to 'Undefined'
        argv[0] = Undefined();
                  ^~~~~~~~~
/Users/Cody/.node-gyp/0.12.0/deps/v8/include/v8.h:305:28: note: candidate function not viable: requires single argument 'isolate', but no
      arguments were provided
  friend Handle<Primitive> Undefined(Isolate* isolate);
                           ^
../src/bcrypt_node.cc:238:20: error: member reference type 'v8::Persistent<v8::Function>' is not a pointer; maybe you meant to use '.'?
    baton->callback->Call(Context::GetCurrent()->Global(), 2, argv);
    ~~~~~~~~~~~~~~~^~
                   .
../src/bcrypt_node.cc:238:22: error: no member named 'Call' in 'v8::Persistent<v8::Function, v8::NonCopyablePersistentTraits<v8::Function> >'
    baton->callback->Call(Context::GetCurrent()->Global(), 2, argv);
    ~~~~~~~~~~~~~~~  ^
../src/bcrypt_node.cc:238:36: error: no member named 'GetCurrent' in 'v8::Context'
    baton->callback->Call(Context::GetCurrent()->Global(), 2, argv);
                          ~~~~~~~~~^
../src/bcrypt_node.cc:246:34: error: unknown type name 'Arguments'; did you mean 'v8::internal::Arguments'?
Handle<Value> GenerateSalt(const Arguments &args) {
                                 ^~~~~~~~~
                                 v8::internal::Arguments
/Users/Cody/.node-gyp/0.12.0/deps/v8/include/v8.h:127:7: note: 'v8::internal::Arguments' declared here
class Arguments;
      ^
../src/bcrypt_node.cc:247:17: error: calling a protected constructor of class 'v8::HandleScope'
    HandleScope scope;
                ^
/Users/Cody/.node-gyp/0.12.0/deps/v8/include/v8.h:816:13: note: declared protected here
  V8_INLINE HandleScope() {}
            ^
../src/bcrypt_node.cc:249:32: error: type 'const v8::internal::Arguments' does not provide a subscript operator
    const ssize_t rounds = args[0]->Int32Value();
                           ~~~~^~
../src/bcrypt_node.cc:250:30: error: type 'const v8::internal::Arguments' does not provide a subscript operator
    const int rand_len = args[1]->Int32Value();
                         ~~~~^~
../src/bcrypt_node.cc:251:58: error: type 'const v8::internal::Arguments' does not provide a subscript operator
    Local<Function> callback = Local<Function>::Cast(args[2]);
                                                     ~~~~^~
../src/bcrypt_node.cc:255:45: error: 'New' is a private member of 'v8::PersistentBase<v8::Function>'
    baton->callback = Persistent<Function>::New(callback);
                                            ^
/Users/Cody/.node-gyp/0.12.0/deps/v8/include/v8.h:572:23: note: declared private here
  V8_INLINE static T* New(Isolate* isolate, T* that);
                      ^
../src/bcrypt_node.cc:255:57: error: too few arguments to function call, expected 2, have 1
    baton->callback = Persistent<Function>::New(callback);
                      ~~~~~~~~~~~~~~~~~~~~~~~~~         ^
/Users/Cody/.node-gyp/0.12.0/deps/v8/include/v8.h:572:3: note: 'New' declared here
  V8_INLINE static T* New(Isolate* isolate, T* that);
  ^
/Users/Cody/.node-gyp/0.12.0/deps/v8/include/v8config.h:289:20: note: expanded from macro 'V8_INLINE'
# define V8_INLINE inline __attribute__((always_inline))
                   ^
../src/bcrypt_node.cc:259:5: error: unknown type name 'uv_work_t'
    uv_work_t* req = new uv_work_t;
    ^
../src/bcrypt_node.cc:259:26: error: unknown type name 'uv_work_t'
    uv_work_t* req = new uv_work_t;
                         ^
fatal error: too many errors emitted, stopping now [-ferror-limit=]
20 errors generated.
make: *** [Release/obj.target/bcrypt_lib/src/bcrypt_node.o] Error 1
gyp ERR! build error
gyp ERR! stack Error: `make` failed with exit code: 2
gyp ERR! stack     at ChildProcess.onExit (/usr/local/lib/node_modules/npm/node_modules/node-gyp/lib/build.js:267:23)
gyp ERR! stack     at ChildProcess.emit (events.js:110:17)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (child_process.js:1067:12)
gyp ERR! System Darwin 13.4.0
gyp ERR! command "node" "/usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"
gyp ERR! cwd /Applications/MAMP/htdocs/richintime/ultimate-seed/node_modules/bcrypt
gyp ERR! node -v v0.12.0
gyp ERR! node-gyp -v v1.0.2
gyp ERR! not ok
npm ERR! Darwin 13.4.0
npm ERR! argv "node" "/usr/local/bin/npm" "install" "bcrypt"
npm ERR! node v0.12.0
npm ERR! npm  v2.7.1
npm ERR! code ELIFECYCLE

npm ERR! bcrypt@0.7.7 install: `node-gyp rebuild`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the bcrypt@0.7.7 install script 'node-gyp rebuild'.
npm ERR! This is most likely a problem with the bcrypt package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     node-gyp rebuild

Body:
If you are on windows run powershell as administrator and use these commands.

npm install --g --production windows-build-tools

and then install bcrypt using

npm install --save bcrypt


问:
Java 8 predicates using methods bodies are called only once?
I have examined the following snippet:

```<code>public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
    Map<Object, Boolean> computed = new ConcurrentHashMap<>();/*IS THIS LINE CALLED ONCE ON STREAM->FILTER NOT MATTER HOW LONG THE STREAM IS*/
    return t -> {return computed.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;};
}

private void test(){
    final long d = Stream.of("JOHN","STEPHEN","ORTIZ","RONDON")
            .filter(distinctByKey(Function.identity()))
            .count();
    System.out.println("d = " + d);
}
</code>```

This code is not mine. I know that using a ConcurrentMap is not the right choice in this example and I should use ConcurrentMap instead of Map in this case, but this is not my concern now.

I thought that the distinctByKey method is called or interpreted in each iteration of the Stream. I mean the Map being instantiated in each turn, but it's not!

Is the body of the Predicate method called only once?

In the Stream iteration, is this an assertion?

Because when I try the following code:

```<code>final Function<String,Integer>a = (name)->name.length();
System.out.println(distinctByKey(a).test("JOHN"));
System.out.println(distinctByKey(a).test("STEPHEN"));
System.out.println(distinctByKey(a).test("ORTIZ"));
System.out.println(distinctByKey(a).test("RONDON"));
</code>```

I can see that the body of the method is indeed called in each line. What makes the body of the filter to only be called once?

答:
When you call .filter(distinctByKey(Function.identity())), the argument passed to filter() is evaluated. That's the only time distinctByKey(Function.identity()) is executed and returns an instance of Predicate<String>.

That Predicate is then evaluated (i.e. it's test() method is executed) multiple times, each time for a different element of the Stream.

To make your last snippet behave similar to the Stream pipeline, it should look like this:

```<code>final Function<String,Integer> a = (name)->name.length();
Predicate<String> pred = distinctByKey(a);
System.out.println(pred.test("JOHN"));
System.out.println(pred.test("STEPHEN"));
System.out.println(pred.test("ORTIZ"));
System.out.println(pred.test("RONDON"));
</code>```

Body:
I have examined the following snippet:

public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
    Map<Object, Boolean> computed = new ConcurrentHashMap<>();/*IS THIS LINE CALLED ONCE ON STREAM->FILTER NOT MATTER HOW LONG THE STREAM IS*/
    return t -> {return computed.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;};
}

private void test(){
    final long d = Stream.of("JOHN","STEPHEN","ORTIZ","RONDON")
            .filter(distinctByKey(Function.identity()))
            .count();
    System.out.println("d = " + d);
}

This code is not mine. I know that using a ConcurrentMap is not the right choice in this example and I should use ConcurrentMap instead of Map in this case, but this is not my concern now.

I thought that the distinctByKey method is called or interpreted in each iteration of the Stream. I mean the Map being instantiated in each turn, but it's not!

Is the body of the Predicate method called only once?

In the Stream iteration, is this an assertion?

Because when I try the following code:

final Function<String,Integer>a = (name)->name.length();
System.out.println(distinctByKey(a).test("JOHN"));
System.out.println(distinctByKey(a).test("STEPHEN"));
System.out.println(distinctByKey(a).test("ORTIZ"));
System.out.println(distinctByKey(a).test("RONDON"));

I can see that the body of the method is indeed called in each line. What makes the body of the filter to only be called once?

Body:
When you call .filter(distinctByKey(Function.identity())), the argument passed to filter() is evaluated. That's the only time distinctByKey(Function.identity()) is executed and returns an instance of Predicate<String>.

That Predicate is then evaluated (i.e. it's test() method is executed) multiple times, each time for a different element of the Stream.

To make your last snippet behave similar to the Stream pipeline, it should look like this:

final Function<String,Integer> a = (name)->name.length();
Predicate<String> pred = distinctByKey(a);
System.out.println(pred.test("JOHN"));
System.out.println(pred.test("STEPHEN"));
System.out.println(pred.test("ORTIZ"));
System.out.println(pred.test("RONDON"));


问:
How do i find out the Structure of a Java Object?
I am working with the HttpExchange class, and want to use the getAttribute function to get the POST parameters. If i just call the function and print the results it works. But there has to be some better way to access the returned object and get the contained data.

The Manual is here: http://download.oracle.com/javase/6/docs/jre/api/net/httpserver/spec/com/sun/net/httpserver/HttpExchange.html#getAttribute%28java.lang.String%29

How can i access the Object? Which methods does it have?

答:
I am not familiar with this API, but it appears that HttpExchange.getAttribute is not the method you would use to get POST parameters. Rather it is a mechanism for sharing information within a chain of Filters. Since you would implement the Filters, you would document and understand the attributes that can be stored.

To read the POST details, wouldn't you do HttpExchange.getRequestBody?


问:
Get routes that use certain middleware or are in certain group?
Is it possible in Laravel in Controller, to get all routes that are in one group, or routes that use certain middleware or something else?
Here is an example of what I mean:

```<code>Route::middleware(['auth', 'admin])->group(function () {
    Route::patch('/updateClient', 'ClientController@update');
    Route::resource('server-groups','ServerGroupsController');
});
</code>```

And in my controller to have something like this, that will get me all routes where middleware is admin:

```<code>$routes = Route::where('middleware', 'admin');
</code>```

Currently I can only get all routes with this code:

```<code>$routes = Route::getRoutes();
</code>```

答:
I found built-in method middleware() that I can use on route and it will give me an array of middlewares, same as @tcj mentioned in his answer. So I took all routes and through loop I added all routes that have desired middleware to a new collection.

```<code> $routes = Route::getRoutes();
 $new_routes = new Collection;
 foreach ($routes as $route) {
     $middleware = $route->middleware();
     for ($i = 0; $i < count($middleware); $i++) {
         if ($middleware[$i] == 'admin') {
             $new_routes ->push($route);
         }
     }
 }
</code>```

Body:
Is it possible in Laravel in Controller, to get all routes that are in one group, or routes that use certain middleware or something else?
Here is an example of what I mean:

Route::middleware(['auth', 'admin])->group(function () {
    Route::patch('/updateClient', 'ClientController@update');
    Route::resource('server-groups','ServerGroupsController');
});

And in my controller to have something like this, that will get me all routes where middleware is admin:

$routes = Route::where('middleware', 'admin');

Currently I can only get all routes with this code:

$routes = Route::getRoutes();

Body:
I found built-in method middleware() that I can use on route and it will give me an array of middlewares, same as @tcj mentioned in his answer. So I took all routes and through loop I added all routes that have desired middleware to a new collection.

 $routes = Route::getRoutes();
 $new_routes = new Collection;
 foreach ($routes as $route) {
     $middleware = $route->middleware();
     for ($i = 0; $i < count($middleware); $i++) {
         if ($middleware[$i] == 'admin') {
             $new_routes ->push($route);
         }
     }
 }


问:
Create a template that shuffles a dynamic array of objects
So I need to create a template function that shuffles a dynamic array of dynamic objects. The exercise is guiding me a bit by giving me a starting point.

```<code>#include<iostream>

using namespace std;

template < class X > void shuffle(X ** myArray, int myArraySize) {
  // TODO: Implement here the shuffle algorithm
}
</code>```

I'm kinda lost on how I should use the pointer inside the function but have a general idea on how the code should be. I know it has a lot of mistakes but it's just an idea.

```<code>for (int i = myArraySize - 1; i > 0; i--) {
  int index = //a random index in the span [0,i]
  int a = myArray[index];

  myArray[index] = myArray[i];
  myArray[i] = a;
}
</code>```

答:
Actually there is already a example on how to shuffle a array in the c++ reference at
http://www.cplusplus.com/reference/algorithm/random_shuffle/ and http://www.cplusplus.com/reference/algorithm/shuffle/
which describe how std::random_shuffle and std::shuffle are implemented</p>

Body:
So I need to create a template function that shuffles a dynamic array of dynamic objects. The exercise is guiding me a bit by giving me a starting point.

#include<iostream>

using namespace std;

template < class X > void shuffle(X ** myArray, int myArraySize) {
  // TODO: Implement here the shuffle algorithm
}

I'm kinda lost on how I should use the pointer inside the function but have a general idea on how the code should be. I know it has a lot of mistakes but it's just an idea.

for (int i = myArraySize - 1; i > 0; i--) {
  int index = //a random index in the span [0,i]
  int a = myArray[index];

  myArray[index] = myArray[i];
  myArray[i] = a;
}


问:
What is meaning of calling superview's viewwillappear?
```<code>-(void)viewwillAppear
{
[super viewwillAppear:animated];
}
</code>```

What does mean of calling [super viewwillAppear:animated] and what happen if we not call it?

答:
By using super you are calling the base class version of the method. You will see similar call  in init, dealloc, viewDidLoad etc. methods. The reason is in base class's implementation something important may be carried out without which the derived class will not work properly. When you have overridden the method in derived class, you will need to make a call to the base version by using super.

The only situation you will not call base class's method by using super is when you know that you don't need the tasks carried out by base class, in other words you are overriding completely. This is not the situation with viewWillAppear:animated or viewDidLoad etc. So we always call super in these cases.

Body:
-(void)viewwillAppear
{
[super viewwillAppear:animated];
}

What does mean of calling [super viewwillAppear:animated] and what happen if we not call it?


问:
Substitute value in a formula using trigger
I am working on a project which has a couple of math calculations which has to be done based on the data fed

I have written a trigger in SQL SERVER to compute this value. I used REPLACE() to replace the variables with values and got the below

For example :

```<code>Value = 100 +a - (b*10)

a=1
b=2
</code>```

I get Value = 100 + 1 -(2*10)

Expected output is  Value = 81

I use the below query :

```<code>SELECT REPLACE(REPLACE(Value,'a',1),'b',2) FROM Formula
</code>```

Is there any better way to get this done ?

答:
Rather than REPLACE, you could store the formula as a parameterized query expression and pass the values as parameters:

```<code>DECLARE @value int;
DECLARE @formula nvarchar(MAX) = N'SET @Value = 100 + @a - (@b * 10);';
EXEC sp_executesql @formula, N'@value int OUTPUT, @a int, @b int', @a = 1, @b = 2, @value = @value OUTPUT;
PRINT @value;
</code>```

Body:
I am working on a project which has a couple of math calculations which has to be done based on the data fed

I have written a trigger in SQL SERVER to compute this value. I used REPLACE() to replace the variables with values and got the below

For example :

Value = 100 +a - (b*10)

a=1
b=2

I get Value = 100 + 1 -(2*10)

Expected output is  Value = 81

I use the below query :

SELECT REPLACE(REPLACE(Value,'a',1),'b',2) FROM Formula

Is there any better way to get this done ?

Body:
Rather than REPLACE, you could store the formula as a parameterized query expression and pass the values as parameters:

DECLARE @value int;
DECLARE @formula nvarchar(MAX) = N'SET @Value = 100 + @a - (@b * 10);';
EXEC sp_executesql @formula, N'@value int OUTPUT, @a int, @b int', @a = 1, @b = 2, @value = @value OUTPUT;
PRINT @value;


问:
sed: How to join the lines of a record with an empty line delimiting records
I would like to use 'sed' to joins three lines that make up a record, with records separated by empty lines, and record fields separated by a space.

Here's a snip of data from the file:

```<code>KDFW
N 32°53.83'
W 097°02.26'

TOC
N 32°48.49'
W 097°01.39'

DART
N 32°17.15'
W 096°48.66'
</code>```

I need to combine the lines like this:

```<code>KDFW N 32°53.83' W 097°02.26'
TOC N 32°48.49' W 097°01.39'
DART N 32°17.15' W 096°48.66'
</code>```

I'm a novice with sed but pieced together this ugly line.

```<code>sed 'N;s/\n/ /' navlog.txt | sed 'N;s/\n/ /'
</code>```

yea - there is a better way...

答:
A bit shorter than the version of Kent,

```<code>awk -v RS= '{$1=$1}1'
</code>```

If RS is null, then records are separated by sequences consisting of a <newline> plus one or more blank lines, leading or trailing blank lines shall not result in empty records at the beginning or end of the input, and a <newline> shall always be a field separator, no matter what the value of FS is.

So the trick here is to redefine the first field $1 by itself, this will rebuild the full record $0 using OFS (default a space) as a field separator, hence merging the lines.

Remark: If multiple consecutive spaces or tabs are placed in the original input, they will be replaced with a single space. This can be resolved by defining FS:

```<code>awk -F\n -v RS= '{$1=$1}1'
</code>```

Body:
I would like to use 'sed' to joins three lines that make up a record, with records separated by empty lines, and record fields separated by a space.

Here's a snip of data from the file:

KDFW
N 32°53.83'
W 097°02.26'

TOC
N 32°48.49'
W 097°01.39'

DART
N 32°17.15'
W 096°48.66'

I need to combine the lines like this:

KDFW N 32°53.83' W 097°02.26'
TOC N 32°48.49' W 097°01.39'
DART N 32°17.15' W 096°48.66'

I'm a novice with sed but pieced together this ugly line.

sed 'N;s/\n/ /' navlog.txt | sed 'N;s/\n/ /'

yea - there is a better way...

Body:
A bit shorter than the version of Kent,

awk -v RS= '{$1=$1}1'

If RS is null, then records are separated by sequences consisting of a <newline> plus one or more blank lines, leading or trailing blank lines shall not result in empty records at the beginning or end of the input, and a <newline> shall always be a field separator, no matter what the value of FS is.

So the trick here is to redefine the first field $1 by itself, this will rebuild the full record $0 using OFS (default a space) as a field separator, hence merging the lines.

Remark: If multiple consecutive spaces or tabs are placed in the original input, they will be replaced with a single space. This can be resolved by defining FS:

awk -F\n -v RS= '{$1=$1}1'


问:
Change rectangle color in Rave runtime Delphi
We print database records in rave using rvproject1 and rvdatasetconnection1 and that works.
How to acomplish this in rave:
If Adotabel1.fieldbyname('something').asstring = 'something' then
 Rectangle1 on a data band.color=black
else
Rectangle1 on a data band.color=green</p>

答:
Rawn,

I believe you must download the Visual Designer Guide.pdf located here

http://www.nevrona.com/Rave/downloadbe.html. What you want to accomplish can be done in several ways(with editor events, from Delphi code, etc). In the manual you will find exactly how to code the band or datatext onbeforeprint event(Rave Report 'language' is very similar to Delphi). At this moment I don't have the time for making you an example.

best regards,

Radu


问:
What can I use besides Sessions in order to use the following method as an API method?
I have a quiz app with a laravel back-end and Vue front-end. I am working on developing an API for this app. However, the problem I have encountered is that I need an API endpoint that: returns a question from Questions table - but it needs to:

Return a question at random every time the method is called

Not be a question that user has already seen (unless all questions have been seen)

Up until now, I have been randomising the questions collection using the shuffle method, and relying on Sessions to store the ids of the unseenQuestions.

However, as API calls are stateless, sessions will not work. I was wonder what ways I could get around this?

```<code>public function random(Module $module, $category){
    // Get question ids in randomised order (for a given module + category)
    $questions =  Question::CategoryForModule(1, $module->id)->shuffle()->pluck('id');

    // Name and Get unseenQuestions
    $sessionName = 'unseenQuestions_' . $category .  strval($module->id); //unseenQuestions_anatomy_2

    if (session()->has($sessionName)) {
        $unseenQuestions = session()->get($sessionName);

    } else {
        $unseenQuestions = collect($questions);

    }
    // Pop new Question
    $newQuestionID = $unseenQuestions->shift();;

    // Store unseenQuestions OR remove unseenQuestions (if it has no items);
    if ($unseenQuestions->count() == 0) {
        session()->forget($sessionName);
    } else {
        session()->put($sessionName, $unseenQuestions);
    }

    return new QuestionResource(Question::find($newQuestionID));
}
</code>```

答:
You can take one of these approaches to do this

Authenticate your API calls: every user has a token that will authenticate the call. Then whenever you extract a question from a DB you store (in DB) the question as seen by the user

Send along with your API an array of seen questions. This approach IMHO is to be avoided because it is exploitable, and you delegate the client to decide wether a question has been seen or not.

I would go for the first option.

Body:
I have a quiz app with a laravel back-end and Vue front-end. I am working on developing an API for this app. However, the problem I have encountered is that I need an API endpoint that: returns a question from Questions table - but it needs to:

Return a question at random every time the method is called

Not be a question that user has already seen (unless all questions have been seen)

Up until now, I have been randomising the questions collection using the shuffle method, and relying on Sessions to store the ids of the unseenQuestions.

However, as API calls are stateless, sessions will not work. I was wonder what ways I could get around this?

public function random(Module $module, $category){
    // Get question ids in randomised order (for a given module + category)
    $questions =  Question::CategoryForModule(1, $module->id)->shuffle()->pluck('id');

    // Name and Get unseenQuestions
    $sessionName = 'unseenQuestions_' . $category .  strval($module->id); //unseenQuestions_anatomy_2

    if (session()->has($sessionName)) {
        $unseenQuestions = session()->get($sessionName);

    } else {
        $unseenQuestions = collect($questions);

    }
    // Pop new Question
    $newQuestionID = $unseenQuestions->shift();;

    // Store unseenQuestions OR remove unseenQuestions (if it has no items);
    if ($unseenQuestions->count() == 0) {
        session()->forget($sessionName);
    } else {
        session()->put($sessionName, $unseenQuestions);
    }

    return new QuestionResource(Question::find($newQuestionID));
}


问:
YouTube iframe embed - full screen
I have a form that is iframed into a web page. Upon completion of the form, a YouTube video is displayed from using iframe embed.

When I enter full screen mode of the YouTube video, nothing really happens.

Is the fullscreen of the nested iframe constrained by the dimensions of the parent iframe?

答:
Noticed mine worked on chrome. Got it to work in Firefox by going to <about:config> and setting full-screen-api.allow-trusted-requests-only to false.

After full screen worked once, I could set that back to true, and full screen still worked which was quite perplexing.

Title: YouTube iframe embed - full screen


问:
Dynamic Allocation for a Struct with template
I have a code, which is an implementation of doubly linked list.

```<code>template<class T>
struct Node{
    T value;
    struct Node * next_;
    struct Node * prev_;
};

template <class T>
class Dex
{
  public:
    struct Node<T> * head = (struct Node<T> *)calloc(1, sizeof(struct Node<T>));
    struct Node<T> * tail = (struct Node<T> *)calloc(1, sizeof(struct Node<T>));
    struct Node<T> * current = (struct Node<T> *)calloc(1, sizeof(struct Node<T>));
</code>```

When I compile this, I receive the following error:

[Error] there are no arguments to 'calloc' that depend on a template parameter, so a declaration of 'calloc' must be available [-fpermissive]

I've tried malloc, new etc. But I want to stick to calloc() for this one. Any other method to allocate memory is appreciated, as long as it works and won't throw any SIGSEV.

I expect the code to compile successfully, and be able to initialize a     (struct Node *) pointer without having to deal with memory problems.

答:
It seems you're just missing the needed include:

```<code>#include <cstdlib>
</code>```

However, you can use new for this. There's virtually no reason to use calloc() in C++. To default-initialize when allocating with new, use:

```<code>Node<T> * head = new Node<T>();
Node<T> * tail = new Node<T>();
Node<T> * current = new Node<T>();
</code>```

The () at the end will default-initialize the struct members. For built-in types, it zeroes them just like calloc() would do.

Off-topic:

You don't need to type struct before the struct name in C++. You can change your code to:

```<code>template<class T>
struct Node {
    T value;
    Node * next_;
    Node * prev_;
};

template <class T>
class Dex {
public:
    Node<T> * head = new Node<T>();
    Node<T> * tail = new Node<T>();
    Node<T> * current = new Node<T>();
</code>```

Body:
I have a code, which is an implementation of doubly linked list.

template<class T>
struct Node{
    T value;
    struct Node * next_;
    struct Node * prev_;
};

template <class T>
class Dex
{
  public:
    struct Node<T> * head = (struct Node<T> *)calloc(1, sizeof(struct Node<T>));
    struct Node<T> * tail = (struct Node<T> *)calloc(1, sizeof(struct Node<T>));
    struct Node<T> * current = (struct Node<T> *)calloc(1, sizeof(struct Node<T>));

When I compile this, I receive the following error:

[Error] there are no arguments to 'calloc' that depend on a template parameter, so a declaration of 'calloc' must be available [-fpermissive]

I've tried malloc, new etc. But I want to stick to calloc() for this one. Any other method to allocate memory is appreciated, as long as it works and won't throw any SIGSEV.

I expect the code to compile successfully, and be able to initialize a     (struct Node *) pointer without having to deal with memory problems.

Body:
It seems you're just missing the needed include:

#include <cstdlib>

However, you can use new for this. There's virtually no reason to use calloc() in C++. To default-initialize when allocating with new, use:

Node<T> * head = new Node<T>();
Node<T> * tail = new Node<T>();
Node<T> * current = new Node<T>();

The () at the end will default-initialize the struct members. For built-in types, it zeroes them just like calloc() would do.

Off-topic:

You don't need to type struct before the struct name in C++. You can change your code to:

template<class T>
struct Node {
    T value;
    Node * next_;
    Node * prev_;
};

template <class T>
class Dex {
public:
    Node<T> * head = new Node<T>();
    Node<T> * tail = new Node<T>();
    Node<T> * current = new Node<T>();


问:
How can I fill a text at the end of my arc?
I'm trying to place a text inside my semi circle, graph. I simplified the arc for you context.arc(92.5, 92.5, 72.5, 3.141592653589793, 3.7699111843077517, false); I want to place a value 2 at the end of arc, since the arc represents 20% of overall value.

So far I have tried is

```<code>context.translate(centerX, centerY);
context.save();
context.translate(x, y);
context.fillText('2', 0, 3);
context.restore();
</code>```

I tried to find x and y interception point using  (−ℎ)2+(−)2=2. But I can't place the text at the end of arc. Can some one please help me to solve this? Thank you.

答:
You will need to find the point where the arc ends:

```<code>let x = center.x + radius * Math.cos(endArc);
let y = center.y + radius * Math.sin(endArc);
</code>```

In this case the center of the circle is in the point {x:92.5,y:92.5}, the radius is 72.5. and the end arc is 3.7699111843077517.

I hope this is what you were asking.

const ctx = canvas.getContext("2d");
let cw = canvas.width = 200;
let ch= canvas.height = 200;
ctx.beginPath();
ctx.arc(92.5, 92.5, 72.5, 3.141592653589793, 3.7699111843077517, false);
ctx.stroke();
//find the point where the arc ends
let x = 92.5 + 72.5 * Math.cos(3.7699111843077517);
let y = 92.5 + 72.5 * Math.sin(3.7699111843077517);
// draw the text
ctx.font="12px Arial";
ctx.textAlign="center";
ctx.textBaseline="bottom";
ctx.fillText("2",x,y);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>canvas{border:1px solid}</code>```

<canvas id="canvas"></canvas>```

Body:
I'm trying to place a text inside my semi circle, graph. I simplified the arc for you context.arc(92.5, 92.5, 72.5, 3.141592653589793, 3.7699111843077517, false); I want to place a value 2 at the end of arc, since the arc represents 20% of overall value.

So far I have tried is

context.translate(centerX, centerY);
context.save();
context.translate(x, y);
context.fillText('2', 0, 3);
context.restore();

I tried to find x and y interception point using  (−ℎ)2+(−)2=2. But I can't place the text at the end of arc. Can some one please help me to solve this? Thank you.

Body:
You will need to find the point where the arc ends:

let x = center.x + radius * Math.cos(endArc);
let y = center.y + radius * Math.sin(endArc);

In this case the center of the circle is in the point {x:92.5,y:92.5}, the radius is 72.5. and the end arc is 3.7699111843077517.

I hope this is what you were asking.

const ctx = canvas.getContext("2d");
let cw = canvas.width = 200;
let ch= canvas.height = 200;
ctx.beginPath();
ctx.arc(92.5, 92.5, 72.5, 3.141592653589793, 3.7699111843077517, false);
ctx.stroke();
//find the point where the arc ends
let x = 92.5 + 72.5 * Math.cos(3.7699111843077517);
let y = 92.5 + 72.5 * Math.sin(3.7699111843077517);
// draw the text
ctx.font="12px Arial";
ctx.textAlign="center";
ctx.textBaseline="bottom";
ctx.fillText("2",x,y);

canvas{border:1px solid}

<canvas id="canvas"></canvas>


问:
Android Work Manager: How to enqueue Jobs once a month
following this question, I looked into Android Job Scheduling and it seems like Work Manager is the latest tool if I want to do something once every month. I built a Worker class and activated it with this snippet in my activity:

```<code>PeriodicWorkRequest myWorkRequest =
                new PeriodicWorkRequest.Builder(MonthlyWorker.class, 20, TimeUnit.MINUTES)
                        .build();
WorkManager.getInstance().enqueueUniquePeriodicWork("my fancy test",ExistingPeriodicWorkPolicy.KEEP, myWorkRequest);
</code>```

While i tested the 20 minutes period successfully, there is a problem: There are no TimeUnits for months available, only days. Doing the job every 30 days wont work for obvious reasons, since I need the task to be executed on the first day of each month. So what should i do? Do I have to use a different API? Thank you.

I could do something like if (dayOfMonth==1) do Function, but I think that undermines the purpose of a scheduler.

答:
You can do by minutes itself:

Just convert days to minutes:

Here : 30 days = 43200 minutes = 1 month

```<code>PeriodicWorkRequest myWorkRequest =
            new PeriodicWorkRequest.Builder(MonthlyWorker.class, 43200, TimeUnit.MINUTES)
                    .build();
WorkManager.getInstance().enqueueUniquePeriodicWork("my fancy test",ExistingPeriodicWorkPolicy.KEEP, myWorkRequest);
</code>```

UPDATE:

As per my requirement, I wanted to perform task every 30 minutes in between 8 am to 6 pm

With help of that worker I made for you as you required  1st of every month in between 12 am to 2 am below:

```<code>public class TestWorker extends Worker {

    private static final String DEFAULT_START_TIME = "00:01"; //12:01 am
    private static final String DEFAULT_END_TIME = "03:00"; // 03:00 am

    private static final String TAG = "TestWorker";

    public TestWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) {
        super(context, workerParams);
    }

    @NonNull
    @Override
    public Result doWork() {

        /**
         * Its for time
         */
        DateFormat dateFormat = new SimpleDateFormat("HH:mm", Locale.getDefault());

        /**
         * Get Current Calendar Instance
         */
        Calendar c = Calendar.getInstance();

        // Get current day of month
        int day = c.get(Calendar.DAY_OF_MONTH);

        /**
         * Get current time and compare with our start and end date.
         */
        Date date = c.getTime();
        String formattedDate = dateFormat.format(date);

        try {
            Date currentDate = dateFormat.parse(formattedDate);
            Date startDate = dateFormat.parse(DEFAULT_START_TIME);
            Date endDate = dateFormat.parse(DEFAULT_END_TIME);

            /**
             * This condition will check that day is 1, and time interval in between give time.
             */
            if (day == 1 && currentDate.after(startDate) && currentDate.before(endDate)) {
                // Do your work here
            }
        } catch (ParseException ignored) {

        }

        return Result.success();
    }
}
</code>```

You can start this test work for X hour interval so it will check every X hour (for example, In your case you can give 2 hours so it will check every two hours)

I do not know whether it will be affected to performance or not, but I think there is no other solution.

You can start worker as below:

```<code>PeriodicWorkRequest periodicWork = new PeriodicWorkRequest.Builder(MyWorker.class, 2, TimeUnit.HOURS)
                .addTag("MYWORK")
                .build();

WorkManager.getInstance().enqueueUniquePeriodicWork("MYWORK", ExistingPeriodicWorkPolicy.REPLACE, periodicWork);
</code>```

Hope it will help.

Body:
following this question, I looked into Android Job Scheduling and it seems like Work Manager is the latest tool if I want to do something once every month. I built a Worker class and activated it with this snippet in my activity:

PeriodicWorkRequest myWorkRequest =
                new PeriodicWorkRequest.Builder(MonthlyWorker.class, 20, TimeUnit.MINUTES)
                        .build();
WorkManager.getInstance().enqueueUniquePeriodicWork("my fancy test",ExistingPeriodicWorkPolicy.KEEP, myWorkRequest);

While i tested the 20 minutes period successfully, there is a problem: There are no TimeUnits for months available, only days. Doing the job every 30 days wont work for obvious reasons, since I need the task to be executed on the first day of each month. So what should i do? Do I have to use a different API? Thank you.

I could do something like if (dayOfMonth==1) do Function, but I think that undermines the purpose of a scheduler.

Body:
You can do by minutes itself:

Just convert days to minutes:

Here : 30 days = 43200 minutes = 1 month

PeriodicWorkRequest myWorkRequest =
            new PeriodicWorkRequest.Builder(MonthlyWorker.class, 43200, TimeUnit.MINUTES)
                    .build();
WorkManager.getInstance().enqueueUniquePeriodicWork("my fancy test",ExistingPeriodicWorkPolicy.KEEP, myWorkRequest);

UPDATE:

As per my requirement, I wanted to perform task every 30 minutes in between 8 am to 6 pm

With help of that worker I made for you as you required  1st of every month in between 12 am to 2 am below:

public class TestWorker extends Worker {

    private static final String DEFAULT_START_TIME = "00:01"; //12:01 am
    private static final String DEFAULT_END_TIME = "03:00"; // 03:00 am

    private static final String TAG = "TestWorker";

    public TestWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) {
        super(context, workerParams);
    }

    @NonNull
    @Override
    public Result doWork() {

        /**
         * Its for time
         */
        DateFormat dateFormat = new SimpleDateFormat("HH:mm", Locale.getDefault());

        /**
         * Get Current Calendar Instance
         */
        Calendar c = Calendar.getInstance();

        // Get current day of month
        int day = c.get(Calendar.DAY_OF_MONTH);

        /**
         * Get current time and compare with our start and end date.
         */
        Date date = c.getTime();
        String formattedDate = dateFormat.format(date);

        try {
            Date currentDate = dateFormat.parse(formattedDate);
            Date startDate = dateFormat.parse(DEFAULT_START_TIME);
            Date endDate = dateFormat.parse(DEFAULT_END_TIME);

            /**
             * This condition will check that day is 1, and time interval in between give time.
             */
            if (day == 1 && currentDate.after(startDate) && currentDate.before(endDate)) {
                // Do your work here
            }
        } catch (ParseException ignored) {

        }

        return Result.success();
    }
}

You can start this test work for X hour interval so it will check every X hour (for example, In your case you can give 2 hours so it will check every two hours)

I do not know whether it will be affected to performance or not, but I think there is no other solution.

You can start worker as below:

PeriodicWorkRequest periodicWork = new PeriodicWorkRequest.Builder(MyWorker.class, 2, TimeUnit.HOURS)
                .addTag("MYWORK")
                .build();

WorkManager.getInstance().enqueueUniquePeriodicWork("MYWORK", ExistingPeriodicWorkPolicy.REPLACE, periodicWork);

Hope it will help.


问:
How to get vertical highlighting in VSC
In Visual Studio Code, I'm trying to get the whole column highlighted where my cursor is. The same way a line is highlighted, I'd like to get the column highlighted as well.

It exists in Atom, as shown below, as an independant package.

I didn't find the same setting or package to do it in VSC. Anyone knows how to achieve that?

答:
I can suggest you the following extension: Editor Crosshair
https://marketplace.visualstudio.com/items?itemName=bitlang.vscode-crosshair

It adds horizontal and vertical rulers around the cursor (screenshot below)

Title: How to get vertical highlighting in VSC


问:
problem in using camera in android
following is the code by which i am capturing images in my app. After capturing the image it saves it in SDcard and shows done and retake when i click the done button i want the captured image to be uploaded to an url.

i am not able to know from where the done and retake button gets appeared pls help me...

```<code>protected static final int TAKE_RECEIPT = 0;
Button b1;
    Intent myIntent;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        b1 = (Button)findViewById(R.id.widget98);

        b1.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                takePictureFromCamera();
            }

            private void takePictureFromCamera()
            {
                 Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
 startActivityForResult(intent, TAKE_RECEIPT);
            }
</code>```

答:
To save the image somewhere specific, you need to provide the Uri using MediaStore.EXTRA_OUTPUT:

```<code>mIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(filename)));
</code>```

The done and retake buttons are shown as part of the MediaStore.ACTION_IMAGE_CAPTURE intent that you call. You cannot change that.

Title: problem in using camera in android

Body:
following is the code by which i am capturing images in my app. After capturing the image it saves it in SDcard and shows done and retake when i click the done button i want the captured image to be uploaded to an url.

i am not able to know from where the done and retake button gets appeared pls help me...

protected static final int TAKE_RECEIPT = 0;
Button b1;
    Intent myIntent;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        b1 = (Button)findViewById(R.id.widget98);

        b1.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                takePictureFromCamera();
            }

            private void takePictureFromCamera()
            {
                 Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
 startActivityForResult(intent, TAKE_RECEIPT);
            }

Body:
To save the image somewhere specific, you need to provide the Uri using MediaStore.EXTRA_OUTPUT:

mIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(filename)));

The done and retake buttons are shown as part of the MediaStore.ACTION_IMAGE_CAPTURE intent that you call. You cannot change that.


问:
Color of status bar icons in Dialog's Window
This is the code which I use for changing color of status bar icon:

```<code>window.decorView.systemUiVisibility = if (light) {
    View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
} else {
    View.SYSTEM_UI_FLAG_VISIBLE
}
</code>```

Unfortunately it does not work for Window object of a Dialog. Any idea why?

EDIT: It is not a duplicate of Android statusbar icons color - the link SO thread doesn't mention Dialogs

答: Activity and child dialog of that activity share's same window. So if you set something on window inside dialog code it will still impact the window of that activity. If you are dealing with dialog title then its not status bar. Its title view of that dialog</p>

Body:
This is the code which I use for changing color of status bar icon:

window.decorView.systemUiVisibility = if (light) {
    View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
} else {
    View.SYSTEM_UI_FLAG_VISIBLE
}

Unfortunately it does not work for Window object of a Dialog. Any idea why?

EDIT: It is not a duplicate of Android statusbar icons color - the link SO thread doesn't mention Dialogs


问:
How to audit a chrome extension's open-source code?
I am concerned that a chrome extension is providing users with different code than that in its open-source repo. The extension is MetaMask, a cryptocurrency wallet that was recently found to be injecting unique identifiers into every website a user visits, despite saying they weren't. I've now heard that MetaMask can also act as a DNS resolver, which is a lot of power for a deceitful app.

What's the best way for me to download this Chrome extension from the web store and compare it's hash to the build of the open-source code? Are there any existing Chrome extensions or websites where you can do this easier, i.e. compare the github repo directly to what's on the chrome web store?

答:
Disclaimer:
This guide assumes the usage of Chrome and a UNIX-style operating system.

Step 1: Get shipped source code

Go to chrome://extensions/ and activate Developer mode in the top right corner.

Click on Details of the extension and find its ID (it will be a long string of random characters)

Locate your chrome profiles' extension folder

find ~ -type d -iname <extension_id> (fill in the extensions ID)

The results of find will show a folder with the extensions (most likely compressed) source-code.

Step 2: Build the source-code yourself

Clone the source-code via git (git clone git@github.com:MetaMask/metamask-extension.git)

Follow the steps from the extensions build guide

Step 3: Compare the two

Run diff recursively on the two folders. folder1 could be the shipped source-code and folder2 your self-built source-code.

diff -r folder1/ folder2/

diff will give you the exact differences in code/files/etc. this can be a lot and will manually have to be checked, to find out what the real differences are...

P.S. I am very interested in the results and will run the comparison myself later...


问:
Update Folder Count on cascade delete in Laravel via eloquent
I have 3 tables:

Tasks

Folders

Folder tasks

Tasks table will have all task_name, Folder table will have folder_name, task_count and Folder Tasks is a pivot table which will store folder_id and task_id.

All tables have many-to-many relationships.

I added cascade delete tasks. So, if i delete a task then it will deleted everywhere including pivot table. I'm deleting tasks using eloquent delete. This is working fine

But, I need to update the count of tasks of each folder in Folders table once I delete a task.

As a task can be stored in multiple folders, it's hard to update the count of all folder's task_count on cascade deleted tasks. I'm stuck here.

How can i update all task_count's of affected folders?

答:
You can use the mysql trigger. Here is the example.

```<code>USE `test`;
DELIMITER
$$
CREATE TRIGGER `tasks_ADEL`
AFTER DELETE ON tasks FOR EACH ROW
-- Edit trigger body code below this line. Do not edit lines above this one
BEGIN
   update folder as f right join folder_tasks as ft on f.id = ft.folder_id set task_count = task_count + 1 where ft.task_id = OLD.id
END;
$$
</code>```

Here you can find the uses example https://www.w3resource.com/mysql/mysql-triggers.php#MTAD

Body:
You can use the mysql trigger. Here is the example.

USE `test`;
DELIMITER
$$
CREATE TRIGGER `tasks_ADEL`
AFTER DELETE ON tasks FOR EACH ROW
-- Edit trigger body code below this line. Do not edit lines above this one
BEGIN
   update folder as f right join folder_tasks as ft on f.id = ft.folder_id set task_count = task_count + 1 where ft.task_id = OLD.id
END;
$$

Here you can find the uses example https://www.w3resource.com/mysql/mysql-triggers.php#MTAD


问:
Django ORM annotate on foreign key query
I have 3 models:

```<code>class Project(models.Model):
    name = models.CharField(max_length=300, unique=True)
    description = models.CharField(
        max_length=2000,
        blank=True,
        null=True,
        default=None
    )

class QuestionSession(models.Model):
    name = models.CharField(
        max_length=500, default=None, null=True, blank=True
    )
    project = models.ForeignKey(
        Project,
        on_delete=models.CASCADE,
        related_name='sessions',
        blank=True,
        null=True,
        default=None
    )

class Question(models.Model):
    description = models.CharField(max_length=500)
    question_session = models.ForeignKey(
        QuestionSession,
        on_delete=models.CASCADE,
        related_name='questions',
        blank=True,
        null=True,
        default=None
    )
</code>```

As you can see, Project contains Sessions, Session contains questions.
What I'm trying to achieve is I wanna fetch a single Project with sessions and number of questions in them. I can do it easily with 2 different queries but I cannot do it in 1 query.

My serializers:

```<code>class SingleProjectSerializer(serializers.ModelSerializer):
    sessions = MinifiedSessionSerializer(many=True)

    class Meta:
        model = Project
        fields = [
            'id',
            'name',
            'description',
            'sessions'
        ]

class MinifiedSessionSerializer(serializers.ModelSerializer):
    questions_number = serializers.IntegerField()

    class Meta:
        model = QuestionSession
        fields = [
            'id',
            'name',
            'questions_number'
        ]
</code>```

I used to grab sessions in a single query like this:

```<code>Project.objects.get(id=project_id).sessions.annotate(questions_number=Count('questions'))
</code>```

But how to do it now? I need to fetch the project first and then annotate on sessions. I have no idea how to do it. I need a query like this:

```<code>Project.objects.filter(pk=project_id).annotate(sessions__questions_number=Count('sessions__questions'))
</code>```

答:
I don't believe it's possible through Django ORM. The only solution which I can think of is changing the way on how you ask for the data:

```<code>sessions = QuestionSession.objects.filter(project_id=project_id).select_related('project').annotate(questions_number=Count('questions'))
project = sessions[0].project
</code>```

That would end up in a single query, but I assume you want to pass this project instance down to the DRF serializer. In such case the project knows nothing about prefetched sessions, so it would need to be handled separately. Additionally there is an issue when particular project has no associated sessions - sessions[0].project would raise exception. To keep the code clean I would probably stay with yours current approach (but then - the issue remains unresolved to keep everything in one db hit).

Body:
I have 3 models:

class Project(models.Model):
    name = models.CharField(max_length=300, unique=True)
    description = models.CharField(
        max_length=2000,
        blank=True,
        null=True,
        default=None
    )

class QuestionSession(models.Model):
    name = models.CharField(
        max_length=500, default=None, null=True, blank=True
    )
    project = models.ForeignKey(
        Project,
        on_delete=models.CASCADE,
        related_name='sessions',
        blank=True,
        null=True,
        default=None
    )

class Question(models.Model):
    description = models.CharField(max_length=500)
    question_session = models.ForeignKey(
        QuestionSession,
        on_delete=models.CASCADE,
        related_name='questions',
        blank=True,
        null=True,
        default=None
    )

As you can see, Project contains Sessions, Session contains questions.
What I'm trying to achieve is I wanna fetch a single Project with sessions and number of questions in them. I can do it easily with 2 different queries but I cannot do it in 1 query.

My serializers:

class SingleProjectSerializer(serializers.ModelSerializer):
    sessions = MinifiedSessionSerializer(many=True)

    class Meta:
        model = Project
        fields = [
            'id',
            'name',
            'description',
            'sessions'
        ]

class MinifiedSessionSerializer(serializers.ModelSerializer):
    questions_number = serializers.IntegerField()

    class Meta:
        model = QuestionSession
        fields = [
            'id',
            'name',
            'questions_number'
        ]

I used to grab sessions in a single query like this:

Project.objects.get(id=project_id).sessions.annotate(questions_number=Count('questions'))

But how to do it now? I need to fetch the project first and then annotate on sessions. I have no idea how to do it. I need a query like this:

Project.objects.filter(pk=project_id).annotate(sessions__questions_number=Count('sessions__questions'))

Body:
I don't believe it's possible through Django ORM. The only solution which I can think of is changing the way on how you ask for the data:

sessions = QuestionSession.objects.filter(project_id=project_id).select_related('project').annotate(questions_number=Count('questions'))
project = sessions[0].project

That would end up in a single query, but I assume you want to pass this project instance down to the DRF serializer. In such case the project knows nothing about prefetched sessions, so it would need to be handled separately. Additionally there is an issue when particular project has no associated sessions - sessions[0].project would raise exception. To keep the code clean I would probably stay with yours current approach (but then - the issue remains unresolved to keep everything in one db hit).


问:
Make image appear for 300ms when pressing space
I asked this question earlier but I think I formulated myself wrong, so this time I will add pictures.

I have a game where there is a man (well actually Donald Trump) at the bottom of the screen shooting bullets upwards to the top of the screen at incoming enemies.

He has a gun, at the end of the gunbarrel I am trying to add that a sprite of a flame will appear when I press space, and after 300ms it will disappear (until I press space again and the cycle continues).

Here is a picture of the game and what I mean:

1 = No keys pressed

2 = Space is pressed

3 = Space is no longer pressed and over 300ms has passed, now I want the flame sprite to go away until space is pressed again

How can I do this? :)

答:
Simply create a variable where you store the timeout value if the key is pressed and substract the time passed each frame from that value.

If that value is > 0, show the image with the fire. If that value is 0, show the image without the fire.

Here's a simple example I hacked together:

```<code>import pygame

class Actor(pygame.sprite.Sprite):
    def __init__(self, *grps):
        super().__init__(*grps)
        # create two images:
        # 1 - the no-fire-image
        # 2 - the with-fire-image
        self.original_image = pygame.Surface((100, 200))
        self.original_image.set_colorkey((1,2,3))
        self.original_image.fill((1,2,3))
        self.original_image.subsurface((0, 100, 100, 100)).fill((255, 255, 255))
        self.fire_image = self.original_image.copy()
        pygame.draw.rect(self.fire_image, (255, 0, 0), (20, 0, 60, 100))

        # we'll start with the no-fire-image
        self.image = self.fire_image
        self.rect = self.image.get_rect(center=(300, 240))

        # a field to keep track of our timeout
        self.timeout = 0

    def update(self, events, dt):

        # every frame, substract the amount of time that has passed
        # from your timeout. Should not be less than 0.
        if self.timeout > 0:
            self.timeout = max(self.timeout - dt, 0)

        # if space is pressed, we make sure the timeout is set to 300ms
        pressed = pygame.key.get_pressed()
        if pressed[pygame.K_SPACE]:
            self.timeout = 300

        # as long as 'timeout' is > 0, show the with-fire-image
        # instead of the default image
        self.image = self.original_image if self.timeout == 0 else self.fire_image

def main():
    pygame.init()
    screen = pygame.display.set_mode((600, 480))
    screen_rect = screen.get_rect()
    clock = pygame.time.Clock()
    dt = 0
    sprites_grp = pygame.sprite.Group()

    # create out sprite
    Actor(sprites_grp)

    # standard pygame mainloop
    while True:
        events = pygame.event.get()
        for e in events:
            if e.type == pygame.QUIT:
                return

        sprites_grp.update(events, dt)

        screen.fill((80, 80, 80))
        sprites_grp.draw(screen)
        pygame.display.flip()
        dt = clock.tick(60)

if __name__ == '__main__':
    main()
</code>```

Body:
Simply create a variable where you store the timeout value if the key is pressed and substract the time passed each frame from that value.

If that value is > 0, show the image with the fire. If that value is 0, show the image without the fire.

Here's a simple example I hacked together:

import pygame

class Actor(pygame.sprite.Sprite):
    def __init__(self, *grps):
        super().__init__(*grps)
        # create two images:
        # 1 - the no-fire-image
        # 2 - the with-fire-image
        self.original_image = pygame.Surface((100, 200))
        self.original_image.set_colorkey((1,2,3))
        self.original_image.fill((1,2,3))
        self.original_image.subsurface((0, 100, 100, 100)).fill((255, 255, 255))
        self.fire_image = self.original_image.copy()
        pygame.draw.rect(self.fire_image, (255, 0, 0), (20, 0, 60, 100))

        # we'll start with the no-fire-image
        self.image = self.fire_image
        self.rect = self.image.get_rect(center=(300, 240))

        # a field to keep track of our timeout
        self.timeout = 0

    def update(self, events, dt):

        # every frame, substract the amount of time that has passed
        # from your timeout. Should not be less than 0.
        if self.timeout > 0:
            self.timeout = max(self.timeout - dt, 0)

        # if space is pressed, we make sure the timeout is set to 300ms
        pressed = pygame.key.get_pressed()
        if pressed[pygame.K_SPACE]:
            self.timeout = 300

        # as long as 'timeout' is > 0, show the with-fire-image
        # instead of the default image
        self.image = self.original_image if self.timeout == 0 else self.fire_image

def main():
    pygame.init()
    screen = pygame.display.set_mode((600, 480))
    screen_rect = screen.get_rect()
    clock = pygame.time.Clock()
    dt = 0
    sprites_grp = pygame.sprite.Group()

    # create out sprite
    Actor(sprites_grp)

    # standard pygame mainloop
    while True:
        events = pygame.event.get()
        for e in events:
            if e.type == pygame.QUIT:
                return

        sprites_grp.update(events, dt)

        screen.fill((80, 80, 80))
        sprites_grp.draw(screen)
        pygame.display.flip()
        dt = clock.tick(60)

if __name__ == '__main__':
    main()


问:
Execute an Array of promises sequentially without using async/await
Lets say I have an array of promises. Each element of my array is a knex.js query builder and is ready to be executed and returns a promise.

How can I run each element of this array sequentially.
The array is built dynamically.

```<code>let promisesArray = [q1,q2,q3] ;
</code>```

Each q is not a promise by itself but it will return a promise upon execution.

答:
If you're using bluebird, you can use Promise.map with concurrency set to 1.

```<code>await Promise.map(arrayOfObj, async (obj) => {
    await this.someOperation();
  },
  {concurrency: 1}
);
</code>```

Body:
Lets say I have an array of promises. Each element of my array is a knex.js query builder and is ready to be executed and returns a promise.

How can I run each element of this array sequentially.
The array is built dynamically.

let promisesArray = [q1,q2,q3] ;

Each q is not a promise by itself but it will return a promise upon execution.

Body:
If you're using bluebird, you can use Promise.map with concurrency set to 1.

await Promise.map(arrayOfObj, async (obj) => {
    await this.someOperation();
  },
  {concurrency: 1}
);


问:
Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays error
Backend (Spring Boot, REST(Spring Data Rest, Spring Data JPA) It's only happening with JPA, without it works perfectly, but a hella lot more code to write).

I tried all the remaining responses but I'm not getting the exact solution.

BACKEND API

```<code>New File
pizzatest.model.ts
export class Pizzas{

    firstName: string;
    description: string;
}

API BELOW

_embedded
pizzas
0
firstName   "Pizza Margarita"
description "Ingredients of Margarita"
_links
self
href    "http://localhost:8080/pizzas/1"
pizza
href    "http://localhost:8080/pizzas/1"
1
firstName   "Detroit Pizza"
description "Ingredients of Detroit Pizza"
_links
self
href    "http://localhost:8080/pizzas/2"
pizza
href    "http://localhost:8080/pizzas/2"
2
firstName   "Greek Pizza"
description "Ingredients of Greek Pizza"
_links
self
href    "http://localhost:8080/pizzas/3"
pizza
href    "http://localhost:8080/pizzas/3"
3
firstName   "Sicilian Pizza"
description "Ingredients of Sicilian Pizza"
_links
self
href    "http://localhost:8080/pizzas/4"
pizza
href    "http://localhost:8080/pizzas/4"
4
firstName   "Chicago Pizza"
description "Ingredients of Chicago Pizza"
_links
self
href    "http://localhost:8080/pizzas/5"
pizza
href    "http://localhost:8080/pizzas/5"
_links
self
href    "http://localhost:8080/pizzas{?page,size,sort}"
templated   true
profile
href    "http://localhost:8080/profile/pizzas"
page
size    20
totalElements   5
totalPages  1
number  0
</code>```

SERVICE

```<code>import { Injectable } from '@angular/core';
import{HttpClient} from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class PizzatestService {

readonly rootUrl = 'http://localhost:8080/'

  constructor(private http: HttpClient) { }

getPizzas(){
  return this.http.get(this.rootUrl + '/pizzas');
}}
</code>```

TYPESCRIPT

```<code>import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { PizzatestService } from './pizzatest.service';
import {Pizzas} from './pizzatest.model';

@Component({
  selector: 'app-pizzatest',
  templateUrl: './pizzatest.component.html',
  styleUrls: ['./pizzatest.component.css']
})
export class PizzatestComponent implements OnInit {

pizzas : Pizzas[]

  constructor(private pizzaTestService: PizzatestService) { }

  ngOnInit() {
this.pizzaTestService.getPizzas().subscribe((data: any) => {
  console.log('from service', data)
  this.pizzas = data;
})
  }
}
</code>```

HTML

```<code><div *ngFor="let pizza of pizzas">
        <ul>
          <li> {{pizza.firstName}}</li>
          <li> {{pizza.description}}</li>
        </ul>
        </div>
</code>```

答:
You expect an array of objects, but I think what you get from the server is an object, which has a pizzas property. Try this way:

```<code>getPizzas(){
  return this.http.get(this.rootUrl + '/pizzas')
    .pipe(map(data => data.pizzas));
}}
</code>```

You can check what you get from the server using

```<code>getPizzas(){
  return this.http.get(this.rootUrl + '/pizzas')
    .pipe(tap(console.log));
}}
</code>```

(You can import tap the same way you did with map)

Body:
Backend (Spring Boot, REST(Spring Data Rest, Spring Data JPA) It's only happening with JPA, without it works perfectly, but a hella lot more code to write).

I tried all the remaining responses but I'm not getting the exact solution.

BACKEND API

New File
pizzatest.model.ts
export class Pizzas{

    firstName: string;
    description: string;
}

API BELOW

_embedded
pizzas
0
firstName   "Pizza Margarita"
description "Ingredients of Margarita"
_links
self
href    "http://localhost:8080/pizzas/1"
pizza
href    "http://localhost:8080/pizzas/1"
1
firstName   "Detroit Pizza"
description "Ingredients of Detroit Pizza"
_links
self
href    "http://localhost:8080/pizzas/2"
pizza
href    "http://localhost:8080/pizzas/2"
2
firstName   "Greek Pizza"
description "Ingredients of Greek Pizza"
_links
self
href    "http://localhost:8080/pizzas/3"
pizza
href    "http://localhost:8080/pizzas/3"
3
firstName   "Sicilian Pizza"
description "Ingredients of Sicilian Pizza"
_links
self
href    "http://localhost:8080/pizzas/4"
pizza
href    "http://localhost:8080/pizzas/4"
4
firstName   "Chicago Pizza"
description "Ingredients of Chicago Pizza"
_links
self
href    "http://localhost:8080/pizzas/5"
pizza
href    "http://localhost:8080/pizzas/5"
_links
self
href    "http://localhost:8080/pizzas{?page,size,sort}"
templated   true
profile
href    "http://localhost:8080/profile/pizzas"
page
size    20
totalElements   5
totalPages  1
number  0

SERVICE

import { Injectable } from '@angular/core';
import{HttpClient} from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class PizzatestService {

readonly rootUrl = 'http://localhost:8080/'

  constructor(private http: HttpClient) { }

getPizzas(){
  return this.http.get(this.rootUrl + '/pizzas');
}}

TYPESCRIPT

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { PizzatestService } from './pizzatest.service';
import {Pizzas} from './pizzatest.model';

@Component({
  selector: 'app-pizzatest',
  templateUrl: './pizzatest.component.html',
  styleUrls: ['./pizzatest.component.css']
})
export class PizzatestComponent implements OnInit {

pizzas : Pizzas[]

  constructor(private pizzaTestService: PizzatestService) { }

  ngOnInit() {
this.pizzaTestService.getPizzas().subscribe((data: any) => {
  console.log('from service', data)
  this.pizzas = data;
})
  }
}

HTML

 {{pizza.firstName}}

 {{pizza.description}}

Body:
You expect an array of objects, but I think what you get from the server is an object, which has a pizzas property. Try this way:

getPizzas(){
  return this.http.get(this.rootUrl + '/pizzas')
    .pipe(map(data => data.pizzas));
}}

You can check what you get from the server using

getPizzas(){
  return this.http.get(this.rootUrl + '/pizzas')
    .pipe(tap(console.log));
}}

(You can import tap the same way you did with map)


问:
I am trying to understand a specific function pointer and assignment
I am reading the source code of the video game “Rise of the Triad: Dark War”, and I came across a line of code I don't understand.

```<code>void (*USL_MeasureString)(char *, int *, int *, font_t *) = (void (*)(char *, int *, int *, font_t *))VW_MeasurePropString, (*USL_DrawString)(char *) = VWB_DrawPropString;
</code>```

As far as I understand it void (*USL_MeasureString)(char *, int *, int *, font_t *) means *USL_MeasureString is a function pointer that takes char *, int *, int *, font_t * as parameters and returns nothing because of void.

But then, I am confused about the rest of the code.

What does it means exactly?

Best regards.

答:
Let's break this long line into three parts:

void
  (*USL_MeasureString)(char *, int *, int *, font_t *) = (void (*)(char *, int *, int *, font_t *))VW_MeasurePropString,
  (*USL_DrawString)(char *) = VWB_DrawPropString;
```

<p>I believe it's easier to understand now. As you've correctly figured out, <code>USL_MeasureString</code> is defined as a function pointer, and the RHS (Right-Hand Side) of the assignment is a type cast applied to the word <code>VW_MeasurePropString</code>.</p>

<p>The second part appears tricky on its own, but once you get to know how the following line works, you'll know it's the same:</p>

<pre class="lang-c prettyprint-override"><code>char (*a) = (char *)"123", (*b) = "xyz";
</code>```

Here, both a and b are pointers to char, so you can think of char as a "base type" for the whole line of variable definitions. And of course you can rewrite it as:

char (*a) = (char *)"123";
char (*b) = "xyz";
```

<p>So the part after the comma in your original code can be rewritten as (where <code>void</code> is the "base type"):</p>

<pre class="lang-c prettyprint-override"><code>void (*USL_DrawString)(char *) = VWB_DrawPropString;
</code>```

As you can see, it's just the definition of another function pointer with a different argument list and no type casting.

Body:
I am reading the source code of the video game “Rise of the Triad: Dark War”, and I came across a line of code I don't understand.

void (*USL_MeasureString)(char *, int *, int *, font_t *) = (void (*)(char *, int *, int *, font_t *))VW_MeasurePropString, (*USL_DrawString)(char *) = VWB_DrawPropString;

As far as I understand it void (*USL_MeasureString)(char *, int *, int *, font_t *) means *USL_MeasureString is a function pointer that takes char *, int *, int *, font_t * as parameters and returns nothing because of void.

But then, I am confused about the rest of the code.

What does it means exactly?

Best regards.

Body:
Let's break this long line into three parts:

void
  (*USL_MeasureString)(char *, int *, int *, font_t *) = (void (*)(char *, int *, int *, font_t *))VW_MeasurePropString,
  (*USL_DrawString)(char *) = VWB_DrawPropString;

I believe it's easier to understand now. As you've correctly figured out, USL_MeasureString is defined as a function pointer, and the RHS (Right-Hand Side) of the assignment is a type cast applied to the word VW_MeasurePropString.

The second part appears tricky on its own, but once you get to know how the following line works, you'll know it's the same:

char (*a) = (char *)"123", (*b) = "xyz";

Here, both a and b are pointers to char, so you can think of char as a "base type" for the whole line of variable definitions. And of course you can rewrite it as:

char (*a) = (char *)"123";
char (*b) = "xyz";

So the part after the comma in your original code can be rewritten as (where void is the "base type"):

void (*USL_DrawString)(char *) = VWB_DrawPropString;

As you can see, it's just the definition of another function pointer with a different argument list and no type casting.


问:
How to pass arguments from iOS (Objc/Swift) to Unity that are structs/classes? (without using UnitySendMessage)
I am trying to find a good way to pass parameters from my native unity plugin in objc/swift to C# unity.

It seems that I will need to use Marshall but I couldn't find a good example of this anywhere.

The only thing I did found is the UnitySendMessage, but that passes strings only as parameters, and even those are limited to 1024 bytes, which is not enough for a JSON representation of the objects, and handling multiple messages seems a bit of an overkill for this.

The idea is to be able to question the plugin for object detection from a MTLTexture and return the objects that are recognised.

Code samples:

SwiftBridge

```<code>import Foundation
import UIKit
import Vision

@objc public class SwiftBridge: NSObject {

  var delegate: DelegateCallbackFunction?

  @objc static let shared = SwiftBridge()

  @objc func evaluate(texture: MTLTexture) -> Bool {
    guard let delegate = self.delegate else {
      return false
    }

    let rect = CGRect(x: 1, y: 2, width: 100, height: 200)
    delegate(rect)

    return true
  }

  @objc func setDelegate(callback: @escaping DelegateCallbackFunction) -> Bool {
    self.delegate = callback

    return true
  }
}
</code>```

Unity

```<code>using System;
using UnityEngine;
using System.Runtime.InteropServices;
using AOT;

[StructLayout(LayoutKind.Sequential)]
public struct CGPoint {
    public float x;
    public float y;
};

[StructLayout(LayoutKind.Sequential)]
public struct CGSize {
    public float width;
    public float height;
};

[StructLayout(LayoutKind.Sequential)]
public struct CGRect {
    public CGPoint origin;
    public CGSize size;

}

public class UnityBridge : MonoBehaviour {

    #region Declare external C interface
    // #if UNITY_IOS && !UNITY_EDITOR

    [DllImport("__Internal")]
    private static extern int _vision_detectObjectsIn(IntPtr texture);

    delegate bool ObjectDetectedCallback(ref CGRect rect);
    [DllImport("__Internal")]
    private static extern void _vision_setDelegate(ObjectDetectedCallback callback);

    [MonoPInvokeCallback(typeof(ObjectDetectedCallback))]
    private static bool delegateMessageReceived(ref CGRect rect) {
        Debug.Log("Message received: " + rect.origin.x);
        return true;
    }
    // #endif
    #endregion

    public void initializeDelegate() {
        if (Application.platform == RuntimePlatform.IPhonePlayer) {
            _vision_setDelegate(delegateMessageReceived);
        }
    }

   #region Wrapped methods and properties
   public void EvaluateTexture(IntPtr texture) {
    initializeDelegate();

    if (texture == IntPtr.Zero) {
      Debug.LogError("[Texture] Pointer to buffer is null.");
      return;
    }

    bool success;

     #if UNITY_IOS && !UNITY_EDITOR
     _vision_detectObjectsIn(texture);
     #endif
   }
   #endregion

   #region Singleton implementation
   private static WeRDetectorUnity _instance;
   public static WeRDetectorUnity Instance {
       get {
           if (_instance == null) {
               var obj = new GameObject("WeRDetectorUnity");
               _instance = obj.AddComponent<WeRDetectorUnity>();
           }
           return _instance;
       }
   }

   void Awake() {
       if (_instance != null) {
           Destroy(gameObject);
           return;
       }

       DontDestroyOnLoad(gameObject);
   }
   #endregion

}
</code>```

The message receive print in Unity does not return a 1 as it should but rather a strange exponent small number.
Any idea??

答:
Blockquote

You need to create struct for pass parameter its you can use parameters on multiple time and also access in main class.

struct Location {
  let latitude:"latitude"
  let longitude: "longitude"
}

Body:
I am trying to find a good way to pass parameters from my native unity plugin in objc/swift to C# unity.

It seems that I will need to use Marshall but I couldn't find a good example of this anywhere.

The only thing I did found is the UnitySendMessage, but that passes strings only as parameters, and even those are limited to 1024 bytes, which is not enough for a JSON representation of the objects, and handling multiple messages seems a bit of an overkill for this.

The idea is to be able to question the plugin for object detection from a MTLTexture and return the objects that are recognised.

Code samples:

SwiftBridge

import Foundation
import UIKit
import Vision

@objc public class SwiftBridge: NSObject {

  var delegate: DelegateCallbackFunction?

  @objc static let shared = SwiftBridge()

  @objc func evaluate(texture: MTLTexture) -> Bool {
    guard let delegate = self.delegate else {
      return false
    }

    let rect = CGRect(x: 1, y: 2, width: 100, height: 200)
    delegate(rect)

    return true
  }

  @objc func setDelegate(callback: @escaping DelegateCallbackFunction) -> Bool {
    self.delegate = callback

    return true
  }
}

Unity

using System;
using UnityEngine;
using System.Runtime.InteropServices;
using AOT;

[StructLayout(LayoutKind.Sequential)]
public struct CGPoint {
    public float x;
    public float y;
};

[StructLayout(LayoutKind.Sequential)]
public struct CGSize {
    public float width;
    public float height;
};

[StructLayout(LayoutKind.Sequential)]
public struct CGRect {
    public CGPoint origin;
    public CGSize size;

}

public class UnityBridge : MonoBehaviour {

    #region Declare external C interface
    // #if UNITY_IOS && !UNITY_EDITOR

    [DllImport("__Internal")]
    private static extern int _vision_detectObjectsIn(IntPtr texture);

    delegate bool ObjectDetectedCallback(ref CGRect rect);
    [DllImport("__Internal")]
    private static extern void _vision_setDelegate(ObjectDetectedCallback callback);

    [MonoPInvokeCallback(typeof(ObjectDetectedCallback))]
    private static bool delegateMessageReceived(ref CGRect rect) {
        Debug.Log("Message received: " + rect.origin.x);
        return true;
    }
    // #endif
    #endregion

    public void initializeDelegate() {
        if (Application.platform == RuntimePlatform.IPhonePlayer) {
            _vision_setDelegate(delegateMessageReceived);
        }
    }

   #region Wrapped methods and properties
   public void EvaluateTexture(IntPtr texture) {
    initializeDelegate();

    if (texture == IntPtr.Zero) {
      Debug.LogError("[Texture] Pointer to buffer is null.");
      return;
    }

    bool success;

     #if UNITY_IOS && !UNITY_EDITOR
     _vision_detectObjectsIn(texture);
     #endif
   }
   #endregion

   #region Singleton implementation
   private static WeRDetectorUnity _instance;
   public static WeRDetectorUnity Instance {
       get {
           if (_instance == null) {
               var obj = new GameObject("WeRDetectorUnity");
               _instance = obj.AddComponent<WeRDetectorUnity>();
           }
           return _instance;
       }
   }

   void Awake() {
       if (_instance != null) {
           Destroy(gameObject);
           return;
       }

       DontDestroyOnLoad(gameObject);
   }
   #endregion

}

The message receive print in Unity does not return a 1 as it should but rather a strange exponent small number.
Any idea??