问:
Laravel 5.2 + mono log critical error send to mail
How I can send every critical error exception to email. in current Laravel 5.2 it log in /storage/logs/laravel.log file. I want get that critical error in to mail with MailHandler but don't know how to implement it.

in file we get this type of error :

```<code>[2017-12-07 09:32:51] local.ERROR: ParseError: syntax error, unexpected 'if' (T_IF) in /home/ilogix/Workspace/cudefender/site/app/Http/Controllers/FormsController.php:53
Stack trace:
#0 /home/ilogix/Workspace/cudefender/site/vendor/composer/ClassLoader.php(301): Composer\Autoload\includeFile('/home/ilogix/Wo...')
#1 [internal function]: Composer\Autoload\ClassLoader->loadClass('App\\Http\\Contro...')
#2 [internal function]: spl_autoload_call('App\\Http\\Contro...')
#3 /home/ilogix/Workspace/cudefender/site/vendor/laravel/framework/src/Illuminate/Routing/Route.php(280): ReflectionMethod->__construct('App\\Http\\Contro...', 'index')
</code>```

i need same in email by monolog mail handler.

答:
You can edit the app/Exceptions/Handler.php file to send emails to a given address. For example, edit the report function to:

```<code>public function report(Exception $e)
{

    try {
      \Mail::raw( $e->__toString(), function ( $m ) {
        $m->from('no-reply@your-app.com', 'APP_NAME');
        $m->to( 'name@domain.com' )->subject('APP_NAME - Fatal Error' );
      });
    } catch ( \Exception $e ) {
      // ignore
    }

    parent::report($e);
}
</code>```

This code will send the contents of the Exception $e to name@domain.com. You can change the from address, and subject to be anything you want.

Depending on the error encountered, the message you receive would look like:

Symfony\Component\HttpKernel\Exception\NotFoundHttpException in
  your-app/vendor/laravel/framework/src/Illuminate/Routing/RouteCollection.php:161

Stack trace: #0
  your-app/vendor/laravel/framework/src/Illuminate/Routing/Router.php(821):
  Illuminate\Routing\RouteCollection->match(Object(Illuminate\Http\Request))

...

Body:
How I can send every critical error exception to email. in current Laravel 5.2 it log in /storage/logs/laravel.log file. I want get that critical error in to mail with MailHandler but don't know how to implement it.

in file we get this type of error :

[2017-12-07 09:32:51] local.ERROR: ParseError: syntax error, unexpected 'if' (T_IF) in /home/ilogix/Workspace/cudefender/site/app/Http/Controllers/FormsController.php:53
Stack trace:
#0 /home/ilogix/Workspace/cudefender/site/vendor/composer/ClassLoader.php(301): Composer\Autoload\includeFile('/home/ilogix/Wo...')
#1 [internal function]: Composer\Autoload\ClassLoader->loadClass('App\\Http\\Contro...')
#2 [internal function]: spl_autoload_call('App\\Http\\Contro...')
#3 /home/ilogix/Workspace/cudefender/site/vendor/laravel/framework/src/Illuminate/Routing/Route.php(280): ReflectionMethod->__construct('App\\Http\\Contro...', 'index')

i need same in email by monolog mail handler.

Body:
You can edit the app/Exceptions/Handler.php file to send emails to a given address. For example, edit the report function to:

public function report(Exception $e)
{

    try {
      \Mail::raw( $e->__toString(), function ( $m ) {
        $m->from('no-reply@your-app.com', 'APP_NAME');
        $m->to( 'name@domain.com' )->subject('APP_NAME - Fatal Error' );
      });
    } catch ( \Exception $e ) {
      // ignore
    }

    parent::report($e);
}

This code will send the contents of the Exception $e to name@domain.com. You can change the from address, and subject to be anything you want.

Depending on the error encountered, the message you receive would look like:

Symfony\Component\HttpKernel\Exception\NotFoundHttpException in
  your-app/vendor/laravel/framework/src/Illuminate/Routing/RouteCollection.php:161

Stack trace: #0
  your-app/vendor/laravel/framework/src/Illuminate/Routing/Router.php(821):
  Illuminate\Routing\RouteCollection->match(Object(Illuminate\Http\Request))

...


来源: stackexchange

问:
UIPanGestureRecognizer velocity in view could be nil?
In UIPanGestureRecognizer, there is this function to calculate the velocity of the gesture:

```<code>func velocity(in view: UIView?) -> CGPoint
</code>```

The doc says:

view

  The view in whose coordinate system the velocity of the pan gesture is computed.

I notice that view could be nil, which is a bit strange. Why and when should we use nil?

答:
I believe it works the same way as location(in view: UIView?) does. If you don't pass a view object, then it'll calculate the velocity in window's coordinate system.

location(in:)

The view object in whose coordinate system you want the touch located. A custom view that is handling the touch may specify self to get the touch location in its own coordinate system. Pass nil to get the touch location in the window’s coordinates.

ContentLicense: CC BY-SA 3.0

Body:
In UIPanGestureRecognizer, there is this function to calculate the velocity of the gesture:

func velocity(in view: UIView?) -> CGPoint

The doc says:

view

  The view in whose coordinate system the velocity of the pan gesture is computed.

I notice that view could be nil, which is a bit strange. Why and when should we use nil?


问:
Taking the address of a function from within that function
First, the question: Is there any reason you can't take the address of a function from within that function?

```<code>#include <stdio.h>

struct foo {
  void(*xf)(void);
  int r;
} sFoo;

void func(void) {
  sFoo.xf = func; /* <-- like this */
}

int main()
{
  func();
  printf("FuncPtr  is: %p\n", sFoo.xf);
  printf("FuncAddr is: %p\n", &func);
  getchar();
  return 0;
}
</code>```

I can't think of a reason why this shouldn't work portably, but that doesn't mean there isn't one. I've tested it with MinGW and MSVC on Windows, and gcc on Ubuntu, and it works fine. The C standard is pretty much silent, except to say that (C99 5.1.1.2) function references are resolved in the final translation phase.

My main aggravation is that I can't find anything that confirms that this is standard behavior. I've run across comments in the past that said that you couldn't take the address of a function from within that function, which I thought were bogus at the time, but didn't really have the time or inclination to actually check it out, until now.

答:
The only constraints on the unary & operator are as follows:

The operand of the unary & operator shall be either a function designator, the result of a [] or unary * operator, or an lvalue that
  designates an object that is not a bit-field and is not declared with
  the register storage-class specifier.

Functions identifiers satisfy this (perhaps counter-intuitively, a function identifier is an lvalue as per 6.3.2.1p1), and so it is always legal to take their address.

In fact, if it were illegal, recursive functions would be impossible, because to call a function, you need to use its designator, and 6.3.2.1p4 defines such use in terms of a conversion to a function pointer:

A function designator is an expression that has function type. Except
  when it is the operand of the sizeof operator, the _Alignof
  operator,65) or the unary & operator, a function designator with type
  ''function returning type'' is converted to an expression that has
  type ''pointer to function returning type''.

Body:
First, the question: Is there any reason you can't take the address of a function from within that function?

#include <stdio.h>

struct foo {
  void(*xf)(void);
  int r;
} sFoo;

void func(void) {
  sFoo.xf = func; /* <-- like this */
}

int main()
{
  func();
  printf("FuncPtr  is: %p\n", sFoo.xf);
  printf("FuncAddr is: %p\n", &func);
  getchar();
  return 0;
}

I can't think of a reason why this shouldn't work portably, but that doesn't mean there isn't one. I've tested it with MinGW and MSVC on Windows, and gcc on Ubuntu, and it works fine. The C standard is pretty much silent, except to say that (C99 5.1.1.2) function references are resolved in the final translation phase.

My main aggravation is that I can't find anything that confirms that this is standard behavior. I've run across comments in the past that said that you couldn't take the address of a function from within that function, which I thought were bogus at the time, but didn't really have the time or inclination to actually check it out, until now.


问:
Error trying to invoke chaincode using Node.js SDK
I am trying to implement Node.js SDK for my Hyperledger Fabric business network. My network has one organisation, four peers, one channel, solo ordered and one CA.

I have successful managed to issue the JWT identity for user Jim and org1 organization.

When I try to invoke the the chaincode using:

```<code>curl -s -X POST \
  http://localhost:4000/channels/c1/chaincodes/txman \
  -H "authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1MTAwODIyNzMsInVzZXJuYW1lIjoiSmltIiwib3JnTmFtZSI6Im9yZzEiLCJpYXQiOjE1MTAwNDYyNzN9.NTDYky6jj_y1COP163Z_HA6q4v7S1_jN6BxL00Bo-Xo" \
  -H "content-type: application/json" \
  -d '{
    "fcn":"queryTx",
    "args":["TX0"]
}'
</code>```

I am getting the following error:

```<code>2017-11-07 11:18:34.286] [DEBUG] SampleWebApp - Decoded from JWT token: username - Jim, orgname - org1
[2017-11-07 11:18:34.287] [DEBUG] SampleWebApp - ==================== INVOKE ON CHAINCODE ==================
[2017-11-07 11:18:34.287] [DEBUG] SampleWebApp - USERNAME: Jim
[2017-11-07 11:18:34.287] [DEBUG] SampleWebApp - ORGNAME: org1
[2017-11-07 11:18:34.287] [DEBUG] SampleWebApp - channelName  : c1
[2017-11-07 11:18:34.288] [DEBUG] SampleWebApp - chaincodeName : txman
[2017-11-07 11:18:34.288] [DEBUG] SampleWebApp - fcn  : queryTx
[2017-11-07 11:18:34.288] [DEBUG] SampleWebApp - args  : TX0
[2017-11-07 11:18:34.292] [DEBUG] invoke-chaincode -
============ invoke transaction on organization org1 ============

[2017-11-07 11:18:34.292] [DEBUG] Helper - [FileKeyValueStore.js]: FileKeyValueStore.js - constructor
[2017-11-07 11:18:34.293] [DEBUG] Helper - [FileKeyValueStore.js]: FileKeyValueStore -- getValue
[2017-11-07 11:18:34.298] [DEBUG] Helper - [crypto_ecdsa_aes]: importKey - start
[2017-11-07 11:18:34.298] [DEBUG] Helper - [crypto_ecdsa_aes]: importKey - have the key [Circular]
[2017-11-07 11:18:34.300] [DEBUG] Helper - [utils.CryptoKeyStore]: _getKeyStore resolving store
[2017-11-07 11:18:34.300] [DEBUG] Helper - [ecdsa/key.js]: ECDSA curve param X: c3cd1a318e957b0200852e4ed6c9601eadc8225eb9f79acc11b1c65df142446a
[2017-11-07 11:18:34.300] [DEBUG] Helper - [ecdsa/key.js]: ECDSA curve param Y: f7bbe9fd43eaae1a0a1d2eb3024ecd79bd63c39a8d1b3b978bc8b4a652d0ef63
[2017-11-07 11:18:34.301] [DEBUG] Helper - [FileKeyValueStore.js]: FileKeyValueStore -- setValue
[2017-11-07 11:18:34.303] [DEBUG] Helper - [utils.CryptoKeyStore]: _getKeyStore resolving store
[2017-11-07 11:18:34.303] [DEBUG] Helper - [FileKeyValueStore.js]: FileKeyValueStore -- getValue
[2017-11-07 11:18:34.304] [DEBUG] Helper - [ecdsa/key.js]: ECDSA curve param X: c3cd1a318e957b0200852e4ed6c9601eadc8225eb9f79acc11b1c65df142446a
[2017-11-07 11:18:34.304] [DEBUG] Helper - [ecdsa/key.js]: ECDSA curve param Y: f7bbe9fd43eaae1a0a1d2eb3024ecd79bd63c39a8d1b3b978bc8b4a652d0ef63
[2017-11-07 11:18:34.305] [DEBUG] Helper - [ecdsa/key.js]: ECDSA curve param X: c3cd1a318e957b0200852e4ed6c9601eadc8225eb9f79acc11b1c65df142446a
[2017-11-07 11:18:34.306] [DEBUG] Helper - [ecdsa/key.js]: ECDSA curve param Y: f7bbe9fd43eaae1a0a1d2eb3024ecd79bd63c39a8d1b3b978bc8b4a652d0ef63
[2017-11-07 11:18:34.308] [DEBUG] Helper - [ecdsa/key.js]: ECDSA curve param X: c3cd1a318e957b0200852e4ed6c9601eadc8225eb9f79acc11b1c65df142446a
[2017-11-07 11:18:34.308] [DEBUG] Helper - [ecdsa/key.js]: ECDSA curve param Y: f7bbe9fd43eaae1a0a1d2eb3024ecd79bd63c39a8d1b3b978bc8b4a652d0ef63
[2017-11-07 11:18:34.309] [DEBUG] Helper - [FileKeyValueStore.js]: FileKeyValueStore -- setValue
[2017-11-07 11:18:34.309] [INFO] Helper - Successfully loaded member from persistence
[2017-11-07 11:18:34.313] [DEBUG] invoke-chaincode - Sending transaction "{"_nonce":{"type":"Buffer","data":[218,130,209,154,87,123,73,36,118,155,194,91,27,250,14,216,117,202,164,5,16,237,96,208]},"_transaction_id":"dba107be47745c51eb75b6a927d68f0afd58b325c5e36326b40a729f9d858f43"}"
[2017-11-07 11:18:34.341] [DEBUG] Helper - [crypto_ecdsa_aes]: ecdsa signature:  Signature {
  r: <BN: cf5e0aaef0fd10d9abf468e025c6f6c1e8991d0dcddf5f5aa6b285ebdcd920ad>,
  s: <BN: 8de356dcfda3ba3fb0d6decfc0e43995b3297bc7037fd3997bfba561e6d626d>,
  recoveryParam: 0 }
error: [client-utils.js]: sendPeersProposal - Promise is rejected: Error: Failed to deserialize creator identity, err The supplied identity is not valid, Verify() returned x509: certificate signed by unknown authority (possibly because of "x509: ECDSA verification failure" while trying to verify candidate authority certificate "ca.org1.example.com")
    at /home/brankoterzic/Desktop/devGC/txman/node_modules/grpc/src/client.js:554:15
error: [client-utils.js]: sendPeersProposal - Promise is rejected: Error: Failed to deserialize creator identity, err The supplied identity is not valid, Verify() returned x509: certificate signed by unknown authority (possibly because of "x509: ECDSA verification failure" while trying to verify candidate authority certificate "ca.org1.example.com")
    at /home/brankoterzic/Desktop/devGC/txman/node_modules/grpc/src/client.js:554:15
error: [client-utils.js]: sendPeersProposal - Promise is rejected: Error: Failed to deserialize creator identity, err The supplied identity is not valid, Verify() returned x509: certificate signed by unknown authority (possibly because of "x509: ECDSA verification failure" while trying to verify candidate authority certificate "ca.org1.example.com")
    at /home/brankoterzic/Desktop/devGC/txman/node_modules/grpc/src/client.js:554:15
error: [client-utils.js]: sendPeersProposal - Promise is rejected: Error: Failed to deserialize creator identity, err The supplied identity is not valid, Verify() returned x509: certificate signed by unknown authority (possibly because of "x509: ECDSA verification failure" while trying to verify candidate authority certificate "ca.org1.example.com")
    at /home/brankoterzic/Desktop/devGC/txman/node_modules/grpc/src/client.js:554:15
error: [client-utils.js]: sendPeersProposal - Promise is rejected: Error: Failed to deserialize creator identity, err The supplied identity is not valid, Verify() returned x509: certificate signed by unknown authority (possibly because of "x509: ECDSA verification failure" while trying to verify candidate authority certificate "ca.org1.example.com")
    at /home/brankoterzic/Desktop/devGC/txman/node_modules/grpc/src/client.js:554:15
[2017-11-07 11:18:34.400] [ERROR] invoke-chaincode - transaction proposal was bad
[2017-11-07 11:18:34.401] [ERROR] invoke-chaincode - transaction proposal was bad
[2017-11-07 11:18:34.401] [ERROR] invoke-chaincode - transaction proposal was bad
[2017-11-07 11:18:34.401] [ERROR] invoke-chaincode - transaction proposal was bad
[2017-11-07 11:18:34.401] [ERROR] invoke-chaincode - transaction proposal was bad
[2017-11-07 11:18:34.401] [ERROR] invoke-chaincode - Failed to send Proposal or receive valid response. Response null or status is not 200. exiting...
[2017-11-07 11:18:34.401] [ERROR] invoke-chaincode - Failed to order the transaction. Error code: undefined
</code>```

I was following the balance-transfer Node.js example: https://github.com/hyperledger/fabric-samples/tree/release/balance-transfer

Thank you for your answers!

答:
I have solved this by setting up the generated crypto for CA

crypto-config/peerOrganizations/org1.example.com/ca/361a9254173cb1a97c057432094a20db9578ca69a152725f96323e00379c5ad6_sk

to

FABRIC_CA_SERVER_CA_KEYFILE=/etc/hyperledger/fabric-ca-server-config/361a9254173cb1a97c057432094a20db9578ca69a152725f96323e00379c5ad6_sk

in docker-compose-base.yaml env variable.

Body:
I am trying to implement Node.js SDK for my Hyperledger Fabric business network. My network has one organisation, four peers, one channel, solo ordered and one CA.

I have successful managed to issue the JWT identity for user Jim and org1 organization.

When I try to invoke the the chaincode using:

curl -s -X POST \
  http://localhost:4000/channels/c1/chaincodes/txman \
  -H "authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1MTAwODIyNzMsInVzZXJuYW1lIjoiSmltIiwib3JnTmFtZSI6Im9yZzEiLCJpYXQiOjE1MTAwNDYyNzN9.NTDYky6jj_y1COP163Z_HA6q4v7S1_jN6BxL00Bo-Xo" \
  -H "content-type: application/json" \
  -d '{
    "fcn":"queryTx",
    "args":["TX0"]
}'

I am getting the following error:

2017-11-07 11:18:34.286] [DEBUG] SampleWebApp - Decoded from JWT token: username - Jim, orgname - org1
[2017-11-07 11:18:34.287] [DEBUG] SampleWebApp - ==================== INVOKE ON CHAINCODE ==================
[2017-11-07 11:18:34.287] [DEBUG] SampleWebApp - USERNAME: Jim
[2017-11-07 11:18:34.287] [DEBUG] SampleWebApp - ORGNAME: org1
[2017-11-07 11:18:34.287] [DEBUG] SampleWebApp - channelName  : c1
[2017-11-07 11:18:34.288] [DEBUG] SampleWebApp - chaincodeName : txman
[2017-11-07 11:18:34.288] [DEBUG] SampleWebApp - fcn  : queryTx
[2017-11-07 11:18:34.288] [DEBUG] SampleWebApp - args  : TX0
[2017-11-07 11:18:34.292] [DEBUG] invoke-chaincode -
============ invoke transaction on organization org1 ============

[2017-11-07 11:18:34.292] [DEBUG] Helper - [FileKeyValueStore.js]: FileKeyValueStore.js - constructor
[2017-11-07 11:18:34.293] [DEBUG] Helper - [FileKeyValueStore.js]: FileKeyValueStore -- getValue
[2017-11-07 11:18:34.298] [DEBUG] Helper - [crypto_ecdsa_aes]: importKey - start
[2017-11-07 11:18:34.298] [DEBUG] Helper - [crypto_ecdsa_aes]: importKey - have the key [Circular]
[2017-11-07 11:18:34.300] [DEBUG] Helper - [utils.CryptoKeyStore]: _getKeyStore resolving store
[2017-11-07 11:18:34.300] [DEBUG] Helper - [ecdsa/key.js]: ECDSA curve param X: c3cd1a318e957b0200852e4ed6c9601eadc8225eb9f79acc11b1c65df142446a
[2017-11-07 11:18:34.300] [DEBUG] Helper - [ecdsa/key.js]: ECDSA curve param Y: f7bbe9fd43eaae1a0a1d2eb3024ecd79bd63c39a8d1b3b978bc8b4a652d0ef63
[2017-11-07 11:18:34.301] [DEBUG] Helper - [FileKeyValueStore.js]: FileKeyValueStore -- setValue
[2017-11-07 11:18:34.303] [DEBUG] Helper - [utils.CryptoKeyStore]: _getKeyStore resolving store
[2017-11-07 11:18:34.303] [DEBUG] Helper - [FileKeyValueStore.js]: FileKeyValueStore -- getValue
[2017-11-07 11:18:34.304] [DEBUG] Helper - [ecdsa/key.js]: ECDSA curve param X: c3cd1a318e957b0200852e4ed6c9601eadc8225eb9f79acc11b1c65df142446a
[2017-11-07 11:18:34.304] [DEBUG] Helper - [ecdsa/key.js]: ECDSA curve param Y: f7bbe9fd43eaae1a0a1d2eb3024ecd79bd63c39a8d1b3b978bc8b4a652d0ef63
[2017-11-07 11:18:34.305] [DEBUG] Helper - [ecdsa/key.js]: ECDSA curve param X: c3cd1a318e957b0200852e4ed6c9601eadc8225eb9f79acc11b1c65df142446a
[2017-11-07 11:18:34.306] [DEBUG] Helper - [ecdsa/key.js]: ECDSA curve param Y: f7bbe9fd43eaae1a0a1d2eb3024ecd79bd63c39a8d1b3b978bc8b4a652d0ef63
[2017-11-07 11:18:34.308] [DEBUG] Helper - [ecdsa/key.js]: ECDSA curve param X: c3cd1a318e957b0200852e4ed6c9601eadc8225eb9f79acc11b1c65df142446a
[2017-11-07 11:18:34.308] [DEBUG] Helper - [ecdsa/key.js]: ECDSA curve param Y: f7bbe9fd43eaae1a0a1d2eb3024ecd79bd63c39a8d1b3b978bc8b4a652d0ef63
[2017-11-07 11:18:34.309] [DEBUG] Helper - [FileKeyValueStore.js]: FileKeyValueStore -- setValue
[2017-11-07 11:18:34.309] [INFO] Helper - Successfully loaded member from persistence
[2017-11-07 11:18:34.313] [DEBUG] invoke-chaincode - Sending transaction "{"_nonce":{"type":"Buffer","data":[218,130,209,154,87,123,73,36,118,155,194,91,27,250,14,216,117,202,164,5,16,237,96,208]},"_transaction_id":"dba107be47745c51eb75b6a927d68f0afd58b325c5e36326b40a729f9d858f43"}"
[2017-11-07 11:18:34.341] [DEBUG] Helper - [crypto_ecdsa_aes]: ecdsa signature:  Signature {
  r: <BN: cf5e0aaef0fd10d9abf468e025c6f6c1e8991d0dcddf5f5aa6b285ebdcd920ad>,
  s: <BN: 8de356dcfda3ba3fb0d6decfc0e43995b3297bc7037fd3997bfba561e6d626d>,
  recoveryParam: 0 }
error: [client-utils.js]: sendPeersProposal - Promise is rejected: Error: Failed to deserialize creator identity, err The supplied identity is not valid, Verify() returned x509: certificate signed by unknown authority (possibly because of "x509: ECDSA verification failure" while trying to verify candidate authority certificate "ca.org1.example.com")
    at /home/brankoterzic/Desktop/devGC/txman/node_modules/grpc/src/client.js:554:15
error: [client-utils.js]: sendPeersProposal - Promise is rejected: Error: Failed to deserialize creator identity, err The supplied identity is not valid, Verify() returned x509: certificate signed by unknown authority (possibly because of "x509: ECDSA verification failure" while trying to verify candidate authority certificate "ca.org1.example.com")
    at /home/brankoterzic/Desktop/devGC/txman/node_modules/grpc/src/client.js:554:15
