问:
Error building Atom from source with Nodejs 7.7.4
I'm trying to build the Atom editor from source on Fedora. I've already installed all dependencies but I couldn't install Node.js 6.x via nvm (as recommended on Atom's Installation Guide "https://github.com/atom/atom/blob/master/docs/build-instructions/linux.md").
So I installed Node.js via nvm and I got Node.js v7.7.4. Now when I run "script/build" on the atom directory I get this error message:

```<code>/home/andre/src/atom/script/lib/verify-machine-requirements.js:23
throw new Error(`Atom does not build properly on node v7+. node v${fullVersion} is installed.`)
^

Error: Atom does not build properly on node v7+. node v7.7.4 is installed.
at verifyNode (/home/andre/src/atom/script/lib/verify-machine-requirements.js:23:11)
at module.exports (/home/andre/src/atom/script/lib/verify-machine-requirements.js:10:3)
at Object.<anonymous> (/home/andre/src/atom/script/bootstrap:18:1)
at Module._compile (module.js:571:32)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
at Module.require (module.js:498:17)
at require (internal/module.js:20:19)
</code>```

I'd like to know how can I install Node.js 6.x and use it when building Atom instead of using Node.js v7.7.4

答:
nvm install 6.x
nvm use 6.x
```

If still problem,
nvm uninstall 7.7.4

Body:
I'm trying to build the Atom editor from source on Fedora. I've already installed all dependencies but I couldn't install Node.js 6.x via nvm (as recommended on Atom's Installation Guide "https://github.com/atom/atom/blob/master/docs/build-instructions/linux.md").
So I installed Node.js via nvm and I got Node.js v7.7.4. Now when I run "script/build" on the atom directory I get this error message:

/home/andre/src/atom/script/lib/verify-machine-requirements.js:23
throw new Error(`Atom does not build properly on node v7+. node v${fullVersion} is installed.`)
^

Error: Atom does not build properly on node v7+. node v7.7.4 is installed.
at verifyNode (/home/andre/src/atom/script/lib/verify-machine-requirements.js:23:11)
at module.exports (/home/andre/src/atom/script/lib/verify-machine-requirements.js:10:3)
at Object.<anonymous> (/home/andre/src/atom/script/bootstrap:18:1)
at Module._compile (module.js:571:32)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
at Module.require (module.js:498:17)
at require (internal/module.js:20:19)

I'd like to know how can I install Node.js 6.x and use it when building Atom instead of using Node.js v7.7.4

Body:
nvm install 6.x
nvm use 6.x

If still problem,
nvm uninstall 7.7.4


来源: stackexchange

问:
Cloud Functions for Firebase suddenly timing out
Suddenly after deploying my functions today some of our functions suddenly always timeout. I see this in the cloud functions console. This seems to happen when nesting and returning promises. Strange thing is this never happened before.

Here's my code.

```<code>exports.pushMessageQueue = functions.database.ref('/userPushMessagesQueue/{userId}/{messageId}').onWrite(event => {
    if (!event.data.exists()) {
        console.log('DOES NOT EXIST!');
        return "not exists";
    }

    console.log("EXISTS!");

    const userId = event.params['userId'];
    const messageId = event.params['messageId'];

    const payload = event.data.val();

    return database.ref('devices').orderByChild('user_id').equalTo(userId).once('value', snapshot => {
        if (!snapshot.exists()) {
            return "no devices found";
        }

        const devices = snapshot.val();

        const deviceTokens = [];

        snapshot.forEach(deviceSnap => {
            const device = deviceSnap.val();
            deviceTokens.push(device['fcm_key']);
        });

        const removeFromQueue = database.ref(`/userPushMessagesQueue/${userId}/${messageId}`);

        console.log('then0');

        return removeFromQueue.set(null).then(() => {
            console.log('then1');
            return admin.messaging().sendToDevice(deviceTokens, payload).then(() => {
                console.log('then2');
                return "send";
            });
        }, (error) => {
            console.log('error1!');
            console.log(error);
        });
    });
});
</code>```

In the console then0 is logged, not then1 and then2. And that while I receive the push notification and the entry is removed from the queue.

Is there something I am doing wrong?

答:
You are returning the once() function, not a promise chain.

Essentially, you've written this:

```<code>//returns the once promise
return ref.once('value', function(snap) {
  /* some stuff that doesn't affect the promise chain happens here */
});
</code>```

When what you wanted is this:

```<code>// returns whatever happens in the .then() callback
return ref.once('value').then(snap => {
   /* now whatever you return here affects the promise chain */
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Suddenly after deploying my functions today some of our functions suddenly always timeout. I see this in the cloud functions console. This seems to happen when nesting and returning promises. Strange thing is this never happened before.

Here's my code.

exports.pushMessageQueue = functions.database.ref('/userPushMessagesQueue/{userId}/{messageId}').onWrite(event => {
    if (!event.data.exists()) {
        console.log('DOES NOT EXIST!');
        return "not exists";
    }

    console.log("EXISTS!");

    const userId = event.params['userId'];
    const messageId = event.params['messageId'];

    const payload = event.data.val();

    return database.ref('devices').orderByChild('user_id').equalTo(userId).once('value', snapshot => {
        if (!snapshot.exists()) {
            return "no devices found";
        }

        const devices = snapshot.val();

        const deviceTokens = [];

        snapshot.forEach(deviceSnap => {
            const device = deviceSnap.val();
            deviceTokens.push(device['fcm_key']);
        });

        const removeFromQueue = database.ref(`/userPushMessagesQueue/${userId}/${messageId}`);

        console.log('then0');

        return removeFromQueue.set(null).then(() => {
            console.log('then1');
            return admin.messaging().sendToDevice(deviceTokens, payload).then(() => {
                console.log('then2');
                return "send";
            });
        }, (error) => {
            console.log('error1!');
            console.log(error);
        });
    });
});

In the console then0 is logged, not then1 and then2. And that while I receive the push notification and the entry is removed from the queue.

Is there something I am doing wrong?

Body:
You are returning the once() function, not a promise chain.

Essentially, you've written this:

//returns the once promise
return ref.once('value', function(snap) {
  /* some stuff that doesn't affect the promise chain happens here */
});

When what you wanted is this:

// returns whatever happens in the .then() callback
return ref.once('value').then(snap => {
   /* now whatever you return here affects the promise chain */
});


问:
Single quote in SQL
I get this error message:

```<code>03-30 00:51:50.373 30267-30267/com.example.text E/JavaBinder: !!! FAILED BINDER TRANSACTION !!!
03-30 00:51:54.273 30267-30267/com.example.text E/SQLiteLog: (1) near "hand": syntax error
03-30 00:51:54.273 30267-30267/com.example.text E/AndroidRuntime: FATAL EXCEPTION: main
                                                                  Process: com.example.text, PID: 30267
                                                                  android.database.sqlite.SQLiteException: near "hand": syntax error (code 1): , while compiling: INSERT INTO Result (Date, Name, Content) VALUES ('20170330_005134', 'Next, adjust the collar.', 'Next, adjust the collar.

                                                                  First, put your left'hand into miyatsukuchi

                                                                  and adjust the collar on the right side

                                                                  so It lies ﬂat. Then, adjust the left collar

                                                                  so it lies ﬂat. There should be a ﬁst-sized space between

                                                                  the back of your neck and the collar.');
                                                                      at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
                                                                      at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:1093)
                                                                      at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:670)
                                                                      at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
                                                                      at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:59)
                                                                      at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
                                                                      at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1798)
                                                                      at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1729)
                                                                      at seeto.fyp.textcamera.ResultHelper.addResult(ResultHelper.java:101)
                                                                      at seeto.fyp.textcamera.ResultActivity$2.onClick(ResultActivity.java:74)
                                                                      at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:162)
                                                                      at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                      at android.os.Looper.loop(Looper.java:145)
                                                                      at android.app.ActivityThread.main(ActivityThread.java:5938)
                                                                      at java.lang.reflect.Method.invoke(Native Method)
                                                                      at java.lang.reflect.Method.invoke(Method.java:372)
                                                                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1400)
                                                                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)
</code>```

I know the problem occurs on the single quote in the text, while I need the single quote (or double quote) in some case.

I have tried content = content.replace("'", "\'");, but it seems doesn't work.

How can I insert the data to the database with the single and double quote?

```<code>public void addResult(String name, String date, String content) {
    database.execSQL("INSERT INTO " + tbName + " (" + keyDate + ", " + keyName + ", " + keyContent + ") VALUES ('" + date + "', '" + name + "', '" + content + "');");
}
</code>```

答:
In SQL, single quotes must be escaped by doubling them.
There would be a helper function to do this, but it is easier to just use parameters:

public void addResult(String name, String date, String content) {
    database.execSQL("INSERT INTO " + tbName +
                     " (" + keyDate + ", " + keyName + ", " + keyContent + ")" +
                     " VALUES (?, ?, ?);",
                     new Object[]{ date, name, content });
}
```

<p>Even easier is to use insert(), which creates the SQL command for you:</p>

<pre class="lang-java prettyprint-override"><code>public void addResult(String name, String date, String content) {
    ContentValues cv = new ContentValues();
    cv.put(keyDate, date);
    cv.put(keyName, name);
    cv.put(keyContent, content);
    database.insertOrThrow(tbName, null, cv);
}
</code>```

Title: Single quote in SQL

Body:
I get this error message:

03-30 00:51:50.373 30267-30267/com.example.text E/JavaBinder: !!! FAILED BINDER TRANSACTION !!!
03-30 00:51:54.273 30267-30267/com.example.text E/SQLiteLog: (1) near "hand": syntax error
03-30 00:51:54.273 30267-30267/com.example.text E/AndroidRuntime: FATAL EXCEPTION: main
                                                                  Process: com.example.text, PID: 30267
                                                                  android.database.sqlite.SQLiteException: near "hand": syntax error (code 1): , while compiling: INSERT INTO Result (Date, Name, Content) VALUES ('20170330_005134', 'Next, adjust the collar.', 'Next, adjust the collar.

                                                                  First, put your left'hand into miyatsukuchi

                                                                  and adjust the collar on the right side

                                                                  so It lies ﬂat. Then, adjust the left collar

                                                                  so it lies ﬂat. There should be a ﬁst-sized space between

                                                                  the back of your neck and the collar.');
                                                                      at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
                                                                      at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:1093)
                                                                      at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:670)
                                                                      at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
                                                                      at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:59)
                                                                      at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
                                                                      at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1798)
                                                                      at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1729)
                                                                      at seeto.fyp.textcamera.ResultHelper.addResult(ResultHelper.java:101)
                                                                      at seeto.fyp.textcamera.ResultActivity$2.onClick(ResultActivity.java:74)
                                                                      at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:162)
                                                                      at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                      at android.os.Looper.loop(Looper.java:145)
                                                                      at android.app.ActivityThread.main(ActivityThread.java:5938)
                                                                      at java.lang.reflect.Method.invoke(Native Method)
                                                                      at java.lang.reflect.Method.invoke(Method.java:372)
                                                                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1400)
                                                                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)

I know the problem occurs on the single quote in the text, while I need the single quote (or double quote) in some case.

I have tried content = content.replace("'", "\'");, but it seems doesn't work.

How can I insert the data to the database with the single and double quote?

