问:
How to define default schema for sequelize migrations when using postgres and umzug?
I am trying to always run migrations with sequelize and umzug to a specific postgresql database schema. Lets call it custom schema. By default all queries go to public schema.
Is there any way to define the default schema to run all migrations to in sequelize or umzug?

http://docs.sequelizejs.com/

https://github.com/sequelize/umzug

Background:

With the following code I am able to define the schema for a single query in a migration:

```<code>// schema defined according to https://sequelize.readthedocs.io/en/latest/docs/migrations/
module.exports = {
  up: async (queryInterface, Sequelize) => {
    return Sequelize.transaction(async transaction => {
      await queryInterface.renameTable({ tableName: 'oldtablename', schema: "custom"}, 'newtablename', { transaction })
    })
  },

  down: async () => {
  }
}
</code>```

And it reports that it is a success and uses the correct schema:

```<code>Migration {
  path:
   'path/to/migrations/migration_test.js',
  file: 'migration_test.js',
  options:
   { storage: 'sequelize',
     storageOptions: [Object],
     logging: [Function: bound consoleCall],
     upName: 'up',
     downName: 'down',
     migrations: [Object],
     schema: 'custom' } } ]
</code>```

However what I require is to be able to define the default schema that all queries in all migrations always run to instead of defining the schema I need in every single query I want to run.

I tried searching, reading the documentation of the libraries and copy pasting schema: 'custom' everywhere, but nothing else worked so far except the above example.

I am using the following code to run the migrations:

```<code>const sequelizeConn = new Sequelize(ENV_DB_URL, {
  schema: 'custom',
  logging: false
})

    const migrator = new Umzug({
      storage: 'sequelize',
      storageOptions: {
        sequelize: sequelizeConn,
        tableName: 'migrations',
        schema: 'custom'
      },
      logging: console.log,
      migrations: {
        params: [
          sequelizeConn.getQueryInterface(),
          sequelizeConn
        ],
        path: `${process.cwd()}/src/database/migrations`,
        pattern: /\.js$/
      }
    })
    migrator.up()
</code>```

My umzug is 2.2.0 and sequelize is 5.3.0.
The migrations table is correctly created to the custom schema, but migrations still run in public schema.

I get the following error when running migrations that do not specify the schema in the query itself. From the error we can see that the schema is undefined:

```<code>{ SequelizeDatabaseError: relation "oldtablename" does not exist
  at Query.formatError (/usr/src/app/node_modules/sequelize/lib/dialects/postgres/query.js:354:16)
  at query.catch.err (/usr/src/app/node_modules/sequelize/lib/dialects/postgres/query.js:71:18)
  at tryCatcher (/usr/src/app/node_modules/bluebird/js/release/util.js:16:23)
  at Promise._settlePromiseFromHandler (/usr/src/app/node_modules/bluebird/js/release/promise.js:512:31)
  at Promise._settlePromise (/usr/src/app/node_modules/bluebird/js/release/promise.js:569:18)
  at Promise._settlePromise0 (/usr/src/app/node_modules/bluebird/js/release/promise.js:614:10)
  at Promise._settlePromises (/usr/src/app/node_modules/bluebird/js/release/promise.js:690:18)
  at _drainQueueStep (/usr/src/app/node_modules/bluebird/js/release/async.js:138:12)
  at _drainQueue (/usr/src/app/node_modules/bluebird/js/release/async.js:131:9)
  at Async._drainQueues (/usr/src/app/node_modules/bluebird/js/release/async.js:147:5)
  at Immediate.Async.drainQueues [as _onImmediate] (/usr/src/app/node_modules/bluebird/js/release/async.js:17:14)
  at runCallback (timers.js:705:18)
  at tryOnImmediate (timers.js:676:5)
  at processImmediate (timers.js:658:5)
  at process.topLevelDomainCallback (domain.js:120:23)
name: 'SequelizeDatabaseError',
parent:
 { error: relation "oldtablename" does not exist
     at Connection.parseE (/usr/src/app/node_modules/pg/lib/connection.js:554:11)
     at Connection.parseMessage (/usr/src/app/node_modules/pg/lib/connection.js:379:19)
     at Socket.<anonymous> (/usr/src/app/node_modules/pg/lib/connection.js:119:22)
     at Socket.emit (events.js:189:13)
     at Socket.EventEmitter.emit (domain.js:441:20)
     at addChunk (_stream_readable.js:284:12)
     at readableAddChunk (_stream_readable.js:265:11)
     at Socket.Readable.push (_stream_readable.js:220:10)
     at TCP.onStreamRead [as onread] (internal/stream_base_commons.js:94:17)
   name: 'error',
   length: 118,
   severity: 'ERROR',
   code: '42P01',
   detail: undefined,
   hint: undefined,
   position: undefined,
   internalPosition: undefined,
   internalQuery: undefined,
   where: undefined,
   schema: undefined,
   table: undefined,
   column: undefined,
   dataType: undefined,
   constraint: undefined,
   file: 'namespace.c',
   line: '420',
   routine: 'RangeVarGetRelidExtended',
   sql:
    'ALTER TABLE "oldtablename" RENAME TO "newtablename";' },
original:
 { error: relation "oldtablename" does not exist
     at Connection.parseE (/usr/src/app/node_modules/pg/lib/connection.js:554:11)
     at Connection.parseMessage (/usr/src/app/node_modules/pg/lib/connection.js:379:19)
     at Socket.<anonymous> (/usr/src/app/node_modules/pg/lib/connection.js:119:22)
     at Socket.emit (events.js:189:13)
     at Socket.EventEmitter.emit (domain.js:441:20)
     at addChunk (_stream_readable.js:284:12)
     at readableAddChunk (_stream_readable.js:265:11)
     at Socket.Readable.push (_stream_readable.js:220:10)
     at TCP.onStreamRead [as onread] (internal/stream_base_commons.js:94:17)
   name: 'error',
   length: 118,
   severity: 'ERROR',
   code: '42P01',
   detail: undefined,
   hint: undefined,
   position: undefined,
   internalPosition: undefined,
   internalQuery: undefined,
   where: undefined,
   schema: undefined,
   table: undefined,
   column: undefined,
   dataType: undefined,
   constraint: undefined,
   file: 'namespace.c',
   line: '420',
   routine: 'RangeVarGetRelidExtended',
   sql:
    'ALTER TABLE "oldtablename" RENAME TO "newtablename";' },
sql:
 'ALTER TABLE "oldtablename" RENAME TO "newtablename";' }
</code>```

答:
It's a bit confusing but you need to define a searchpath and dialect option for the connection.</p>

```<code>const sequelizeConn = new Sequelize(ENV_DB_URL, {
  schema: 'custom',
  logging: false,
  searchPath: 'custom',
  dialectOptions: {
    prependSearchPath: true
}
})
</code>```

Body:
I am trying to always run migrations with sequelize and umzug to a specific postgresql database schema. Lets call it custom schema. By default all queries go to public schema.
Is there any way to define the default schema to run all migrations to in sequelize or umzug?

http://docs.sequelizejs.com/

https://github.com/sequelize/umzug

Background:

With the following code I am able to define the schema for a single query in a migration:

// schema defined according to https://sequelize.readthedocs.io/en/latest/docs/migrations/
module.exports = {
  up: async (queryInterface, Sequelize) => {
    return Sequelize.transaction(async transaction => {
      await queryInterface.renameTable({ tableName: 'oldtablename', schema: "custom"}, 'newtablename', { transaction })
    })
  },

  down: async () => {
  }
}

And it reports that it is a success and uses the correct schema:

Migration {
  path:
   'path/to/migrations/migration_test.js',
  file: 'migration_test.js',
  options:
   { storage: 'sequelize',
     storageOptions: [Object],
     logging: [Function: bound consoleCall],
     upName: 'up',
     downName: 'down',
     migrations: [Object],
     schema: 'custom' } } ]

However what I require is to be able to define the default schema that all queries in all migrations always run to instead of defining the schema I need in every single query I want to run.

I tried searching, reading the documentation of the libraries and copy pasting schema: 'custom' everywhere, but nothing else worked so far except the above example.

I am using the following code to run the migrations:

const sequelizeConn = new Sequelize(ENV_DB_URL, {
  schema: 'custom',
  logging: false
})

    const migrator = new Umzug({
      storage: 'sequelize',
      storageOptions: {
        sequelize: sequelizeConn,
        tableName: 'migrations',
        schema: 'custom'
      },
      logging: console.log,
      migrations: {
        params: [
          sequelizeConn.getQueryInterface(),
          sequelizeConn
        ],
        path: `${process.cwd()}/src/database/migrations`,
        pattern: /\.js$/
      }
    })
    migrator.up()

My umzug is 2.2.0 and sequelize is 5.3.0.
The migrations table is correctly created to the custom schema, but migrations still run in public schema.

I get the following error when running migrations that do not specify the schema in the query itself. From the error we can see that the schema is undefined:

{ SequelizeDatabaseError: relation "oldtablename" does not exist
  at Query.formatError (/usr/src/app/node_modules/sequelize/lib/dialects/postgres/query.js:354:16)
  at query.catch.err (/usr/src/app/node_modules/sequelize/lib/dialects/postgres/query.js:71:18)
  at tryCatcher (/usr/src/app/node_modules/bluebird/js/release/util.js:16:23)
  at Promise._settlePromiseFromHandler (/usr/src/app/node_modules/bluebird/js/release/promise.js:512:31)
  at Promise._settlePromise (/usr/src/app/node_modules/bluebird/js/release/promise.js:569:18)
  at Promise._settlePromise0 (/usr/src/app/node_modules/bluebird/js/release/promise.js:614:10)
  at Promise._settlePromises (/usr/src/app/node_modules/bluebird/js/release/promise.js:690:18)
  at _drainQueueStep (/usr/src/app/node_modules/bluebird/js/release/async.js:138:12)
  at _drainQueue (/usr/src/app/node_modules/bluebird/js/release/async.js:131:9)
  at Async._drainQueues (/usr/src/app/node_modules/bluebird/js/release/async.js:147:5)
  at Immediate.Async.drainQueues [as _onImmediate] (/usr/src/app/node_modules/bluebird/js/release/async.js:17:14)
  at runCallback (timers.js:705:18)
  at tryOnImmediate (timers.js:676:5)
  at processImmediate (timers.js:658:5)
  at process.topLevelDomainCallback (domain.js:120:23)
name: 'SequelizeDatabaseError',
parent:
 { error: relation "oldtablename" does not exist
     at Connection.parseE (/usr/src/app/node_modules/pg/lib/connection.js:554:11)
     at Connection.parseMessage (/usr/src/app/node_modules/pg/lib/connection.js:379:19)
     at Socket.<anonymous> (/usr/src/app/node_modules/pg/lib/connection.js:119:22)
     at Socket.emit (events.js:189:13)
     at Socket.EventEmitter.emit (domain.js:441:20)
     at addChunk (_stream_readable.js:284:12)
     at readableAddChunk (_stream_readable.js:265:11)
     at Socket.Readable.push (_stream_readable.js:220:10)
     at TCP.onStreamRead [as onread] (internal/stream_base_commons.js:94:17)
   name: 'error',
   length: 118,
   severity: 'ERROR',
   code: '42P01',
   detail: undefined,
   hint: undefined,
   position: undefined,
   internalPosition: undefined,
   internalQuery: undefined,
   where: undefined,
   schema: undefined,
   table: undefined,
   column: undefined,
   dataType: undefined,
   constraint: undefined,
   file: 'namespace.c',
   line: '420',
   routine: 'RangeVarGetRelidExtended',
   sql:
    'ALTER TABLE "oldtablename" RENAME TO "newtablename";' },
original:
 { error: relation "oldtablename" does not exist
     at Connection.parseE (/usr/src/app/node_modules/pg/lib/connection.js:554:11)
     at Connection.parseMessage (/usr/src/app/node_modules/pg/lib/connection.js:379:19)
     at Socket.<anonymous> (/usr/src/app/node_modules/pg/lib/connection.js:119:22)
     at Socket.emit (events.js:189:13)
     at Socket.EventEmitter.emit (domain.js:441:20)
     at addChunk (_stream_readable.js:284:12)
     at readableAddChunk (_stream_readable.js:265:11)
     at Socket.Readable.push (_stream_readable.js:220:10)
     at TCP.onStreamRead [as onread] (internal/stream_base_commons.js:94:17)
   name: 'error',
   length: 118,
   severity: 'ERROR',
   code: '42P01',
   detail: undefined,
   hint: undefined,
   position: undefined,
   internalPosition: undefined,
   internalQuery: undefined,
   where: undefined,
   schema: undefined,
   table: undefined,
   column: undefined,
   dataType: undefined,
   constraint: undefined,
   file: 'namespace.c',
   line: '420',
   routine: 'RangeVarGetRelidExtended',
   sql:
    'ALTER TABLE "oldtablename" RENAME TO "newtablename";' },
sql:
 'ALTER TABLE "oldtablename" RENAME TO "newtablename";' }