error: [client-utils.js]: sendPeersProposal - Promise is rejected: Error: Failed to deserialize creator identity, err The supplied identity is not valid, Verify() returned x509: certificate signed by unknown authority (possibly because of "x509: ECDSA verification failure" while trying to verify candidate authority certificate "ca.org1.example.com")
    at /home/brankoterzic/Desktop/devGC/txman/node_modules/grpc/src/client.js:554:15
error: [client-utils.js]: sendPeersProposal - Promise is rejected: Error: Failed to deserialize creator identity, err The supplied identity is not valid, Verify() returned x509: certificate signed by unknown authority (possibly because of "x509: ECDSA verification failure" while trying to verify candidate authority certificate "ca.org1.example.com")
    at /home/brankoterzic/Desktop/devGC/txman/node_modules/grpc/src/client.js:554:15
error: [client-utils.js]: sendPeersProposal - Promise is rejected: Error: Failed to deserialize creator identity, err The supplied identity is not valid, Verify() returned x509: certificate signed by unknown authority (possibly because of "x509: ECDSA verification failure" while trying to verify candidate authority certificate "ca.org1.example.com")
    at /home/brankoterzic/Desktop/devGC/txman/node_modules/grpc/src/client.js:554:15
[2017-11-07 11:18:34.400] [ERROR] invoke-chaincode - transaction proposal was bad
[2017-11-07 11:18:34.401] [ERROR] invoke-chaincode - transaction proposal was bad
[2017-11-07 11:18:34.401] [ERROR] invoke-chaincode - transaction proposal was bad
[2017-11-07 11:18:34.401] [ERROR] invoke-chaincode - transaction proposal was bad
[2017-11-07 11:18:34.401] [ERROR] invoke-chaincode - transaction proposal was bad
[2017-11-07 11:18:34.401] [ERROR] invoke-chaincode - Failed to send Proposal or receive valid response. Response null or status is not 200. exiting...
[2017-11-07 11:18:34.401] [ERROR] invoke-chaincode - Failed to order the transaction. Error code: undefined

I was following the balance-transfer Node.js example: https://github.com/hyperledger/fabric-samples/tree/release/balance-transfer

Thank you for your answers!


问:
Same request parameter several times results in a comma seperated string?
When passing the same request parameter in a URL several times:

```<code>mypage?lang=en&lang=co&lang=he
</code>```

When looking on the server side, it seems that it's translated to a comma seperated string:

```<code>string Lang = Request.Params["lang"];
// Lang = "en,co,he"
</code>```

Is this normal behaviour? Is there any server side setting or a proper coding way to eliminate this behaviour and get only the first value and dismiss all other parameters? By dismissing, I mean "clean" all other URL parameters from the query string (I find this cannot be done so easily).

答:
If you are certain that you will always want to use the first param and use en then you can do this as well

```<code>var langParams =  Request.Params["lang"].Split(
                  new string[] {","},
                  StringSplitOptions.None)[0];
</code>```

This will return en

Body:
When passing the same request parameter in a URL several times:

mypage?lang=en&lang=co&lang=he

When looking on the server side, it seems that it's translated to a comma seperated string:

string Lang = Request.Params["lang"];
// Lang = "en,co,he"

Is this normal behaviour? Is there any server side setting or a proper coding way to eliminate this behaviour and get only the first value and dismiss all other parameters? By dismissing, I mean "clean" all other URL parameters from the query string (I find this cannot be done so easily).

Body:
If you are certain that you will always want to use the first param and use en then you can do this as well

var langParams =  Request.Params["lang"].Split(
                  new string[] {","},
                  StringSplitOptions.None)[0];

This will return en


问:
Google Calendar API gives 404 while inserting events to calendar after pods updation.
i integrated google calendar in my iOS application, and insert events from application using this Call "
https://www.googleapis.com/calendar/v3/calendars/primary/events "
and events inserted sucessfully in my google calendar

i updated pods due to ios 11 now this api
now it gives this error in response. cant figure it out where the problem is.

ERROR: Invalid value for: Invalid format: \"2017-12-07 07:00:00\" is malformed at \" 07:00:00\

答:
The error prolly is due to wrong time format. Follow the RFC3339 for date time formats. It looks something like:

```<code>2015-05-28T09:00:00-07:00
</code>```

Notice the letter T which stands for full date/full-time.

Body:
The error prolly is due to wrong time format. Follow the RFC3339 for date time formats. It looks something like:

2015-05-28T09:00:00-07:00

Notice the letter T which stands for full date/full-time.


问:
C# service not starting on first reboot
I have a windows service written in C# 4.61.  On a unpatched Windows 2008R2, Windows 2012R2, or Windows 2016 server it refuses to start automatically on the first reboot after install.

I even have it set to Automatic (Delayed Start) and it still gives the error:

```<code>Entry 1

A timeout was reached (30000 milliseconds) while waiting for (servicename) service to connect.

Entry 2

The (servicename) service failed to start due to the following error: The service did not respond to the start or control request in a timely fashion.
</code>```

On any reboot from then on it starts with no issue.

I know that the proper thing would be to patch the system, however I would like to be able to identify what hotfix/update corrects this problem.

Throughout all the searching that I have done, most people suggest to extend the global service timeout to correct this issue, and that is not acceptable for me to go changing global settings on someones production machines.

I know that the issue is not how long my service takes to start, as manually starting it only takes a few seconds.

答:
You should try this :</p>

```<code>System.Threading.Tasks.Task.Run(() =>
{
    this.YourFunction();
});

private void YourFunction()
{
    // Your code
}
</code>```

Title: C# service not starting on first reboot

Body:
I have a windows service written in C# 4.61.  On a unpatched Windows 2008R2, Windows 2012R2, or Windows 2016 server it refuses to start automatically on the first reboot after install.

I even have it set to Automatic (Delayed Start) and it still gives the error:

Entry 1

A timeout was reached (30000 milliseconds) while waiting for (servicename) service to connect.

Entry 2

The (servicename) service failed to start due to the following error: The service did not respond to the start or control request in a timely fashion.

On any reboot from then on it starts with no issue.

I know that the proper thing would be to patch the system, however I would like to be able to identify what hotfix/update corrects this problem.

Throughout all the searching that I have done, most people suggest to extend the global service timeout to correct this issue, and that is not acceptable for me to go changing global settings on someones production machines.

I know that the issue is not how long my service takes to start, as manually starting it only takes a few seconds.

Body:
You should try this :

System.Threading.Tasks.Task.Run(() =>
{
    this.YourFunction();
});

private void YourFunction()
{
    // Your code
}


问:
QueryException SQLSTATE[42S02]: Base table or view not found: 1146 Table
i learn foreign key in laravel for the first time .. i have this message error when i insert data on the form to table . i think my table is fine. can u tell me how to solve this ?

Controller :

```<code>public function tambah(Request $request){
    $a = new Admin;
    $this->validate($request, ['nama'=>'required|unique:ab']);
    $a->id = $request->id;
    $a->nama = $request->nama;
    $a->save();

    return redirect()->to('admin/data_desa')->with('success','Data berhasil ditambahkan');
}

}
</code>```

table :

```<code> class CreateDesasTable extends Migration
 {
/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    //
    Schema::dropIfExist('desas');
    Schema::create('desas', function(Blueprint $table){
    $table->increments('id');
    $table->string('nama');

});
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    //
    Schema::dropIfExist('desas');

}
}
</code>```

Route :

```<code>Route::group(['middleware' => 'web'], function(){
Route::group(['prefix' => 'tanitani'], function(){
    Route::get('admin', 'AdminController@index');
    Route::get('admin/data_desa','AdminController@tampil');
    Route::post('admin/data_desa', 'AdminController@tambah');
</code>```

答:
You have tou override the table name ih the Admin model, since you have a different table name.

Why ?

Because by convetion Laravel will assume that the table name is admins.

So add this line to your model :

```<code>protected $table = 'desas';
</code>```

Body:
i learn foreign key in laravel for the first time .. i have this message error when i insert data on the form to table . i think my table is fine. can u tell me how to solve this ?

Controller :

public function tambah(Request $request){
    $a = new Admin;
    $this->validate($request, ['nama'=>'required|unique:ab']);
    $a->id = $request->id;
    $a->nama = $request->nama;
    $a->save();

    return redirect()->to('admin/data_desa')->with('success','Data berhasil ditambahkan');
}

}

table :

 class CreateDesasTable extends Migration
 {
/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    //
    Schema::dropIfExist('desas');
    Schema::create('desas', function(Blueprint $table){
    $table->increments('id');
    $table->string('nama');

});
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    //
    Schema::dropIfExist('desas');

}
}

Route :