public void addResult(String name, String date, String content) {
    database.execSQL("INSERT INTO " + tbName + " (" + keyDate + ", " + keyName + ", " + keyContent + ") VALUES ('" + date + "', '" + name + "', '" + content + "');");
}

Body:
In SQL, single quotes must be escaped by doubling them.
There would be a helper function to do this, but it is easier to just use parameters:

public void addResult(String name, String date, String content) {
    database.execSQL("INSERT INTO " + tbName +
                     " (" + keyDate + ", " + keyName + ", " + keyContent + ")" +
                     " VALUES (?, ?, ?);",
                     new Object[]{ date, name, content });
}

Even easier is to use insert(), which creates the SQL command for you:

public void addResult(String name, String date, String content) {
    ContentValues cv = new ContentValues();
    cv.put(keyDate, date);
    cv.put(keyName, name);
    cv.put(keyContent, content);
    database.insertOrThrow(tbName, null, cv);
}


问:
exports.__esModule = true; shows as an error in angular 1.6 transpiled code
I don't know what's the change by babel, but i am trying to resolve from past 2 days :(

Issue is:

```<code>Uncaught ReferenceError: exports is not defined at app.js:2
</code>```

and I have 102 issues in chrome console due to a single line in my transpiled code i.e.

```<code>exports.__esModule = true;
</code>```

Following things are used in my project as follows:

```<code>Angular 1.6
Typescript
Babel@6
</code>```

Any help would be appreciated. Thanks :)

答:
npm install @types/node

https://www.npmjs.com/package/@types/node

The .d.ts files will define the exports global

Body:
I don't know what's the change by babel, but i am trying to resolve from past 2 days :(

Issue is:

Uncaught ReferenceError: exports is not defined at app.js:2

and I have 102 issues in chrome console due to a single line in my transpiled code i.e.

exports.__esModule = true;

Following things are used in my project as follows:

Angular 1.6
Typescript
Babel@6

Any help would be appreciated. Thanks :)


问:
FailingHttpStatusCodeException: 401 Unauthorized acess using HtmlUnit
I'm trying to connect to a page using HtmlUnit using this code:

```<code>WebClient webClient = new WebClient();
webClient.getOptions().setThrowExceptionOnScriptError(false);
HtmlPage loginPage = webClient.getPage(WEBSPHERE_URL);
</code>```

But I'm always getting this error:

```<code>18:06:00,390 ERROR [stderr] (Refresh Thread: Equinox Container: 90609616-a614-0017-138e-e6e4aa4a0871) com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException: 401 Unauthorized for https://portal-intranet.ti.sabesp.com.br/wps/myportal
18:06:00,390 ERROR [stderr] (Refresh Thread: Equinox Container: 90609616-a614-0017-138e-e6e4aa4a0871)   at com.gargoylesoftware.htmlunit.WebClient.throwFailingHttpStatusCodeExceptionIfNecessary(WebClient.java:576)
18:06:00,390 ERROR [stderr] (Refresh Thread: Equinox Container: 90609616-a614-0017-138e-e6e4aa4a0871)   at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:401)
</code>```

When I try access the URL using a browser, it works perfectly. How should I do to get this problem fixed?

UPDATE

Now I'm getting this error:

```<code>21:43:35,746 ERROR [osgi.logging.setup_environment] (Thread-257) [br.com.sabesp.setupenvironment.portlet.SetupEnvironmentAction(2427)] The activate method has thrown an exception : java.lang.LinkageError: loader constraint violation: when resolving method "com.gargoylesoftware.htmlunit.WebClient.setCredentialsProvider(Lorg/apache/http/client/CredentialsProvider;)V" the class loader (instance of org/eclipse/osgi/internal/loader/EquinoxClassLoader) of the current class, br/com/sabesp/setupenvironment/importer/util/WebContentUtil, and the class loader (instance of org/eclipse/osgi/internal/loader/EquinoxClassLoader) for the method's defining class, com/gargoylesoftware/htmlunit/WebClient, have different Class objects for the type org/apache/http/client/CredentialsProvider used in the signature
</code>```

When I try do this:

```<code>DefaultCredentialsProvider userCredentials = new DefaultCredentialsProvider();
userCredentials.addCredentials("username", "password");
webClient.setCredentialsProvider(userCredentials);
</code>```

I'm working with Liferay DXP witch is based on OSGi framework and I'm using also Gradle.

答:
You seem to run against an intranet website, and this can detect your username from the browser I guess.

With HtmlUnit, you can use NTLM authentication:

```<code>DefaultCredentialsProvider credentialsProvider =
                (DefaultCredentialsProvider) webClient.getCredentialsProvider();
credentialsProvider.addCredentials("username", "password");
//OR
credentialsProvider.addNTLMCredentials("username", "password", null, -1, "localhost", "domain");
</code>```

You can also enable traffic logging to see what type of authentication is needed:

```<code>LogManager.getLogger("org.apache.http.wire").setLevel(Level.ALL);
</code>```

Update :

You seem to have conflicting httpclient jars, please remove one of them.

The following code would tell which one is being used:

```<code>System.out.println(CredentialsProvider.class.getProtectionDomain()
    .getCodeSource().getLocation());
</code>```

Body:
I'm trying to connect to a page using HtmlUnit using this code:

WebClient webClient = new WebClient();
webClient.getOptions().setThrowExceptionOnScriptError(false);
HtmlPage loginPage = webClient.getPage(WEBSPHERE_URL);

But I'm always getting this error:

18:06:00,390 ERROR [stderr] (Refresh Thread: Equinox Container: 90609616-a614-0017-138e-e6e4aa4a0871) com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException: 401 Unauthorized for https://portal-intranet.ti.sabesp.com.br/wps/myportal
18:06:00,390 ERROR [stderr] (Refresh Thread: Equinox Container: 90609616-a614-0017-138e-e6e4aa4a0871)   at com.gargoylesoftware.htmlunit.WebClient.throwFailingHttpStatusCodeExceptionIfNecessary(WebClient.java:576)
18:06:00,390 ERROR [stderr] (Refresh Thread: Equinox Container: 90609616-a614-0017-138e-e6e4aa4a0871)   at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:401)

When I try access the URL using a browser, it works perfectly. How should I do to get this problem fixed?

UPDATE

Now I'm getting this error:

21:43:35,746 ERROR [osgi.logging.setup_environment] (Thread-257) [br.com.sabesp.setupenvironment.portlet.SetupEnvironmentAction(2427)] The activate method has thrown an exception : java.lang.LinkageError: loader constraint violation: when resolving method "com.gargoylesoftware.htmlunit.WebClient.setCredentialsProvider(Lorg/apache/http/client/CredentialsProvider;)V" the class loader (instance of org/eclipse/osgi/internal/loader/EquinoxClassLoader) of the current class, br/com/sabesp/setupenvironment/importer/util/WebContentUtil, and the class loader (instance of org/eclipse/osgi/internal/loader/EquinoxClassLoader) for the method's defining class, com/gargoylesoftware/htmlunit/WebClient, have different Class objects for the type org/apache/http/client/CredentialsProvider used in the signature

When I try do this:

DefaultCredentialsProvider userCredentials = new DefaultCredentialsProvider();
userCredentials.addCredentials("username", "password");
webClient.setCredentialsProvider(userCredentials);

I'm working with Liferay DXP witch is based on OSGi framework and I'm using also Gradle.

Body:
You seem to run against an intranet website, and this can detect your username from the browser I guess.

With HtmlUnit, you can use NTLM authentication:

DefaultCredentialsProvider credentialsProvider =
                (DefaultCredentialsProvider) webClient.getCredentialsProvider();
credentialsProvider.addCredentials("username", "password");
//OR
credentialsProvider.addNTLMCredentials("username", "password", null, -1, "localhost", "domain");

You can also enable traffic logging to see what type of authentication is needed:

LogManager.getLogger("org.apache.http.wire").setLevel(Level.ALL);

Update :

You seem to have conflicting httpclient jars, please remove one of them.

The following code would tell which one is being used:

System.out.println(CredentialsProvider.class.getProtectionDomain()
    .getCodeSource().getLocation());


问:
Unable to display printer options with AirPrint
I want to add AirPrint functionality to my iPad application

I have been trying to display printer ontions described in Apple's Drawing and Printing Guide

I have toolbar and UIBarButtonItem *printButton. In controller I receive onPrintClick and try to display printer options by such code:

```<code>UIPrintInteractionController *controller = [UIPrintInteractionController sharedPrintController];
 [controller setDelegate:self];
 if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
  [controller presentFromBarButtonItem:self.printButton animated:YES
         completionHandler:completionHandler];
 } else {
  [controller presentAnimated:YES completionHandler:nil];
 }
</code>```

Please help, because I do receive nothing :(

答:
You need to set printItem/printItems property in order to use an AirPrint.

```<code>controller.printItem = a URL to PDF or image file;
</code>```

Body:
I want to add AirPrint functionality to my iPad application

I have been trying to display printer ontions described in Apple's Drawing and Printing Guide

I have toolbar and UIBarButtonItem *printButton. In controller I receive onPrintClick and try to display printer options by such code:

UIPrintInteractionController *controller = [UIPrintInteractionController sharedPrintController];
 [controller setDelegate:self];
 if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
  [controller presentFromBarButtonItem:self.printButton animated:YES
         completionHandler:completionHandler];
 } else {
  [controller presentAnimated:YES completionHandler:nil];
 }