Body:
It's a bit confusing but you need to define a searchpath and dialect option for the connection.

const sequelizeConn = new Sequelize(ENV_DB_URL, {
  schema: 'custom',
  logging: false,
  searchPath: 'custom',
  dialectOptions: {
    prependSearchPath: true
}
})


来源: stackexchange

问:
Overcome git svn caveats
I am reading the CAVEATS of git-svn. via this SO question.

What I understand is that:

If you are mirroring svn trunk, branches etc on git repo, don't merge or rebase anything locally on those branches. Specifically master points to the trunk.

My point is that, this would make git-svn crippled. What's the point of git, if I can't branch from master and then merge that changed branch back into the master? Perhaps I am missing some caveat in the caveat that says it is ok to merge certain branches that have the same parent without any rebases.

Can anyone point to me exactly what needs to be avoided and what is allowed. I'd want the local branches, if necessary, those need to be mirrored and merged and most importantly git should do the merges than the svn.

If I am using git branches to mirror svn branches and I cannot merge git branches, whats really the point of git-svn anyway?

答:
You can merge git branches, that is the ones which aren't directly mirrored from SVN.

I would to have my own set of Git branches, made from the "git-svn" branches, and rebased regularly on top of said "git-svn" branches.

That way, I do all the merges I need locally in the Git repo, then I cherry-pick what I need in order to update the "git-svn" branches, that I can safely dcommit without worrying about the first parent mentioned in the CAVEAT section of git-svn

ContentLicense: CC BY-SA 3.0

Title: Overcome git svn caveats


问:
Ajax: update and add to table
I have an html table as such

```<code><table>
    <tr id="headers">
        <td>Name</td>
        <td>Last Communicated</td>
        <td>Status</td>
    </tr>
    <tr id="data">
        <td id="name"></td>
        <td id="lastCom"></td>
        <td id="status"</td>
    </tr>
</table>
</code>```

I have an ajax call that gets the data from an SQL database and returns a list of values. How can I use the data returned from Ajax to update the table and add an entry if the list has grown?

Thanks!

答:
```<code> $.ajax({
            type: 'post',
            datatype: "json",
            url: url,//Here are the background methods
            data: data,
            success: function (msg) {
               //Requery your query list statement
            }
        });
</code>```

ContentLicense: CC BY-SA 4.0

Title: Ajax: update and add to table

Body:
I have an html table as such

        Name
        Last Communicated
        Status

        <td id="status"

I have an ajax call that gets the data from an SQL database and returns a list of values. How can I use the data returned from Ajax to update the table and add an entry if the list has grown?

Thanks!


问:
Moving array via ajax from PHP to JS with valid JSON format
I started with an array from php, which when called via ajax looked like this:

```<code>Array
(
    [0] => {id:"12",from:"09:00:00",to:"15:00:00"}
    [1] => {id:"13",from:"08:00:00",to:"10:00:00"}
    [2] => {id:"12",from:"15:00:00",to:"17:00:00"}
)
</code>```

PHP code

```<code>public static function getBookedTime($date) {

    $query = "SELECT * FROM booking WHERE cid = ".$_SESSION["cid"]." AND doc_date='".strftime("%Y-%m-%d",strtotime($date))."'";
    $result = self::qry($query);

    while ($line = mysqli_fetch_array($result, MYSQLI_ASSOC)) {

        $obj = "{";
        $obj.= 'id:'.'"'.$line["person_id"].'",';
        $obj.= 'from:'.'"'.$line["from_time"].'",';
        $obj.= 'to:'.'"'.$line["to_time"].'"';
        $obj.= "}";

        $time_array[] = $obj;

    }

    print_r( json_encode($time_array) );

}
</code>```

So I added json_encode($myarray) to the PHP and also added  JSON.parse(response) to the javascript.  Now in my page, after being called via ajax, it looks like this:

```<code>var booking1 = {id:"12",from:"09:00:00",to:"15:00:00"},{id:"13",from:"08:00:00",to:"10:00:00"},{id:"12",from:"15:00:00",to:"17:00:00"};
</code>```

The trouble is, I still cannot access any of the values. This is not a valid format in js.

Using either JS or php, how can I get booking1 to look like booking2 (or any valid format)?  I tried array.push and about a thousand things but it just won't budge.

```<code>var booking2 = [
    {id:"12",from:"09:00:00",to:"15:00:00"},
    {id:"13",from:"08:00:00",to:"10:00:00"},
    {id:"12",from:"15:00:00",to:"17:00:00"}
  ];
</code>```

(jQuery answers are ok!)

答:
Based on your edit: You should not attempt to build a json string manually in your loop. Instead, add the values you need to an array and add that.

Also note that you need to echo and not use print_r() as that will invalidate your json.

And if you only select the fields you need, it is even easier:

```<code>public static function getBookedTime($date) {
    $query = "SELECT person_id, from_time, to_time FROM booking WHERE cid = ".$_SESSION["cid"]." AND doc_date='".strftime("%Y-%m-%d",strtotime($date))."'";

    $result = self::qry($query);

    echo json_encode(mysqli_fetch_all($result, MYSQLI_ASSOC));
}
</code>```

Note: You should also use a prepared statement with bound variables to avoid sql injection. That might not be possible here due to the values used, but using it everywhere is always a good idea.

Body:
I started with an array from php, which when called via ajax looked like this:

Array
(
    [0] => {id:"12",from:"09:00:00",to:"15:00:00"}
    [1] => {id:"13",from:"08:00:00",to:"10:00:00"}
    [2] => {id:"12",from:"15:00:00",to:"17:00:00"}
)

PHP code

public static function getBookedTime($date) {

    $query = "SELECT * FROM booking WHERE cid = ".$_SESSION["cid"]." AND doc_date='".strftime("%Y-%m-%d",strtotime($date))."'";
    $result = self::qry($query);

    while ($line = mysqli_fetch_array($result, MYSQLI_ASSOC)) {

        $obj = "{";
        $obj.= 'id:'.'"'.$line["person_id"].'",';
        $obj.= 'from:'.'"'.$line["from_time"].'",';
        $obj.= 'to:'.'"'.$line["to_time"].'"';
        $obj.= "}";

        $time_array[] = $obj;

    }

    print_r( json_encode($time_array) );

}

So I added json_encode($myarray) to the PHP and also added  JSON.parse(response) to the javascript.  Now in my page, after being called via ajax, it looks like this:

var booking1 = {id:"12",from:"09:00:00",to:"15:00:00"},{id:"13",from:"08:00:00",to:"10:00:00"},{id:"12",from:"15:00:00",to:"17:00:00"};

The trouble is, I still cannot access any of the values. This is not a valid format in js.

Using either JS or php, how can I get booking1 to look like booking2 (or any valid format)?  I tried array.push and about a thousand things but it just won't budge.

var booking2 = [
    {id:"12",from:"09:00:00",to:"15:00:00"},
    {id:"13",from:"08:00:00",to:"10:00:00"},
    {id:"12",from:"15:00:00",to:"17:00:00"}
  ];

(jQuery answers are ok!)

Body:
Based on your edit: You should not attempt to build a json string manually in your loop. Instead, add the values you need to an array and add that.

Also note that you need to echo and not use print_r() as that will invalidate your json.

And if you only select the fields you need, it is even easier:

public static function getBookedTime($date) {
    $query = "SELECT person_id, from_time, to_time FROM booking WHERE cid = ".$_SESSION["cid"]." AND doc_date='".strftime("%Y-%m-%d",strtotime($date))."'";

    $result = self::qry($query);

    echo json_encode(mysqli_fetch_all($result, MYSQLI_ASSOC));
}

Note: You should also use a prepared statement with bound variables to avoid sql injection. That might not be possible here due to the values used, but using it everywhere is always a good idea.


问:
Android Login monitoring using Foreground service
I am trying to implement a login status monitoring in my application. What I am trying to achieve is calling an API in background service continuously. It will give a response depending on if the user is eligible to remain logged in. If the response states the user is not eligible to remain logged in, then the app should log out.

How I Implemented this

I created a foreground service and called the API inside an AsyncTask method. I called this method inside the service's onStartCommand() method.

My doubts

Is this the proper way to implement this work flow?.

I called the login activity from service like this

```<code>    Intent dialogIntent = new Intent(BluetoothLeService.this,SplashScreen.class);
    dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    dialogIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(dialogIntent);
</code>```

How do I finish the Activity from the service?

EDIT- Why Iam trying this way

If a user's activation is removed manually from back end then according to this work flow app will sign out automatically.Basically my app is a BLE based alert system.So logout after certain time is not possible.The only situation for logout is if the back end (ie; the service providers) find that user is not eligible for using the service, they will change the mentioned API result is to false.Due to this scenario I calls the API all time.What will be a better workaround for this?

答:
You should do the login monitoring on Clint side instead of calling and api, which will be a better option.

You can use a countdown timer of a fix time for the time management.

Whenever there is some event occurred you can restart the timer.

Depending upon the inactivity time (when timer finished) you can send the user to the login activity again.

Handling a service with a regular api call is not a right option.

But if you required a regular api call and if it is the final option, In that case timer will be a far better option as compared to service

Hope this will help you!

Body:
I am trying to implement a login status monitoring in my application. What I am trying to achieve is calling an API in background service continuously. It will give a response depending on if the user is eligible to remain logged in. If the response states the user is not eligible to remain logged in, then the app should log out.

How I Implemented this

I created a foreground service and called the API inside an AsyncTask method. I called this method inside the service's onStartCommand() method.

My doubts

Is this the proper way to implement this work flow?.

I called the login activity from service like this

    Intent dialogIntent = new Intent(BluetoothLeService.this,SplashScreen.class);
    dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    dialogIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(dialogIntent);

How do I finish the Activity from the service?

EDIT- Why Iam trying this way

If a user's activation is removed manually from back end then according to this work flow app will sign out automatically.Basically my app is a BLE based alert system.So logout after certain time is not possible.The only situation for logout is if the back end (ie; the service providers) find that user is not eligible for using the service, they will change the mentioned API result is to false.Due to this scenario I calls the API all time.What will be a better workaround for this?


问:
KVO lost when entering background, trying to fix
I have this method, adding an observer in myViewController:

```<code>-(void) observeSpeakerVolume{
    [[AVAudioSession sharedInstance] setActive:YES error:nil];
    [[AVAudioSession sharedInstance] addObserver:self forKeyPath:@"outputVolume" options:NSKeyValueObservingOptionNew context:nil];
}
</code>```

I invoke this method in the viewdidLoad of myViewController:

```<code>- (void)viewDidLoad {
    [self performSelectorInBackground:@selector(observeSpeakerVolume) withObject:nil];
    [super viewDidLoad];
}
</code>```

and finally I monitor the observer as follows:

```<code>-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
    if ([keyPath isEqualToString:@"outputVolume"]) {
        if ([[change valueForKey:@"new"] isEqualToNumber:@0]){
            ...
        } else {
            ...
        }
    }
}
</code>```

This all works fine, but as soon as my app is send to the background, eg by hitting the home button, the observer seems to be automatically removed.

To fix that, I do this in my AppDelegate:

```<code>- (void)applicationWillEnterForeground:(UIApplication *)application {
    myViewController * wfc = [[myViewController alloc]init];
    [wfc observeSpeakerVolume];
}
</code>```

That seems to work, however, switching back and forth several times between back- and foreground, eventually changing the volume of my iPhone crashes the app.