Route::group(['middleware' => 'web'], function(){
Route::group(['prefix' => 'tanitani'], function(){
    Route::get('admin', 'AdminController@index');
    Route::get('admin/data_desa','AdminController@tampil');
    Route::post('admin/data_desa', 'AdminController@tambah');

Body:
You have tou override the table name ih the Admin model, since you have a different table name.

Why ?

Because by convetion Laravel will assume that the table name is admins.

So add this line to your model :

protected $table = 'desas';


问:
Octave - Excel - Xlsread reads Nan instead of text
The Universities spread sheat in Excel include:

```<code>ID & University Name
0    Mechanical Engineering
1    Civil Engineering

filename = 'test.xlsx';
sheet = 'Universities';
xlRange = 'A2:B31';
UniversityNames = xlsread(filename,sheet,xlRange);
</code>```

but when I display universitynames matrix. I can see ID number but university Name is displayed as 'NaN'. I need to see names of university in this UniversityNames matrix. How can I fix this? OS is Windows 10, Excel 2010.

答:
Octave's xlsread function has multiple outputs. The first output returned is the numeric data from the input range, which is what you're currently reading in as UniversityNames. The optional second output returns the text strings from the input range, which I'm assuming is what you're looking for. You can also utilize the optional third output, which returns a cell array of the raw strings from the input range.

```<code>filename = 'test.xlsx';
sheet = 'Universities';
xlRange = 'A2:B31';
[UniversityNames_numeric, UniversityNames_textual] = xlsread(filename, sheet, xlRange);
</code>```

Or

```<code>filename = 'test.xlsx';
sheet = 'Universities';
xlRange = 'A2:B31';
[~, ~, rawdata] = xlsread(filename, sheet, xlRange);
</code>```

Body:
The Universities spread sheat in Excel include:

ID & University Name
0    Mechanical Engineering
1    Civil Engineering

filename = 'test.xlsx';
sheet = 'Universities';
xlRange = 'A2:B31';
UniversityNames = xlsread(filename,sheet,xlRange);

but when I display universitynames matrix. I can see ID number but university Name is displayed as 'NaN'. I need to see names of university in this UniversityNames matrix. How can I fix this? OS is Windows 10, Excel 2010.

Body:
Octave's xlsread function has multiple outputs. The first output returned is the numeric data from the input range, which is what you're currently reading in as UniversityNames. The optional second output returns the text strings from the input range, which I'm assuming is what you're looking for. You can also utilize the optional third output, which returns a cell array of the raw strings from the input range.

filename = 'test.xlsx';
sheet = 'Universities';
xlRange = 'A2:B31';
[UniversityNames_numeric, UniversityNames_textual] = xlsread(filename, sheet, xlRange);

Or

filename = 'test.xlsx';
sheet = 'Universities';
xlRange = 'A2:B31';
[~, ~, rawdata] = xlsread(filename, sheet, xlRange);


问:
Python: how to increment number and store in variable every time function runs
(I'm a beginner in Python, just so you know)

What I'm trying to do: I want to keep count of how many times a user choose a wrong option and if it exceeds a number of times, he fails.

My approach was to store the count in a variable within a function and check with if/else statement if the number of times is exceeded.

Part of the code:

```<code>    choice = int(input("> "))

if choice == 1:
    print("This is the wrong hall.")
    increment()
elif choice == 2:
    print("This is the wrong hall.")
    increment()
elif choice == 3:
    hall_passage()
else:
    end("You failed")

COUNT = 0
def increment():
    global COUNT
    COUNT += 1

increment()

print(COUNT)
</code>```

The increment part is from this thread and read using global scope is not a good practice.

The part I don't really understand is how you store count in a variable and it remembers the last value every time the function runs.

What is the best way to do this?

答:
maybe something like this...</p>

```<code>class Counter():
    def __init__(self):
        self.counter = 0

    def increment(self):
        self.counter += 1

    def reset(self):
        self.counter = 0

    def get_value(self):
        return self.counter

mc = Counter()

while mc.get_value() < 3:
    v = int(input('a number: '))
    if v == 1:
        print('You won!')
        mc.counter = 3
    else:
        print('Wrong guess, guess again...')
        if mc.counter == 2:
            print('Last guess...')
        mc.increment()
</code>```

Body:
(I'm a beginner in Python, just so you know)

What I'm trying to do: I want to keep count of how many times a user choose a wrong option and if it exceeds a number of times, he fails.

My approach was to store the count in a variable within a function and check with if/else statement if the number of times is exceeded.

Part of the code:

    choice = int(input("> "))

if choice == 1:
    print("This is the wrong hall.")
    increment()
elif choice == 2:
    print("This is the wrong hall.")
    increment()
elif choice == 3:
    hall_passage()
else:
    end("You failed")

COUNT = 0
def increment():
    global COUNT
    COUNT += 1

increment()

print(COUNT)

The increment part is from this thread and read using global scope is not a good practice.

The part I don't really understand is how you store count in a variable and it remembers the last value every time the function runs.

What is the best way to do this?

Body:
maybe something like this...

class Counter():
    def __init__(self):
        self.counter = 0

    def increment(self):
        self.counter += 1

    def reset(self):
        self.counter = 0

    def get_value(self):
        return self.counter

mc = Counter()

while mc.get_value() < 3:
    v = int(input('a number: '))
    if v == 1:
        print('You won!')
        mc.counter = 3
    else:
        print('Wrong guess, guess again...')
        if mc.counter == 2:
            print('Last guess...')
        mc.increment()


问:
MySql - vacancy query and group by
Got a problem finding vacancies over a week in a booking system.
I can get the NULL items no problem, but the issue is that bookings can have any of four values: enquiry, optioned, paid or cancelled.
(status in example below - values being 1,2,3 or 4)

So if in a week I have any that are "enquiry, optioned or paid" then I do not show the item - it's regarded as in use.
If they are cancelled that counts as empty - but within that week I can have multiple bookings, so if another booking was "enquiry, optioned or paid" then the item is not empty for that week.
There's my problem : I seem to need a GROUP BY on the subclause and then another GROUP BY conditional on that.

Here's what I have

```<code>SELECT unit_num FROM unitmap
LEFT OUTER JOIN bookings ON bookings.unit_ref_id=unitmap.unit_id
AND (bookings.end_d>='".$start."' AND bookings.start_d<='".$end."')
WHERE (bk_id IS NULL OR status>=4)
GROUP BY unit_id
</code>```

This is wrong in that I get the item if it has BOTH a cancelled and an 'active' booking, whereas I want to see it if it's ONLY got a cancelled (or is null). I've tried lots of things!

```<code>id     unit    datestart  dateend       status
1     21      2017-12-15   2017-12-30     2
2     21      2017-12-11   2017-12-12     4
3     13      2017-12-15   2017-12-30     4
4     13      2017-12-11   2017-12-12     4
5     14      2017-12-15   2017-12-30     2
</code>```

For week starting 11 Dec:

Unit 21 would not show in vacancies table as it has an active booking (id 1 with status 2).

Unit 13 would show as both bookings were cancelled (status 4).

Unit 14 has an active booking (id 5 with status 2) so would not show.

(All the other unlisted units would show as they have a NULL booking id)

答:
Start with the query that gives you the bookings

```<code>SELECT unit_ref_id FROM bookings
 WHERE bookings.end_d>='".$start."' AND bookings.start_d<='".$end."' AND status in (1,2,3)
</code>```

Right? Now join that to your units table, with a left join, and select only the ones that have no matching record on this booked units query.

```<code>SELECT unit_num
  FROM unitmap
       LEFT JOIN
          (SELECT unit_ref_id FROM bookings
            WHERE (bookings.end_d>='".$start."' AND bookings.start_d<='".$end."' AND status in (1,2,3))
        AS BookedUnits
        ON unitmap.unit_id = BookedUnits.unit_ref_id
WHERE BookedUnits.unit_ref_id is null
</code>```

If the unit has any (1 or more) bookings that match those conditions in the first query, in the second query (without the where clause) that unit would show one or more times (once for each booking) with a unit_ref_id that is NOT null.  But the ones that have NO bookings will show only once, with a NULL in the BookedUnits.unit_ref_id.  The WHERE clause at the end then picks out only those that have no bookings - null BookedUnits.unit_ref_id.

Depending on your data and what you find most readable, you might be able to say status < 4 rather than status in (1,2,3).

You could add a DISTINCT qualifier to that inner query (SELECT DISTINCT unit_ref_id FROM bookings...).  Depending on your data and the queries you get (what start and end dates), that might be more efficient, but I doubt you will ever notice the difference one way or another.

Title: MySql - vacancy query and group by

Body:
Got a problem finding vacancies over a week in a booking system.
I can get the NULL items no problem, but the issue is that bookings can have any of four values: enquiry, optioned, paid or cancelled.
(status in example below - values being 1,2,3 or 4)

So if in a week I have any that are "enquiry, optioned or paid" then I do not show the item - it's regarded as in use.
If they are cancelled that counts as empty - but within that week I can have multiple bookings, so if another booking was "enquiry, optioned or paid" then the item is not empty for that week.
There's my problem : I seem to need a GROUP BY on the subclause and then another GROUP BY conditional on that.

Here's what I have

SELECT unit_num FROM unitmap
LEFT OUTER JOIN bookings ON bookings.unit_ref_id=unitmap.unit_id
AND (bookings.end_d>='".$start."' AND bookings.start_d<='".$end."')
WHERE (bk_id IS NULL OR status>=4)
GROUP BY unit_id

This is wrong in that I get the item if it has BOTH a cancelled and an 'active' booking, whereas I want to see it if it's ONLY got a cancelled (or is null). I've tried lots of things!

id     unit    datestart  dateend       status
1     21      2017-12-15   2017-12-30     2
2     21      2017-12-11   2017-12-12     4
3     13      2017-12-15   2017-12-30     4
4     13      2017-12-11   2017-12-12     4
5     14      2017-12-15   2017-12-30     2

For week starting 11 Dec:

Unit 21 would not show in vacancies table as it has an active booking (id 1 with status 2).

Unit 13 would show as both bookings were cancelled (status 4).

Unit 14 has an active booking (id 5 with status 2) so would not show.

(All the other unlisted units would show as they have a NULL booking id)

Body:
Start with the query that gives you the bookings

SELECT unit_ref_id FROM bookings
 WHERE bookings.end_d>='".$start."' AND bookings.start_d<='".$end."' AND status in (1,2,3)

Right? Now join that to your units table, with a left join, and select only the ones that have no matching record on this booked units query.

SELECT unit_num
  FROM unitmap
       LEFT JOIN
          (SELECT unit_ref_id FROM bookings
            WHERE (bookings.end_d>='".$start."' AND bookings.start_d<='".$end."' AND status in (1,2,3))
        AS BookedUnits
        ON unitmap.unit_id = BookedUnits.unit_ref_id
WHERE BookedUnits.unit_ref_id is null

If the unit has any (1 or more) bookings that match those conditions in the first query, in the second query (without the where clause) that unit would show one or more times (once for each booking) with a unit_ref_id that is NOT null.  But the ones that have NO bookings will show only once, with a NULL in the BookedUnits.unit_ref_id.  The WHERE clause at the end then picks out only those that have no bookings - null BookedUnits.unit_ref_id.

Depending on your data and what you find most readable, you might be able to say status < 4 rather than status in (1,2,3).

You could add a DISTINCT qualifier to that inner query (SELECT DISTINCT unit_ref_id FROM bookings...).  Depending on your data and the queries you get (what start and end dates), that might be more efficient, but I doubt you will ever notice the difference one way or another.


问:
Can we read the google sheet of specific version?
Scenario: Multiple people are working on a single google sheet, hence it is getting updated constantly. I've a java program to read the google sheet data of the current version.
However, I want to read the data of a particular time stamp or the named version.

For example: I want to get only the data of "Version 1.2". So that the further updates to this version doesn't affect my work.

答:
You can use the Revision methods in Drive API. First call the Revisions.list to get a list of changes that happened. After obtaining the revisionId, use Revisions.get to obtain that revision.

Hope that helps.


问:
How to easily output x to the power of n as a string
I need to output large numbers like for example 847288609443 as 3⁴⁵. All of my numbers have the form 3^n or 3^n -1. I use the hints from this post. For now my code looks like :

```<code>public static void main(String[] args) throws IOException {
   Map<String,Character> map = new HashMap<>();
   map.put("-", '\u207b');       map.put("5", '\u2075');
   map.put("0", '\u2070');       map.put("6", '\u2076');
   map.put("1", '\u00b9');       map.put("7", '\u2077');
   map.put("2", '\u00b2');       map.put("8", '\u2078');
   map.put("3", '\u00b3');       map.put("9", '\u2079');
   map.put("4", '\u2074');

   for(int i = 1; i< 50; i++){
       String [] s = String.valueOf(i).split("");
       StringBuilder sb = new StringBuilder();
       sb.append("3");
       Stream.of(s).forEach(e->sb.append(map.get(e)));
       System.out.println(sb.toString());
   }
}
</code>```

unicode values are from this wiki page:(https://en.wikipedia.org/wiki/Unicode_subscripts_and_superscripts)

Is there another way of doing such a conversion instead of spliting the string value of my exponents and appending unicode chars?

答:
You can implement this as a mapping of codepoints. Here is an implementation for non-negative numbers:

```<code>private static final int[] superCodepoint = new int[] {
'\u2070', '\u00b9', '\u00b2', '\u00b3', '\u2074', '\u2075', '\u2076', '\u2077', '\u2078', '\u2079'
};
public static String ToSuperscript(String s) {
    return s.codePoints()
        .map(c -> Character.isDigit(c) ? superCodepoint[Character.digit(c, 10)] : c)
        .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
        .toString();
}
</code>```

Demo.

Body:
I need to output large numbers like for example 847288609443 as 3⁴⁵. All of my numbers have the form 3^n or 3^n -1. I use the hints from this post. For now my code looks like :

public static void main(String[] args) throws IOException {
   Map<String,Character> map = new HashMap<>();
   map.put("-", '\u207b');       map.put("5", '\u2075');
   map.put("0", '\u2070');       map.put("6", '\u2076');
   map.put("1", '\u00b9');       map.put("7", '\u2077');
   map.put("2", '\u00b2');       map.put("8", '\u2078');
   map.put("3", '\u00b3');       map.put("9", '\u2079');
   map.put("4", '\u2074');

   for(int i = 1; i< 50; i++){
       String [] s = String.valueOf(i).split("");
       StringBuilder sb = new StringBuilder();
       sb.append("3");
       Stream.of(s).forEach(e->sb.append(map.get(e)));
       System.out.println(sb.toString());
   }
}

unicode values are from this wiki page:(https://en.wikipedia.org/wiki/Unicode_subscripts_and_superscripts)

Is there another way of doing such a conversion instead of spliting the string value of my exponents and appending unicode chars?

Body:
You can implement this as a mapping of codepoints. Here is an implementation for non-negative numbers:

private static final int[] superCodepoint = new int[] {
'\u2070', '\u00b9', '\u00b2', '\u00b3', '\u2074', '\u2075', '\u2076', '\u2077', '\u2078', '\u2079'
};
public static String ToSuperscript(String s) {
    return s.codePoints()
        .map(c -> Character.isDigit(c) ? superCodepoint[Character.digit(c, 10)] : c)
        .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
        .toString();
}

Demo.


问:
Resume music using Service when we Resume the application
I'm developing an application, which plays music in the background by using service.
Music stops when we hit back app will be paused and but, music is not resuming when I get back to the application.

```<code>public class backService extends Service implements ComponentCallbacks2 {
    private MediaPlayer mp;
    SharedPreferences sharedpreferences;
    public Boolean musicSwitch;

 @Override
 public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
 }

 @Override
 public void onDestroy() {
 super.onDestroy();
 if (mp != null){
        mp.stop();
        mp.release();
  }
}

@Override
public void onCreate() {
    super.onCreate();
    sharedpreferences = getSharedPreferences(mypreference,
            Context.MODE_PRIVATE);
    musicSwitch = sharedpreferences.getBoolean("music", true);
    if(musicSwitch){
        mp = MediaPlayer.create(this, R.raw.all);
        mp.setLooping(true);
        mp.start();
    }
}

@Override
public void onTrimMemory(final int level) {
    if (level == ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN) {
        if(mp != null){
            mp.pause();
        }
    }
}

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}
    }
</code>```

I want the application to resume music when we get back to the application, I have tried using onResume method, but there is no onResume method in services.
TIA

答:
1) You need to create foreground service to prevent it from killing by OS
How can we prevent a Service from being killed by OS?

2) You can bind service (bindService(serviceIntent)) and use Binder interface
https://developer.android.com/guide/components/bound-services.html#Binder

```<code>public class LocalService extends Service {
// Binder given to clients
private final IBinder mBinder = new LocalBinder();
// Random number generator
private final Random mGenerator = new Random();

/**
 * Class used for the client Binder.  Because we know this service always
 * runs in the same process as its clients, we don't need to deal with IPC.
 */
public class LocalBinder extends Binder {
    LocalService getService() {
        // Return this instance of LocalService so clients can call public methods
        return LocalService.this;
    }
}

@Override
public IBinder onBind(Intent intent) {
    return mBinder;
}

/** method for clients */
public int getRandomNumber() {
  return mGenerator.nextInt(100);
}
}
</code>```

Activity:

```<code>public class BindingActivity extends Activity {
LocalService mService;
boolean mBound = false;

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

@Override
protected void onStart() {
    super.onStart();
    // Bind to LocalService
    Intent intent = new Intent(this, LocalService.class);
    bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}

@Override
protected void onStop() {
    super.onStop();
    unbindService(mConnection);
    mBound = false;
}

/** Called when a button is clicked (the button in the layout file attaches to
  * this method with the android:onClick attribute) */
public void onButtonClick(View v) {
    if (mBound) {
        // Call a method from the LocalService.
        // However, if this call were something that might hang, then this request should
        // occur in a separate thread to avoid slowing down the activity performance.
        int num = mService.getRandomNumber();
        Toast.makeText(this, "number: " + num, Toast.LENGTH_SHORT).show();
    }
}

/** Defines callbacks for service binding, passed to bindService() */
private ServiceConnection mConnection = new ServiceConnection() {

    @Override
    public void onServiceConnected(ComponentName className,
            IBinder service) {
        // We've bound to LocalService, cast the IBinder and get LocalService instance
        LocalBinder binder = (LocalBinder) service;
        mService = binder.getService();
        mBound = true;
    }

    @Override
    public void onServiceDisconnected(ComponentName arg0) {
        mBound = false;
    }
}
}
</code>```

3) Then, in your activity onResume you can call method from your Binder to control music

Body:
I'm developing an application, which plays music in the background by using service.
Music stops when we hit back app will be paused and but, music is not resuming when I get back to the application.

public class backService extends Service implements ComponentCallbacks2 {
    private MediaPlayer mp;
    SharedPreferences sharedpreferences;
    public Boolean musicSwitch;

 @Override
 public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
 }

 @Override
 public void onDestroy() {
 super.onDestroy();
 if (mp != null){
        mp.stop();
        mp.release();
  }
}

@Override
public void onCreate() {
    super.onCreate();
    sharedpreferences = getSharedPreferences(mypreference,
            Context.MODE_PRIVATE);
    musicSwitch = sharedpreferences.getBoolean("music", true);
    if(musicSwitch){
        mp = MediaPlayer.create(this, R.raw.all);
        mp.setLooping(true);
        mp.start();
    }
}

@Override
public void onTrimMemory(final int level) {
    if (level == ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN) {
        if(mp != null){
            mp.pause();
        }
    }
}

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}
    }

I want the application to resume music when we get back to the application, I have tried using onResume method, but there is no onResume method in services.
TIA

Body:
1) You need to create foreground service to prevent it from killing by OS
How can we prevent a Service from being killed by OS?

2) You can bind service (bindService(serviceIntent)) and use Binder interface
https://developer.android.com/guide/components/bound-services.html#Binder

public class LocalService extends Service {
// Binder given to clients
private final IBinder mBinder = new LocalBinder();
// Random number generator
private final Random mGenerator = new Random();

/**
 * Class used for the client Binder.  Because we know this service always
 * runs in the same process as its clients, we don't need to deal with IPC.
 */
public class LocalBinder extends Binder {
    LocalService getService() {
        // Return this instance of LocalService so clients can call public methods
        return LocalService.this;
    }
}

@Override
public IBinder onBind(Intent intent) {
    return mBinder;
}

/** method for clients */
public int getRandomNumber() {
  return mGenerator.nextInt(100);
}
}

Activity:

public class BindingActivity extends Activity {
LocalService mService;
boolean mBound = false;

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

@Override
protected void onStart() {
    super.onStart();
    // Bind to LocalService
    Intent intent = new Intent(this, LocalService.class);
    bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}

@Override
protected void onStop() {
    super.onStop();
    unbindService(mConnection);
    mBound = false;
}

/** Called when a button is clicked (the button in the layout file attaches to
  * this method with the android:onClick attribute) */
public void onButtonClick(View v) {
    if (mBound) {
        // Call a method from the LocalService.
        // However, if this call were something that might hang, then this request should
        // occur in a separate thread to avoid slowing down the activity performance.
        int num = mService.getRandomNumber();
        Toast.makeText(this, "number: " + num, Toast.LENGTH_SHORT).show();
    }
}

/** Defines callbacks for service binding, passed to bindService() */
private ServiceConnection mConnection = new ServiceConnection() {

    @Override
    public void onServiceConnected(ComponentName className,
            IBinder service) {
        // We've bound to LocalService, cast the IBinder and get LocalService instance
        LocalBinder binder = (LocalBinder) service;
        mService = binder.getService();
        mBound = true;
    }

    @Override
    public void onServiceDisconnected(ComponentName arg0) {
        mBound = false;
    }
}
}

3) Then, in your activity onResume you can call method from your Binder to control music


问:
Read two columns and draw the graph
I already asked my problem: How to read two columns using python, but my goal is to draw a graph oX = f(oY).

I tried with:

```<code>import matplotlib.pyplot as plt
from matplotlib import style
import csv

with open('file.csv') as f:
    reader = csv.reader(f)
    for row in reader:
        res = row[0].split()
        oX = res[0]
        oY = res[1]
        print (oX , oY)
</code>```

It does not work for me.

答:
Plotting labels (strings) using scatter is only possible if you are using matplotlib 2.1.0 or higher. 2.1.0 is the latest stable release at the time of writing this answer.

```<code>import pandas as pd
import json
from matplotlib import pyplot as plt

import csv
x = []
y = []
with open('e:/projects/data.txt') as f:
    reader = csv.reader(f)
    for row in reader:
        res = row[0].split()
        oX = res[0]
        oY = res[1]
        x.append(oX)
        y.append(oY)
        print (oX, oY)
</code>```

Using your original code only the last coordinate in your input file is plotted. You need to store oX and oY in a list, for example in x and y.

```<code>plt.scatter (x, y, linewidth = 0.1, color = "black", label = 'V')
plt.show ()
</code>```

Using the input from your other questions, your graph should look like this

Title: Read two columns and draw the graph

Body:
I already asked my problem: How to read two columns using python, but my goal is to draw a graph oX = f(oY).

I tried with:

import matplotlib.pyplot as plt
from matplotlib import style
import csv

with open('file.csv') as f:
    reader = csv.reader(f)
    for row in reader:
        res = row[0].split()
        oX = res[0]
        oY = res[1]
        print (oX , oY)

It does not work for me.

Body:
Plotting labels (strings) using scatter is only possible if you are using matplotlib 2.1.0 or higher. 2.1.0 is the latest stable release at the time of writing this answer.

import pandas as pd
import json
from matplotlib import pyplot as plt

import csv
x = []
y = []
with open('e:/projects/data.txt') as f:
    reader = csv.reader(f)
    for row in reader:
        res = row[0].split()
        oX = res[0]
        oY = res[1]
        x.append(oX)
        y.append(oY)
        print (oX, oY)

Using your original code only the last coordinate in your input file is plotted. You need to store oX and oY in a list, for example in x and y.

plt.scatter (x, y, linewidth = 0.1, color = "black", label = 'V')
plt.show ()

Using the input from your other questions, your graph should look like this


问:
Linkage of formal parameters
I have a function say foo defined as

```<code>void foo (int foo_arg)
{
  printf("%d",foo_arg);
}
</code>```

What is the linkage type of foo_arg?

答:
In C there  are three kinds of linkage: external, internal, and none.

Formal parameters have no linkage

Section 6.2.2/6 (ISO C99)

The following identiﬁers have no linkage:

an identiﬁer declared to be anything other than
an object or a function;

an identiﬁer declared to be a function parameter;

a block scope
identiﬁer for an object declared without the storage-class speciﬁer extern.

Also read this thread.

ContentLicense: CC BY-SA 2.5

Title: Linkage of formal parameters

Body:
I have a function say foo defined as

void foo (int foo_arg)
{
  printf("%d",foo_arg);
}

What is the linkage type of foo_arg?


问:
RabbitMQ: Message Queue loses its Consumers
I have a Message Queue which loses its Consumers from time to time.

What could be the possible reasons for this? And how can I prevent this from happening?

答:
What could be the possible reasons for this?

The most obvious reason is your client application stopping or crashing. Without more information, it is impossible to answer this question.


问:
Is there a way to turn on ES6/ES7 syntax support in vscode?
Edit 3:  Starting in version 0.4.0, ES6 syntax can be turned on by adding a jsconfig.json file to the project folder with the following contents:

```<code>{
    "compilerOptions": {
        "target": "ES6"
    }
}
</code>```

Edit 2:  You can vote for this feature on user voice

Is there a way to "turn on" ES6/ES7 in Visual Studio Code?

Edit 1

Tried @sarvesh's suggestion- overrode javascript.validate.target and restarted vscode.  Didn't help.

答:
As of this date and according to the ESLint docs on the VSCode Marketplace, including a .eslintrc configuration file in the root of the project enables ES6 linting in the ESLint VSCode extension.

My .eslintrc config file looks like this:

```<code>extends:
  - standard
parser: babel-eslint
rules:
  object-curly-spacing: [ error, always ]
  react/prop-types: off
  space-before-function-paren: off
</code>```

I have eslint installed via npm in node_modules and all I know is that with .eslintrc in the project root folder ES6 linting works and without it, it doesn't.

Hope this helps...

Body:
Edit 3:  Starting in version 0.4.0, ES6 syntax can be turned on by adding a jsconfig.json file to the project folder with the following contents:

{
    "compilerOptions": {
        "target": "ES6"
    }
}

Edit 2:  You can vote for this feature on user voice

Is there a way to "turn on" ES6/ES7 in Visual Studio Code?

Edit 1

Tried @sarvesh's suggestion- overrode javascript.validate.target and restarted vscode.  Didn't help.

Body:
As of this date and according to the ESLint docs on the VSCode Marketplace, including a .eslintrc configuration file in the root of the project enables ES6 linting in the ESLint VSCode extension.

My .eslintrc config file looks like this:

extends:
  - standard
parser: babel-eslint
rules:
  object-curly-spacing: [ error, always ]
  react/prop-types: off
  space-before-function-paren: off

I have eslint installed via npm in node_modules and all I know is that with .eslintrc in the project root folder ES6 linting works and without it, it doesn't.

Hope this helps...


问:
Js - solving challenge Range Sum Query - Immutable with creating object and its properties
I was going through the problems on leetcode site, and saw a problem that I don't know how to approach. This is how they explain it:

Given an integer array nums, find the sum of the elements between
  indices i and j (i ≤ j), inclusive.

Example: Given nums = [-2, 0, 3, -5, 2, -1]

sumRange(0, 2) -> 1 sumRange(2, 5) -> -1 sumRange(0, 5) -> -3 Note:
  You may assume that the array does not change. There are many calls to
  sumRange function.

And this is the code:

```<code>/**
 * @param {number[]} nums
 */
var NumArray = function(nums) {
   this.nums = nums;
};

/**
 * @param {number} i
 * @param {number} j
 * @return {number}
 */
NumArray.prototype.sumRange = function(i, j) {
    let sum = 0;
    for (i; i <= j; i++) {
        sum += this[i];
    }
    return sum;
};

/**
 * Your NumArray object will be instantiated and called as such:
 * var obj = Object.create(NumArray).createNew(nums)
 * var param_1 = obj.sumRange(i,j)
 */
</code>```

What I don't know how to do is, or what exactly it means is this part:

```<code>var obj = Object.create(NumArray).createNew(nums)
</code>```

Am I suppose to create a property createNew that takes mums and creats and array, and why should I do that if the nums are already sent as an array?

答:
what exactly it means is this part:

```<code>var obj = Object.create(NumArray).createNew(nums)
</code>```

They messed it up and meant simply var obj = new NumArray(nums) (which still is unnecessarily complicated for a functional language like JS).

Apparently the description was changed at some point by someone clueless, as all the old JavaScript submissions in the discussion section (e.g. this one) have the correct code in the comment.

Body:
I was going through the problems on leetcode site, and saw a problem that I don't know how to approach. This is how they explain it:

Given an integer array nums, find the sum of the elements between
  indices i and j (i ≤ j), inclusive.

Example: Given nums = [-2, 0, 3, -5, 2, -1]

sumRange(0, 2) -> 1 sumRange(2, 5) -> -1 sumRange(0, 5) -> -3 Note:
  You may assume that the array does not change. There are many calls to
  sumRange function.

And this is the code:

/**
 * @param {number[]} nums
 */
var NumArray = function(nums) {
   this.nums = nums;
};

/**
 * @param {number} i
 * @param {number} j
 * @return {number}
 */
NumArray.prototype.sumRange = function(i, j) {
    let sum = 0;
    for (i; i <= j; i++) {
        sum += this[i];
    }
    return sum;
};

/**
 * Your NumArray object will be instantiated and called as such:
 * var obj = Object.create(NumArray).createNew(nums)
 * var param_1 = obj.sumRange(i,j)
 */

What I don't know how to do is, or what exactly it means is this part:

var obj = Object.create(NumArray).createNew(nums)

Am I suppose to create a property createNew that takes mums and creats and array, and why should I do that if the nums are already sent as an array?

Body:
what exactly it means is this part:

var obj = Object.create(NumArray).createNew(nums)

They messed it up and meant simply var obj = new NumArray(nums) (which still is unnecessarily complicated for a functional language like JS).

Apparently the description was changed at some point by someone clueless, as all the old JavaScript submissions in the discussion section (e.g. this one) have the correct code in the comment.


问:
Jenkins restoring Nuget packages - Proxy not working
I've got a Jenkins server up and running and a single job configured.  It's behind a proxy and I've configured the proxy settings in the relevant Nuget.config file.

When the job runs it seems that the entries for the proxy settings are ignored and I get a series of errors for each package that nuget tries to restore:

```<code>The remote server returned an error: (407) Proxy Authentication Required.
</code>```

If I copy the command line that Jenkins fires off to launch Nuget and paste it into a command prompt window the restore operation works perfectly.

I'm I missing something to get nuget package restores working behind a proxy?

答: Turns out that I needed to also set the Jenkins service to run under a domain account as well as having the config file setup with the proxy login details. </p>

Body:
I've got a Jenkins server up and running and a single job configured.  It's behind a proxy and I've configured the proxy settings in the relevant Nuget.config file.

When the job runs it seems that the entries for the proxy settings are ignored and I get a series of errors for each package that nuget tries to restore:

The remote server returned an error: (407) Proxy Authentication Required.

If I copy the command line that Jenkins fires off to launch Nuget and paste it into a command prompt window the restore operation works perfectly.

I'm I missing something to get nuget package restores working behind a proxy?


问:
Sharing AMP pages on Google products
If I share an amp page that validates with the AMP validator by the original URL on Google+ users are presented with a redirection warning. Why?

What is the correct way to share AMP pages on Google+? Am I supposed to be sharing the cache URL?

答:
There's the official amp-social-share that you can use to share on platforms like Google+, Facebook, Twitter, etc.

Setup

Import the amp-social-share component in the header.

Ensure you've configured your canonical URL.

```<code>< link rel="canonical" href="https://ampbyexample.com/components/amp-social-share/" >
</code>```

Origin trial tokens for ampbyexample.com and *.cdn.ampproject.org. (Needed for type=system; see below.)

```<code>< meta http-equiv="origin-trial" data-feature="Web Share" data-expires="2017-04-04" content="Ajcrk411RcpUCQ3ovgC8le4e7Te/1kARZsW5Hd/OCnW6vIHTs5Kcq1PaABs7SzcrtfvT0TIlFh9Vdb5xWi9LiQsAAABSeyJvcmlnaW4iOiJodHRwczovL2FtcGJ5ZXhhbXBsZS5jb206NDQzIiwiZmVhdHVyZSI6IldlYlNoYXJlIiwiZXhwaXJ5IjoxNDkxMzM3MDEwfQ==" >
</code>```

Title: Sharing AMP pages on Google products

Body:
There's the official amp-social-share that you can use to share on platforms like Google+, Facebook, Twitter, etc.

Setup

Import the amp-social-share component in the header.

Ensure you've configured your canonical URL.

< link rel="canonical" href="https://ampbyexample.com/components/amp-social-share/" >

Origin trial tokens for ampbyexample.com and *.cdn.ampproject.org. (Needed for type=system; see below.)

< meta http-equiv="origin-trial" data-feature="Web Share" data-expires="2017-04-04" content="Ajcrk411RcpUCQ3ovgC8le4e7Te/1kARZsW5Hd/OCnW6vIHTs5Kcq1PaABs7SzcrtfvT0TIlFh9Vdb5xWi9LiQsAAABSeyJvcmlnaW4iOiJodHRwczovL2FtcGJ5ZXhhbXBsZS5jb206NDQzIiwiZmVhdHVyZSI6IldlYlNoYXJlIiwiZXhwaXJ5IjoxNDkxMzM3MDEwfQ==" >


问:
Ionic 2 Promise - Finishing the first process before executing the second process
For my Ionic 2 project, I have two functions executing one after another. Each function consists of an API call. I want to wait until the first function finishes executing everything before going to the second function.

The issue I'm having is that since the first function takes some time to finish, the second function executes before the first function finishes executing.

I'm learning how to use Promise as I was told it can solve this issue.
I've simplified the code so it's easier to follow:

```<code>const first = () => {
  self.pspService.post('/api/Conversation/GetPersonalCalendarData',
    {
    }, result => {
      result.Data.forEach(lAppointment => {
      });
    });

  return new Promise((resolve, reject) => {
    resolve();
  });

};

const second = () => {
  self.pspService.post('/api/Conversation/AddPersonalAppointment', {
  }, result => {

  });

  return new Promise((resolve, reject) => {
    resolve();
  });
};

first().then(() => {
  return second();
});
</code>```

答:
You can use async/await to handle exactly such scenarios.Asynchronous functions are prefixed with the async keyword; await suspends the execution until an asynchronous function return promise is fulfilled and unwraps the value from the Promise returned.

```<code>async func(){
    const first = () => {
      self.pspService.post('/api/Conversation/GetPersonalCalendarData',
        {
        }, result => {
          result.Data.forEach(lAppointment => {
          });
        });

      return new Promise((resolve, reject) => {
        resolve();
      });

    };

    const second = () => {
      self.pspService.post('/api/Conversation/AddPersonalAppointment', {
      }, result => {

      });

      return new Promise((resolve, reject) => {
        resolve();
      });
    };

    let firstValue = await first();
    console.log("First Value", firstValue);
    let secondValue = await second();
    console.log("Second Value", secondValue);
  }
</code>```

Body:
For my Ionic 2 project, I have two functions executing one after another. Each function consists of an API call. I want to wait until the first function finishes executing everything before going to the second function.

The issue I'm having is that since the first function takes some time to finish, the second function executes before the first function finishes executing.

I'm learning how to use Promise as I was told it can solve this issue.
I've simplified the code so it's easier to follow:

const first = () => {
  self.pspService.post('/api/Conversation/GetPersonalCalendarData',
    {
    }, result => {
      result.Data.forEach(lAppointment => {
      });
    });

  return new Promise((resolve, reject) => {
    resolve();
  });

};

const second = () => {
  self.pspService.post('/api/Conversation/AddPersonalAppointment', {
  }, result => {

  });

  return new Promise((resolve, reject) => {
    resolve();
  });
};

first().then(() => {
  return second();
});

Body:
You can use async/await to handle exactly such scenarios.Asynchronous functions are prefixed with the async keyword; await suspends the execution until an asynchronous function return promise is fulfilled and unwraps the value from the Promise returned.

async func(){
    const first = () => {
      self.pspService.post('/api/Conversation/GetPersonalCalendarData',
        {
        }, result => {
          result.Data.forEach(lAppointment => {
          });
        });

      return new Promise((resolve, reject) => {
        resolve();
      });

    };

    const second = () => {
      self.pspService.post('/api/Conversation/AddPersonalAppointment', {
      }, result => {

      });

      return new Promise((resolve, reject) => {
        resolve();
      });
    };

    let firstValue = await first();
    console.log("First Value", firstValue);
    let secondValue = await second();
    console.log("Second Value", secondValue);
  }


问:
Action Script random
I have created a project in which there will be three puzzle. When the user enter the game one of the puzzle will appear to him. In order to solve the puzzle he have to enter the write number in the input boxes. the problem is that each puzzle have different solution and i was not able to do the checking for which puzzle the random code chosen.

the time line

pass layer is where i placed the input boxes

layer 5 is Puzzle 1
game Two layer is puzzle 2
game Three layer is puzzle 3

this is the code before i added the random. Before i had each puzzle in different scenes. the code for checking if the input is correct

```<code>import flash.events.Event;
solved.visible=false;
txtOne.maxChars=1;
txtTwo.maxChars=1;
txtThree.maxChars=1;
txtFour.maxChars=1;
solved.visible=false;

txtOne.addEventListener(Event.CHANGE,onClicks);
txtTwo.addEventListener(Event.CHANGE,onClicks);
txtThree.addEventListener(Event.CHANGE,onClicks);
txtFour.addEventListener(Event.CHANGE,onClicks);

function onClicks(e:Event): void{
if(txtOne.text=="2" && txtTwo.text=="4" && txtThree.text=="2" && txtFour.text=="8")
{
    solved.visible=true;
    gotoAndStop(2);

}

}
</code>```

the same code i used for the other puzzles.

Then i combined them in same scene and did the random code
/////////////
my code for the random

```<code>import flash.events.MouseEvent;

stop();
var array1:Array=new Array(1, 2, 3);
Puzz_mc1.visible=false;
Puzz_mc2.visible=false;
Puzz_mc3.visible=false;
this["Puzz_mc"+array1[Math.floor(Math.random()*3)]].visible=true;
</code>```

//////////////
then i did this code to check if the answer is correct
i said that first i need to check which puzzle is opened by the random code after that to check if the answer is correct or not. But this code did not work with me.

```<code>import flash.events.Event;
solved.visible=false;
txtOne.maxChars=1;
txtTwo.maxChars=1;
txtThree.maxChars=1;
txtFour.maxChars=1;
solved.visible=false;

txtOne.addEventListener(Event.CHANGE,onClicks);
txtTwo.addEventListener(Event.CHANGE,onClicks);
txtThree.addEventListener(Event.CHANGE,onClicks);
txtFour.addEventListener(Event.CHANGE,onClicks);

function onClicks(e:Event): void{
    if(Puzz_mc1.visible==true)
    {

       if(txtOne.text=="2" && txtTwo.text=="4" && txtThree.text=="2" && txtFour.text=="8")
{
    solved.visible=true;
    gotoAndStop(2);

}
}
else if(Puzz_mc2.visible==true)
{
    if(txtOne.text=="5" && txtTwo.text=="2" && txtThree.text=="8" && txtFour.text=="2")
{
    solved.visible=true;
    gotoAndStop(2);

}
}
else if(Puzz_mc3.visible==true)
{
    if(txtOne.text=="2" && txtTwo.text=="0" && txtThree.text=="1" && txtFour.text=="4")
{
    solved.visible=true;
    gotoAndStop(2);

}
}

}
</code>```

i have four input boxes.

first puzzle:

Second puzzle:

Third puzzle:

Input boxes for the all puzzle is the same:

I have a problem when i tried to enter anything in the boxes nothing is being entered

答:
Where you have

```<code>if(Puzz_mc1.visible=true)
</code>```

you need to use == instead of =

```<code>if(Puzz_mc1.visible==true)
</code>```

= is for assigning values to variables, whereas == is for comparing the values of variables.

Title: Action Script random

Body:
I have created a project in which there will be three puzzle. When the user enter the game one of the puzzle will appear to him. In order to solve the puzzle he have to enter the write number in the input boxes. the problem is that each puzzle have different solution and i was not able to do the checking for which puzzle the random code chosen.

the time line

pass layer is where i placed the input boxes

layer 5 is Puzzle 1
game Two layer is puzzle 2
game Three layer is puzzle 3

this is the code before i added the random. Before i had each puzzle in different scenes. the code for checking if the input is correct

import flash.events.Event;
solved.visible=false;
txtOne.maxChars=1;
txtTwo.maxChars=1;
txtThree.maxChars=1;
txtFour.maxChars=1;
solved.visible=false;

txtOne.addEventListener(Event.CHANGE,onClicks);
txtTwo.addEventListener(Event.CHANGE,onClicks);
txtThree.addEventListener(Event.CHANGE,onClicks);
txtFour.addEventListener(Event.CHANGE,onClicks);

function onClicks(e:Event): void{
if(txtOne.text=="2" && txtTwo.text=="4" && txtThree.text=="2" && txtFour.text=="8")
{
    solved.visible=true;
    gotoAndStop(2);

}

}

the same code i used for the other puzzles.

Then i combined them in same scene and did the random code
/////////////
my code for the random

import flash.events.MouseEvent;

stop();
var array1:Array=new Array(1, 2, 3);
Puzz_mc1.visible=false;
Puzz_mc2.visible=false;
Puzz_mc3.visible=false;
this["Puzz_mc"+array1[Math.floor(Math.random()*3)]].visible=true;

//////////////
then i did this code to check if the answer is correct
i said that first i need to check which puzzle is opened by the random code after that to check if the answer is correct or not. But this code did not work with me.

import flash.events.Event;
solved.visible=false;
txtOne.maxChars=1;
txtTwo.maxChars=1;
txtThree.maxChars=1;
txtFour.maxChars=1;
solved.visible=false;

txtOne.addEventListener(Event.CHANGE,onClicks);
txtTwo.addEventListener(Event.CHANGE,onClicks);
txtThree.addEventListener(Event.CHANGE,onClicks);
txtFour.addEventListener(Event.CHANGE,onClicks);

function onClicks(e:Event): void{
    if(Puzz_mc1.visible==true)
    {

       if(txtOne.text=="2" && txtTwo.text=="4" && txtThree.text=="2" && txtFour.text=="8")
{
    solved.visible=true;
    gotoAndStop(2);

}
}
else if(Puzz_mc2.visible==true)
{
    if(txtOne.text=="5" && txtTwo.text=="2" && txtThree.text=="8" && txtFour.text=="2")
{
    solved.visible=true;
    gotoAndStop(2);

}
}
else if(Puzz_mc3.visible==true)
{
    if(txtOne.text=="2" && txtTwo.text=="0" && txtThree.text=="1" && txtFour.text=="4")
{
    solved.visible=true;
    gotoAndStop(2);

}
}

}

i have four input boxes.

first puzzle:

Second puzzle:

Third puzzle:

Input boxes for the all puzzle is the same:

I have a problem when i tried to enter anything in the boxes nothing is being entered

Body:
Where you have

if(Puzz_mc1.visible=true)

you need to use == instead of =

if(Puzz_mc1.visible==true)

= is for assigning values to variables, whereas == is for comparing the values of variables.


问:
Angular5 - TypeError: Cannot read property 'template' of undefined
I have added EDIT, DELETE and DETAILS buttons to each row in mat-table using Angular material@5.0.0-rc.2.
All buttons are working but,
  * I am getting an error "Cannot read property 'template' of undefined" and
  * for each button click, everything is displaying on the same page

itemlist.component.html

```<code><mat-table #table [dataSource]="dataSource">
  <ng-container matColumnDef="name">
    <mat-header-cell *matHeaderCellDef> Name </mat-header-cell>
    <mat-cell *matCellDef="let row"> {{row.name}} </mat-cell>
  </ng-container>

  <ng-container matColumnDef="description">
    <mat-header-cell *matHeaderCellDef> Description </mat-header-cell>
    <mat-cell *matCellDef="let row"> {{row.description}} </mat-cell>
  </ng-container>

  <ng-container matColumnDef="actions">
    <mat-cell *matCellDef="let row">
      <button mat-button (click)="showDetails(row)">DETAILS</button>
      <button mat-button (click)="editItem(row)">EDIT</button>
      <button mat-button (click)="deleteItem(row)">DELETE</button>
    </mat-cell>
  </ng-container>

  <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
  <mat-row *matRowDef="let row; columns:displayedColumns"></mat-row>
</mat-table>
</code>```

itemlist.component.ts

```<code>export class ItemListComponent {
  @Input() dataSource;
  displayedColumns = ['name', 'description', 'actions'];

  @Input() items: Item[];
  @Output() onEdit = new EventEmitter<Item>();
  @Output() onShow = new EventEmitter<Item>();
  @Output() onDelete = new EventEmitter<Item>();

  itemsTrackByFn = (index: string, item: Item) => item.id;

  showDetails(item: Item) {
    this.onShow.emit(item);
  }
  editItem(item: Item) {
    this.onEdit.emit(item)
  }
  deleteItem(item: Item) {
    this.onDelete.emit(item)
  }
}
</code>```

itemindex.component.html

```<code><app-item-list [dataSource]="dataSource"
              (onShow)="showItem($event)"
              (onDelete)="deleteItem($event)"
              (onEdit)="editItem($event)"
></app-item-list>
</code>```

itemindex.component.ts

```<code>export class ItemIndexComponent implements OnInit {
  items$: Observable<Item[]>;
  public dataSource: ItemsDatasource;

  constructor(public store: Store<fromRoot.State>, private router: Router){}

  ngOnInit() {
    this.items$ = this.store.select(fromItems.getAllItems);
    this.store.dispatch(new itemsActions.LoadAll());
    this.dataSource = new ItemsDatasource(this.items$);
  }

  editItem(item: Item) {
    this.store.dispatch(new itemsActions.SetCurrentItemId(item.id));
    this.router.navigate(['/items', item.id, 'edit'])
  }
  showItem(item: Item) {
    this.store.dispatch(new itemsActions.SetCurrentItemId(item.id));
    this.router.navigate(['/items', item.id])
  }
  deleteItem(item: Item) {
     this.store.dispatch(new itemsActions.Delete(item.id));
   }
 }
}

export class ItemsDatasource extends DataSource<Item> {

  public constructor(private items$: Observable<Item[]>) {
    super()
  }

  public connect(collectionViewer: CollectionViewer): Observable<Item[]> {
    return this.items$;
  }

  public disconnect(collectionViewer: CollectionViewer): void {}
}
</code>```

Any suggestion would be helpful

答:
Check the configuration in .ts file</p>

```<code>displayedColumns = ['name', 'description', 'action'];
dataSource = new MatTableDataSource<Element>(ELEMENT_DATA);

const ELEMENT_DATA: Element[] = [
    { name: '', description: '' },
    { name: '', description: '' }
]
</code>```

Body:
I have added EDIT, DELETE and DETAILS buttons to each row in mat-table using Angular material@5.0.0-rc.2.
All buttons are working but,
  * I am getting an error "Cannot read property 'template' of undefined" and
  * for each button click, everything is displaying on the same page

itemlist.component.html

<mat-table #table [dataSource]="dataSource">
  <ng-container matColumnDef="name">
    <mat-header-cell *matHeaderCellDef> Name </mat-header-cell>
    <mat-cell *matCellDef="let row"> {{row.name}} </mat-cell>
  </ng-container>

  <ng-container matColumnDef="description">
    <mat-header-cell *matHeaderCellDef> Description </mat-header-cell>
    <mat-cell *matCellDef="let row"> {{row.description}} </mat-cell>
  </ng-container>

  <ng-container matColumnDef="actions">
    <mat-cell *matCellDef="let row">
      <button mat-button (click)="showDetails(row)">DETAILS</button>
      <button mat-button (click)="editItem(row)">EDIT</button>
      <button mat-button (click)="deleteItem(row)">DELETE</button>
    </mat-cell>
  </ng-container>

  <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
  <mat-row *matRowDef="let row; columns:displayedColumns"></mat-row>
</mat-table>

itemlist.component.ts

export class ItemListComponent {
  @Input() dataSource;
  displayedColumns = ['name', 'description', 'actions'];

  @Input() items: Item[];
  @Output() onEdit = new EventEmitter<Item>();
  @Output() onShow = new EventEmitter<Item>();
  @Output() onDelete = new EventEmitter<Item>();

  itemsTrackByFn = (index: string, item: Item) => item.id;

  showDetails(item: Item) {
    this.onShow.emit(item);
  }
  editItem(item: Item) {
    this.onEdit.emit(item)
  }
  deleteItem(item: Item) {
    this.onDelete.emit(item)
  }
}

itemindex.component.html

<app-item-list [dataSource]="dataSource"
              (onShow)="showItem($event)"
              (onDelete)="deleteItem($event)"
              (onEdit)="editItem($event)"
></app-item-list>

itemindex.component.ts

export class ItemIndexComponent implements OnInit {
  items$: Observable<Item[]>;
  public dataSource: ItemsDatasource;

  constructor(public store: Store<fromRoot.State>, private router: Router){}

  ngOnInit() {
    this.items$ = this.store.select(fromItems.getAllItems);
    this.store.dispatch(new itemsActions.LoadAll());
    this.dataSource = new ItemsDatasource(this.items$);
  }

  editItem(item: Item) {
    this.store.dispatch(new itemsActions.SetCurrentItemId(item.id));
    this.router.navigate(['/items', item.id, 'edit'])
  }
  showItem(item: Item) {
    this.store.dispatch(new itemsActions.SetCurrentItemId(item.id));
    this.router.navigate(['/items', item.id])
  }
  deleteItem(item: Item) {
     this.store.dispatch(new itemsActions.Delete(item.id));
   }
 }
}