Please help, because I do receive nothing :(

Body:
You need to set printItem/printItems property in order to use an AirPrint.

controller.printItem = a URL to PDF or image file;

ContentLicense: CC BY-SA 2.5


问:
Get all data from a sap.m.table
I have a sap.m.Table bound to an OData model and I want in my controller to get all the values in the table (using the ID or using the model).

Any ideas?

答:
It depends on what you want to use the data for. The most general way of doing this is with the following snippet:

var aData = (oTable.getItems() || []).map(function(oItem){
   // assuming that you are using the default model
   return oItem.getBindingContext().getObject();
});
```

If you want to do something like a table export, check out this example:
https://openui5.hana.ondemand.com/explored.html#/sample/sap.m.sample.TableExport/preview

Later edit: the getBindingContext method expects a model name. If none is provided, then it uses the default model. If your OData model has a name, then you will have to pass this name to the getBindingContext method call.

Title: Get all data from a sap.m.table

Body:
It depends on what you want to use the data for. The most general way of doing this is with the following snippet:

var aData = (oTable.getItems() || []).map(function(oItem){
   // assuming that you are using the default model
   return oItem.getBindingContext().getObject();
});

If you want to do something like a table export, check out this example:
https://openui5.hana.ondemand.com/explored.html#/sample/sap.m.sample.TableExport/preview

Later edit: the getBindingContext method expects a model name. If none is provided, then it uses the default model. If your OData model has a name, then you will have to pass this name to the getBindingContext method call.


问:
cannot read html page in facebook api
I'm trying to read a website html output in facebook messenger api, the code is working on the server, but it gives errors when I try it in facebook api (messenger), This is what I get:

```<code>    Automatically populating $HTTP_RAW_POST_DATA is deprecated and will be removed in a future version. To avoid this warning set 'always_populate_raw_post_data' to '-1' in php.ini and use the php://input stream instead.
</code>```

I've tried file_get_contents, fopen,readfile, curl and all brought up the same error.

I've tried to change the website to a secure connection (https) when using curl, to https://google.com, and the error message changed to:

```<code>    <HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
    <TITLE>302 Moved</TITLE></HEAD><BODY>
    <H1>302 Moved</H1>
    The document has moved
    <A HREF="https://www.google.ca/?gfe_rd=cr&ei=SaHbWPOrQXp_JvNB">here</A>.
    </BODY></HTML>
</code>```

And stackoverflow shows:

```<code>    <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
    <html><head>
    <title>403 Forbidden</title>
    </head><body>
    <h1>Forbidden</h1>
    <p>You don't have permission to access /
    on this server.<br />
    </p>
    <p>Additionally, a 403 Forbidden
    error was encountered while trying to use an ErrorDocument to handle the request.</p>
    </body></html>
</code>```

What should I do?

答:
Google can not be used in iframe and curl the google server blocks it , your code would work just fine in other sites, only way is to build owm page and use google search api.

code example:

Making HTTP Requests Directly

If Google Authentication is desired for external applications, or a Google API is not available yet in this library, HTTP requests can be made directly.

The authorize method returns an authorized Guzzle Client, so any request made using the client will contain the corresponding authorization.

```<code>// create the Google client
$client = new Google_Client();

/**
 * Set your method for authentication. Depending on the API, This could be
 * directly with an access token, API key, or (recommended) using
 * Application Default Credentials.
 */
$client->useApplicationDefaultCredentials();
$client->addScope(Google_Service_Plus::PLUS_ME);

// returns a Guzzle HTTP Client
$httpClient = $client->authorize();

// make an HTTP request
$response = $httpClient->get('https://www.googleapis.com/plus/v1/people/me');
</code>```

Title: cannot read html page in facebook api

Body:
I'm trying to read a website html output in facebook messenger api, the code is working on the server, but it gives errors when I try it in facebook api (messenger), This is what I get:

    Automatically populating $HTTP_RAW_POST_DATA is deprecated and will be removed in a future version. To avoid this warning set 'always_populate_raw_post_data' to '-1' in php.ini and use the php://input stream instead.

I've tried file_get_contents, fopen,readfile, curl and all brought up the same error.

I've tried to change the website to a secure connection (https) when using curl, to https://google.com, and the error message changed to:

    <meta http-equiv="content-type" content="text/html;charset=utf-8">
    <TITLE>302 Moved</TITLE>

302 Moved

    The document has moved
    here.

And stackoverflow shows:

    <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">

    <title>403 Forbidden</title>

Forbidden

You don't have permission to access /
    on this server.

Additionally, a 403 Forbidden
    error was encountered while trying to use an ErrorDocument to handle the request.

What should I do?

Body:
Google can not be used in iframe and curl the google server blocks it , your code would work just fine in other sites, only way is to build owm page and use google search api.

code example:

Making HTTP Requests Directly

If Google Authentication is desired for external applications, or a Google API is not available yet in this library, HTTP requests can be made directly.

The authorize method returns an authorized Guzzle Client, so any request made using the client will contain the corresponding authorization.

// create the Google client
$client = new Google_Client();

/**
 * Set your method for authentication. Depending on the API, This could be
 * directly with an access token, API key, or (recommended) using
 * Application Default Credentials.
 */
$client->useApplicationDefaultCredentials();
$client->addScope(Google_Service_Plus::PLUS_ME);

// returns a Guzzle HTTP Client
$httpClient = $client->authorize();

// make an HTTP request
$response = $httpClient->get('https://www.googleapis.com/plus/v1/people/me');


问:
diff() and date_diff() in PHP not working for some reason
I’m having a problem using PHP’s ‘diff()’ or ‘date_diff()’ between two dates of mine.  Basically when I run anything that attempts to compare dates or try to define something as a date the page will stop loading at that point.

```<code><?php

    // My starting point is the $dirty_date variable.
    // It is collected from a string, parsed,
    // and ends up being an integer-based date / seconds past Unix Epoch

    //I am also including some echos along the way for debugging purposes.

    echo "Check 1: ".$dirty_date."<br>";

    $systemdate = date("U");
    echo "Check 2: ".$systemdate."<br>";

    //$interval =  $dirty_date->diff($systemdate);
    echo "check 3: ".$interval;
</code>```

Here are the results:

Check 1: 1490781836

Check 2: 1490806703

check 3:

Check 3 returned nothing because I have the line which diffs it commented out.  I have it commented out because if it is enabled, the page doesn't load anything else past that point.

答:
Here's an example

```<code>    $dirty_date = new \DateTime();
    $dirty_date->setTimestamp("your integer date");
    echo "Check 1: ".$dirty_date->format(\DateTime::ISO8601)."<br>";

    $systemdate = new \DateTime();
    echo "Check 2: ".$systemdate->format(\DateTime::ISO8601)."<br>";

    $interval =  $dirty_date->diff($systemdate);
    echo "check 3: ".$interval->format("%R%a days");
</code>```

link to DateInterval ($interval var) formats http://php.net/manual/en/dateinterval.format.php

Body:
I’m having a problem using PHP’s ‘diff()’ or ‘date_diff()’ between two dates of mine.  Basically when I run anything that attempts to compare dates or try to define something as a date the page will stop loading at that point.

<?php

    // My starting point is the $dirty_date variable.
    // It is collected from a string, parsed,
    // and ends up being an integer-based date / seconds past Unix Epoch

    //I am also including some echos along the way for debugging purposes.

    echo "Check 1: ".$dirty_date."
";

    $systemdate = date("U");
    echo "Check 2: ".$systemdate."
";

    //$interval =  $dirty_date->diff($systemdate);
    echo "check 3: ".$interval;

Here are the results:

Check 1: 1490781836

Check 2: 1490806703

check 3:

Check 3 returned nothing because I have the line which diffs it commented out.  I have it commented out because if it is enabled, the page doesn't load anything else past that point.

Body:
Here's an example

    $dirty_date = new \DateTime();
    $dirty_date->setTimestamp("your integer date");
    echo "Check 1: ".$dirty_date->format(\DateTime::ISO8601)."<br>";

    $systemdate = new \DateTime();
    echo "Check 2: ".$systemdate->format(\DateTime::ISO8601)."<br>";

    $interval =  $dirty_date->diff($systemdate);
    echo "check 3: ".$interval->format("%R%a days");

link to DateInterval ($interval var) formats http://php.net/manual/en/dateinterval.format.php


答:
First, $newdate is not defined. Second, $dirty_date must be a DateTime object currently it is just an integer. I will assume you want to compare $dirty_date and $systemdate

Try this:

```<code>$dirty_date_obj = new DateTime();
$dirty_date_obj->setTimestamp((int) $dirty_date);

$system_date_obj = new DateTime();
$system_date_obj->setTimestamp((int) $systemdate);

echo "interval between dirty and system: ".$dirty_date_obj->diff($system_date_obj)->format('%a Days and %h hours');
</code>```

Also please type this in the beginning of your code to see the error messages so it isn't just a blank page if some error happens:

```<code>error_reporting(E_ALL); ini_set('display_errors', '1');
</code>```

Title: diff() and date_diff() in PHP not working for some reason

Body:
First, $newdate is not defined. Second, $dirty_date must be a DateTime object currently it is just an integer. I will assume you want to compare $dirty_date and $systemdate

Try this:

$dirty_date_obj = new DateTime();
$dirty_date_obj->setTimestamp((int) $dirty_date);

$system_date_obj = new DateTime();
$system_date_obj->setTimestamp((int) $systemdate);

echo "interval between dirty and system: ".$dirty_date_obj->diff($system_date_obj)->format('%a Days and %h hours');

Also please type this in the beginning of your code to see the error messages so it isn't just a blank page if some error happens:

error_reporting(E_ALL); ini_set('display_errors', '1');


问:
Port 51347 seems to be used by another program
On running the sample code given in the dispy documentation

def compute(n):
    import time, socket
    time.sleep(n)
    host = socket.gethostname()
    return (host, n)
if name == 'main':
    import dispy, random
    cluster = dispy.JobCluster(compute)
    jobs = []
    for i in range(10):
        # schedule execution of 'compute' on a node (running 'dispynode')
        # with a parameter (random number in this case)
        job = cluster.submit(random.randint(5,20))
        job.id = i # optionally associate an ID to job (if needed later)
        jobs.append(job)
    # cluster.wait() # wait for all scheduled jobs to finish
    for job in jobs:
        host, n = job() # waits for job to finish and returns results
        print('%s executed job %s at %s with %s' % (host, job.id, job.start_time, n))
        # other fields of 'job' that may be useful:
        # print(job.stdout, job.stderr, job.exception, job.ip_addr, job.start_time, job.end_time)
    cluster.print_status()

I get the following output

2017-03-29 22:39:52 asyncoro - version 4.5.2 with epoll I/O notifier

2017-03-29 22:39:52 dispy - dispy client version: 4.7.3

2017-03-29 22:39:52 dispy - Port 51347 seems to be used by another program

And then nothing happens.
How to free the 51347 port?

答:
If you are under Linux, run sudo netstat -tuanp | grep 51347 and take note of the pid using that port.

Then execute ps ax | grep <pid> to check which service/program is running with that pid.

Then execute kill <pid> to terminate the process using that port.

Please check which process is using the port before killing it just in case it is something that you should not kill.


问:
Javascript loader issue
Im currently developing a website and i have the most basic code on it at the moment and i went to add a "loader" however it says one of my lines of code in my javascript file is broken and cant figure out why. i am a beginner so that might be why. however when i load the website in a browser the loader works but it doesnt fade and show the website it just keeps spinning.

Below is my java code :

```<code><script>
var myVar;

function myFunction() {
myVar = setTimeout(showPage, 3000);
}

function showPage() {
document.getElementById("loader").style.display = "none";
document.getElementById("myDiv").style.display = "block";
}
</script>
</code>```

And here is my HTML code for the loader :

```<code><body onload="myFunction()" style="margin:0;">

<div id="loader"></div>

<div style="display:none;" id="myDiv" class="animate-bottom">
<h2>Tada!</h2>
<p>Some text in my newly loaded page..</p>
</div>
</code>```

Any help is appreciated.

答:
Works for me.  It's not an issue with your browser or code:

var myVar;

function myFunction() {
  myVar = setTimeout(showPage, 3000);
}

function showPage() {
  document.getElementById("loader").style.display = "none";
  document.getElementById("myDiv").style.display = "block";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body onload="myFunction()" style="margin:0;">

  <div id="loader"></div>

  <div style="display:none;" id="myDiv" class="animate-bottom">
    <h2>Tada!</h2>
    <p>Some text in my newly loaded page..</p>
  </div>

</body></code>```

Given the screenshot of your error, this may be a Dreamweaver issue.  Perhaps setTimeout doesn't exist, or the application isn't properly hoisting your function.

You can try:

moving showPage function above your myFunction in the code

qualifying your setTimeout with window.setTimeout

removing the

Title: Javascript loader issue

Body:
Im currently developing a website and i have the most basic code on it at the moment and i went to add a "loader" however it says one of my lines of code in my javascript file is broken and cant figure out why. i am a beginner so that might be why. however when i load the website in a browser the loader works but it doesnt fade and show the website it just keeps spinning.

Below is my java code :

And here is my HTML code for the loader :

Tada!

Some text in my newly loaded page..

Any help is appreciated.

Body:
Works for me.  It's not an issue with your browser or code:

var myVar;

function myFunction() {
  myVar = setTimeout(showPage, 3000);
}

function showPage() {
  document.getElementById("loader").style.display = "none";
  document.getElementById("myDiv").style.display = "block";
}

<body onload="myFunction()" style="margin:0;">

  <div id="loader"></div>

  <div style="display:none;" id="myDiv" class="animate-bottom">
    <h2>Tada!</h2>
    <p>Some text in my newly loaded page..</p>
  </div>

</body>

Given the screenshot of your error, this may be a Dreamweaver issue.  Perhaps setTimeout doesn't exist, or the application isn't properly hoisting your function.

You can try:

moving showPage function above your myFunction in the code

qualifying your setTimeout with window.setTimeout

removing the <script> elements from your JavaScript

Sidenote:

add "use strict"; to the top of your JavaScript files to detect and prevent future errors sooner.


问:
Sum of factoriais to be equal a given number
I'm trying to solve the following problem:

What is the smallest number of factoriais summed that are needed to be equal an given number a? (1 ≤ a ≤ 10^5)

Example:

Input: 10, Output: 3. (10 = 3! + 2! + 2!)

Input: 25, Output: 2. (25 = 4! + 1!)

My code:

```<code>#include<bits/stdc++.h>

using namespace std;

int a;

int rec(int vet){

    int count = 0;

    a = a - vet;
        if(a >= vet){
            count++;
            rec(vet);
        }
    count++;
    return count;
}

int main(){

    int vet[8] = {1}, count = 0;

    cin >> a;

    for(int i = 2; i <= 8; i++){
        vet[i-1] = vet[i-2]*i;
    }

    for(int i = 7; i >= 0; i--){
        if(a < vet[i]){
            continue;
        }

        count += rec(vet[i]);
    }

    cout << count << endl;
}
</code>```

My logic:

1°: a max is equal to 100000, so the maximum fatorial we have to
compare is 8!;

2°: I take a factioral that is equal or nearest small to a,
subtract the factorial from it and count++; If after the subtraction,
a still bigger then my factorial, I do the same step recursively.

This code pass on the base cases, but I got a wrong answer. I wasn't capable to find what case it didn't pass, so I'm here.

Can you find where am I wrong? Or if my solution is not good and I should try another approach.

Thanks for the help!

答:
The problem is easily solved by a recursive approach.

Here is checked code:

```<code>    #include <iostream>

using namespace std;

int factorial(int n) {
        return n<=1 ? 1 : n * factorial(n-1);
    }

int MinFact(int number)
{
            static int num_of_facts;
            int a = 1;
            if (number)
            {
                        while(factorial(a+1)<=number)a++;
                        cout << a << "!" << endl;
                        num_of_facts++;
                        MinFact((number-factorial(a)));
            }
            return num_of_facts;
}

int main()
{
            int num;
            cout << "Enter number" << endl;
            cin >> num;
            num = MinFact(num);
            cout << "Number of factorials: " << num;
            return 0;
}
</code>```

Body:
I'm trying to solve the following problem:

What is the smallest number of factoriais summed that are needed to be equal an given number a? (1 ≤ a ≤ 10^5)

Example:

Input: 10, Output: 3. (10 = 3! + 2! + 2!)

Input: 25, Output: 2. (25 = 4! + 1!)

My code:

#include<bits/stdc++.h>

using namespace std;

int a;

int rec(int vet){

    int count = 0;

    a = a - vet;
        if(a >= vet){
            count++;
            rec(vet);
        }
    count++;
    return count;
}

int main(){

    int vet[8] = {1}, count = 0;

    cin >> a;

    for(int i = 2; i <= 8; i++){
        vet[i-1] = vet[i-2]*i;
    }

    for(int i = 7; i >= 0; i--){
        if(a < vet[i]){
            continue;
        }

        count += rec(vet[i]);
    }

    cout << count << endl;
}

My logic:

1°: a max is equal to 100000, so the maximum fatorial we have to
compare is 8!;

2°: I take a factioral that is equal or nearest small to a,
subtract the factorial from it and count++; If after the subtraction,
a still bigger then my factorial, I do the same step recursively.

This code pass on the base cases, but I got a wrong answer. I wasn't capable to find what case it didn't pass, so I'm here.

Can you find where am I wrong? Or if my solution is not good and I should try another approach.

Thanks for the help!

Body:
The problem is easily solved by a recursive approach.

Here is checked code:

    #include <iostream>

using namespace std;

int factorial(int n) {
        return n<=1 ? 1 : n * factorial(n-1);
    }

int MinFact(int number)
{
            static int num_of_facts;
            int a = 1;
            if (number)
            {
                        while(factorial(a+1)<=number)a++;
                        cout << a << "!" << endl;
                        num_of_facts++;
                        MinFact((number-factorial(a)));
            }
            return num_of_facts;
}

int main()
{
            int num;
            cout << "Enter number" << endl;
            cin >> num;
            num = MinFact(num);
            cout << "Number of factorials: " << num;
            return 0;
}


问:
Create Column in data table with grep of partial string (with numbers)
How can I use grep to find a partial string match and return only a portion of that string to a new column in my existing data table?

For example, I have a column $remarks in dt:"FC3"

Some of the remarks say "blah blah blah 57 DAYS LATE blah blah"

Is there a statement I can use to grab the '57 DAYS LATE' part and put it in a new column? Of course, it is not always 57 days, sometimes its 145, sometimes just 8 - so the length of the string is dynamic.

per request: here is example/reproducable data (i think this is what you were asking for)

```<code>7548    1D10000 2016    2016 CAT 1 WAS SUBMITTED 9 DAYS LATE
3647    1D10001 2011    PENALTY PAID
3547    1D39949 2013    2013 CAT 1 WAS 57 DAYS LATE SUBMIT
</code>```

here, the column containing the strings "2016 CAT 1 WAS SUBITTED 9 DAYS LATE", as well as the string "2013 CAT 1 WAS 57 DAYS LATE SUBMIT" in their respective rows are the strings I am referring to. What process would be best for me to be able to search for, grab, and place the "9 DAYS LATE" or the "57 DAYS LATE" strings in a new column?

The column name containing the string i want is FC4$remarks

Thank you and I hope this clarifies!

答:
you can use gsub() and a capture expression, like this:

```<code>dt <- data.table(remarks = c("blah blah blah 57 DAYS LATE blah blah",
                             "blah blah blah 145 DAYS LATE blah blah",
                             "2013 CAT 1 WAS 123 DAYS LATE SUBMIT",
                             "2016 CAT 1 WAS SUBMITTED 9 DAYS LATE"))

dt$new_column <- gsub(".* (\\d+ DAYS LATE).*", "\\1", dt$remarks)
# captures one or more consecutive digits and the string " DAYS LATE"

dt
                                  remarks    new_column
1:  blah blah blah 57 DAYS LATE blah blah  57 DAYS LATE
2: blah blah blah 145 DAYS LATE blah blah 145 DAYS LATE
3:    2013 CAT 1 WAS 123 DAYS LATE SUBMIT 123 DAYS LATE
4:   2016 CAT 1 WAS SUBMITTED 9 DAYS LATE   9 DAYS LATE

sessionInfo()
R version 3.3.2 (2016-10-31)
Platform: x86_64-apple-darwin13.4.0 (64-bit)
Running under: macOS Sierra 10.12.1

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
 [1] data.table_1.9.6 magrittr_1.5     dplyr_0.5.0      purrr_0.2.2      readr_1.0.0      tidyr_0.6.1      tibble_1.2
 [8] tidyverse_1.0.0  ggmap_2.7        ggplot2_2.2.1
</code>```

Body:
How can I use grep to find a partial string match and return only a portion of that string to a new column in my existing data table?

For example, I have a column $remarks in dt:"FC3"

Some of the remarks say "blah blah blah 57 DAYS LATE blah blah"

Is there a statement I can use to grab the '57 DAYS LATE' part and put it in a new column? Of course, it is not always 57 days, sometimes its 145, sometimes just 8 - so the length of the string is dynamic.

per request: here is example/reproducable data (i think this is what you were asking for)

7548    1D10000 2016    2016 CAT 1 WAS SUBMITTED 9 DAYS LATE
3647    1D10001 2011    PENALTY PAID
3547    1D39949 2013    2013 CAT 1 WAS 57 DAYS LATE SUBMIT

here, the column containing the strings "2016 CAT 1 WAS SUBITTED 9 DAYS LATE", as well as the string "2013 CAT 1 WAS 57 DAYS LATE SUBMIT" in their respective rows are the strings I am referring to. What process would be best for me to be able to search for, grab, and place the "9 DAYS LATE" or the "57 DAYS LATE" strings in a new column?

The column name containing the string i want is FC4$remarks

Thank you and I hope this clarifies!

Body:
you can use gsub() and a capture expression, like this:

dt <- data.table(remarks = c("blah blah blah 57 DAYS LATE blah blah",
                             "blah blah blah 145 DAYS LATE blah blah",
                             "2013 CAT 1 WAS 123 DAYS LATE SUBMIT",
                             "2016 CAT 1 WAS SUBMITTED 9 DAYS LATE"))

dt$new_column <- gsub(".* (\\d+ DAYS LATE).*", "\\1", dt$remarks)
# captures one or more consecutive digits and the string " DAYS LATE"

dt
                                  remarks    new_column
1:  blah blah blah 57 DAYS LATE blah blah  57 DAYS LATE
2: blah blah blah 145 DAYS LATE blah blah 145 DAYS LATE
3:    2013 CAT 1 WAS 123 DAYS LATE SUBMIT 123 DAYS LATE
4:   2016 CAT 1 WAS SUBMITTED 9 DAYS LATE   9 DAYS LATE

sessionInfo()
R version 3.3.2 (2016-10-31)
Platform: x86_64-apple-darwin13.4.0 (64-bit)
Running under: macOS Sierra 10.12.1

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
 [1] data.table_1.9.6 magrittr_1.5     dplyr_0.5.0      purrr_0.2.2      readr_1.0.0      tidyr_0.6.1      tibble_1.2
 [8] tidyverse_1.0.0  ggmap_2.7        ggplot2_2.2.1


问:
Can a Yodlee API actually transfer the money from one account to another?
I am developing an application that needs to complete money transfers to users. I understand that Yodlee has APIs that can collect data on transfers and various transactions for financial accounts.

However, can the Yodlee API actually perform the money transfers, or is the API only designed for information aggregation?

答:
Yodlee has an API for funds transfer, they call it "Money Movement API".

However, the money movement api is not available in the sandbox and is only available to large corporations as there are legalities involved.

This is the email I got from their Sales Development Team:

The Money Movement API is for larger global financial institutions as
  they hold all of the licensing and liability. No, it's not available
  in the sandbox.

This doesn't mean you can't get it. You will have to talk to them about this.


问:
How to do authorization for mobile cloud app in IBM Bluemix
There are multiple tutorials about authentication in Bluemix, but I yet to find a good tutorial about authorization. In my mobile app, I need to group users and only users with a group get to see the messages allowed to this group. Is there a service can help to implement this?

Someone mentioned Stormpath in the forum, it  has built in features for user registry, login, authorization etc, which is what I need. Does it work with mobile app? is it free to use with Bluemix? It has tutorial to integrate with node.js, assume that works with Bluemix?

Thanks.

Zheng

答:
The Stormpath API has been deprecated, so if you are using it you'll need to migrate by August 17th 2017.

There are currently a few options in the Bluemix catalog.

Passport is a third party option that is similar to Stormpath but also has some additional user management features. IBM is offering App ID, but I believe this is only offering social authentication and then service authorization. If you don't want social login, you'd have to bring your own Identity Provider.

I am not aware of any free offerings in the Bluemix catalog.


问:
Tracking remote uncommitted changes
I'm trying to track modified files on a live website with GIT, I have deployed a non-bare repository on the website, with a post-receive hook.

Is it possible to see what changes have been made in the remote's working copy without committing them?

I'll give an example to clarify things:

I have a live installation of Wordpress with a repository on its root.

I push changes from local repository, but Wordpress itself has made changes to remote's files, so the push won't affect these files since they have uncommitted changes.

I would like to see what changes has Wordpress made so I can stage them or not.

答:
Think of Wordpress itself as just another person using Git.  He is Word Press <word@press.program>.

If Mr Press does not commit his changes, the only way for you to get his changes is some "out of band" method.  For instance, he could run git diff and email you the result.

If Mr Press does commit his changes, and you have access (such as git fetch permission) to his repository, then you can get those changes into your own repository directly, via Git commands.

ContentLicense: CC BY-SA 4.0

Title: Tracking remote uncommitted changes


问:
Increasing stack not working
How do can i properly increase the stack available for a program using either Bloodshed Dev C++ or Code::Block? Im running simple bubble and quick sort that work, but when i changed the stack in Code::Block (found out how over here) it made my program crash even faster, despite using much more than suggested space. originally, the program was crashing while sorting 64K of random integers (using the rand() function). Now, its crashing at 32K. im getting the error: Process returned -1073741571 (0xC00000FD)

the program actually runs faster without having the stack changed, assuming im doing it right. gcc -Wl,--stack,1099511627776

i cant figure out how to change it at all in Dev C++

What should i do?
is there any way to change the stack within the code itself?
here is the code im using for bubble and quick sort. there are two of each: one is with vectors, the other is with arrays. i think that the bubble sort. should be correct. the quick sort, im not so sure about. sorry if its a bit messy

```<code>vector <int> v_bubble(vector <int> array){
    // Vector Bubble Sort
    if (array.size() < 2){
        return array;
    }
    int s = 1;
    while (s){
        s = 0;
        for (unsigned int x = 0; x < (array.size() - 1); x++){
            if (array[x] > array[x + 1]){
                int t = array[x];
                array[x] = array[x + 1];
                array[x + 1] = t;
                s = 1;
            }
        }
    }
    return array;
}

void a_bubble(int array[], int size){
    // Array Bubble Sort
    int s = 1;
    while (s){
        s = 0;
        for (int x = 0; x < (size - 1); x++){
            if (array[x] > array[x + 1]){
                int t = array[x];
                array[x] = array[x + 1];
                array[x + 1] = t;
                s = 1;
            }
        }
    }
}

vector <int> v_quick(vector <int> array){
    //Vector Quick Sort
    if (array.size() < 2){
        return array;
    }
    vector <int> left;
    vector <int> right;
    int p_location = array.size() / 2 - 1;
    int pivot = array[p_location];
    for(unsigned int x = p_location; x < array.size() - 1; x++){
        array[x] = array[x + 1];
    }
    array.pop_back();
    for(unsigned int x = 0; x < array.size(); x++){
        if (array[x] <= pivot) {
            left.push_back(array[x]);
        }
        else if (array[x] > pivot){
            right.push_back(array[x]);
        }
    }
    vector <int> p;
    p.push_back(pivot);
    return combine(combine(v_quick(left), p), v_quick(right));
}

int a_quick(int array[], int size, int l_index = -1, int r_index = -1){
    //Array Quick Sort
    if (size < 2){
        return array[size];
    }
    array[size] = array[size];
    int left[size];
    int right[size];
    l_index = 0;
    r_index = 0;
    int p_location = size / 2 - 1;
    int pivot = array[p_location];
    for(int x = p_location; x < size - 1; x++){
        array[x] = array[x + 1];
    }
    size--;
    for(unsigned int x = 0; x < size; x++){
        if (array[x] <= pivot) {
            left[l_index] = array[x];
            l_index++;
        }
        else if (array[x] > pivot){
            right[r_index] = array[x];
            r_index++;
        }
    }
    return a_quick(left, l_index, l_index, r_index) + pivot + a_quick(right, r_index, l_index, r_index);
}
</code>```

the rest of the code is simply generating arrays and vectors with 32, 64 and 128 k entries, sorting them using the above code and returning the time. that part im pretty sure i did not screw up

my main is basically just

```<code>    start = clock();
    a_quick(array1, 32000);
    end = clock();
    cout << "\nQuick Sort\tArray\t32000\t" << ((double) end - start)/CLOCKS_PER_SEC << " seconds\n";
</code>```

over and over again

答:
In function int a_bubble(int array[], int size) : you return array[size], that is out of bound. The same is true for a_quick().

And post also your main() please.

EDIT: no, it returns the element that is after the last element of the array. Some could say that even accessing it is UB, and they would be right.

Is it debug build you are running? I think the error code corresponds to "out of bound exception", but I don't understand why it have to be so cryptic.

EDIT2: it's worse. What int array[1 << 20] stands for? The old version was OK, you just had to remove return array[size]. Make the functions returning void, you already have both, array and its size in the callee.

Title: Increasing stack not working

Body:
How do can i properly increase the stack available for a program using either Bloodshed Dev C++ or Code::Block? Im running simple bubble and quick sort that work, but when i changed the stack in Code::Block (found out how over here) it made my program crash even faster, despite using much more than suggested space. originally, the program was crashing while sorting 64K of random integers (using the rand() function). Now, its crashing at 32K. im getting the error: Process returned -1073741571 (0xC00000FD)

the program actually runs faster without having the stack changed, assuming im doing it right. gcc -Wl,--stack,1099511627776

i cant figure out how to change it at all in Dev C++

What should i do?
is there any way to change the stack within the code itself?
here is the code im using for bubble and quick sort. there are two of each: one is with vectors, the other is with arrays. i think that the bubble sort. should be correct. the quick sort, im not so sure about. sorry if its a bit messy

vector <int> v_bubble(vector <int> array){
    // Vector Bubble Sort
    if (array.size() < 2){
        return array;
    }
    int s = 1;
    while (s){
        s = 0;
        for (unsigned int x = 0; x < (array.size() - 1); x++){
            if (array[x] > array[x + 1]){
                int t = array[x];
                array[x] = array[x + 1];
                array[x + 1] = t;
                s = 1;
            }
        }
    }
    return array;
}

void a_bubble(int array[], int size){
    // Array Bubble Sort
    int s = 1;
    while (s){
        s = 0;
        for (int x = 0; x < (size - 1); x++){
            if (array[x] > array[x + 1]){
                int t = array[x];
                array[x] = array[x + 1];
                array[x + 1] = t;
                s = 1;
            }
        }
    }
}

vector <int> v_quick(vector <int> array){
    //Vector Quick Sort
    if (array.size() < 2){
        return array;
    }
    vector <int> left;
    vector <int> right;
    int p_location = array.size() / 2 - 1;
    int pivot = array[p_location];
    for(unsigned int x = p_location; x < array.size() - 1; x++){
        array[x] = array[x + 1];
    }
    array.pop_back();
    for(unsigned int x = 0; x < array.size(); x++){
        if (array[x] <= pivot) {
            left.push_back(array[x]);
        }
        else if (array[x] > pivot){
            right.push_back(array[x]);
        }
    }
    vector <int> p;
    p.push_back(pivot);
    return combine(combine(v_quick(left), p), v_quick(right));
}

int a_quick(int array[], int size, int l_index = -1, int r_index = -1){
    //Array Quick Sort
    if (size < 2){
        return array[size];
    }
    array[size] = array[size];
    int left[size];
    int right[size];
    l_index = 0;
    r_index = 0;
    int p_location = size / 2 - 1;
    int pivot = array[p_location];
    for(int x = p_location; x < size - 1; x++){
        array[x] = array[x + 1];
    }
    size--;
    for(unsigned int x = 0; x < size; x++){
        if (array[x] <= pivot) {
            left[l_index] = array[x];
            l_index++;
        }
        else if (array[x] > pivot){
            right[r_index] = array[x];
            r_index++;
        }
    }
    return a_quick(left, l_index, l_index, r_index) + pivot + a_quick(right, r_index, l_index, r_index);
}

the rest of the code is simply generating arrays and vectors with 32, 64 and 128 k entries, sorting them using the above code and returning the time. that part im pretty sure i did not screw up

my main is basically just

    start = clock();
    a_quick(array1, 32000);
    end = clock();
    cout << "\nQuick Sort\tArray\t32000\t" << ((double) end - start)/CLOCKS_PER_SEC << " seconds\n";

over and over again


问:
jQuery slide repeated code
I would like top know if there is a way to create several slides and panels using minimal code and avoid this:

```<code>$(document).ready(function(){
    $("#slide1").click(function(){
        $("#panel1").slideToggle("slow");
    });
    $("#slide2").click(function(){
        $("#panel2").slideToggle("slow");
    });
});
</code>```

As you can see, for every pair of panel and slide I have to create 3 new lines of jQuery. Is there a way to avoid this? I'm open to solutions that use Javascript as well. The goal of this is to simply have a few lines of code, and for every panel and slide involved, I don't have to add any code whatsoever. I simply have to add a slide and panel, and it will function.

答:
I would use the each() function in jquery for this. Similar to what Santi suggested, you'll first need a common identifier to capture each element you want in your query. You can do what he said and add a class manually to each element. You can also use a 'begins with' (^) to match elements with an id that begins with 'panel'. Then inside the each() function, you will use the $(this) variable to refer to the DOM element that you want to add slideToggle() to:

js:

```<code>$('[id^=panel]').each(function(){
    /* Comment
       Inside this function, "$(this)" would be the element
       just the same as if you said: $('#panel1')
    End Comment */

    $(this).click(function(){
        slideToggle('slow');
    });
});
</code>```

$('[id^=panel]') is how you would match elements with an id starting with 'panel'.

Title: jQuery slide repeated code

Body:
I would like top know if there is a way to create several slides and panels using minimal code and avoid this:

$(document).ready(function(){
    $("#slide1").click(function(){
        $("#panel1").slideToggle("slow");
    });
    $("#slide2").click(function(){
        $("#panel2").slideToggle("slow");
    });
});

As you can see, for every pair of panel and slide I have to create 3 new lines of jQuery. Is there a way to avoid this? I'm open to solutions that use Javascript as well. The goal of this is to simply have a few lines of code, and for every panel and slide involved, I don't have to add any code whatsoever. I simply have to add a slide and panel, and it will function.

Body:
I would use the each() function in jquery for this. Similar to what Santi suggested, you'll first need a common identifier to capture each element you want in your query. You can do what he said and add a class manually to each element. You can also use a 'begins with' (^) to match elements with an id that begins with 'panel'. Then inside the each() function, you will use the $(this) variable to refer to the DOM element that you want to add slideToggle() to:

js:

$('[id^=panel]').each(function(){
    /* Comment
       Inside this function, "$(this)" would be the element
       just the same as if you said: $('#panel1')
    End Comment */

    $(this).click(function(){
        slideToggle('slow');
    });
});

$('[id^=panel]') is how you would match elements with an id starting with 'panel'.


问:
Convert String to DateTime keeping datetime unchanged
Have the below string which i want to convert to a DateTime in c# code.

```<code>string dateTime = "2017-03-29T17:51:44.8389637Z";
DateTime dt1 = Convert.ToDateTime(dateTime);
</code>```

The above code converts it to: 3/29/2017 10:51:44 AM
I lose about 7 hours with the conversion, how can i get the result as: 2017-03-29 17:51:44. I think it has something to do with culture..?

Please help.

答:
I recommend using DateTime.Parse to provided a more robust conversion:</p>

```<code>DateTime dt1 = DateTime.Parse("2017-03-29T17:51:44.8389637Z", CultureInfo.CurrentCulture, DateTimeStyles.AssumeLocal);
</code>```

Body:
Have the below string which i want to convert to a DateTime in c# code.

string dateTime = "2017-03-29T17:51:44.8389637Z";
DateTime dt1 = Convert.ToDateTime(dateTime);

The above code converts it to: 3/29/2017 10:51:44 AM
I lose about 7 hours with the conversion, how can i get the result as: 2017-03-29 17:51:44. I think it has something to do with culture..?

Please help.

Body:
I recommend using DateTime.Parse to provided a more robust conversion:

DateTime dt1 = DateTime.Parse("2017-03-29T17:51:44.8389637Z", CultureInfo.CurrentCulture, DateTimeStyles.AssumeLocal);


问:
Cant insert utf8 characters on mysql (with utf8 collation, charset and nameset)
im facing a really stressing problem here.. i have everything in UTF-8 , all my DB and tables are utf8_general_ci but when trying to insert or update from a single PHP script all i see are symbols.. but if i edit in phpmyadmin the words are shown correctly.. i found that if i run the utf8_decode() function to my strings in php i can make it work, but im not planning to do that because is a mess and it should work without doing that :S

Here is a basic code im using to test this:

```<code><?php
$conn=mysql_connect("localhost","root","root")
  or die("Error");
mysql_select_db("mydb",$conn) or
  die("Error");
mysql_query("UPDATE `mydb`.`Clients` SET `name` = '".utf8_decode("Araña")."' WHERE `Clients`.`id` =25;",
   $conn) or die(mysql_error());
mysql_close($conn);
echo "Success.";
?>
</code>```

This is what i get if i dont decode utf8 with php utf8_decode function:

instead of Araña, i get : AraÃ±a

答: "AraÃ±a" IS UTF-8.  The characters "Ã±" represent the two bytes into which the Spanish ñ are encoded in UTF-8.  Whatever you're reading it back with is not handling the UTF-8 and is displaying it as (it appears) ISO-8859-1.</p>

Body:
im facing a really stressing problem here.. i have everything in UTF-8 , all my DB and tables are utf8_general_ci but when trying to insert or update from a single PHP script all i see are symbols.. but if i edit in phpmyadmin the words are shown correctly.. i found that if i run the utf8_decode() function to my strings in php i can make it work, but im not planning to do that because is a mess and it should work without doing that :S

Here is a basic code im using to test this:

<?php
$conn=mysql_connect("localhost","root","root")
  or die("Error");
mysql_select_db("mydb",$conn) or
  die("Error");
mysql_query("UPDATE `mydb`.`Clients` SET `name` = '".utf8_decode("Araña")."' WHERE `Clients`.`id` =25;",
   $conn) or die(mysql_error());
mysql_close($conn);
echo "Success.";
?>

This is what i get if i dont decode utf8 with php utf8_decode function:

instead of Araña, i get : AraÃ±a


问:
how to create a numpy list of names from names of numpy files
I have a set of numpy files, they are in one folder.
I need to create a numpy list where I can put in every line some details about each file'name:

Example:
The file name:

```<code>AES_Trace=300001_key=000102030405060708090a0b0c0d0e0f_Plaintext=f9f19b259648feb20d842480745de16f_Ciphertext=a3140be40735f9f1865aa6b1b32b5667.npy
</code>```

Each line in my list must include:

```<code>300001 000102030405060708090a0b0c0d0e0f f9f19b259648feb20d842480745de16f a3140be40735f9f1865aa6b1b32b5667
</code>```

I mean that I need to put only  numbers then space.

I use this method but it gives all the name of my file.

```<code>import os
path_For_Numpy_Files = 'C:\\Users\\user\\My_Test_Traces\\1000_Traces_bin'
path_List_File='C:\\Users\\user\\My_Test_Traces\\NewTest.list_bin'
os.chdir(path_For_Numpy_Files)
list_files=os.listdir(os.getcwd())
with open(path_List_File, 'w') as fp:
    fp.write('\n'.join(sorted((list_files),key=os.path.getmtime)))
</code>```

Hou could I correct it to give me the waited result please?

答:
You may try this: </p>

```<code> def reformat_name(old):
        key0=  old.split('_key=')[1].split('_Plaintext=')[0]
        key1 = old.split('_Plaintext=')[1].split('_Ciphertext=')[0]
        key2 = old.split('_Ciphertext=')[1].split('.bin')[0]
        name = old.split('AES_Trace=')[1].split('_key=')[0]
        #new_filename =  '{:07d}'.format(int(name)) + '    ' + key0 + '    ' + key1 + '    '+ key2 + '    '
        new_filename = '{:07d}'.format(int(name)) + '    ' + key0 + '    ' + key1 + '    '+ key2 + '    '
        return new_filename

    import os
    path_For_Numpy_Files='C:\\Users\\user\\My_Test_Traces\\3_Traces_npy'
    path_List_File='C:\\Users\\user\\My_Test_Traces\\ttttttTest.list_npy'
    os.chdir(path_For_Numpy_Files)
    list_files_Without_Sort=os.listdir(os.getcwd())
    list_files_Sorted=sorted((list_files_Without_Sort),key=os.path.getmtime)
    with open(path_List_File, 'w') as fp:
        for file in list_files_Sorted:
            new_name = reformat_name(file)
            fp.write(new_name+ '\n')
</code>```

Body:
I have a set of numpy files, they are in one folder.
I need to create a numpy list where I can put in every line some details about each file'name:

Example:
The file name:

AES_Trace=300001_key=000102030405060708090a0b0c0d0e0f_Plaintext=f9f19b259648feb20d842480745de16f_Ciphertext=a3140be40735f9f1865aa6b1b32b5667.npy

Each line in my list must include:

300001 000102030405060708090a0b0c0d0e0f f9f19b259648feb20d842480745de16f a3140be40735f9f1865aa6b1b32b5667

I mean that I need to put only  numbers then space.

I use this method but it gives all the name of my file.

import os
path_For_Numpy_Files = 'C:\\Users\\user\\My_Test_Traces\\1000_Traces_bin'
path_List_File='C:\\Users\\user\\My_Test_Traces\\NewTest.list_bin'
os.chdir(path_For_Numpy_Files)
list_files=os.listdir(os.getcwd())
with open(path_List_File, 'w') as fp:
    fp.write('\n'.join(sorted((list_files),key=os.path.getmtime)))

Hou could I correct it to give me the waited result please?

Body:
You may try this:

 def reformat_name(old):
        key0=  old.split('_key=')[1].split('_Plaintext=')[0]
        key1 = old.split('_Plaintext=')[1].split('_Ciphertext=')[0]
        key2 = old.split('_Ciphertext=')[1].split('.bin')[0]
        name = old.split('AES_Trace=')[1].split('_key=')[0]
        #new_filename =  '{:07d}'.format(int(name)) + '    ' + key0 + '    ' + key1 + '    '+ key2 + '    '
        new_filename = '{:07d}'.format(int(name)) + '    ' + key0 + '    ' + key1 + '    '+ key2 + '    '
        return new_filename

    import os
    path_For_Numpy_Files='C:\\Users\\user\\My_Test_Traces\\3_Traces_npy'
    path_List_File='C:\\Users\\user\\My_Test_Traces\\ttttttTest.list_npy'
    os.chdir(path_For_Numpy_Files)
    list_files_Without_Sort=os.listdir(os.getcwd())
    list_files_Sorted=sorted((list_files_Without_Sort),key=os.path.getmtime)
    with open(path_List_File, 'w') as fp:
        for file in list_files_Sorted:
            new_name = reformat_name(file)
            fp.write(new_name+ '\n')


问:
OleDb - Incorrect syntax near the keyword 'DEFAULT'
Alright so, Im trying to do a simple update query to a table but I keep getting this error Incorrect syntax near the keyword 'DEFAULT'. The thing is. it only goes wrong when ome values are NULL, but I've checked and IT DOES allow null values. Here is my code for the query

```<code>public void UpdateQuery(String[] valores)
{
    conexion = this.Connections.OLEDBCONNECTION.ConnectionString;
    String query = " UPDATE [UTB_CUENTAS] SET CODTYP=ISNULL(?,CODTYP), CODORG=ISNULL(?,CODORG), CODGRP=ISNULL(?,CODGRP), TXTDEN=ISNULL(?,TXTDEN),"
                 + " IDEACC=ISNULL(?,IDEACC), CODAPP=ISNULL(?,CODAPP), NUMPLZ=ISNULL(?,NUMPLZ), CODCUR=ISNULL(?,CODCUR), DATING=ISNULL(?,DATING),"
                 + " NUMACCCTE=ISNULL(?,NUMACCCTE), DATCAN=ISNULL(?,DATCAN), FLGESTADO=ISNULL(?,FLGESTADO), DATELI=ISNULL(?,DATELI),"
                 + " DATUPD=ISNULL(?,DATUPD), TXTADR=ISNULL(?,TXTADR), CODUSR=ISNULL(?,CODUSR)"
                 + " WHERE NUMACC = ?";

    using (OleDbConnection con = new OleDbConnection(conexion))
    {
        con.Open();
        using (OleDbCommand cmd = con.CreateCommand())
        {
            cmd.Parameters.Add("@CODTYP", OleDbType.VarChar, 3).Value = valores[1];
            cmd.Parameters.Add("@CODORG", OleDbType.VarChar, 18).Value = valores[2];
            cmd.Parameters.Add("@CODGRP", OleDbType.VarChar, 4).Value = valores[3];
            cmd.Parameters.Add("@TXTDEN", OleDbType.VarChar, 150).Value = valores[4];
            cmd.Parameters.Add("@IDEACC", OleDbType.Char, 1).Value = valores[5];
            cmd.Parameters.Add("@CODAPP", OleDbType.VarChar, 2).Value = valores[6];
            cmd.Parameters.Add("@NUMPLZ", OleDbType.VarChar, 3).Value = valores[7];
            cmd.Parameters.Add("@CODCUR", OleDbType.Char, 3).Value = valores[8];

            if (valores[9] == null)
                cmd.Parameters.Add("@DATING", OleDbType.DBTimeStamp).Value = DBNull.Value;
            else
                cmd.Parameters.Add("@DATING", OleDbType.DBTimeStamp).Value = Convert.ToDateTime(valores[9]);

            cmd.Parameters.Add("@NUMACCCTE", OleDbType.VarChar, 18).Value = valores[10];

            if (valores[11] == null)
                cmd.Parameters.Add("@DATCAN", OleDbType.DBTimeStamp).Value = DBNull.Value;
            else
                cmd.Parameters.Add("@DATCAN", OleDbType.DBTimeStamp).Value = Convert.ToDateTime(valores[11]);

            cmd.Parameters.Add("@FLGESTADO", OleDbType.Char, 1).Value = valores[12];

            if (valores[13] == null)
                cmd.Parameters.Add("@DATELI", OleDbType.DBTimeStamp).Value = DBNull.Value;
            else
                cmd.Parameters.Add("@DATELI", OleDbType.DBTimeStamp).Value = Convert.ToDateTime(valores[13]);

            cmd.Parameters.Add("@DATUPD", OleDbType.DBTimeStamp).Value = Convert.ToDateTime(valores[14]);
            cmd.Parameters.Add("@TXTADR", OleDbType.VarChar, 100).Value = valores[15];
            cmd.Parameters.Add("@CODUSR", OleDbType.VarChar, 7).Value = valores[16];
            cmd.Parameters.Add("@NUMACC", OleDbType.VarChar, 18).Value = valores[0];

            cmd.CommandText = query;
            try
            {
                cmd.ExecuteNonQuery();
            }
            catch (OleDbException ex)
            {
                byte[] emptybytes = new byte[0];

                this.Log("CustomMessage: Error en NUMACC: " + valores[0] + " | " + ex.Message, 0, emptybytes);
            }
            cmd.Parameters.Clear();
        }
        con.Close();
    }
}
</code>```

I have given the "yyyy-MM-dd HH:mm:ss" format for the datetime column. It works when I do it from SQl Server Management Studio, but thats it. Now, I know OLEDB doesnt really care about parameter name, it works on the same order is called in the query. Thats why I did it this way.

I've testing with just using

```<code>String query = " UPDATE [UTB_CUENTAS] SET CODTYP=ISNULL(?,CODTYP) WHERE NUMACC = ?"
</code>```

and only using the first parameter and it works! but using the second value CODORG it throws the error.

In this case, valores[2] and valores[3] are null values, but since Im using ISNULL() in the query, I believe it shouldnt be a problem. Even if it is, the column allow null values, but its not updating

答: You must create the WHERE clausole dinamically, check in the program the value, if is null dont add to query string the sql code for the value and dont add parameter to command</p>

Body:
Alright so, Im trying to do a simple update query to a table but I keep getting this error Incorrect syntax near the keyword 'DEFAULT'. The thing is. it only goes wrong when ome values are NULL, but I've checked and IT DOES allow null values. Here is my code for the query

public void UpdateQuery(String[] valores)
{
    conexion = this.Connections.OLEDBCONNECTION.ConnectionString;
    String query = " UPDATE [UTB_CUENTAS] SET CODTYP=ISNULL(?,CODTYP), CODORG=ISNULL(?,CODORG), CODGRP=ISNULL(?,CODGRP), TXTDEN=ISNULL(?,TXTDEN),"
                 + " IDEACC=ISNULL(?,IDEACC), CODAPP=ISNULL(?,CODAPP), NUMPLZ=ISNULL(?,NUMPLZ), CODCUR=ISNULL(?,CODCUR), DATING=ISNULL(?,DATING),"
                 + " NUMACCCTE=ISNULL(?,NUMACCCTE), DATCAN=ISNULL(?,DATCAN), FLGESTADO=ISNULL(?,FLGESTADO), DATELI=ISNULL(?,DATELI),"
                 + " DATUPD=ISNULL(?,DATUPD), TXTADR=ISNULL(?,TXTADR), CODUSR=ISNULL(?,CODUSR)"
                 + " WHERE NUMACC = ?";

    using (OleDbConnection con = new OleDbConnection(conexion))
    {
        con.Open();
        using (OleDbCommand cmd = con.CreateCommand())
        {
            cmd.Parameters.Add("@CODTYP", OleDbType.VarChar, 3).Value = valores[1];
            cmd.Parameters.Add("@CODORG", OleDbType.VarChar, 18).Value = valores[2];
            cmd.Parameters.Add("@CODGRP", OleDbType.VarChar, 4).Value = valores[3];
            cmd.Parameters.Add("@TXTDEN", OleDbType.VarChar, 150).Value = valores[4];
            cmd.Parameters.Add("@IDEACC", OleDbType.Char, 1).Value = valores[5];
            cmd.Parameters.Add("@CODAPP", OleDbType.VarChar, 2).Value = valores[6];
            cmd.Parameters.Add("@NUMPLZ", OleDbType.VarChar, 3).Value = valores[7];
            cmd.Parameters.Add("@CODCUR", OleDbType.Char, 3).Value = valores[8];

            if (valores[9] == null)
                cmd.Parameters.Add("@DATING", OleDbType.DBTimeStamp).Value = DBNull.Value;
            else
                cmd.Parameters.Add("@DATING", OleDbType.DBTimeStamp).Value = Convert.ToDateTime(valores[9]);

            cmd.Parameters.Add("@NUMACCCTE", OleDbType.VarChar, 18).Value = valores[10];

            if (valores[11] == null)
                cmd.Parameters.Add("@DATCAN", OleDbType.DBTimeStamp).Value = DBNull.Value;
            else
                cmd.Parameters.Add("@DATCAN", OleDbType.DBTimeStamp).Value = Convert.ToDateTime(valores[11]);

            cmd.Parameters.Add("@FLGESTADO", OleDbType.Char, 1).Value = valores[12];

            if (valores[13] == null)
                cmd.Parameters.Add("@DATELI", OleDbType.DBTimeStamp).Value = DBNull.Value;
            else
                cmd.Parameters.Add("@DATELI", OleDbType.DBTimeStamp).Value = Convert.ToDateTime(valores[13]);

            cmd.Parameters.Add("@DATUPD", OleDbType.DBTimeStamp).Value = Convert.ToDateTime(valores[14]);
            cmd.Parameters.Add("@TXTADR", OleDbType.VarChar, 100).Value = valores[15];
            cmd.Parameters.Add("@CODUSR", OleDbType.VarChar, 7).Value = valores[16];
            cmd.Parameters.Add("@NUMACC", OleDbType.VarChar, 18).Value = valores[0];

            cmd.CommandText = query;
            try
            {
                cmd.ExecuteNonQuery();
            }
            catch (OleDbException ex)
            {
                byte[] emptybytes = new byte[0];

                this.Log("CustomMessage: Error en NUMACC: " + valores[0] + " | " + ex.Message, 0, emptybytes);
            }
            cmd.Parameters.Clear();
        }
        con.Close();
    }
}

I have given the "yyyy-MM-dd HH:mm:ss" format for the datetime column. It works when I do it from SQl Server Management Studio, but thats it. Now, I know OLEDB doesnt really care about parameter name, it works on the same order is called in the query. Thats why I did it this way.

I've testing with just using

String query = " UPDATE [UTB_CUENTAS] SET CODTYP=ISNULL(?,CODTYP) WHERE NUMACC = ?"

and only using the first parameter and it works! but using the second value CODORG it throws the error.

In this case, valores[2] and valores[3] are null values, but since Im using ISNULL() in the query, I believe it shouldnt be a problem. Even if it is, the column allow null values, but its not updating


问:
Low memory after quitting distributed Tensorflow execution
I am applying machine learning in MNIST through Tensorflow. I do this on a cluster where every nodes runs a distributed execution of Tensorflow. I run the individual executions via a bash script on a master node. This master node connects to a set of nodes from the cluster using ssh, and then runs the Python script running Tensorflow.

While Tensorflow is running on nodes I often get the following error message, causing a node to crash:

```<code>2017-03-29 20:34:02.749498: I tensorflow/core/distributed_runtime/rpc/grpc_server_lib.cc:239] Started server with target: grpc://localhost:8338
Extracting /home/mvo010/.tmp/tensorflow/mnist/input_data/train-images-idx3-ubyte.gz
Extracting /home/mvo010/.tmp/tensorflow/mnist/input_data/train-labels-idx1-ubyte.gz
Extracting /home/mvo010/.tmp/tensorflow/mnist/input_data/t10k-images-idx3-ubyte.gz
Extracting /home/mvo010/.tmp/tensorflow/mnist/input_data/t10k-labels-idx1-ubyte.gz
Traceback (most recent call last):
  File "/home/mvo010/inf3203-1/mnist_softmax.py", line 173, in <module>
    tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)
  File "/share/apps/lib/python2.7/site-packages/tensorflow/python/platform/app.py", line 44, in run
    _sys.exit(main(_sys.argv[:1] + flags_passthrough))
  File "/home/mvo010/inf3203-1/mnist_softmax.py", line 24, in main
    mnist = input_data.read_data_sets(FLAGS.data_dir, one_hot=True)
  File "/share/apps/lib/python2.7/site-packages/tensorflow/contrib/learn/python/learn/datasets/mnist.py", line 256, in read_data_sets
    train = DataSet(train_images, train_labels, dtype=dtype, reshape=reshape)
  File "/share/apps/lib/python2.7/site-packages/tensorflow/contrib/learn/python/learn/datasets/mnist.py", line 138, in __init__
    images = numpy.multiply(images, 1.0 / 255.0)
MemoryError
</code>```

This is because of low memory. When I log in on a node to check the memory I discover that the free memory is really low. The problem is that memory on the node does not get freed when a node is done (or gets killed by the master bash script when it timeouts).

Is there a trivial way to clean up memory for a node after quitting the Tensorflow application? I do not have any sudo permissions.

答: Have you tried closing the session. I believe that it's sess.close().</p>

Body:
I am applying machine learning in MNIST through Tensorflow. I do this on a cluster where every nodes runs a distributed execution of Tensorflow. I run the individual executions via a bash script on a master node. This master node connects to a set of nodes from the cluster using ssh, and then runs the Python script running Tensorflow.

While Tensorflow is running on nodes I often get the following error message, causing a node to crash:

2017-03-29 20:34:02.749498: I tensorflow/core/distributed_runtime/rpc/grpc_server_lib.cc:239] Started server with target: grpc://localhost:8338
Extracting /home/mvo010/.tmp/tensorflow/mnist/input_data/train-images-idx3-ubyte.gz
Extracting /home/mvo010/.tmp/tensorflow/mnist/input_data/train-labels-idx1-ubyte.gz
Extracting /home/mvo010/.tmp/tensorflow/mnist/input_data/t10k-images-idx3-ubyte.gz
Extracting /home/mvo010/.tmp/tensorflow/mnist/input_data/t10k-labels-idx1-ubyte.gz
Traceback (most recent call last):
  File "/home/mvo010/inf3203-1/mnist_softmax.py", line 173, in <module>
    tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)
  File "/share/apps/lib/python2.7/site-packages/tensorflow/python/platform/app.py", line 44, in run
    _sys.exit(main(_sys.argv[:1] + flags_passthrough))
  File "/home/mvo010/inf3203-1/mnist_softmax.py", line 24, in main
    mnist = input_data.read_data_sets(FLAGS.data_dir, one_hot=True)
  File "/share/apps/lib/python2.7/site-packages/tensorflow/contrib/learn/python/learn/datasets/mnist.py", line 256, in read_data_sets
    train = DataSet(train_images, train_labels, dtype=dtype, reshape=reshape)
  File "/share/apps/lib/python2.7/site-packages/tensorflow/contrib/learn/python/learn/datasets/mnist.py", line 138, in __init__
    images = numpy.multiply(images, 1.0 / 255.0)