I tried to manually remove the observer when entering the background, but that also crashes the app, supporting the suggestion that the OS removes the observer automatically when entering the background.

So, I assume, that I'm adding the observer several times, but I don't see where, since ViewDidLoad is not called when the app enters the foreground.

What is wrong in my logic here?

thanks for your insights.

答:
Bit late, but I had similar issue.

If you call

```<code>    [[AVAudioSession sharedInstance] setActive:YES error:nil];
</code>```

after your app is back from background e.g. in

```<code>- (void)applicationWillEnterForeground:(UIApplication *)application;
</code>```

then the observer will work again.

Body:
I have this method, adding an observer in myViewController:

-(void) observeSpeakerVolume{
    [[AVAudioSession sharedInstance] setActive:YES error:nil];
    [[AVAudioSession sharedInstance] addObserver:self forKeyPath:@"outputVolume" options:NSKeyValueObservingOptionNew context:nil];
}

I invoke this method in the viewdidLoad of myViewController:

- (void)viewDidLoad {
    [self performSelectorInBackground:@selector(observeSpeakerVolume) withObject:nil];
    [super viewDidLoad];
}

and finally I monitor the observer as follows:

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
    if ([keyPath isEqualToString:@"outputVolume"]) {
        if ([[change valueForKey:@"new"] isEqualToNumber:@0]){
            ...
        } else {
            ...
        }
    }
}

This all works fine, but as soon as my app is send to the background, eg by hitting the home button, the observer seems to be automatically removed.

To fix that, I do this in my AppDelegate:

- (void)applicationWillEnterForeground:(UIApplication *)application {
    myViewController * wfc = [[myViewController alloc]init];
    [wfc observeSpeakerVolume];
}

That seems to work, however, switching back and forth several times between back- and foreground, eventually changing the volume of my iPhone crashes the app.

I tried to manually remove the observer when entering the background, but that also crashes the app, supporting the suggestion that the OS removes the observer automatically when entering the background.

So, I assume, that I'm adding the observer several times, but I don't see where, since ViewDidLoad is not called when the app enters the foreground.

What is wrong in my logic here?

thanks for your insights.

Body:
Bit late, but I had similar issue.

If you call

    [[AVAudioSession sharedInstance] setActive:YES error:nil];

after your app is back from background e.g. in

- (void)applicationWillEnterForeground:(UIApplication *)application;

then the observer will work again.


问:
How to convert a codepoint to utf-8?
I have some code that reads in an a unicode codepoint (as escaped in a string 0xF00).

Since im using boost, I'm speculating if the following is best (and correct) approach:

```<code>unsigned int codepoint{0xF00};
boost::locale::conv::utf_to_utf<char>(&codepoint, &codepoint+1);
</code>```

?

答:
As mentioned, a codepoint in this form is (conveniently) UTF-32, so what you're looking for is a transcoding.

For a solution that does not rely on functions deprecated since C++17, and isn't really ugly, and which also does not require hefty third-party libraries, you can use the very lightweight UTF8-CPP (four small headers!) and its function utf8::utf32to8.

It's going to look something like this:

```<code>const uint32_t codepoint{0xF00};
std::vector<unsigned char> result;

try
{
   utf8::utf32to8(&codepoint, &codepoint + 1, std::back_inserter(result));
}
catch (const utf8::invalid_code_point&)
{
   // something
}
</code>```

(There's also a utf8::unchecked::utf32to8, if you're allergic to exceptions.)

(And consider reading into vector<char8_t> or std::u8string, since C++20).