export class ItemsDatasource extends DataSource<Item> {

  public constructor(private items$: Observable<Item[]>) {
    super()
  }

  public connect(collectionViewer: CollectionViewer): Observable<Item[]> {
    return this.items$;
  }

  public disconnect(collectionViewer: CollectionViewer): void {}
}

Any suggestion would be helpful

Body:
Check the configuration in .ts file

displayedColumns = ['name', 'description', 'action'];
dataSource = new MatTableDataSource<Element>(ELEMENT_DATA);

const ELEMENT_DATA: Element[] = [
    { name: '', description: '' },
    { name: '', description: '' }
]


问:
python - converting objects to float in list of lists
I'm trying to make a program in Python 3 where user gives multiple values in one input separated by space and these values are added to a list in form of a list, thus creating a list of lists. But I just cant convert these values to float.

This is the "base" of the code:

```<code>lst = []
ln = input()
values = ln.split(" ")
lst.extend([values])
while ln != "":
    ln = input()
    values = ln.split(" ")
    lst.extend([values])
</code>```

Which would give me list like this

```<code>[['1', '2'], ['3', '4']]
</code>```

So the problem is that I cannot convert these strings to floats. One of the ways I've tried is

```<code>for i in lst:
    for j in i:
        j = float(j)
</code>```