MemoryError

This is because of low memory. When I log in on a node to check the memory I discover that the free memory is really low. The problem is that memory on the node does not get freed when a node is done (or gets killed by the master bash script when it timeouts).

Is there a trivial way to clean up memory for a node after quitting the Tensorflow application? I do not have any sudo permissions.


问:
elastic search combining multiple term and range queries is providing zero results
I am struggling on this for a week now. I need to write an elasticsearch query api in java with following combinations:

Price range (0 to n number of ranges)

Age range (0 to n number of ranges)

Search text

Term Filters (can match more than one field

I want to have OR relationship within each group (e.g. price 0-10 or 11-15) but AND relationship among different groups (e.g. price 0-10 AND productType="clothing")

I have written the below code in Java, I have verified that the data exists for the range and filter I am testing with but I am getting zero resultset.  I am not sure what is missing here.

```<code>@Override
public List<Shoppingi> search(SearchCriteria criteria, Pageable pageable) {

    final NativeSearchQueryBuilder searchQuery = new NativeSearchQueryBuilder();
    BoolQueryBuilder boolQuery = boolQuery();
    // apply the text search
    if (StringUtils.isNotBlank(criteria.getSearchText()))
        boolQuery.must(multiMatchQuery(criteria.getSearchText(), FIELD_NAMES_FOR_TERM_SEARCH));
    // apply the term filters
    BoolQueryBuilder termsQuery = boolQuery();
    criteria.getFilters().entrySet().stream().forEach(entry -> termsQuery.should(termsQuery(entry.getKey(), entry.getValue())));
    // apply the range filters
    BoolQueryBuilder rangeQuery = boolQuery();
    criteria.getRangeFilters().forEach((key, value) -> rangeQuery.should(rangeQuery(key).gte(value.getLowerBound()).lt(value.getUpperBound())));
    boolQuery.must(termsQuery);
    boolQuery.must(rangeQuery);
    searchQuery.withQuery(boolQuery);
    searchQuery.withPageable(pageable);
    NativeSearchQuery query = searchQuery.build();
    log.info("query: {}", query.getQuery().toString());
    return elasticsearchTemplate.queryForList(query,Shopping.class);
}
</code>```

答: I annotated the price object as index.no, which caused the query to not work. Once I re-indexed my data with price as non_analyzed, my code started working. So it was nothing wrong with the code above, it was the way I configured the variable I was querying against. </p>

Body:
I am struggling on this for a week now. I need to write an elasticsearch query api in java with following combinations:

Price range (0 to n number of ranges)

Age range (0 to n number of ranges)

Search text

Term Filters (can match more than one field

I want to have OR relationship within each group (e.g. price 0-10 or 11-15) but AND relationship among different groups (e.g. price 0-10 AND productType="clothing")

I have written the below code in Java, I have verified that the data exists for the range and filter I am testing with but I am getting zero resultset.  I am not sure what is missing here.

@Override
public List<Shoppingi> search(SearchCriteria criteria, Pageable pageable) {

    final NativeSearchQueryBuilder searchQuery = new NativeSearchQueryBuilder();
    BoolQueryBuilder boolQuery = boolQuery();
    // apply the text search
    if (StringUtils.isNotBlank(criteria.getSearchText()))
        boolQuery.must(multiMatchQuery(criteria.getSearchText(), FIELD_NAMES_FOR_TERM_SEARCH));
    // apply the term filters
    BoolQueryBuilder termsQuery = boolQuery();
    criteria.getFilters().entrySet().stream().forEach(entry -> termsQuery.should(termsQuery(entry.getKey(), entry.getValue())));
    // apply the range filters
    BoolQueryBuilder rangeQuery = boolQuery();
    criteria.getRangeFilters().forEach((key, value) -> rangeQuery.should(rangeQuery(key).gte(value.getLowerBound()).lt(value.getUpperBound())));
    boolQuery.must(termsQuery);
    boolQuery.must(rangeQuery);
    searchQuery.withQuery(boolQuery);
    searchQuery.withPageable(pageable);
    NativeSearchQuery query = searchQuery.build();
    log.info("query: {}", query.getQuery().toString());
    return elasticsearchTemplate.queryForList(query,Shopping.class);
}


问:
In Java, how can I use .equalsIgnoreCase to apply to multiple strings?
In Java, how can I use equalsIgnoreCase to apply to multiple strings?
I am new to Java and I want the user to enter a or c or e in either lowercase or uppercase.

答:
Just connect your possibilities with the logical OR operator (||):

```<code>if ("a".equalsIgnoreCase(string)
 || "c".equalsIgnoreCase(string)
 || "e".equalsIgnoreCase(string)) {
    // Valid string
} else {
    // Invalid string
}
</code>```

Body:
Just connect your possibilities with the logical OR operator (||):

if ("a".equalsIgnoreCase(string)
 || "c".equalsIgnoreCase(string)
 || "e".equalsIgnoreCase(string)) {
    // Valid string
} else {
    // Invalid string
}


问:
How update UI when AsyncTask.onProgressUpdate() finish?
When open Activity I start long (10 sek) process. This process create list of 10 items. And finish after 10 sec. As result the list show (UI update) AFTER 10 seconds.

But I need to show every item right after it create. So, first item must show after 1 second.

So I create AsyncTask for this:

```<code>onCreate() {
 BackgroundTask  backgroundTask  = new BackgroundTask ();
   backgroundTask.execute(newsDetailsList);
}

    private class BackgroundTask  extends AsyncTask<List<NewsDetails>, NewsDetails, Void> {

        @Override
        protected Void doInBackground(List<NewsDetails>... newsDetailsList) {
            List<NewsDetails> passedList = newsDetailsList[0];
            for (NewsDetails newsDetails : passedList) {
                publishProgress(newsDetails);
            }
            return null;
        }

        @Override
        protected void onProgressUpdate(final NewsDetails... passedNewsDetails) {
           super.onProgressUpdate(passedNewsDetails);
           final NewsDetails newsDetails = passedNewsDetails[0];
          // here create UI for new items newsDetails
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
        }
}
</code>```

But UI is updated AFTER onPostExecute() finish (after 10 SECONDS). But I need to update UI after every finish (10 times) method onProgressUpdate().

How I can do this?

答:
Just call the notifyDataSetChanged

```<code>      @Override
        protected void onProgressUpdate(final NewsDetails... passedNewsDetails) {
           super.onProgressUpdate(passedNewsDetails);
                adapter.notifyDataSetChanged();
        }
</code>```

Basicly, you refresh the ListView each time progress updated

Body:
When open Activity I start long (10 sek) process. This process create list of 10 items. And finish after 10 sec. As result the list show (UI update) AFTER 10 seconds.

But I need to show every item right after it create. So, first item must show after 1 second.

So I create AsyncTask for this:

onCreate() {
 BackgroundTask  backgroundTask  = new BackgroundTask ();
   backgroundTask.execute(newsDetailsList);
}

    private class BackgroundTask  extends AsyncTask<List<NewsDetails>, NewsDetails, Void> {

        @Override
        protected Void doInBackground(List<NewsDetails>... newsDetailsList) {
            List<NewsDetails> passedList = newsDetailsList[0];
            for (NewsDetails newsDetails : passedList) {
                publishProgress(newsDetails);
            }
            return null;
        }

        @Override
        protected void onProgressUpdate(final NewsDetails... passedNewsDetails) {
           super.onProgressUpdate(passedNewsDetails);
           final NewsDetails newsDetails = passedNewsDetails[0];
          // here create UI for new items newsDetails
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
        }
}

But UI is updated AFTER onPostExecute() finish (after 10 SECONDS). But I need to update UI after every finish (10 times) method onProgressUpdate().

How I can do this?

Body:
Just call the notifyDataSetChanged

      @Override
        protected void onProgressUpdate(final NewsDetails... passedNewsDetails) {
           super.onProgressUpdate(passedNewsDetails);
                adapter.notifyDataSetChanged();
        }

Basicly, you refresh the ListView each time progress updated


问:
Merging same columns from a table with different conditions
I want to retrieve data from one table but the data is based on conditions this is my query:

```<code>Select
    Store_ID,
    (select Stc_Item_Desc, Imported_Date, Store_ID, Quantity_On_Hand
     from DailyStockHistory
     where Stc_Item_Desc = 'SAWA/QuickNet prepaid triosim'
       and Imported_Date = '3-15-2017'
       and Store_ID like 'S%'),
    (select Stc_Item_Desc, Imported_Date, Store_ID, Quantity_On_Hand
     from DailyStockHistory
     where Stc_Item_Desc = 'SAWA/QuickNet prepaid triosim'
       and Imported_Date = '3-22-2017'
       and Store_ID like 'S%')
from
    DailyStockHistory
</code>```

Any help please.

Thanks in advance.

答:
Why don't you combine conditions in one query instead of combining 2 query results:

```<code>Select Store_ID,
     (select Stc_Item_Desc, Imported_Date,Store_ID, Quantity_On_Hand
     from DailyStockHistory
     where Stc_Item_Desc = 'SAWA/QuickNet prepaid triosim' AND
         ((Imported_Date = '3-15-2017') OR (Imported_Date = '3-22-2017'))
         AND Store_ID like 'S%'
      )
     from DailyStockHistory
</code>```

To get Quantity_On_Hand for a given day you could simply do another query

```<code>     select Quantity_On_Hand
     from *above result*
     where Imported_Date = '3-15-2017'
</code>```

Body:
I want to retrieve data from one table but the data is based on conditions this is my query:

Select
    Store_ID,
    (select Stc_Item_Desc, Imported_Date, Store_ID, Quantity_On_Hand
     from DailyStockHistory
     where Stc_Item_Desc = 'SAWA/QuickNet prepaid triosim'
       and Imported_Date = '3-15-2017'
       and Store_ID like 'S%'),
    (select Stc_Item_Desc, Imported_Date, Store_ID, Quantity_On_Hand
     from DailyStockHistory
     where Stc_Item_Desc = 'SAWA/QuickNet prepaid triosim'
       and Imported_Date = '3-22-2017'
       and Store_ID like 'S%')
from
    DailyStockHistory

Any help please.

Thanks in advance.

Body:
Why don't you combine conditions in one query instead of combining 2 query results:

Select Store_ID,
     (select Stc_Item_Desc, Imported_Date,Store_ID, Quantity_On_Hand
     from DailyStockHistory
     where Stc_Item_Desc = 'SAWA/QuickNet prepaid triosim' AND
         ((Imported_Date = '3-15-2017') OR (Imported_Date = '3-22-2017'))
         AND Store_ID like 'S%'
      )
     from DailyStockHistory

To get Quantity_On_Hand for a given day you could simply do another query

     select Quantity_On_Hand
     from *above result*
     where Imported_Date = '3-15-2017'