(Finally, note that I've specifically used uint32_t to ensure the input has the proper width.)

I tend to use this library in projects until I need something a little heavier for other purposes (at which point I'll typically switch to ICU).

Title: How to convert a codepoint to utf-8?

Body:
I have some code that reads in an a unicode codepoint (as escaped in a string 0xF00).

Since im using boost, I'm speculating if the following is best (and correct) approach:

unsigned int codepoint{0xF00};
boost::locale::conv::utf_to_utf<char>(&codepoint, &codepoint+1);

?

Body:
As mentioned, a codepoint in this form is (conveniently) UTF-32, so what you're looking for is a transcoding.

For a solution that does not rely on functions deprecated since C++17, and isn't really ugly, and which also does not require hefty third-party libraries, you can use the very lightweight UTF8-CPP (four small headers!) and its function utf8::utf32to8.

It's going to look something like this:

const uint32_t codepoint{0xF00};
std::vector<unsigned char> result;

try
{
   utf8::utf32to8(&codepoint, &codepoint + 1, std::back_inserter(result));
}
catch (const utf8::invalid_code_point&)
{
   // something
}

(There's also a utf8::unchecked::utf32to8, if you're allergic to exceptions.)

(And consider reading into vector<char8_t> or std::u8string, since C++20).

(Finally, note that I've specifically used uint32_t to ensure the input has the proper width.)

I tend to use this library in projects until I need something a little heavier for other purposes (at which point I'll typically switch to ICU).


问:
How to programmatically invoke MBeans operation of target process
I want to simulate what jconsole does by:

Identifying a running process that exposes jmx functionality (e.g: pid: 14796 FreshProject.jar)

Listing the available MBeans libraries (e.g: org.jacoco)

Invoking an operation (e.g: clicking dump)

I've tried using the simplejmx library as mentioned here but I am confused as to what hostName and port I should use. I tried passing localhost and 1099 as I've read these are the default values but it errors java.net.ConnectException: Connection refused: connect.

Please don't point me to a different sof post and close this as I most probably already read and tried it several times.

答: Please check the link - How to get a thread and heap dump of a Java process on Windows that's not running in a console , where i have posted an answer in which programmatically heap is dumped by using JMX & Reflection. You can refer the program as a sample. This code works from JDK 6 onwards.</p>


问:
Running website on app in xcode and getting error "Thread 1: signal SIGABRT"
I'm setting up an app with my website and I was getting no errors until i run the app and get the next one: "Thread 1: signal SIGABRT".

```<code>import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

// this is where i am getting the error "Thread 1: signal SIGABRT"

var window: UIWindow?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    return true
}

func applicationWillResignActive(_ application: UIApplication) {
</code>```

//error i get when running is *** Terminating app due to uncaught exception 'NSInvalidUnarchiveOperationException', reason: 'Could not instantiate class named WKWebView because no class named WKWebView was found; the class needs to be defined in source code or linked in from a library (ensure the class is part of the correct target)'

答:
Open Project > Build Phases > Link Binary with Libraries

Click on + icon and add WebKit.framework.

Clean Project and Run will fix your issue.

Body:
I'm setting up an app with my website and I was getting no errors until i run the app and get the next one: "Thread 1: signal SIGABRT".

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

// this is where i am getting the error "Thread 1: signal SIGABRT"

var window: UIWindow?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    return true
}

func applicationWillResignActive(_ application: UIApplication) {

//error i get when running is *** Terminating app due to uncaught exception 'NSInvalidUnarchiveOperationException', reason: 'Could not instantiate class named WKWebView because no class named WKWebView was found; the class needs to be defined in source code or linked in from a library (ensure the class is part of the correct target)'


问:
How to refresh a table without clicking again on my button
For my school I have to make a club management with a table, so I have a menu to choose to show the table, I submit and I have my table, and I want to Order By my table, I did it with input, but to show the Order By that I've made, I have to click again on the button that shows the Table, do you know how to update this table without make this click again ?</p>

```<code>if(isset($_POST['submitmenu'])){
     if($_POST['choix']=="inserer"){
     form_insert();
}

    if($_POST['choix']=="afficher"){
       afficher_equip();
    }

    if($_POST['choix']=="supprimer"){
        suppr();
    }

     if($_POST['choix']=="match"){
        match();
     }
}

function afficher_equip(){
    $link = mysqli_connect("venus","aparent","","aparent");
    $res = mysqli_query($link,"SELECT Equipe, Etat, Classement, Match_Joue, Victoire, Defaite, id FROM hockey_club ORDER BY Classement ASC");

    if(isset($_GET['sortaz'])){
        $res = mysqli_query($link,"SELECT Equipe, Etat, Classement, Match_Joue, Victoire, Defaite, id FROM hockey_club ORDER BY Equipe ASC");
   }

echo "<table style='border-collapse: collapse;' class='tableau'>";

    echo "<tr>";
        echo "<th>Equipe</th>";
        echo "<th>Etat</th>";
        echo "<th>Classement</th>";
        echo "<th>Match joues</th>";
        echo "<th>Victoires</th>";
        echo "<th>Defaites</th>";
        echo "<th>ID</th>";
        echo "</tr>";
        echo "<tr style='border: 1px solid black;'>";

    while ($hockey_club = mysqli_fetch_assoc($res)){

        foreach($hockey_club as $i => $valeur){
            echo "<td style='border: 2px solid black;  padding-left: 50px; padding-right: 50px; padding-bottom: 10px; padding-top: 10px; text-align: center; '>$valeur</td>";
        }
        echo "</tr>";
    }

    echo "</table><br>";

    echo"<div class='buttonsort'>
    Il faut appuyer a nouveau sur Afficher le classement apres avoir choisi le Order By: a corriger
        <form method='GET' action=''>
        <input type='submit' class='sort' style='vertical-align:middle' name='sortaz' value='A-Z'/>
        <input type='submit' class='sort' style='vertical-align:middle' name='sortetat' value='Etat'/>
        <input type='submit' class='sort' style='vertical-align:middle' name='sortclassement' value='Classement'/>
        <input type='submit' class='sort' style='vertical-align:middle' name='sortmj' value='Match Joues'/>
        <input type='submit' class='sort' style='vertical-align:middle' name='sortvic' value='Victoires'/>
        <input type='submit' class='sort' style='vertical-align:middle' name='sortdef' value='Defaites'/>
        <input type='submit' class='sort' style='vertical-align:middle' name='sortid' value='ID'/></form></div>";
}
</code>```

答:
If I understand your question correctly, you're wanting to order a table by a certain metric and then refresh the table to view this change.

One thing you could do is, when the user selects a metric to order the table by, call the function which builds the table (the one that is called when a user clicks 'Show Table').

Doing it this way means you don't need to write much more code and you're reusing existing code, which is normally good practice.

Body:
For my school I have to make a club management with a table, so I have a menu to choose to show the table, I submit and I have my table, and I want to Order By my table, I did it with input, but to show the Order By that I've made, I have to click again on the button that shows the Table, do you know how to update this table without make this click again ?

if(isset($_POST['submitmenu'])){
     if($_POST['choix']=="inserer"){
     form_insert();
}

    if($_POST['choix']=="afficher"){
       afficher_equip();
    }

    if($_POST['choix']=="supprimer"){
        suppr();
    }

     if($_POST['choix']=="match"){
        match();
     }
}

function afficher_equip(){
    $link = mysqli_connect("venus","aparent","","aparent");
    $res = mysqli_query($link,"SELECT Equipe, Etat, Classement, Match_Joue, Victoire, Defaite, id FROM hockey_club ORDER BY Classement ASC");

    if(isset($_GET['sortaz'])){
        $res = mysqli_query($link,"SELECT Equipe, Etat, Classement, Match_Joue, Victoire, Defaite, id FROM hockey_club ORDER BY Equipe ASC");
   }

echo "
";

    echo "
";
        echo "Equipe	";
        echo "Etat	";
        echo "Classement	";
        echo "Match joues	";
        echo "Victoires	";
        echo "Defaites	";
        echo "ID	";
        echo "
";
        echo "
";

    while ($hockey_club = mysqli_fetch_assoc($res)){

        foreach($hockey_club as $i => $valeur){
            echo "$valeur	";
        }
        echo "
";
    }

    echo "

";

    echo"

    Il faut appuyer a nouveau sur Afficher le classement apres avoir choisi le Order By: a corriger
        <form method='GET' action=''>
        <input type='submit' class='sort' style='vertical-align:middle' name='sortaz' value='A-Z'/>
        <input type='submit' class='sort' style='vertical-align:middle' name='sortetat' value='Etat'/>
        <input type='submit' class='sort' style='vertical-align:middle' name='sortclassement' value='Classement'/>
        <input type='submit' class='sort' style='vertical-align:middle' name='sortmj' value='Match Joues'/>
        <input type='submit' class='sort' style='vertical-align:middle' name='sortvic' value='Victoires'/>
        <input type='submit' class='sort' style='vertical-align:middle' name='sortdef' value='Defaites'/>
        <input type='submit' class='sort' style='vertical-align:middle' name='sortid' value='ID'/></form>
";
}


问:
Git: Internal error: refs/remotes/origin/master is not a valid packed reference
I am attempting to clone a git repository on a Windows network drive, but the process fails. It first throws a internal error: refs/remotes/origin/master is not a valid packed reference, and then repeatedly relates that it failed to unlink an index file.

```<code>x:\code\source> git clone x:\code\repos\project.git
Cloning into 'project'...
done.
error: internal error: refs/remotes/origin/master is not a valid packed reference!
fatal: update_ref failed for ref 'HEAD': cannot update the ref 'HEAD':
  Trying to write ref refs/heads/master with nonexistent object d34950c3faee46d8a7f3b8e7950b04fcc5da9d1c
Unlink of file 'project/.git/objects/pack/pack-....idx' failed. Should I try again? (y/n)
</code>```

I am able to clone without issue to a local drive from a bare repo on the network drive, but am unable to clone to a network drive.

答:
For future readers who are trying to use GitExtensions and getting this error: David C's answer works for our purposes as well, and you can type in file:// before the 'Repo to clone' location name.

This error arises when the Repo to clone and destination directory are both on a local network drive.

Body:
I am attempting to clone a git repository on a Windows network drive, but the process fails. It first throws a internal error: refs/remotes/origin/master is not a valid packed reference, and then repeatedly relates that it failed to unlink an index file.

x:\code\source> git clone x:\code\repos\project.git
Cloning into 'project'...
done.
error: internal error: refs/remotes/origin/master is not a valid packed reference!
fatal: update_ref failed for ref 'HEAD': cannot update the ref 'HEAD':
  Trying to write ref refs/heads/master with nonexistent object d34950c3faee46d8a7f3b8e7950b04fcc5da9d1c
Unlink of file 'project/.git/objects/pack/pack-....idx' failed. Should I try again? (y/n)

I am able to clone without issue to a local drive from a bare repo on the network drive, but am unable to clone to a network drive.


问:
Where is the default CA certs used in nodejs?
I'm connecting to a server whos cert is signed by my own CA, the ca's cert had installed into system's keychain.

connecting with openssl s_client -connect some.where says Verify return code: 0 (ok)

but i cant connect with nodejs's tls/https module, which fails with
Error: SELF_SIGNED_CERT_IN_CHAIN

but connecting to a normal server (i.e google.com:443) works fine.

seems that nodejs's openssl is not sharing same keychain with system's openssl.

but I cannt find where is it. i tried overide with SSL_CERT_DIR but not seemed working.

BTW: i can bypass the server verifying by setting NODE_TLS_REJECT_UNAUTHORIZED=0 , but that's not pretty enough ;)

Im using OSX 10.8.3 with OpenSSL 0.9.8r, node v0.9.8

答:
You can make node use the system's OpenSSL certificates. This is done by starting node via:

```<code>node --use-openssl-ca
</code>```

See the docs for further information.

See this answer on how system certificates are extended for Debian and Ubuntu

Body:
You can make node use the system's OpenSSL certificates. This is done by starting node via:

node --use-openssl-ca

See the docs for further information.

See this answer on how system certificates are extended for Debian and Ubuntu


问:
opening a native app from a webapp
I was wondering if it's possible to achieve some sort of thing?

I have a web app, and for example - I want it to run facebook native app, is it possible?

答:
You could use a custom URL scheme for your app.

See this question iPhone/iPad URL Custom Scheme to open a file

Title: opening a native app from a webapp


问:
Get values from a number line at specific position
I have a dataframe with three columns. The first is "A" or "B" the second is a value and the third is a value (from and to). Now I want to get the values of the first column for given values of the two other columns.

I got this data frame:

```<code>a <- c('A','B','A','B')
b <- c(0,40,60,80)
c <- c(40,60,80,100)

frame <- data.frame(a,b,c)

> frame
  a  b   c
1 A  0  40
2 B 40  60
3 A 60  80
4 B 80 100
</code>```

And I want to generate this second data frame from the first one.

```<code>> frame2
   d   e
1  A  10
2  A  20
3  A  30
4  A  40
5  B  50
6  B  60
7  A  70
8  A  80
9  B  90
10 B 100
</code>```

答:
An idea via base R,

```<code>l1 <- setNames(Map(function(i, j)seq(i, j, 10)[-1], frame$b, frame$c), frame$a)
data.frame(d = rep(names(l1), lengths(l1)), e = unlist(l1))
#   d   e
#1  A  10
#2  A  20
#3  A  30
#4  A  40
#5  B  50
#6  B  60
#7  A  70
#8  A  80
#9  B  90
#10 B 100
</code>```

A simpler way is to use stack (as @Ronak Shah mentions in comments)

```<code>stack(setNames(mapply(seq, frame$b + 10, frame$c, MoreArgs = list(by = 10)), frame$a))
</code>```

Body:
I have a dataframe with three columns. The first is "A" or "B" the second is a value and the third is a value (from and to). Now I want to get the values of the first column for given values of the two other columns.

I got this data frame:

a <- c('A','B','A','B')
b <- c(0,40,60,80)
c <- c(40,60,80,100)

frame <- data.frame(a,b,c)

> frame
  a  b   c
1 A  0  40
2 B 40  60
3 A 60  80
4 B 80 100

And I want to generate this second data frame from the first one.

> frame2
   d   e
1  A  10
2  A  20
3  A  30
4  A  40
5  B  50
6  B  60
7  A  70
8  A  80
9  B  90
10 B 100

Body:
An idea via base R,

l1 <- setNames(Map(function(i, j)seq(i, j, 10)[-1], frame$b, frame$c), frame$a)
data.frame(d = rep(names(l1), lengths(l1)), e = unlist(l1))
#   d   e
#1  A  10
#2  A  20
#3  A  30
#4  A  40
#5  B  50
#6  B  60
#7  A  70
#8  A  80
#9  B  90
#10 B 100

A simpler way is to use stack (as @Ronak Shah mentions in comments)

stack(setNames(mapply(seq, frame$b + 10, frame$c, MoreArgs = list(by = 10)), frame$a))


问:
My request in ajax with PUT method is returning error 500
I'm trying to use Ajax's put method to update my table, which is stored on a rest server but I'm getting 500 error (intenal server error), I do not know what to do, can anyone help me? I'm new to ajax programming </p>

```<code>$(document).on('click', "#modalgravar", function(){

var eURL = 'http://localhost:8081/datasnap/rest/TCadastros/Grupo/';
    var Ecdgrupo = $("#Cdgrupoedit").val();
    var Egrupo = $("#grupoedit").val();
    var eData ={"Cdgrupo": Ecdgrupo, "Grupos": Egrupo};

alert(JSON.stringify(eData));

    $.ajax({
       type:'PUT',
       url: eURL,
       data: JSON.stringify(eData),
        success: function(){
        alert("Editado!");
              },
        error: function(){
            alert("ERRO:  O grupo não foi editado!");
        }
    });
</code>```

答:
If You want to use PUT method in Datasnap You need to change procedure name on server side. Name should start with 'accept' like 'acceptURIMethodName'. So in this case propably 'acceptGrupo'. Then method URL will be:
http://localhost:8081/datasnap/rest/TCadastros/acceptGrupo/</p>

Body:
I'm trying to use Ajax's put method to update my table, which is stored on a rest server but I'm getting 500 error (intenal server error), I do not know what to do, can anyone help me? I'm new to ajax programming

$(document).on('click', "#modalgravar", function(){

var eURL = 'http://localhost:8081/datasnap/rest/TCadastros/Grupo/';
    var Ecdgrupo = $("#Cdgrupoedit").val();
    var Egrupo = $("#grupoedit").val();
    var eData ={"Cdgrupo": Ecdgrupo, "Grupos": Egrupo};

alert(JSON.stringify(eData));

    $.ajax({
       type:'PUT',
       url: eURL,
       data: JSON.stringify(eData),
        success: function(){
        alert("Editado!");
              },
        error: function(){
            alert("ERRO:  O grupo não foi editado!");
        }
    });


问:
Cant send data to Firebase using AT commands
I'm using an Arduino with a GSM modem to try to send data to firebase.
However, when I try to, I get the following error:

SEND OK HTTP/1.1 400 Bad Request Server: nginx Date: Mon, 27 May 2019
  22:34:09 GMT Content-Type: text/html Content-Length: 166 Connection:
  close Strict-Transport-Security: max-age=31556926; includeSubDomains;
  preload

 400 Bad Request
400 Bad Request

nginx

CLOSED

The AT commands I issue are:

AT+QIOPEN="TCP", "drone-polution.firebaseio.com", 443
  OK

CONNECT OK

AT+QISEND

>

POST /NewDB/.json

Accept: application/json

Content-Type: application/json

Content-Length: 9

{"a":"b"}

The last line is the actual payload.

Any help appreciated.

答:
First, try this to program SAM chip to create an interface between Modem and your console PC (I found that there are good ready functions in MC20_Arduino_Interface.h which you can setup the modem.)

A simple program looks like this:

```<code>#include "MC20_Arduino_Interface.h"

// set serial port that connects to MC20
//#define serialMC20 Serial1

void setup()
{
    //Begin serial comunication with Arduino and Arduino IDE (Serial Monitor)
    SerialUSB.begin(115200);
    while (!Serial);

    //Being serial communication witj Arduino and MC20
    serialMC20.begin(115200);
    delay(1000);

    SerialUSB.println("Setup Complete!");
}

void loop()
{
    //Read MC20 output (if available) and print it in Arduino IDE Serial Monitor
    if (serialMC20.available())
    {
        SerialUSB.write(serialMC20.read());
    }
    //Read Arduino IDE Serial Monitor inputs (if available) and send them to MC20
    if (SerialUSB.available())
    {
        serialMC20.write(SerialUSB.read());
    }
}
</code>```

Also, I suggest you use Arduino's serial monitor for communication.

If the Modem starts successfully you will see SMS Ready and Call Ready in the serial monitor.
According to Quectel HTTP docs for a POST request:

3.2. Send POST Request to HTTP Server

```<code>AT+QIFGCNT=0
OK
AT+QICSGP=1,"CMNET" //Set APN
OK
AT+QIREGAPP //Optional
OK
AT+QIACT //Optional
OK
AT+QHTTPURL=58,30 //Set URL
CONNECT
<Input data>
//For example, input 58 bytes:
http://api.efxnow.com/DEMOWebServices2.8/Service.asmx/Echo
OK
//POST the data whose size is 18 bytes and the maximum latency time for inputting is 50s.
//It is recommended to set the latency time as long as enough to download all the data in the latency time.
AT+QHTTPPOST=18,50,10
CONNECT
//This means module enters into data mode and is ready to receive data from UART.
//For example, input 18 bytes: Message=helloworld.
OK
//This means all data has been received, and DCD is set to high.
AT+QHTTPREAD=30 //Read the response of HTTP server.
CONNECT
<Output data> //Output the response data of HTTP server to UART.
//For example, UART outputs:
<?xml version="1.0" encoding="utf-8"?>
<string xmlns="https://api.efxnow.com/webservices2.3">Message='helloworld' ASCII:104 101 108 108
111 119 111 114 108 100 </string>
OK
AT+QIDEACT //Deactivate PDP context.
DEACT OK
</code>```

For example for httpbin.org/post it would become something like this:

```<code>16:45:56.416 -> AT+QIFGCNT=0
16:45:56.416 -> OK
16:46:02.918 -> AT+QICSGP=1,"mtnirancell"
16:46:02.918 -> OK
16:46:07.850 -> AT+QIREGAPP
16:46:07.850 -> OK
16:46:12.275 -> AT+QIACT
16:46:12.275 -> OK
16:46:27.467 -> AT+QHTTPURL=23,60
16:46:27.467 -> CONNECT
16:46:27.467 -> <http://httpbin.org/post>
16:46:36.965 -> OK
16:46:36.965 ->
16:46:48.786 -> AT+QHTTPPOST=18,50,10
16:46:48.786 -> CONNECT
16:46:48.786 -> <message=helloworld>
16:47:02.094 -> OK
16:47:02.094 ->
16:47:06.569 -> AT+QHTTPREAD=30
16:47:06.569 -> CONNECT
16:47:06.569 -> {
16:47:06.569 ->   "args": {},
16:47:06.569 ->   "data": "",
16:47:06.569 ->   "files": {},
16:47:06.569 ->   "form": {
16:47:06.569 ->     "message": "helloworld"
16:47:06.569 ->   },
16:47:06.569 ->   "headers": {
16:47:06.569 ->     "Accept": "*/*",
16:47:06.569 ->     "Content-Length": "18",
16:47:06.569 ->     "Content-Type": "application/x-www-form-urlencoded",
16:47:06.602 ->     "Host": "httpbin.org",
16:47:06.602 ->     "User-Agent": "QUECTEL_MODULE"
16:47:06.602 ->   },
16:47:06.602 ->   "json": null,
16:47:06.602 ->   "origin": "*******, ********",
16:47:06.602 ->   "url": "https://httpbin.org/post"
16:47:06.602 -> }
16:47:06.602 -> OK
</code>```

Body:
First, try this to program SAM chip to create an interface between Modem and your console PC (I found that there are good ready functions in MC20_Arduino_Interface.h which you can setup the modem.)

A simple program looks like this:

#include "MC20_Arduino_Interface.h"

// set serial port that connects to MC20
//#define serialMC20 Serial1

void setup()
{
    //Begin serial comunication with Arduino and Arduino IDE (Serial Monitor)
    SerialUSB.begin(115200);
    while (!Serial);

    //Being serial communication witj Arduino and MC20
    serialMC20.begin(115200);
    delay(1000);

    SerialUSB.println("Setup Complete!");
}

void loop()
{
    //Read MC20 output (if available) and print it in Arduino IDE Serial Monitor
    if (serialMC20.available())
    {
        SerialUSB.write(serialMC20.read());
    }
    //Read Arduino IDE Serial Monitor inputs (if available) and send them to MC20
    if (SerialUSB.available())
    {
        serialMC20.write(SerialUSB.read());
    }
}

Also, I suggest you use Arduino's serial monitor for communication.

If the Modem starts successfully you will see SMS Ready and Call Ready in the serial monitor.
According to Quectel HTTP docs for a POST request:

3.2. Send POST Request to HTTP Server

AT+QIFGCNT=0
OK
AT+QICSGP=1,"CMNET" //Set APN
OK
AT+QIREGAPP //Optional
OK
AT+QIACT //Optional
OK
AT+QHTTPURL=58,30 //Set URL
CONNECT
<Input data>
//For example, input 58 bytes:
http://api.efxnow.com/DEMOWebServices2.8/Service.asmx/Echo
OK
//POST the data whose size is 18 bytes and the maximum latency time for inputting is 50s.
//It is recommended to set the latency time as long as enough to download all the data in the latency time.
AT+QHTTPPOST=18,50,10
CONNECT
//This means module enters into data mode and is ready to receive data from UART.
//For example, input 18 bytes: Message=helloworld.
OK
//This means all data has been received, and DCD is set to high.
AT+QHTTPREAD=30 //Read the response of HTTP server.
CONNECT
<Output data> //Output the response data of HTTP server to UART.
//For example, UART outputs:
<?xml version="1.0" encoding="utf-8"?>
<string xmlns="https://api.efxnow.com/webservices2.3">Message='helloworld' ASCII:104 101 108 108
111 119 111 114 108 100 </string>
OK
AT+QIDEACT //Deactivate PDP context.
DEACT OK

For example for httpbin.org/post it would become something like this:

16:45:56.416 -> AT+QIFGCNT=0
16:45:56.416 -> OK
16:46:02.918 -> AT+QICSGP=1,"mtnirancell"
16:46:02.918 -> OK
16:46:07.850 -> AT+QIREGAPP
16:46:07.850 -> OK
16:46:12.275 -> AT+QIACT
16:46:12.275 -> OK
16:46:27.467 -> AT+QHTTPURL=23,60
16:46:27.467 -> CONNECT
16:46:27.467 -> <http://httpbin.org/post>
16:46:36.965 -> OK
16:46:36.965 ->
16:46:48.786 -> AT+QHTTPPOST=18,50,10
16:46:48.786 -> CONNECT
16:46:48.786 -> <message=helloworld>
16:47:02.094 -> OK
16:47:02.094 ->
16:47:06.569 -> AT+QHTTPREAD=30
16:47:06.569 -> CONNECT
16:47:06.569 -> {
16:47:06.569 ->   "args": {},
16:47:06.569 ->   "data": "",
16:47:06.569 ->   "files": {},
16:47:06.569 ->   "form": {
16:47:06.569 ->     "message": "helloworld"
16:47:06.569 ->   },
16:47:06.569 ->   "headers": {
16:47:06.569 ->     "Accept": "*/*",
16:47:06.569 ->     "Content-Length": "18",
16:47:06.569 ->     "Content-Type": "application/x-www-form-urlencoded",
16:47:06.602 ->     "Host": "httpbin.org",
16:47:06.602 ->     "User-Agent": "QUECTEL_MODULE"
16:47:06.602 ->   },
16:47:06.602 ->   "json": null,
16:47:06.602 ->   "origin": "*******, ********",
16:47:06.602 ->   "url": "https://httpbin.org/post"
16:47:06.602 -> }
16:47:06.602 -> OK


问:
How to render a nested array?
I am getting a response from an endpoint which is this:

```<code>[[{"1":"91"}],[{"1":"1"}],[{"1":"0"}],[{"1":"0"}],[{"1":"0"}],[{"1":"0"}],[{"1":"0"}],[{"1":"0"}]]
</code>```

I fetched them and I get the results but I cannot render them. This is what I have been trying:

```<code>render() {
        const {count} = this.state;
        return (
            <div>
                {count.count && count.count.map(item => (
                    item.value.map(data => (
                        data.value.map(x => (
                            <p>{x.value}</p>
                        ))
                    ))
                ))}
            </div>
        )
    }
</code>```

I expect the out to be all the numbers shown in the json response. Ex. 91 1 0 0 0 etc.

答:
First of all, the structure the array you're trying to iterate is like an array of arrays, with objects within. So, start iterate first and second arrays first, then iterate the object within. Object.keys can be used for that.

You can access it like the following,

```<code>...
    <div>
      {count &&
        count.length > 0 &&
        count.map(
          item =>
            item.length > 0 &&
            item.map(
              el =>
                Object.keys(el).length > 0 &&
                Object.keys(el).map(val => <p>{el[val]}</p>)
            )
        )}
    </div>
...
</code>```

Codesandbox demo here

Stackblitz demo here

Title: How to render a nested array?

Body:
I am getting a response from an endpoint which is this:

[[{"1":"91"}],[{"1":"1"}],[{"1":"0"}],[{"1":"0"}],[{"1":"0"}],[{"1":"0"}],[{"1":"0"}],[{"1":"0"}]]

I fetched them and I get the results but I cannot render them. This is what I have been trying:

render() {
        const {count} = this.state;
        return (

                {count.count && count.count.map(item => (
                    item.value.map(data => (
                        data.value.map(x => (

{x.value}

                        ))
                    ))
                ))}

        )
    }

I expect the out to be all the numbers shown in the json response. Ex. 91 1 0 0 0 etc.

Body:
First of all, the structure the array you're trying to iterate is like an array of arrays, with objects within. So, start iterate first and second arrays first, then iterate the object within. Object.keys can be used for that.

You can access it like the following,

...
    <div>
      {count &&
        count.length > 0 &&
        count.map(
          item =>
            item.length > 0 &&
            item.map(
              el =>
                Object.keys(el).length > 0 &&
                Object.keys(el).map(val => <p>{el[val]}</p>)
            )
        )}
    </div>
...

Codesandbox demo here

Stackblitz demo here


问:
Magento 1 - How to redirect on previous page after login
I'm using Magento 1.9.* and I would like to redirect previous page after user login successfully login.</p>

答:
The solutions of Dhrumin and Sandipan work, but I did not want to overwrite core classes and I needed a solution for login and redirect. For magento 1.9.x it seems that the only thing we have todo is to set the variable "BeforeAuthUrl" of the consumer session. Both the login and register method redirect to this url (if it exists). I put this code snippet in my header.phtml:</p>

```<code>if (!Mage::helper('customer')->isLoggedIn()) {
$loginback = $this->helper('core/url')->getCurrentUrl();
$checkLogin = strstr($loginback, 'customer/account/login');
$checkRegister = strstr($loginback, 'customer/account/create');
if (!strlen($checkLogin) && !strlen($checkRegister) ) {
    Mage::getSingleton('customer/session')->setBeforeAuthUrl($loginback);
 }
}
</code>```

Body:
The solutions of Dhrumin and Sandipan work, but I did not want to overwrite core classes and I needed a solution for login and redirect. For magento 1.9.x it seems that the only thing we have todo is to set the variable "BeforeAuthUrl" of the consumer session. Both the login and register method redirect to this url (if it exists). I put this code snippet in my header.phtml:

if (!Mage::helper('customer')->isLoggedIn()) {
$loginback = $this->helper('core/url')->getCurrentUrl();
$checkLogin = strstr($loginback, 'customer/account/login');
$checkRegister = strstr($loginback, 'customer/account/create');
if (!strlen($checkLogin) && !strlen($checkRegister) ) {
    Mage::getSingleton('customer/session')->setBeforeAuthUrl($loginback);
 }
}


问:
How to reset Combo when SWT.READ_ONLY
I am using the org.eclipse.swt.widgets.Combo class and I am doing the following

```<code>Combo myCombo = new Combo(container, SWT.READ_ONLY);
myCombo.add("1");
myCombo.add("2");

//later on
myCombo.setText(""); //will not work because READ_ONLY
</code>```

The user will choose an element of the combo, and I am providing a reset button where I want the value to be set to null. However, according to the javadoc, the setText method is ignored when the receiver is READ_ONLY. I like the Combo being read only because I only want the user to select what I provide.. But I want to set the value back to null or "" if possible. Can I do this with a the read only receiver? Or what is another good way of doing this?

Thanks!

答:
The best way is to use ComboViewer

```<code>    List<String> input = new ArrayList<String>();
    input.add("1");
    input.add("2");
    combo = new ComboViewer(container, SWT.READ_ONLY);
    combo.setLabelProvider(new LabelProvider());
    combo.setContentProvider(ArrayContentProvider.getInstance());
    combo.setInput(input);
</code>```

And to clear it

```<code>combo.setSelection(StructuredSelection.EMPTY);
</code>```

Regards

Title: How to reset Combo when SWT.READ_ONLY

Body:
I am using the org.eclipse.swt.widgets.Combo class and I am doing the following

Combo myCombo = new Combo(container, SWT.READ_ONLY);
myCombo.add("1");
myCombo.add("2");

//later on
myCombo.setText(""); //will not work because READ_ONLY

The user will choose an element of the combo, and I am providing a reset button where I want the value to be set to null. However, according to the javadoc, the setText method is ignored when the receiver is READ_ONLY. I like the Combo being read only because I only want the user to select what I provide.. But I want to set the value back to null or "" if possible. Can I do this with a the read only receiver? Or what is another good way of doing this?

Thanks!

Body:
The best way is to use ComboViewer

    List<String> input = new ArrayList<String>();
    input.add("1");
    input.add("2");
    combo = new ComboViewer(container, SWT.READ_ONLY);
    combo.setLabelProvider(new LabelProvider());
    combo.setContentProvider(ArrayContentProvider.getInstance());
    combo.setInput(input);

And to clear it

combo.setSelection(StructuredSelection.EMPTY);

Regards


问:
how to send email at backend of application in iPhone?
hi
I want to send an email when user open the application but that email should be sent at back end so that user can not judge that application send an email.
any body can help me?
thanx</p>

答:
You will need to use a third party library for that. The SDK doesn't allow you to send emails in the background.

Here's one you can use:
http://code.google.com/p/skpsmtpmessage/


问:
How to run two or more topologies with the same APPLICATION_ID_CONFIG?
I want to run 2 topologies on same instance. 1 topology involves state store and other involves global store. How do I do this succesfully?

I have created 1 topic with 3 partitions and then added a state store in 1 topology and global store in 2nd topology.

Topology 1 :

```<code>    public void createTopology() {
    Topology topology = new Topology();

    topology.addSource("source", new KeyDeserializer(), new ValueDeserializer(), "topic1");
    topology.addProcessor("processor1", new CustomProcessorSupplier1(), "source");

    final KeyValueStoreBuilder<Bytes, byte[]> rStoreBuilder = new KeyValueStoreBuilder<>(new RocksDbKeyValueBytesStoreSupplier("rstore"), Serdes.Bytes(), Serdes.ByteArray(), Time.SYSTEM);
    rStoreBuilder.withLoggingEnabled(new HashMap<>());

    topology.addStateStore(rStoreBuilder, "processor1");

    Properties p = new Properties();
    p.put(APPLICATION_ID_CONFIG, "stream1");
    p.put(BOOTSTRAP_SERVERS_CONFIG, KafkaUtil.getBootStrapServers());
    p.put(DEFAULT_KEY_SERDE_CLASS_CONFIG, KeySerde.class);
    p.put(DEFAULT_VALUE_SERDE_CLASS_CONFIG, ValueSerde.class);
    streams = new KafkaStreams(topology, p);
    streams.start();
}
</code>```

Topology 2 :

```<code>public void createTopology() {
    Topology topology = new Topology();

    final KeyValueStoreBuilder<Bytes, byte[]> rStoreBuilder = new KeyValueStoreBuilder<>(new RocksDbKeyValueBytesStoreSupplier("rstoreg"), Serdes.Bytes(), Serdes.ByteArray(), Time.SYSTEM);
    rStoreBuilder.withLoggingDisabled();

    topology.addGlobalStore(rStoreBuilder, "globalprocessname", Serdes.Bytes().deserializer(), Serdes.ByteArray().deserializer(), "topic1", "processor2", new CustomProcessorSupplier1());

    Properties p = new Properties();
    p.put(APPLICATION_ID_CONFIG, "stream1");
    p.put(BOOTSTRAP_SERVERS_CONFIG, KafkaUtil.getBootStrapServers());
    p.put(DEFAULT_KEY_SERDE_CLASS_CONFIG, KeySerde.class);
    p.put(DEFAULT_VALUE_SERDE_CLASS_CONFIG, ValueSerde.class);
    p.put(STATE_DIR_CONFIG, "/tmp/" + System.getProperty("server.port"));
    streams = new KafkaStreams(topology, p);
    streams.start();
}
}
</code>```

When running single instance:-

Expected:
Both state-store and global-store must contain all keys (data from all input partitions of topic1

Actual:
State store contains data from 2 partitions
Global store contains data from 1 partition

When running 2 instances of this code:-

Expected: Both global stores must contain all the data. 3 partitions are divided among 2 state stores and contain partial data

Actual: (S means statestore, G means global store, P means partition of input data)
S1 - P1
G1 - P2
S2 - P3
G2 - P1, P2, P3

答:
The issue is with StreamsConfig.APPLICATION_ID_CONFIG. You use same for two different types of applications.

Value of StreamsConfig.APPLICATION_ID_CONFIG is used as group.id.
group.id is used for scaling application. If you have two instance of same application (with same group.id), they start processing messages from subset of partitions.

In your case you have two different applications but they used same StreamsConfig.APPLICATION_ID_CONFIG. For each of them subset of partitions is assign (App1: 2 partitions, App2: 1 partition) and they process only subset of whole message. It is Consumer group mechanizm.

More about Consumer group you can find:

https://www.confluent.io/blog/apache-kafka-data-access-semantics-consumers-and-membership

Body:
I want to run 2 topologies on same instance. 1 topology involves state store and other involves global store. How do I do this succesfully?

I have created 1 topic with 3 partitions and then added a state store in 1 topology and global store in 2nd topology.

Topology 1 :

    public void createTopology() {
    Topology topology = new Topology();

    topology.addSource("source", new KeyDeserializer(), new ValueDeserializer(), "topic1");
    topology.addProcessor("processor1", new CustomProcessorSupplier1(), "source");

    final KeyValueStoreBuilder<Bytes, byte[]> rStoreBuilder = new KeyValueStoreBuilder<>(new RocksDbKeyValueBytesStoreSupplier("rstore"), Serdes.Bytes(), Serdes.ByteArray(), Time.SYSTEM);
    rStoreBuilder.withLoggingEnabled(new HashMap<>());

    topology.addStateStore(rStoreBuilder, "processor1");

    Properties p = new Properties();
    p.put(APPLICATION_ID_CONFIG, "stream1");
    p.put(BOOTSTRAP_SERVERS_CONFIG, KafkaUtil.getBootStrapServers());
    p.put(DEFAULT_KEY_SERDE_CLASS_CONFIG, KeySerde.class);
    p.put(DEFAULT_VALUE_SERDE_CLASS_CONFIG, ValueSerde.class);
    streams = new KafkaStreams(topology, p);
    streams.start();
}

Topology 2 :

public void createTopology() {
    Topology topology = new Topology();

    final KeyValueStoreBuilder<Bytes, byte[]> rStoreBuilder = new KeyValueStoreBuilder<>(new RocksDbKeyValueBytesStoreSupplier("rstoreg"), Serdes.Bytes(), Serdes.ByteArray(), Time.SYSTEM);
    rStoreBuilder.withLoggingDisabled();

    topology.addGlobalStore(rStoreBuilder, "globalprocessname", Serdes.Bytes().deserializer(), Serdes.ByteArray().deserializer(), "topic1", "processor2", new CustomProcessorSupplier1());

    Properties p = new Properties();
    p.put(APPLICATION_ID_CONFIG, "stream1");
    p.put(BOOTSTRAP_SERVERS_CONFIG, KafkaUtil.getBootStrapServers());
    p.put(DEFAULT_KEY_SERDE_CLASS_CONFIG, KeySerde.class);
    p.put(DEFAULT_VALUE_SERDE_CLASS_CONFIG, ValueSerde.class);
    p.put(STATE_DIR_CONFIG, "/tmp/" + System.getProperty("server.port"));
    streams = new KafkaStreams(topology, p);
    streams.start();
}
}

When running single instance:-

Expected:
Both state-store and global-store must contain all keys (data from all input partitions of topic1

Actual:
State store contains data from 2 partitions
Global store contains data from 1 partition

When running 2 instances of this code:-

Expected: Both global stores must contain all the data. 3 partitions are divided among 2 state stores and contain partial data

Actual: (S means statestore, G means global store, P means partition of input data)
S1 - P1
G1 - P2
S2 - P3
G2 - P1, P2, P3


问:
My API request code produces a bug I can't debug or understand
I am not sure where to identify the problem in this code

```<code>var events = [Events]()

    let URL_GET_DATA = "http://192.168.100.4/PrototypeWebService/api/getevents.php"

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        Alamofire.request(URL_GET_DATA).responseJSON{ response in
            if let json = response.result.value {
                print(json)
                let swiftvar = JSON(json).array
                for i in 0..<(swiftvar?.count)! {
                    let jsonObject = swiftvar?[i].object
                    self.events.append(jsonObject as! Events)
                }
                self.EventTable.reloadData()
            }
        }
    }
</code>```

I expect it to create an array of objects of type Events but it produces this error :

Thread 1: EXC_BREAKPOINT (code=1, subcode=0x102ca0f4c

答:
Your code is getting the SwiftJSON API wrong. The culprit is the line

jsonObject as! Events
```

<p>If you were actually writing the code in a safe manner using <code>as?</code> dynamic downcast operator, the compiler would gladly denounce to you that type <code>Events</code> and the type of <code>jsonObject</code> are parts of separate type hierarchies and thus the downcasting will always fail.</p>

<p>As per SwiftJSON documentation that can be found at https://github.com/SwiftyJSON/SwiftyJSON the framework does manage deserialization however its basic API does not provide any object population facilities and thus it's the programmers task.</p>

<p>Say, the <code>Events</code> type has 2 stored properties, <code>let string: String</code> and <code>let int: Int</code>.
In order to create an <code>Events</code> object off a parsed JSON object, you need to extract the values manually as such</p>

<pre class="lang-swift prettyprint-override"><code>let string = jsonObject["name"].string
let int = jsonObject["int"].int
</code>```

and then you should pass these values into your own custom-written constructor as such

let events = Events(string, int)
```

Only after this point you actually will have an Events object that you can use.

Edit: also since the release of Swift 4 there is a Codable protocol and a JSONDecoder type, which provide a robust, flexible and type-safe facilities to decode your json payloads represented by Data object and you should probably ditch the SwiftyJSON because it's an unnecessary dependency.

Body:
I am not sure where to identify the problem in this code

var events = [Events]()

    let URL_GET_DATA = "http://192.168.100.4/PrototypeWebService/api/getevents.php"

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        Alamofire.request(URL_GET_DATA).responseJSON{ response in
            if let json = response.result.value {
                print(json)
                let swiftvar = JSON(json).array
                for i in 0..<(swiftvar?.count)! {
                    let jsonObject = swiftvar?[i].object
                    self.events.append(jsonObject as! Events)
                }
                self.EventTable.reloadData()
            }
        }
    }

I expect it to create an array of objects of type Events but it produces this error :

Thread 1: EXC_BREAKPOINT (code=1, subcode=0x102ca0f4c

Body:
Your code is getting the SwiftJSON API wrong. The culprit is the line

jsonObject as! Events

If you were actually writing the code in a safe manner using as? dynamic downcast operator, the compiler would gladly denounce to you that type Events and the type of jsonObject are parts of separate type hierarchies and thus the downcasting will always fail.

As per SwiftJSON documentation that can be found at https://github.com/SwiftyJSON/SwiftyJSON the framework does manage deserialization however its basic API does not provide any object population facilities and thus it's the programmers task.

Say, the Events type has 2 stored properties, let string: String and let int: Int.
In order to create an Events object off a parsed JSON object, you need to extract the values manually as such

let string = jsonObject["name"].string
let int = jsonObject["int"].int

and then you should pass these values into your own custom-written constructor as such

let events = Events(string, int)

Only after this point you actually will have an Events object that you can use.

Edit: also since the release of Swift 4 there is a Codable protocol and a JSONDecoder type, which provide a robust, flexible and type-safe facilities to decode your json payloads represented by Data object and you should probably ditch the SwiftyJSON because it's an unnecessary dependency.


问:
pygsheet operation time out [Errno 60]
I followed all the instructions in
https://pygsheets.readthedocs.io/en/latest/

But the script does not run well and reports a operation time out error.

```<code>TimeoutError: [Errno 60] Operation timed out
</code>```

I am in China therefore I am using a Proxy - Shadowsocks to access google server. The connection is quit well since I can watch youtube HD videos.

I am on Mac and python version is 3.6.

I have tried gspread and pygsheets both.  Below I only give pygsheet codes. I have checks credentials and api enabling as in https://gspread.readthedocs.io/en/latest/oauth2.html. Besides I tried to migrate from google api v3 to v4. The problem remains.

```<code>import pygsheets
from oauth2client.service_account import ServiceAccountCredentials

gc = pygsheets.authorize(service_file='client_secret_new.json')

wks = gc.open("test").sheet1

print(wks.get_all_records())
</code>```

I expect the connection could be set well and all the data in google sheets could be retried, whether from gspread or pygsheets.

答:
import socket

import socks

socket.setdefaulttimeout(150)

socks.set_default_proxy(socks.SOCKS5, "127.0.0.1", 1086)
socket.socket = socks.socksocket
```

Title: pygsheet operation time out [Errno 60]

Body:
I followed all the instructions in
https://pygsheets.readthedocs.io/en/latest/

But the script does not run well and reports a operation time out error.

TimeoutError: [Errno 60] Operation timed out

I am in China therefore I am using a Proxy - Shadowsocks to access google server. The connection is quit well since I can watch youtube HD videos.

I am on Mac and python version is 3.6.

I have tried gspread and pygsheets both.  Below I only give pygsheet codes. I have checks credentials and api enabling as in https://gspread.readthedocs.io/en/latest/oauth2.html. Besides I tried to migrate from google api v3 to v4. The problem remains.

import pygsheets
from oauth2client.service_account import ServiceAccountCredentials

gc = pygsheets.authorize(service_file='client_secret_new.json')

wks = gc.open("test").sheet1

print(wks.get_all_records())

I expect the connection could be set well and all the data in google sheets could be retried, whether from gspread or pygsheets.


问:
Include json file in webextension
How to include json file (a dictionary) and then access data from it in my webextension? (Should work on Firefox/Chrome and preferrably others)</p>

答:
Another method is to load your JSON data as a variable in a regular javascript file:

json.js:

```<code>var data = {
  1: "hello",
  2: "world"
}
</code>```

Then include it as you would include any other script.

Title: Include json file in webextension

Body:
Another method is to load your JSON data as a variable in a regular javascript file:

json.js:

var data = {
  1: "hello",
  2: "world"
}

Then include it as you would include any other script.


问:
PHP intl extension is installed, but CakePHP install says it is missing
For over a day I have been trying to start a CakePHP 3 project. When I run the composer install command, I get the following error:

```<code>cakephp/cakephp 3.3.x requires ext-intl * -> the requested PHP extension intl is missing from your system.
</code>```

I am using MacOS Sierra 10.12.2. XCode and all that jazz are fully up-to-date. I am running PHP 5.6.25 via MAMP Pro 4.0.1 (3985). And I am trying to install CakePHP 3.3.x through my terminal, which is using ZSH instead of Bash.

I've spent quite a while trying to get intl installed. And by now I'm pretty confident that it is indeed installed:

When I run php -m I see intl in the list of PHP modules.

I have extension=intl.so in my php.ini, located in /Applications/MAMP/bin/php/php5.6.25/conf/php.ini.

The file intl.so is located in the directory /Applications/MAMP/bin/php/php5.6.25/lib/php/extensions/no-debug-non-zts-20131226.

On MAMP's phpinfo page I can see '--enable-intl' in the Configure Command cell. Further down the page, it has its own table, showing that internationalization is supported with version 1.1.0. However, in this table, for the row intl.default_locale the value is no value. Could this be my problem?

In my ~/.zshrc file I have alias php="/Applications/MAMP/bin/php/php5.6.25/bin/php" so I can be sure I'm using the correct version and installation of PHP.

I hope I haven't ruined anything by trying to use so many articles and StackOverflow answers to get this working. I know there are a number of similar intl questions here, but so far I've had no luck with any answers.

So I suppose here are my two main questions:

Is the evidence I listed above enough to suggest I truly have the intl extension correctly installed, and why does CakePHP still complain about the extension being missed if it is correctly installed?

If it is not correctly installed, how can I correct this and get CakePHP to install?

Thank you!

答: I think you have not enabled intl extension from php.ini file.

Body:
For over a day I have been trying to start a CakePHP 3 project. When I run the composer install command, I get the following error:

cakephp/cakephp 3.3.x requires ext-intl * -> the requested PHP extension intl is missing from your system.

I am using MacOS Sierra 10.12.2. XCode and all that jazz are fully up-to-date. I am running PHP 5.6.25 via MAMP Pro 4.0.1 (3985). And I am trying to install CakePHP 3.3.x through my terminal, which is using ZSH instead of Bash.

I've spent quite a while trying to get intl installed. And by now I'm pretty confident that it is indeed installed:

When I run php -m I see intl in the list of PHP modules.

I have extension=intl.so in my php.ini, located in /Applications/MAMP/bin/php/php5.6.25/conf/php.ini.

The file intl.so is located in the directory /Applications/MAMP/bin/php/php5.6.25/lib/php/extensions/no-debug-non-zts-20131226.

On MAMP's phpinfo page I can see '--enable-intl' in the Configure Command cell. Further down the page, it has its own table, showing that internationalization is supported with version 1.1.0. However, in this table, for the row intl.default_locale the value is no value. Could this be my problem?

In my ~/.zshrc file I have alias php="/Applications/MAMP/bin/php/php5.6.25/bin/php" so I can be sure I'm using the correct version and installation of PHP.

I hope I haven't ruined anything by trying to use so many articles and StackOverflow answers to get this working. I know there are a number of similar intl questions here, but so far I've had no luck with any answers.

So I suppose here are my two main questions:

Is the evidence I listed above enough to suggest I truly have the intl extension correctly installed, and why does CakePHP still complain about the extension being missed if it is correctly installed?

If it is not correctly installed, how can I correct this and get CakePHP to install?

Thank you!


问:
How to use a variable/Parameter with an IN clause in ORACLE SQL
I have a simple select query:

```<code>SELECT A
FROM B
WHERE A IN :conditions
</code>```

where A is a char.

If i do the full query as:

```<code>SELECT A
FROM B
WHERE A IN ('A','E','I','O','U')
</code>```

it works

but if i use the parameter, when i try to execute with ORACLE SQL Developer i cannot get it to work.

I've already tried to submit the parameter as:

```<code>1* ('A','E','I','O','U')
2* 'A','E','I','O','U'
3* A,E,I,O,U
</code>```

and query returns no results

What's the correct syntax to do so?

Thank U all

答:
Passing comma separated string as bind variable for VO query's IN operator

This problem vexed me for years before I discovered this solution.

I used this technique to build an object search at the CLI, where I pass in a list of schemas to a :BIND

```<code>SELECT owner,
       object_name,
       object_type
  FROM all_objects
 WHERE object_name LIKE :SEARCH
   AND owner NOT IN (
    'SYS',
    'MDSYS',
    'DBSNMP',
    'SYSTEM',
    'DVSYS',
    'APEX_050100',
    'PUBLIC',
    'ORDS_METADATA',
    'APEX_LISTENER'
)
   AND object_type IN (
    SELECT regexp_substr(:bind_ename_comma_sep_list,'[^,]+',1,level)
      FROM dual CONNECT BY
        regexp_substr(:bind_ename_comma_sep_list,'[^,]+',1,level) IS NOT NULL
)
 ORDER BY owner,
          object_name,
          object_type;
</code>```

Body:
I have a simple select query:

SELECT A
FROM B
WHERE A IN :conditions

where A is a char.

If i do the full query as:

SELECT A
FROM B
WHERE A IN ('A','E','I','O','U')

it works

but if i use the parameter, when i try to execute with ORACLE SQL Developer i cannot get it to work.

I've already tried to submit the parameter as:

1* ('A','E','I','O','U')
2* 'A','E','I','O','U'
3* A,E,I,O,U

and query returns no results

What's the correct syntax to do so?

Thank U all

Body:
Passing comma separated string as bind variable for VO query's IN operator

This problem vexed me for years before I discovered this solution.

I used this technique to build an object search at the CLI, where I pass in a list of schemas to a :BIND

SELECT owner,
       object_name,
       object_type
  FROM all_objects
 WHERE object_name LIKE :SEARCH
   AND owner NOT IN (
    'SYS',
    'MDSYS',
    'DBSNMP',
    'SYSTEM',
    'DVSYS',
    'APEX_050100',
    'PUBLIC',
    'ORDS_METADATA',
    'APEX_LISTENER'
)
   AND object_type IN (
    SELECT regexp_substr(:bind_ename_comma_sep_list,'[^,]+',1,level)
      FROM dual CONNECT BY
        regexp_substr(:bind_ename_comma_sep_list,'[^,]+',1,level) IS NOT NULL
)
 ORDER BY owner,
          object_name,
          object_type;


问:
Why does an empty Perl hash have one key?
The standard googleable answer to "How do I find out the size of a hash in Perl?" is "take the size of keys(%hash)":

```<code>my %h = {};
print scalar (keys (%h));
</code>```

This prints '1'. I was expecting zero. On the other hand. Similarly,

```<code>my %h = {};
$h{"a"} = "b";
$h{"x"} = "y";
print scalar keys (%h);
print "\nKey: $_" for (keys %h);
</code>```

Prints:

3

Key: a

Key: x

Key: HASH(0x229e8)

Where has this extra value come from?

答:
```<code>$ perl -Mwarnings -e'my %h = {}'
Reference found where even-sized list expected at -e line 1.
</code>```

strict and warnings are included with Perl for very good reasons. There is no reason not to use them.

Even better, add diagnostics into the mix too:

```<code>$ perl -Mwarnings -Mdiagnostics -e'my %h = {}'
Reference found where even-sized list expected at -e line 1 (#1)
    (W misc) You gave a single reference where Perl was expecting a list
    with an even number of elements (for assignment to a hash). This usually
    means that you used the anon hash constructor when you meant to use
    parens. In any case, a hash requires key/value pairs.

        %hash = { one => 1, two => 2, };    # WRONG
        %hash = [ qw/ an anon array / ];    # WRONG
        %hash = ( one => 1, two => 2, );    # right
        %hash = qw( one 1 two 2 );      # also fine
</code>```

Body:
The standard googleable answer to "How do I find out the size of a hash in Perl?" is "take the size of keys(%hash)":

my %h = {};
print scalar (keys (%h));

This prints '1'. I was expecting zero. On the other hand. Similarly,

my %h = {};
$h{"a"} = "b";
$h{"x"} = "y";
print scalar keys (%h);
print "\nKey: $_" for (keys %h);

Prints:

3

Key: a

Key: x

Key: HASH(0x229e8)

Where has this extra value come from?

Body:
$ perl -Mwarnings -e'my %h = {}'
Reference found where even-sized list expected at -e line 1.

strict and warnings are included with Perl for very good reasons. There is no reason not to use them.

Even better, add diagnostics into the mix too:

$ perl -Mwarnings -Mdiagnostics -e'my %h = {}'
Reference found where even-sized list expected at -e line 1 (#1)
    (W misc) You gave a single reference where Perl was expecting a list
    with an even number of elements (for assignment to a hash). This usually
    means that you used the anon hash constructor when you meant to use
    parens. In any case, a hash requires key/value pairs.

        %hash = { one => 1, two => 2, };    # WRONG
        %hash = [ qw/ an anon array / ];    # WRONG
        %hash = ( one => 1, two => 2, );    # right
        %hash = qw( one 1 two 2 );      # also fine


问:
search by comprenent attribute on angular
I'm creating an Angular application using PokéAPi that help me lists all the pokémon.

I want to add a search area so we can find a pokémon by his name from the list.

I tried to use Pipe & filter but it's not working.

Here's my component.html code:

```<code>  <h1>Pokédex Application using Angular </h1>
   <span>Voici le listing des Pokemons</span>
  <input [(ngModel)]="searchText" placeholder="search text goes here">

 <div class="pokedex">
  <div class="pokedex-pokemon" *ngFor="let p of pokemon | filter :
  searchText">
  <div class="pokedex-pokemon-id">
  #{{ p.id}}
   </div>
    <img [ngClass]="{'hidden': !p.imageLoaded}" class="pokedex-pokemon-
 sprite" (load)="p.imageLoaded = true" [attr.src]="p.sprite">
<div class="pokedex-pokemon-name">
  {{ p.name | capitalize }}
 </div>
 </div>
</div>
 <button class="load-button" (click)="loadMore()" [disabled]="isLoading">
 <span *ngIf="!error">
 <span *ngIf="isLoading">Plus...</span>
 <span *ngIf="!isLoading">Plus</span>
 </span>
  <span *ngIf="error">
 Erreur de chargement
  </span>
 </button>
</code>```

My compenent.ts

```<code> import { Component } from '@angular/core';

 import { PokedexService } from './pokedex.service';
 import { Pokemon } from './pokemon';

 @Component({
  selector: 'app-root',
 templateUrl: 'app.component.html',
 styleUrls: ['app.component.css']
 })
export class AppComponent {
 pokemon: Pokemon[] = [];
 isLoading: boolean ;
 error: boolean ;

 constructor(private pokedexService: PokedexService) { }

 ngOnInit() {
this.loadMore();
}
loadMore() {
this.isLoading = true;

this.pokedexService.getPokemon(this.pokemon.length, 9)
  .then(pokemon => {
    pokemon = pokemon.map(p => {
      p.imageLoaded = false;
      return p;
    });
    this.pokemon = this.pokemon.concat(pokemon);
    this.isLoading = false;
    this.error = false;
  })
  .catch(() => {
    this.error = true;
    this.isLoading = false;
  });
  }
  }
</code>```

and filter.pipe.ts

```<code>  import { Pipe, PipeTransform } from '@angular/core';
 @Pipe({
name: 'filter'
 })
 export class FilterPipe implements PipeTransform {
transform(items: any[], searchText: string): any[] {
    if(!items) return [];
    if(!searchText) return items;
    searchText = searchText.toLowerCase();
    return items.filter( it => {
        return it.toLowerCase().includes(searchText);
    });
     }
   }
</code>```

Here's an overview of what I've got in my browser :

can you help me detect where is the problem and how to fix it because the search is not working?

答:
You are filtering the whole object not it's properties. Try something like that:

```<code>import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
  name: 'filter'
})
export class FilterPipe implements PipeTransform {
  transform(items: any[], searchText: string): any[] {
    if (!items) return [];
    if (!searchText) return items;
    searchText = searchText.toLowerCase();
    return items.filter(it => {
      let hit = false;
      const keys = Object.keys(it);
      for (const key of keys) {
        if (typeof it[key] === 'string') {
          const property = it[key] as string;
          if (property.toLowerCase().includes(searchText)) {
            hit = true;
            break;
          }
        }
      }
      return hit;
    });
  }
}
</code>```

Here a working example: https://stackblitz.com/edit/angular-ztn6by

Body:
I'm creating an Angular application using PokéAPi that help me lists all the pokémon.

I want to add a search area so we can find a pokémon by his name from the list.

I tried to use Pipe & filter but it's not working.

Here's my component.html code:

Pokédex Application using Angular

   Voici le listing des Pokemons
  <input [(ngModel)]="searchText" placeholder="search text goes here">

  #{{ p.id}}

  {{ p.name | capitalize }}

 <button class="load-button" (click)="loadMore()" [disabled]="isLoading">

 Plus...
 Plus

 Erreur de chargement

 </button>

My compenent.ts

 import { Component } from '@angular/core';

 import { PokedexService } from './pokedex.service';
 import { Pokemon } from './pokemon';

 @Component({
  selector: 'app-root',
 templateUrl: 'app.component.html',
 styleUrls: ['app.component.css']
 })
export class AppComponent {
 pokemon: Pokemon[] = [];
 isLoading: boolean ;
 error: boolean ;

 constructor(private pokedexService: PokedexService) { }

 ngOnInit() {
this.loadMore();
}
loadMore() {
this.isLoading = true;

this.pokedexService.getPokemon(this.pokemon.length, 9)
  .then(pokemon => {
    pokemon = pokemon.map(p => {
      p.imageLoaded = false;
      return p;
    });
    this.pokemon = this.pokemon.concat(pokemon);
    this.isLoading = false;
    this.error = false;
  })
  .catch(() => {
    this.error = true;
    this.isLoading = false;
  });
  }
  }

and filter.pipe.ts

  import { Pipe, PipeTransform } from '@angular/core';
 @Pipe({
name: 'filter'
 })
 export class FilterPipe implements PipeTransform {
transform(items: any[], searchText: string): any[] {
    if(!items) return [];
    if(!searchText) return items;
    searchText = searchText.toLowerCase();
    return items.filter( it => {
        return it.toLowerCase().includes(searchText);
    });
     }
   }

Here's an overview of what I've got in my browser :

can you help me detect where is the problem and how to fix it because the search is not working?

Body:
You are filtering the whole object not it's properties. Try something like that:

import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
  name: 'filter'
})
export class FilterPipe implements PipeTransform {
  transform(items: any[], searchText: string): any[] {
    if (!items) return [];
    if (!searchText) return items;
    searchText = searchText.toLowerCase();
    return items.filter(it => {
      let hit = false;
      const keys = Object.keys(it);
      for (const key of keys) {
        if (typeof it[key] === 'string') {
          const property = it[key] as string;
          if (property.toLowerCase().includes(searchText)) {
            hit = true;
            break;
          }
        }
      }
      return hit;
    });
  }
}

Here a working example: https://stackblitz.com/edit/angular-ztn6by


问:
GuzzleHttp\Client JSON Return as String
I have very simple question, how to convert this strings to JSON ?

This string i am getting from Guzzle POST Request and here is code :

```<code>return $body->getBody()->getContents();
</code>```

Result:

```<code>""k\n\n{\"success\":true,\"payload\":{\"id\":\"txn_ngS2aS9FY7raxy8JTUivAZCtWJy7EeznwPE8\"}}""
</code>```

with var_dump result and what is that k before ?

```<code>string(79) "k {"success":true,"payload":{"id":"txn_eeM6T6Fvkq3Pr4AWtK2TKYmNwKmodNwVqJod"}}"
</code>```

答:
I found problem isn't in my code but it was in external api payload, payload sending json data with "k" string.

Thanks @Ozan Kurt to figure out external link.

So right now only picking curly brackets with regex :

```<code>$result = preg_match("/{.+}", $body->getBody()->getContents(), $matched);

if ($matched) {
  return json_decode($matched[0]);
}
</code>```

Title: GuzzleHttp\Client JSON Return as String

Body:
I have very simple question, how to convert this strings to JSON ?

This string i am getting from Guzzle POST Request and here is code :

return $body->getBody()->getContents();

Result:

""k\n\n{\"success\":true,\"payload\":{\"id\":\"txn_ngS2aS9FY7raxy8JTUivAZCtWJy7EeznwPE8\"}}""

with var_dump result and what is that k before ?

string(79) "k {"success":true,"payload":{"id":"txn_eeM6T6Fvkq3Pr4AWtK2TKYmNwKmodNwVqJod"}}"

Body:
I found problem isn't in my code but it was in external api payload, payload sending json data with "k" string.

Thanks @Ozan Kurt to figure out external link.

So right now only picking curly brackets with regex :

$result = preg_match("/{.+}", $body->getBody()->getContents(), $matched);

if ($matched) {
  return json_decode($matched[0]);
}


问:
Start BottomSheetFragment for result
I want to get results from BottomSheetFragment. I tried to do it through getActivity().setResult(Activity.RESULT_OK, null); inside

```<code>    @Override
public void onDismiss(DialogInterface dialog) {
    getActivity().setResult(Activity.RESULT_OK, null);
    super.onDismiss(dialog);
}
</code>```

but activity's method onActivityResult not called. What am I doing wrong?

```<code>    @Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    Toast.makeText(this, requestCode, Toast.LENGTH_SHORT).show();
    super.onActivityResult(requestCode, resultCode, data);
}
</code>```

Dialog start method

```<code>BottomSheetDialogFragment bottomSheetFragment = new BottomSheetDialogFragment();
            Bundle bundle = new Bundle();
            bottomSheetFragment.setArguments(bundle);
            bottomSheetFragment.show(getSupportFragmentManager(), bottomSheetFragment.getTag());
</code>```

答:
I decided to implement the interface as suggested to me by DEVV911

```<code>interface OnFinishedListener {

        void onFinished(ArrayList<TestCard> acceptList, ArrayList<TestCard> rejectList);

        void onFailure(Throwable t);
    }
</code>```

add it into dialog's construction method

```<code>private TestActivityContract.OnFinishedListener onFinishedListener;

BottomSheetFragment(TestActivityContract.OnFinishedListener onFinishedListener) {
    this.onFinishedListener = onFinishedListener;
}
</code>```

And call the onFinished method in onDismiss

```<code>    @Override
public void onDismiss(DialogInterface dialog) {
    super.onDismiss(dialog);
    onFinishedListener.onFinished(acceptList, rejectList);
}
</code>```

Title: Start BottomSheetFragment for result

Body:
I want to get results from BottomSheetFragment. I tried to do it through getActivity().setResult(Activity.RESULT_OK, null); inside

    @Override
public void onDismiss(DialogInterface dialog) {
    getActivity().setResult(Activity.RESULT_OK, null);
    super.onDismiss(dialog);
}

but activity's method onActivityResult not called. What am I doing wrong?

    @Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    Toast.makeText(this, requestCode, Toast.LENGTH_SHORT).show();
    super.onActivityResult(requestCode, resultCode, data);
}

Dialog start method

BottomSheetDialogFragment bottomSheetFragment = new BottomSheetDialogFragment();
            Bundle bundle = new Bundle();
            bottomSheetFragment.setArguments(bundle);
            bottomSheetFragment.show(getSupportFragmentManager(), bottomSheetFragment.getTag());

Body:
I decided to implement the interface as suggested to me by DEVV911

interface OnFinishedListener {

        void onFinished(ArrayList<TestCard> acceptList, ArrayList<TestCard> rejectList);

        void onFailure(Throwable t);
    }

add it into dialog's construction method

private TestActivityContract.OnFinishedListener onFinishedListener;

BottomSheetFragment(TestActivityContract.OnFinishedListener onFinishedListener) {
    this.onFinishedListener = onFinishedListener;
}

And call the onFinished method in onDismiss

    @Override
public void onDismiss(DialogInterface dialog) {
    super.onDismiss(dialog);
    onFinishedListener.onFinished(acceptList, rejectList);
}


问:
Add whole S3 images bucket to Amazon Rekognition collection
In AWS CLI, I can add to a collection only a single image at a time.

Is there any way to add the whole S3 bucket to a collection?

答:
The IndexFaces() API call accepts only one image at a time, but can index up to 100 faces from that image.

If you wish to add faces from multiple images (eg a whole bucket or folder), you would need to call IndexFaces() multiple times (once per image). This would involve a call to Amazon S3 to list the files, then a loop to call IndexFaces().

It would be relatively simple in a scripting language like Python.


答: A naive explanation would be that .diff() literally subtracts following entries while np.gradient() uses a central difference scheme.

Title: python pandas: how to calculate derivative/gradient

Body:
Given that I have the following two vectors:

In [99]: time_index
Out[99]:
[1484942413,
 1484942712,
 1484943012,
 1484943312,
 1484943612,
 1484943912,
 1484944212,
 1484944511,
 1484944811,
 1484945110]

In [100]: bytes_in
Out[100]:
[1293981210388,
 1293981379944,
 1293981549960,
 1293981720866,
 1293981890968,
 1293982062261,
 1293982227492,
 1293982391244,
 1293982556526,
 1293982722320]

Where bytes_in is an incremental only counter, and time_index is a list to unix timestamps (epoch).

Objective: What I would like to calculate is the bitrate.

That means that I will build a data frame like

In [101]: timeline = pandas.to_datetime(time_index, unit="s")

In [102]: recv = pandas.Series(bytes_in, timeline).resample("300S").mean().ffill().apply(lambda i: i*8)

In [103]: recv
Out[103]:
2017-01-20 20:00:00    10351849683104
2017-01-20 20:05:00    10351851039552
2017-01-20 20:10:00    10351852399680
2017-01-20 20:15:00    10351853766928
2017-01-20 20:20:00    10351855127744
2017-01-20 20:25:00    10351856498088
2017-01-20 20:30:00    10351857819936
2017-01-20 20:35:00    10351859129952
2017-01-20 20:40:00    10351860452208
2017-01-20 20:45:00    10351861778560
Freq: 300S, dtype: int64

Question: Now, what is strange, calculating the gradient manually gives me :

In [104]: (bytes_in[1]-bytes_in[0])*8/300
Out[104]: 4521.493333333333

which is the correct value ..

while calculating the gradient with pandas gives me

In [124]: recv.diff()
Out[124]:
2017-01-20 20:00:00          NaN
2017-01-20 20:05:00    1356448.0
2017-01-20 20:10:00    1360128.0
2017-01-20 20:15:00    1367248.0
2017-01-20 20:20:00    1360816.0
2017-01-20 20:25:00    1370344.0
2017-01-20 20:30:00    1321848.0
2017-01-20 20:35:00    1310016.0
2017-01-20 20:40:00    1322256.0
2017-01-20 20:45:00    1326352.0
Freq: 300S, dtype: float64

which is not the same as above, 1356448.0 is different than 4521.493333333333

Could you please enlighten on what I am doing wrong ?