Which just gives me "ValueError: could not convert string to float:". I've also tried mapping but that doesn't work either.

答:
Python has less than intuitive ways to modify primitive objects within a list- many times the easiest way to get around that is to create a new list:</p>

```<code>lst = [['1', '2'], ['3', '4']]

floatlist = []
for l in lst:
    floatlist.append([float(i) for i in l])

print(floatlist)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to make a program in Python 3 where user gives multiple values in one input separated by space and these values are added to a list in form of a list, thus creating a list of lists. But I just cant convert these values to float.

This is the "base" of the code:

lst = []
ln = input()
values = ln.split(" ")
lst.extend([values])
while ln != "":
    ln = input()
    values = ln.split(" ")
    lst.extend([values])

Which would give me list like this

[['1', '2'], ['3', '4']]

So the problem is that I cannot convert these strings to floats. One of the ways I've tried is

for i in lst:
    for j in i:
        j = float(j)

Which just gives me "ValueError: could not convert string to float:". I've also tried mapping but that doesn't work either.

Body:
Python has less than intuitive ways to modify primitive objects within a list- many times the easiest way to get around that is to create a new list:

lst = [['1', '2'], ['3', '4']]

floatlist = []
for l in lst:
    floatlist.append([float(i) for i in l])

print(floatlist)


问:
Unable to call an REST API for FileUpload in php
There is an API build in C# and i am successfully able to to call that api from postman but the same thing i want to do with php.

Postman

Header info need to set before call api

Actual File Upload in attachment parameter.

Using Postman Tool I am able to upload file successfully.

But The Problem is Same thing i want to do using php Code.

What I Tried in PHP CODE:

```<code>$headers = array('DistributorCode:'.$_SERVER['HTTP_DISTRIBUTORAPIKEY'],'FolderName:'.$_SERVER['HTTP_DISTRIBUTORAPIKEY']);

$this->CallRestAPI('POST', 'http://192.168.1.55/api/upload' , array('attachment'=> file_get_contents(REPORTPATH . $_SERVER['HTTP_DISTRIBUTORAPIKEY'] . "\\07122017163625.zip")), $headers);

function CallRestAPI($method, $url, $data , $headers) {
        $curl = curl_init($url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);

        switch ($method) {
            case "GET":
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
                curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "GET");
                break;
            case "POST":
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
                curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
                break;
            case "PUT":
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
                curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
                break;
            case "DELETE":
                curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE");
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
                break;
        }
        $response = curl_exec($curl);
        echo "Response:".$response;die;

        /* Check for 404 (file not found). */
        $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        // Check the HTTP Status code
        switch ($httpCode) {
            case 200:
                $error_status = "200: Success";
                return ($data);
                break;
            case 404:
                $error_status = "404: API Not found";
                break;
            case 500:
                $error_status = "500: servers replied with an error.";
                break;
            case 502:
                $error_status = "502: servers may be down or being upgraded. Hopefully they'll be OK soon!";
                break;
            case 503:
                $error_status = "503: service unavailable. Hopefully they'll be OK soon!";
                break;
            default:
                $error_status = "Undocumented error: " . $httpCode . " : " . curl_error($curl);
                break;
        }
        curl_close($curl);
        echo $error_status;
        die;
    }
</code>```

答: You can get the code from postman on the top right corner. The "code" button. It generates the code any language what you want.

Body:
There is an API build in C# and i am successfully able to to call that api from postman but the same thing i want to do with php.

Postman

Header info need to set before call api

Actual File Upload in attachment parameter.

Using Postman Tool I am able to upload file successfully.

But The Problem is Same thing i want to do using php Code.

What I Tried in PHP CODE:

$headers = array('DistributorCode:'.$_SERVER['HTTP_DISTRIBUTORAPIKEY'],'FolderName:'.$_SERVER['HTTP_DISTRIBUTORAPIKEY']);

$this->CallRestAPI('POST', 'http://192.168.1.55/api/upload' , array('attachment'=> file_get_contents(REPORTPATH . $_SERVER['HTTP_DISTRIBUTORAPIKEY'] . "\\07122017163625.zip")), $headers);

function CallRestAPI($method, $url, $data , $headers) {
        $curl = curl_init($url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);

        switch ($method) {
            case "GET":
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
                curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "GET");
                break;
            case "POST":
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
                curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
                break;
            case "PUT":
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
                curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
                break;
            case "DELETE":
                curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE");
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
                break;
        }
        $response = curl_exec($curl);
        echo "Response:".$response;die;

        /* Check for 404 (file not found). */
        $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        // Check the HTTP Status code
        switch ($httpCode) {
            case 200:
                $error_status = "200: Success";
                return ($data);
                break;
            case 404:
                $error_status = "404: API Not found";
                break;
            case 500:
                $error_status = "500: servers replied with an error.";
                break;
            case 502:
                $error_status = "502: servers may be down or being upgraded. Hopefully they'll be OK soon!";
                break;
            case 503:
                $error_status = "503: service unavailable. Hopefully they'll be OK soon!";
                break;
            default:
                $error_status = "Undocumented error: " . $httpCode . " : " . curl_error($curl);
                break;
        }
        curl_close($curl);
        echo $error_status;
        die;
    }


问:
Python read/write/seek operations under the hood
While creating a character device on a Linux system, I interacted with it using Python and its basic file operations.

After experiencing several crashes, I started printing debug messages and noticed a strange behavior: it seems that Python "optimizes" file operations in a weird sense.

Let's peek at an example; here's a basic code and output of an interaction:

Kernel module

```<code>// Several includes and kernel module initialization

static ssize_t dev_read(struct file *filep, char *buffer, size_t len, long long *offset){
    printk(KERN_INFO "[DEBUGGER] - dev_read with len: %d, offset: 0x%llx.\n", len, offset[0]);
    return len;
}

static ssize_t dev_write(struct file *filep, const char *buffer, size_t len, long long *offset){
    printk(KERN_INFO "[DEBUGGER] - dev_write with len: %d, offset: 0x%llx.\n", len, offset[0]);
    return len;
}

static long long dev_llseek(struct file *filep, long long offset, int orig){
    printk(KERN_INFO "[DEBUGGER] - dev_llseek with offset: 0x%llx, orig: %d\n", offset, orig);
    return offset;
}

static int dev_release(struct inode *inodep, struct file *filep){
    return 0; // Success
}

static int dev_open(struct inode *inodep, struct file *filep){
    return 0; // Success
}

static struct file_operations fops =
{
   .open = dev_open,
   .read = dev_read,
   .write = dev_write,
   .release = dev_release,
   .llseek = dev_llseek,
};

int init_module(void){
   // Code to create character device
   return 0;
}

void cleanup_module(void){
   // Code to delete character device
}
</code>```

Python

with open("/dev/chardevice", "r+b") as character:
   character.seek(1)
   character.read(4)
   character.seek(0x7f123456)
   character.read(20)
   character.write("\xff" * 4)
```

<h3>Output</h3>

```# seek(1)
[DEBUGGER] - dev_llseek with offset: 0x0, orig: 0
[DEBUGGER] - dev_read with len: 1, offset: 0x0.
[DEBUGGER] - dev_llseek with offset: 0x1, orig: 0
# read(4)
[DEBUGGER] - dev_read with len: 4, offset: 0x0.
# seek(0x7f123456)
[DEBUGGER] - dev_llseek with offset: 0x7f123000, orig: 0
[DEBUGGER] - dev_read with len: 1110, offset: 0x0.
# read(20)
[DEBUGGER] - dev_read with len: 4096, offset: 0x0.
# write("\xff" * 4)
[DEBUGGER] - dev_write with len: 4, offset: 0x0.
```

It is clear that the basic file operations do not translate directly to the same operations on file, with the clearest examples being that seek to 0x7f123000 instead of 0x7f123456 and the read of 4096 bytes while only a read on 20 bytes was requested.

This raises the following questions:

Why is this a feature?

What optimization does it achieve, as most of it doesn't look like a good "next-operation" prediction?

Is it documented anywhere, to know what to expect when programming a read/write functionality beforehand?

Besides pure interest about this area, I still wish to use Python for easier access - so is there any way to disable this optimization, and force Python to behave like a C code executing these operations?

Thanks!

答: I am not sure that's the case here but I think this has to do with the time penalty of reading a byte being the same as reading a whole sector, so why not read always whole sectors from disk (or maybe you can't even ask to read less bytes than the sector size to underlying system) </p>

Body:
While creating a character device on a Linux system, I interacted with it using Python and its basic file operations.

After experiencing several crashes, I started printing debug messages and noticed a strange behavior: it seems that Python "optimizes" file operations in a weird sense.

Let's peek at an example; here's a basic code and output of an interaction:

Kernel module

// Several includes and kernel module initialization

static ssize_t dev_read(struct file *filep, char *buffer, size_t len, long long *offset){
    printk(KERN_INFO "[DEBUGGER] - dev_read with len: %d, offset: 0x%llx.\n", len, offset[0]);
    return len;
}

static ssize_t dev_write(struct file *filep, const char *buffer, size_t len, long long *offset){
    printk(KERN_INFO "[DEBUGGER] - dev_write with len: %d, offset: 0x%llx.\n", len, offset[0]);
    return len;
}

static long long dev_llseek(struct file *filep, long long offset, int orig){
    printk(KERN_INFO "[DEBUGGER] - dev_llseek with offset: 0x%llx, orig: %d\n", offset, orig);
    return offset;
}

static int dev_release(struct inode *inodep, struct file *filep){
    return 0; // Success
}

static int dev_open(struct inode *inodep, struct file *filep){
    return 0; // Success
}

static struct file_operations fops =
{
   .open = dev_open,
   .read = dev_read,
   .write = dev_write,
   .release = dev_release,
   .llseek = dev_llseek,
};

int init_module(void){
   // Code to create character device
   return 0;
}

void cleanup_module(void){
   // Code to delete character device
}

Python

with open("/dev/chardevice", "r+b") as character:
   character.seek(1)
   character.read(4)
   character.seek(0x7f123456)
   character.read(20)
   character.write("\xff" * 4)

Output

# seek(1)
[DEBUGGER] - dev_llseek with offset: 0x0, orig: 0
[DEBUGGER] - dev_read with len: 1, offset: 0x0.
[DEBUGGER] - dev_llseek with offset: 0x1, orig: 0
# read(4)
[DEBUGGER] - dev_read with len: 4, offset: 0x0.
# seek(0x7f123456)
[DEBUGGER] - dev_llseek with offset: 0x7f123000, orig: 0
[DEBUGGER] - dev_read with len: 1110, offset: 0x0.
# read(20)
[DEBUGGER] - dev_read with len: 4096, offset: 0x0.
# write("\xff" * 4)
[DEBUGGER] - dev_write with len: 4, offset: 0x0.

It is clear that the basic file operations do not translate directly to the same operations on file, with the clearest examples being that seek to 0x7f123000 instead of 0x7f123456 and the read of 4096 bytes while only a read on 20 bytes was requested.

This raises the following questions:

Why is this a feature?

What optimization does it achieve, as most of it doesn't look like a good "next-operation" prediction?

Is it documented anywhere, to know what to expect when programming a read/write functionality beforehand?

Besides pure interest about this area, I still wish to use Python for easier access - so is there any way to disable this optimization, and force Python to behave like a C code executing these operations?

Thanks!