问:
FB.getLoginStatus does not fires callback function
I have a difficult problem. Difficult means I searched through the net and StackOverflow as well the whole FBJS SDK documentation and haven't find answer.

I am building a Page Tab application where I'd like to let fans to rsvp events. So I have to check if the user is logged in and if it doesn't I have to login. That sounds pretty easy, but FB.getLoginStatus doesn't fires callback function. This is the code excerpt:

```<code>FB.init({
   appId: window.appID,
   status: true,
   xfbml: true,
   cookie: true,
   oauth: true,
   channelUrl: 'http://example.com/fb/channel.html'
 });
</code>```

and then I simply - of course after the user clicks on a button - call FB.getLoginStatus, but it seems it doesn't do anything.

I've already checked sandbox mode, FB.init success, URLs in application settings and developing environment. I can call FB.ui, although FB.ui with method: 'oauth' I get an error message saying " The "redirect_uri" parameter cannot be used in conjunction with the "next" parameter, which is deprecated.". Which is very weird because I didn't used "next" parameter. But when I set next to undefined, it works fine, I get the window, but it says "Given URL is not allowed by the Application configuration.". Expect from that, I can login, then I've got the access_token. But in the new window, getLoginStatus still doesn't do anything.

So any advices are welcome.

Thanks,
Tamas

UPDATE:

```<code>function onBodyLoad() { //on body onload
    FB.init({
     appId: window.appID,
     status: true,
     xfbml: true,
     cookie: true,
     oauth: true,
     channelUrl: 'http://example.com/fb/channel.html'
    });
   }
...
function getName() { // on button onclick
 FB.getLoginStatus(function(response){
  if (response.authResponse)
   {
    window.loggedIn = true;
    debugString('Logged in');
   } else
   {
    window.loggedIn=false;
    debugString('Not logged in');
   }
}, true);
if (window.loggedIn === undefined)   {
     debugString('getLoginStatus did not exec'); // I always get this message
  }
</code>```

}

UPDATE 2: I created a new App on a different URL, which is configured as a standalone website. There these codes work perfectly, I can getLoginStatus, I can login, etc. Is there any difference working in the context of FB, and in a standalone website, using FB JavaScript SDK?

答:
I had the same problem. I was working on the facebook login process of our website. During development the "FB.getLoginStatus" did not return a response. I fixed it in the settings of the app on facebook:

-In facebook go to "manage apps"

-Go to the "facebook login" settings of your app

-Add your development url (for example "https://localhost") to the "Valid OAuth Redirect URIs"

(Don't forget to remove the "https://localhost" from the OAuth Redirect URIs when you are finished with developping.)

Body:
I have a difficult problem. Difficult means I searched through the net and StackOverflow as well the whole FBJS SDK documentation and haven't find answer.

I am building a Page Tab application where I'd like to let fans to rsvp events. So I have to check if the user is logged in and if it doesn't I have to login. That sounds pretty easy, but FB.getLoginStatus doesn't fires callback function. This is the code excerpt:

FB.init({
   appId: window.appID,
   status: true,
   xfbml: true,
   cookie: true,
   oauth: true,
   channelUrl: 'http://example.com/fb/channel.html'
 });

and then I simply - of course after the user clicks on a button - call FB.getLoginStatus, but it seems it doesn't do anything.

I've already checked sandbox mode, FB.init success, URLs in application settings and developing environment. I can call FB.ui, although FB.ui with method: 'oauth' I get an error message saying " The "redirect_uri" parameter cannot be used in conjunction with the "next" parameter, which is deprecated.". Which is very weird because I didn't used "next" parameter. But when I set next to undefined, it works fine, I get the window, but it says "Given URL is not allowed by the Application configuration.". Expect from that, I can login, then I've got the access_token. But in the new window, getLoginStatus still doesn't do anything.

So any advices are welcome.

Thanks,
Tamas

UPDATE:

function onBodyLoad() { //on body onload
    FB.init({
     appId: window.appID,
     status: true,
     xfbml: true,
     cookie: true,
     oauth: true,
     channelUrl: 'http://example.com/fb/channel.html'
    });
   }
...
function getName() { // on button onclick
 FB.getLoginStatus(function(response){
  if (response.authResponse)
   {
    window.loggedIn = true;
    debugString('Logged in');
   } else
   {
    window.loggedIn=false;
    debugString('Not logged in');
   }
}, true);
if (window.loggedIn === undefined)   {
     debugString('getLoginStatus did not exec'); // I always get this message
  }

}

UPDATE 2: I created a new App on a different URL, which is configured as a standalone website. There these codes work perfectly, I can getLoginStatus, I can login, etc. Is there any difference working in the context of FB, and in a standalone website, using FB JavaScript SDK?


来源: stackexchange

问:
NumPy Slicing with Multiple Tuples
Consider the following:

```<code>import numpy as np

arr = np.arange(3 * 4 * 5).reshape((3, 4, 5))
</code>```

If I slice arr using slices, I get, e.g.:

```<code>arr[:, 0:2, :].shape
# (3, 2, 5)
</code>```

If now I slice arr using a mixture of slice() and tuple(), I get:

```<code>arr[:, (0, 1), :].shape
# (3, 2, 5)

np.all(arr[:, (0, 1), :] == arr[:, :2, :])
# True
</code>```

and:

```<code>arr[:, :, (0, 1)].shape
# (3, 4, 2)

np.all(arr[:, :, (0, 1)] == arr[:, :, :2])
# True
</code>```

HOWEVER, if I do:

```<code>arr[:, (0, 1), (0, 1)].shape
# (3, 2)
</code>```

which is basically, arr[:, 0, 0] and arr[:, 1, 1] concatenated.

I was expecting to get:

```<code>arr[:, (0, 1), (0, 1)].shape
# (3, 2, 2)

np.all(arr[:, (0, 1), (0, 1)] == arr[:, :2, :2])
# True
</code>```

but it is clearly not the case.

If I concatenate two separate slicing, I would be able to obtain the desired result, i.e.:

```<code>arr[:, (0, 1), :][:, :, (0, 1)].shape
# (3, 2, 2)

np.all(arr[:, (0, 1), :][:, :, (0, 1)] == arr[:, :2, :2])
# True
</code>```

Is it possible to obtain the same result as arr[:, (0, 1), :][:, :, (0, 1)] but USING a single slicing?

Now, this example is not so interesting, because I could replace the tuple() with a slice(), but if that is not true, it all becomes a lot more relevant, e.g.:

```<code>arr[:, (0, 2, 3), :][:, :, (0, 2, 3, 4)]
# [[[ 0  2  3  4]
#   [10 12 13 14]
#   [15 17 18 19]]

#  [[20 22 23 24]
#   [30 32 33 34]
#   [35 37 38 39]]

#  [[40 42 43 44]
#   [50 52 53 54]
#   [55 57 58 59]]]
</code>```

for which arr[:, (0, 2, 3), (0, 2, 3, 4)] would be a much more convenient syntax.

EDIT

@Divakar @hpaulj and @MadPhysicist comments / answers pointed towards a properly broadcasted Iterable to be equivalent of multiple concatenated slicing.

However, this is not the case, e.g.:

```<code>s = np.ix_((0, 1), (0, 1, 2, 3))
arr[s[0], slice(3), s[1]]
# [[[ 0  5 10]
#   [ 1  6 11]
#   [ 2  7 12]
#   [ 3  8 13]]
#
#  [[20 25 30]
#   [21 26 31]
#   [22 27 32]
#   [23 28 33]]]
</code>```

But:

```<code>arr[(0, 1), :, :][:, :3, :][:, :, (0, 1, 2, 3)]
# [[[ 0  1  2  3]
#   [ 5  6  7  8]
#   [10 11 12 13]]
#
#  [[20 21 22 23]
#   [25 26 27 28]
#   [30 31 32 33]]]
</code>```

and:

```<code>np.all(arr[:2, :3, :4] == arr[(0, 1), :, :][:, :3, :][:, :, (0, 1, 2, 3)])
# True

np.all(arr[s[0], slice(3), s[1]] == arr[(0, 1), :, :][:, :3, :][:, :, (0, 1, 2, 3)])
# False
</code>```

答:
If you want to achieve the ability to slice your array programmatically, the answer is slice objects, not sequences of indices. For example, :2 becomes slice(None, 2):

```<code>np.all(arr[:, slice(None, 2), slice(None, 2)] == arr[:, :2, :2])
</code>```

Slices select a portion of an axis. Index arrays do not: they select individual elements. The shape of the index determines the shape of the output in that case.

If you want to select arbitrary indices across multiple dimensions, the shape of the index arrays must be same shape as the desired output, or broadcast to it:

```<code>arr[:, [[0], [2], [3]], [[0, 2, 3, 4]]]
</code>```

ContentLicense: CC BY-SA 4.0

Title: NumPy Slicing with Multiple Tuples

Body:
Consider the following:

import numpy as np

arr = np.arange(3 * 4 * 5).reshape((3, 4, 5))

If I slice arr using slices, I get, e.g.:

arr[:, 0:2, :].shape
# (3, 2, 5)

If now I slice arr using a mixture of slice() and tuple(), I get:

arr[:, (0, 1), :].shape
# (3, 2, 5)

np.all(arr[:, (0, 1), :] == arr[:, :2, :])
# True

and:

arr[:, :, (0, 1)].shape
# (3, 4, 2)

np.all(arr[:, :, (0, 1)] == arr[:, :, :2])
# True

HOWEVER, if I do:

arr[:, (0, 1), (0, 1)].shape
# (3, 2)

which is basically, arr[:, 0, 0] and arr[:, 1, 1] concatenated.

I was expecting to get:

arr[:, (0, 1), (0, 1)].shape
# (3, 2, 2)

np.all(arr[:, (0, 1), (0, 1)] == arr[:, :2, :2])
# True

but it is clearly not the case.

If I concatenate two separate slicing, I would be able to obtain the desired result, i.e.:

arr[:, (0, 1), :][:, :, (0, 1)].shape
# (3, 2, 2)

np.all(arr[:, (0, 1), :][:, :, (0, 1)] == arr[:, :2, :2])
# True

Is it possible to obtain the same result as arr[:, (0, 1), :][:, :, (0, 1)] but USING a single slicing?

Now, this example is not so interesting, because I could replace the tuple() with a slice(), but if that is not true, it all becomes a lot more relevant, e.g.:

arr[:, (0, 2, 3), :][:, :, (0, 2, 3, 4)]
# [[[ 0  2  3  4]
#   [10 12 13 14]
#   [15 17 18 19]]

#  [[20 22 23 24]
#   [30 32 33 34]
#   [35 37 38 39]]

#  [[40 42 43 44]
#   [50 52 53 54]
#   [55 57 58 59]]]

for which arr[:, (0, 2, 3), (0, 2, 3, 4)] would be a much more convenient syntax.

EDIT

@Divakar @hpaulj and @MadPhysicist comments / answers pointed towards a properly broadcasted Iterable to be equivalent of multiple concatenated slicing.

However, this is not the case, e.g.:

s = np.ix_((0, 1), (0, 1, 2, 3))
arr[s[0], slice(3), s[1]]
# [[[ 0  5 10]
#   [ 1  6 11]
#   [ 2  7 12]
#   [ 3  8 13]]
#
#  [[20 25 30]
#   [21 26 31]
#   [22 27 32]
#   [23 28 33]]]

But:

arr[(0, 1), :, :][:, :3, :][:, :, (0, 1, 2, 3)]
# [[[ 0  1  2  3]
#   [ 5  6  7  8]
#   [10 11 12 13]]
#
#  [[20 21 22 23]
#   [25 26 27 28]
#   [30 31 32 33]]]

and:

np.all(arr[:2, :3, :4] == arr[(0, 1), :, :][:, :3, :][:, :, (0, 1, 2, 3)])
# True

np.all(arr[s[0], slice(3), s[1]] == arr[(0, 1), :, :][:, :3, :][:, :, (0, 1, 2, 3)])
# False

Body:
If you want to achieve the ability to slice your array programmatically, the answer is slice objects, not sequences of indices. For example, :2 becomes slice(None, 2):

np.all(arr[:, slice(None, 2), slice(None, 2)] == arr[:, :2, :2])

Slices select a portion of an axis. Index arrays do not: they select individual elements. The shape of the index determines the shape of the output in that case.

If you want to select arbitrary indices across multiple dimensions, the shape of the index arrays must be same shape as the desired output, or broadcast to it:

arr[:, [[0], [2], [3]], [[0, 2, 3, 4]]]


问:
Trouble passing int data from one view controller to another (segue)
I would like to pass an int data from one view controller to another one.

The problem is that the int data received in the second view controller doesn't match the first view controller's int data.

View controller 1:

```<code>import UIKit
class levelsSelector: UIViewController {
    var levelSelected: Int = 0
    var gameWanted: Int = 0

    @IBAction func level1Tapped(_ sender: Any) {
        gameWanted = 1
        performSegue(withIdentifier: "gameOn", sender: self)
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "gameOne" {
            let levelsSelector = segue.destination as! game
            levelsSelector.finalGame = levelSelected
            let levelsSelector2 = segue.destination as! game
            levelsSelector2.finalLevel = gameWanted
        }
    }
}
</code>```

View controller 2:

```<code>import UIKit
class game: UIViewController {
    var finalLevel: Int = 0
    var finalGame: Int = 0

    override func viewDidLoad() {
        super.viewDidLoad()

        print(finalLevel)
        print(finalGame)
    }
}
</code>```

答:
You've made a typo in your segue name

```<code>performSegue(withIdentifier: "gameOn", sender: self)

...

if segue.identifier == "gameOne" {
</code>```

these two identifiers need to match

Body:
I would like to pass an int data from one view controller to another one.

The problem is that the int data received in the second view controller doesn't match the first view controller's int data.

View controller 1:

import UIKit
class levelsSelector: UIViewController {
    var levelSelected: Int = 0
    var gameWanted: Int = 0

    @IBAction func level1Tapped(_ sender: Any) {
        gameWanted = 1
        performSegue(withIdentifier: "gameOn", sender: self)
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "gameOne" {
            let levelsSelector = segue.destination as! game
            levelsSelector.finalGame = levelSelected
            let levelsSelector2 = segue.destination as! game
            levelsSelector2.finalLevel = gameWanted
        }
    }
}

View controller 2:

import UIKit
class game: UIViewController {
    var finalLevel: Int = 0
    var finalGame: Int = 0

    override func viewDidLoad() {
        super.viewDidLoad()

        print(finalLevel)
        print(finalGame)
    }
}

Body:
You've made a typo in your segue name

performSegue(withIdentifier: "gameOn", sender: self)

...

if segue.identifier == "gameOne" {

these two identifiers need to match


问:
React Native Release Signed APK crash on app start
I have an issue with react native release APK.

The app run on debug mode but it crash immediately on release mode

Some Phone it will be installed but when i will run it then it crash immediately and some other phone it will not installed Here is my app like looking this...

Here is my packege dependencies list

```<code>"dependencies": {
    "axios": "^0.18.0",
    "jwt-decode": "^2.2.0",
    "native-base": "^2.12.1",
    "react": "16.8.3",
    "react-native": "0.59.8",
    "react-native-awesome-alerts": "^1.2.0",
    "react-native-elements": "^1.1.0",
    "react-native-gesture-handler": "^1.2.1",
    "react-native-maps": "^0.24.2",
    "react-native-otp-inputs": "^3.0.2",
    "react-native-swiper": "^1.5.14",
    "react-native-vector-icons": "^6.4.2",
    "react-navigation": "^3.9.2",
    "react-redux": "^5.0.7",
    "redux": "^3.7.2",
    "redux-thunk": "^2.2.0"
},
</code>```

And my android/build.gradle file is -

```<code>buildscript {
    ext {
        buildToolsVersion = "28.0.3"
        minSdkVersion = 16
        compileSdkVersion = 28
        targetSdkVersion = 28
        supportLibVersion = "28.0.0"
        multiDexEnabled = true
    }
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.3.1'
    }
}
</code>```

My android studio log cat crash ....

答:
I had the same error, change react-native to 0.59.3

run

yarn add react-native@0.59.3

or

npm i --save react-native@0.59.3

I also removed both android/app/build and node_modules/ (To make a fresh build)

Apparently it's a bug associated with version 0.59.8

Body:
I have an issue with react native release APK.

The app run on debug mode but it crash immediately on release mode

Some Phone it will be installed but when i will run it then it crash immediately and some other phone it will not installed Here is my app like looking this...

Here is my packege dependencies list

"dependencies": {
    "axios": "^0.18.0",
    "jwt-decode": "^2.2.0",
    "native-base": "^2.12.1",
    "react": "16.8.3",
    "react-native": "0.59.8",
    "react-native-awesome-alerts": "^1.2.0",
    "react-native-elements": "^1.1.0",
    "react-native-gesture-handler": "^1.2.1",
    "react-native-maps": "^0.24.2",
    "react-native-otp-inputs": "^3.0.2",
    "react-native-swiper": "^1.5.14",
    "react-native-vector-icons": "^6.4.2",
    "react-navigation": "^3.9.2",
    "react-redux": "^5.0.7",
    "redux": "^3.7.2",
    "redux-thunk": "^2.2.0"
},

And my android/build.gradle file is -

buildscript {
    ext {
        buildToolsVersion = "28.0.3"
        minSdkVersion = 16
        compileSdkVersion = 28
        targetSdkVersion = 28
        supportLibVersion = "28.0.0"
        multiDexEnabled = true
    }
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.3.1'
    }
}

My android studio log cat crash ....


问:
How to start Apache Storm UI from Java code?
I develop a stream processing project with Storm. I created a topology and run it by executing the Main class of my project.

In Storm tutorials, I saw a UI that is accessed from 8080 port and it shows detailed information for spouts and bolts. But, I couldn't find a way to start the UI. How can I do that?

pom.xml file:

```<code><dependency>
    <groupId>org.apache.storm</groupId>
    <artifactId>storm-core</artifactId>
    <version>1.2.2</version>
    <scope>compile</scope>
</dependency>
</code>```

Main class:

```<code>TopologyBuilder builder = new TopologyBuilder();
builder.setSpout("TwitchSpout", new TwitchSpout());
builder.setBolt("MessageBolt", new MessageBolt()).shuffleGrouping("TwitchSpout");

Config conf = new Config();
conf.setDebug(false);

new LocalCluster().submitTopology("MyFirstTopo", conf, builder.createTopology());
</code>```

The UI that I want to start:

答:
You are running your topology as a local cluster, which is just intended for testing. You should run it on a real cluster instead (see https://storm.apache.org/releases/2.0.0-SNAPSHOT/Setting-up-a-Storm-cluster.html).

Once you've set it up, you can start Storm UI with the command storm ui using the storm.sh script in storm/bin. There is currently not a way to start Storm UI in a LocalCluster.

Body:
I develop a stream processing project with Storm. I created a topology and run it by executing the Main class of my project.

In Storm tutorials, I saw a UI that is accessed from 8080 port and it shows detailed information for spouts and bolts. But, I couldn't find a way to start the UI. How can I do that?

pom.xml file:

<dependency>
    <groupId>org.apache.storm</groupId>
    <artifactId>storm-core</artifactId>
    <version>1.2.2</version>
    <scope>compile</scope>
</dependency>

Main class:

TopologyBuilder builder = new TopologyBuilder();
builder.setSpout("TwitchSpout", new TwitchSpout());
builder.setBolt("MessageBolt", new MessageBolt()).shuffleGrouping("TwitchSpout");

Config conf = new Config();
conf.setDebug(false);

new LocalCluster().submitTopology("MyFirstTopo", conf, builder.createTopology());

The UI that I want to start:


问:
Calling C functions from x86 assembly language
Is it possible to generate assembly language functions from C functions using GCC, so that they can be invoked from an assembly language program? I know that gcc compiles C to machine code (which can easily be disassembled into assembly language), and I already know that it's possible to inline assembly language functions in C, but I haven't yet found a way to invoke C functions from assembly language programs, which is basically the inverse of this.

Here, I'm attempting to inline a C function in an x86 assembly program. If inlining isn't possible, then is there some other way to invoke a C function from an assembly language program?

```<code>.686p
.model flat,stdcall
.stack 2048

.data

.code
start:

invoke  ExitProcess, 0

printSomething PROC ;now I'm attempting to inline a C function here
    void printSomething(thingToPrint){
        printf("This is a C function that I want to invoke from an assembly language program.");
        printf("There must be some way to do this - is it possible somehow?");
    }
printSomething ENDP

end start
</code>```

答:
For x86_64, note that you have to be careful with some extra things:

the stack must be 16-bit aligned before making C calls.

If you define your function in assembly, the function that called your function put the return value on stack, misaligning it, and so you have to subtract 8 more byte somehow, usually push %rbp.

This got me here for example: Why does calling the C abort() function from an x86_64 assembly function lead to segmentation fault (SIGSEGV) instead of an abort signal?

if you are doing a call from assembly for some reason (TODO why would you ever want to do that?) you have to worry about:

marking all the non-callee saved registers as clobbered

the red zone for your arguments

Here is an example: Calling printf in extended inline ASM

ContentLicense: CC BY-SA 3.0

Body:
Is it possible to generate assembly language functions from C functions using GCC, so that they can be invoked from an assembly language program? I know that gcc compiles C to machine code (which can easily be disassembled into assembly language), and I already know that it's possible to inline assembly language functions in C, but I haven't yet found a way to invoke C functions from assembly language programs, which is basically the inverse of this.

Here, I'm attempting to inline a C function in an x86 assembly program. If inlining isn't possible, then is there some other way to invoke a C function from an assembly language program?

.686p
.model flat,stdcall
.stack 2048

.data

.code
start:

invoke  ExitProcess, 0

printSomething PROC ;now I'm attempting to inline a C function here
    void printSomething(thingToPrint){
        printf("This is a C function that I want to invoke from an assembly language program.");
        printf("There must be some way to do this - is it possible somehow?");
    }
printSomething ENDP

end start


问:
Count columns and sum
I am very new to the SQL, and I have a table with id (question id) and risk areas (risk1, risk2, and risk3).

```<code>+----+-------+------+------+
| id | risk1 | risk2| risk3|
+----+-------+------+------+
| 0  |   h   |   l  |   h  |
| 1  |   m   |   l  |   l  |
| 2  |   h   |   h  |   h  |
| 3  |   l   |   l  |   h  |
+----+-------+------+------+
</code>```

My aim is to calculate the sum of 'h' for individual ids. For example the query should return '2' for id=0, '0' for id=1, '3' for id=2, and '1' for id=3. Any suggestion will be appreciated.

答:
A more conventional (we could say 'better') solution might be as follows:

```<code>DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table
(id INT NOT NULL
,risk_no INT NOT NULL
,risk_type CHAR(1) NOT NULL
,PRIMARY KEY(id,risk_no)
);

INSERT INTO my_table VALUES
(1,1,'h'),
(2,1,'m'),
(3,1,'h'),
(4,1,'l'),

(1,2,'l'),
(2,2,'l'),
(3,2,'h'),
(4,2,'l'),

(1,3,'h'),
(2,3,'l'),
(3,3,'h'),
(4,3,'h');

SELECT id, COUNT(*) total FROM my_table WHERE risk_type = 'h' GROUP BY id;
+----+-------+
| id | total |
+----+-------+
|  1 |     2 |
|  3 |     3 |
|  4 |     1 |
+----+-------+
</code>```

or

```<code>SELECT id, SUM(risk_type = 'h') total FROM my_table GROUP BY id;
+----+-------+
| id | total |
+----+-------+
|  1 |     2 |
|  2 |     0 |
|  3 |     3 |
|  4 |     1 |
+----+-------+
</code>```

Title: Count columns and sum

Body:
I am very new to the SQL, and I have a table with id (question id) and risk areas (risk1, risk2, and risk3).

+----+-------+------+------+
| id | risk1 | risk2| risk3|
+----+-------+------+------+
| 0  |   h   |   l  |   h  |
| 1  |   m   |   l  |   l  |
| 2  |   h   |   h  |   h  |
| 3  |   l   |   l  |   h  |
+----+-------+------+------+

My aim is to calculate the sum of 'h' for individual ids. For example the query should return '2' for id=0, '0' for id=1, '3' for id=2, and '1' for id=3. Any suggestion will be appreciated.

Body:
A more conventional (we could say 'better') solution might be as follows:

DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table
(id INT NOT NULL
,risk_no INT NOT NULL
,risk_type CHAR(1) NOT NULL
,PRIMARY KEY(id,risk_no)
);

INSERT INTO my_table VALUES
(1,1,'h'),
(2,1,'m'),
(3,1,'h'),
(4,1,'l'),

(1,2,'l'),
(2,2,'l'),
(3,2,'h'),
(4,2,'l'),

(1,3,'h'),
(2,3,'l'),
(3,3,'h'),
(4,3,'h');

SELECT id, COUNT(*) total FROM my_table WHERE risk_type = 'h' GROUP BY id;
+----+-------+
| id | total |
+----+-------+
|  1 |     2 |
|  3 |     3 |
|  4 |     1 |
+----+-------+

or

SELECT id, SUM(risk_type = 'h') total FROM my_table GROUP BY id;
+----+-------+
| id | total |
+----+-------+
|  1 |     2 |
|  2 |     0 |
|  3 |     3 |
|  4 |     1 |
+----+-------+


问:
Vbscript method GetAbsolutePathName() in HTML do not return the current path of the HTML document
Hi all I can't understand why GetAbsolutePathName() in HTML does not return the current path of the HTML document it returns to me the only Desktop path

if I run the same cod as .vbs all work perfectly it returns to me a real path and doesn't matter in which directory I run this script

Ran from .vbs desktop

Ran from another directory

```<code>Option Explicit

dim fs,path
set fs= CreateObject("Scripting.FileSystemObject")
path=fs.GetAbsolutePathName(".")

MsgBox path
</code>```

答:
I use this. It's "almost" the same but I don't know why it works so smoothly, giving me back the whole path of the file  </p>

```<code>Set fso = CreateObject("Scripting.FileSystemObject")

Ruta1=(fso.GetParentFolderName(WScript.ScriptFullName))&"\"

MsgBox ruta1
</code>```

Body:
Hi all I can't understand why GetAbsolutePathName() in HTML does not return the current path of the HTML document it returns to me the only Desktop path

if I run the same cod as .vbs all work perfectly it returns to me a real path and doesn't matter in which directory I run this script

Ran from .vbs desktop

Ran from another directory

Option Explicit

dim fs,path
set fs= CreateObject("Scripting.FileSystemObject")
path=fs.GetAbsolutePathName(".")

MsgBox path

Body:
I use this. It's "almost" the same but I don't know why it works so smoothly, giving me back the whole path of the file

Set fso = CreateObject("Scripting.FileSystemObject")

Ruta1=(fso.GetParentFolderName(WScript.ScriptFullName))&"\"

MsgBox ruta1


问:
Updating JSON column takes too long
```<code>  create_table "drugs", options: "ENGINE=InnoDB DEFAULT CHARSET=utf8", force: :cascade do |t|
    t.integer "item_seq"
    t.string "name"
    t.string "short_description"
    t.string "short_notice"
    t.json "package_insert"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
</code>```

I am trying to update my model Drug which is shown above. It has around 50,000 rows of data and I am using ruby code to update the items in the model using the data I am getting from separate api server.
The column I am trying to update is package_insert which has the type json.
I am only trying to update certain keys of the package_insert(BAR_CODE, EDI_CODE).

The problem I am having is that I cannot update multiple rows because it throws an error after performing commit on the first row.

The ruby code is shown below.

```<code>require 'json'
require 'net/http'
require 'active_support/core_ext/hash'

for i in 1..501
    response = Net::HTTP.get_response(URI.parse(ENV["API_SERVER"])).body
    hashed_response = Hash.from_xml(response)
    hashed_response['response']['body']['items']['item'].each do |item|
        #select drug to be updated
        drug_to_change = Drug.find_by(item_seq: item['ITEM_SEQ'])
        unless drug_to_change.nil?
            package = JSON.parse(drug_to_change.package_insert)
            package['DRB_ITEM']['BAR_CODE'] = item['BAR_CODE']
            if !item['EDI_CODE'].nil?
                package['DRB_ITEM']['EDI_CODE'] = item['EDI_CODE']
            end

            drug_to_change.update(package_insert: package.to_json)
        else
            new_item = Drug.new
            new_item.item_seq = item['ITEM_SEQ']
            new_item.name = item['ITEM_NAME']
            #update
            a = Hash.new
            a["DRB_ITEM"] = item
            new_item.save
        end
    end
end
</code>```

when I run

```<code># terminal
bin/rails runner lib/file_name.rb
# result
Running via Spring preloader in process 51929
Traceback (most recent call last):
        85: from -e:1:in `<main>'
        84: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/site_ruby/2.5.0/rubygems/core_ext/kernel_require.rb:54:in `require'
        83: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/site_ruby/2.5.0/rubygems/core_ext/kernel_require.rb:54:in `require'
        82: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/activesupport-5.2.2/lib/active_support/dependencies.rb:285:in `load'
        81: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/activesupport-5.2.2/lib/active_support/dependencies.rb:257:in `load_dependency'
        80: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/activesupport-5.2.2/lib/active_support/dependencies.rb:285:in `block in load'
        79: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/bootsnap-1.3.2/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:50:in `load'
        78: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/bootsnap-1.3.2/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:50:in `load'
        77: from /Users/jamie/Desktop/test_branch/bin/rails:9:in `<main>'
        76: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/activesupport-5.2.2/lib/active_support/dependencies.rb:291:in `require'
        75: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/activesupport-5.2.2/lib/active_support/dependencies.rb:257:in `load_dependency'
        74: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/activesupport-5.2.2/lib/active_support/dependencies.rb:291:in `block in require'
        73: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/bootsnap-1.3.2/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:29:in `require'
        72: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/bootsnap-1.3.2/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:20:in `require_with_bootsnap_lfi'
        71: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/bootsnap-1.3.2/lib/bootsnap/load_path_cache/loaded_features_index.rb:65:in `register'
        70: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/bootsnap-1.3.2/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:21:in `block in require_with_bootsnap_lfi'
        69: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/bootsnap-1.3.2/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:21:in `require'
        68: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/railties-5.2.2/lib/rails/commands.rb:18:in `<main>'
        67: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/railties-5.2.2/lib/rails/command.rb:46:in `invoke'
        66: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/railties-5.2.2/lib/rails/command/base.rb:65:in `perform'
        65: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/thor-0.20.3/lib/thor.rb:387:in `dispatch'
        64: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/thor-0.20.3/lib/thor/invocation.rb:126:in `invoke_command'
        63: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/thor-0.20.3/lib/thor/command.rb:27:in `run'
        62: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/railties-5.2.2/lib/rails/commands/runner/runner_command.rb:38:in `perform'
        61: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/bootsnap-1.3.2/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:55:in `load'
        60: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/bootsnap-1.3.2/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:55:in `load'
        59: from /Users/jamie/Desktop/test_branch/lib/renew_all.rb:5:in `<main>'
        58: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/activesupport-5.2.2/lib/active_support/core_ext/range/each.rb:9:in `each'
        57: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/activesupport-5.2.2/lib/active_support/core_ext/range/each.rb:9:in `each'
        56: from /Users/jamie/Desktop/test_branch/lib/renew_all.rb:9:in `block in <main>'
        55: from /Users/jamie/Desktop/test_branch/lib/renew_all.rb:9:in `each'
        54: from /Users/jamie/Desktop/test_branch/lib/renew_all.rb:17:in `block (2 levels) in <main>'
        53: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/activerecord-5.2.2/lib/active_record/persistence.rb:424:in `update'
        52: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/activerecord-5.2.2/lib/active_record/transactions.rb:385:in `with_transaction_returning_status'
        51: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/activerecord-5.2.2/lib/active_record/transactions.rb:212:in `transaction'
        50: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/activerecord-5.2.2/lib/active_record/connection_adapters/abstract/database_statements.rb:259:in `transaction'
        49: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/activerecord-5.2.2/lib/active_record/connection_adapters/abstract/transaction.rb:236:in `within_new_transaction'
        48: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/2.5.0/monitor.rb:226:in `mon_synchronize'
        47: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/activerecord-5.2.2/lib/active_record/connection_adapters/abstract/transaction.rb:252:in `block in within_new_transaction'
        46: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/activerecord-5.2.2/lib/active_record/connection_adapters/abstract/transaction.rb:213:in `commit_transaction'
        45: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/2.5.0/monitor.rb:226:in `mon_synchronize'
        44: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/activerecord-5.2.2/lib/active_record/connection_adapters/abstract/transaction.rb:223:in `block in commit_transaction'
        43: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/activerecord-5.2.2/lib/active_record/connection_adapters/abstract/transaction.rb:128:in `commit_records'
        42: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/activerecord-5.2.2/lib/active_record/transactions.rb:346:in `committed!'
        41: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/activesupport-5.2.2/lib/active_support/callbacks.rb:816:in `_run_commit_callbacks'
        40: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/activesupport-5.2.2/lib/active_support/callbacks.rb:133:in `run_callbacks'
        39: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/activesupport-5.2.2/lib/active_support/callbacks.rb:517:in `invoke_after'
        38: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/activesupport-5.2.2/lib/active_support/callbacks.rb:517:in `each'
        37: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/activesupport-5.2.2/lib/active_support/callbacks.rb:517:in `block in invoke_after'
        36: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/activesupport-5.2.2/lib/active_support/callbacks.rb:261:in `block in conditional'
        35: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/activesupport-5.2.2/lib/active_support/callbacks.rb:426:in `block in make_lambda'
        34: from /Users/jamie/searchkick_forked/lib/searchkick/model.rb:78:in `reindex'
        33: from /Users/jamie/searchkick_forked/lib/searchkick/record_indexer.rb:51:in `reindex'
        32: from /Users/jamie/searchkick_forked/lib/searchkick/record_indexer.rb:74:in `reindex_record'
        31: from /Users/jamie/searchkick_forked/lib/searchkick/logging.rb:27:in `store'
        30: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/activesupport-5.2.2/lib/active_support/notifications.rb:168:in `instrument'
        29: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/activesupport-5.2.2/lib/active_support/notifications/instrumenter.rb:23:in `instrument'
        28: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/activesupport-5.2.2/lib/active_support/notifications.rb:168:in `block in instrument'
        27: from /Users/jamie/searchkick_forked/lib/searchkick/logging.rb:28:in `block in store'
        26: from /Users/jamie/searchkick_forked/lib/searchkick/index.rb:125:in `store'
        25: from /Users/jamie/searchkick_forked/lib/searchkick/bulk_indexer.rb:43:in `bulk_index'
        24: from /Users/jamie/searchkick_forked/lib/searchkick/indexer.rb:11:in `queue'
        23: from /Users/jamie/searchkick_forked/lib/searchkick/logging.rb:126:in `perform'
        22: from /Users/jamie/searchkick_forked/lib/searchkick/indexer.rb:18:in `perform'
        21: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/elasticsearch-api-6.1.0/lib/elasticsearch/api/actions/bulk.rb:95:in `bulk'
        20: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/elasticsearch-transport-6.1.0/lib/elasticsearch/transport/client.rb:131:in `perform_request'
        19: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/elasticsearch-transport-6.1.0/lib/elasticsearch/transport/transport/http/faraday.rb:20:in `perform_request'
        18: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/elasticsearch-transport-6.1.0/lib/elasticsearch/transport/transport/base.rb:266:in `perform_request'
        17: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/elasticsearch-transport-6.1.0/lib/elasticsearch/transport/transport/http/faraday.rb:23:in `block in perform_request'
        16: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/faraday-0.15.4/lib/faraday/connection.rb:387:in `run_request'
        15: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/faraday-0.15.4/lib/faraday/rack_builder.rb:143:in `build_response'
        14: from /Users/jamie/searchkick_forked/lib/searchkick/middleware.rb:9:in `call'
        13: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/faraday_middleware-aws-sigv4-0.2.4/lib/faraday_middleware/request/aws_sigv4.rb:15:in `call'
        12: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/faraday-0.15.4/lib/faraday/adapter/net_http.rb:38:in `call'
        11: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/faraday-0.15.4/lib/faraday/adapter/net_http.rb:92:in `with_net_http_connection'
        10: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/faraday-0.15.4/lib/faraday/adapter/net_http.rb:43:in `block in call'
         9: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/faraday-0.15.4/lib/faraday/adapter/net_http.rb:87:in `perform_request'
         8: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/2.5.0/net/http.rb:1455:in `request'
         7: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/2.5.0/net/http.rb:909:in `start'
         6: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/2.5.0/net/http.rb:920:in `do_start'
         5: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/2.5.0/net/http.rb:935:in `connect'
         4: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/2.5.0/timeout.rb:103:in `timeout'
         3: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/2.5.0/timeout.rb:93:in `block in timeout'
         2: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/2.5.0/net/http.rb:937:in `block in connect'
         1: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/2.5.0/net/http.rb:937:in `open'
/Users/jamie/.rbenv/versions/2.5.3/lib/ruby/2.5.0/net/http.rb:937:in `initialize': execution expired (Faraday::ConnectionFailed)
</code>```

Same code in rails console results:

```<code>irb(main):017:0>drug_to_change.update(package_insert: package.to_json)
   (17.2ms)  BEGIN
   (0.3ms)  COMMIT
  Drug Store (30237.8ms)  {"id":1,"exception":["Faraday::ConnectionFailed","execution expired"],"exception_object":"execution expired"}
Traceback (most recent call last):
        1: from (irb):17
Faraday::ConnectionFailed (execution expired)
</code>```

I am guessing the problem is due to mysql commit taking too long. How can I solve this issue? Thanks in advance.

```<code>SHOW CREATE TABLE drugs;
</code>```

答:
Error Faraday::ConnectionFailed suggests that you have an http request somewhere in the update chain (package_insert= setter, model validation or callbacks) that fails with this error. This is also proven by fact that simple update via console gives the same result.

Since error is reproduced by simple obj.update(package_insert: some_json), it does not relate directly to script you provided. Look into your model, especially before_*/after_*, most probably there's some after_save callback that makes an http request (as a rule of thumb - external requests from model callbacks are generally a bad idea unless you're sure how and why you do them)

Title: Updating JSON column takes too long

Body:
  create_table "drugs", options: "ENGINE=InnoDB DEFAULT CHARSET=utf8", force: :cascade do |t|
    t.integer "item_seq"
    t.string "name"
    t.string "short_description"
    t.string "short_notice"
    t.json "package_insert"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false

I am trying to update my model Drug which is shown above. It has around 50,000 rows of data and I am using ruby code to update the items in the model using the data I am getting from separate api server.
The column I am trying to update is package_insert which has the type json.
I am only trying to update certain keys of the package_insert(BAR_CODE, EDI_CODE).

The problem I am having is that I cannot update multiple rows because it throws an error after performing commit on the first row.

The ruby code is shown below.

require 'json'
require 'net/http'
require 'active_support/core_ext/hash'

for i in 1..501
    response = Net::HTTP.get_response(URI.parse(ENV["API_SERVER"])).body
    hashed_response = Hash.from_xml(response)
    hashed_response['response']['body']['items']['item'].each do |item|
        #select drug to be updated
        drug_to_change = Drug.find_by(item_seq: item['ITEM_SEQ'])
        unless drug_to_change.nil?
            package = JSON.parse(drug_to_change.package_insert)
            package['DRB_ITEM']['BAR_CODE'] = item['BAR_CODE']
            if !item['EDI_CODE'].nil?
                package['DRB_ITEM']['EDI_CODE'] = item['EDI_CODE']
            end

            drug_to_change.update(package_insert: package.to_json)
        else
            new_item = Drug.new
            new_item.item_seq = item['ITEM_SEQ']
            new_item.name = item['ITEM_NAME']
            #update
            a = Hash.new
            a["DRB_ITEM"] = item
            new_item.save
        end
    end
end

when I run

# terminal
bin/rails runner lib/file_name.rb
# result
Running via Spring preloader in process 51929
Traceback (most recent call last):
        85: from -e:1:in `'
        84: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/site_ruby/2.5.0/rubygems/core_ext/kernel_require.rb:54:in `require'
        83: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/site_ruby/2.5.0/rubygems/core_ext/kernel_require.rb:54:in `require'
        82: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/activesupport-5.2.2/lib/active_support/dependencies.rb:285:in `load'
        81: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/activesupport-5.2.2/lib/active_support/dependencies.rb:257:in `load_dependency'
        80: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/activesupport-5.2.2/lib/active_support/dependencies.rb:285:in `block in load'
        79: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/bootsnap-1.3.2/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:50:in `load'
        78: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/bootsnap-1.3.2/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:50:in `load'
        77: from /Users/jamie/Desktop/test_branch/bin/rails:9:in `'
        76: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/activesupport-5.2.2/lib/active_support/dependencies.rb:291:in `require'
        75: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/activesupport-5.2.2/lib/active_support/dependencies.rb:257:in `load_dependency'
        74: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/activesupport-5.2.2/lib/active_support/dependencies.rb:291:in `block in require'
        73: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/bootsnap-1.3.2/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:29:in `require'
        72: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/bootsnap-1.3.2/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:20:in `require_with_bootsnap_lfi'
        71: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/bootsnap-1.3.2/lib/bootsnap/load_path_cache/loaded_features_index.rb:65:in `register'
        70: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/bootsnap-1.3.2/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:21:in `block in require_with_bootsnap_lfi'
        69: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/bootsnap-1.3.2/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:21:in `require'
        68: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/railties-5.2.2/lib/rails/commands.rb:18:in `'
        67: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/railties-5.2.2/lib/rails/command.rb:46:in `invoke'
        66: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/railties-5.2.2/lib/rails/command/base.rb:65:in `perform'
        65: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/thor-0.20.3/lib/thor.rb:387:in `dispatch'
        64: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/thor-0.20.3/lib/thor/invocation.rb:126:in `invoke_command'
        63: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/thor-0.20.3/lib/thor/command.rb:27:in `run'
        62: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/railties-5.2.2/lib/rails/commands/runner/runner_command.rb:38:in `perform'
        61: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/bootsnap-1.3.2/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:55:in `load'
        60: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/bootsnap-1.3.2/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:55:in `load'
        59: from /Users/jamie/Desktop/test_branch/lib/renew_all.rb:5:in `'
        58: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/activesupport-5.2.2/lib/active_support/core_ext/range/each.rb:9:in `each'
        57: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/activesupport-5.2.2/lib/active_support/core_ext/range/each.rb:9:in `each'
        56: from /Users/jamie/Desktop/test_branch/lib/renew_all.rb:9:in `block in '
        55: from /Users/jamie/Desktop/test_branch/lib/renew_all.rb:9:in `each'
        54: from /Users/jamie/Desktop/test_branch/lib/renew_all.rb:17:in `block (2 levels) in '
        53: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/activerecord-5.2.2/lib/active_record/persistence.rb:424:in `update'
        52: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/activerecord-5.2.2/lib/active_record/transactions.rb:385:in `with_transaction_returning_status'
        51: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/activerecord-5.2.2/lib/active_record/transactions.rb:212:in `transaction'
        50: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/activerecord-5.2.2/lib/active_record/connection_adapters/abstract/database_statements.rb:259:in `transaction'
        49: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/activerecord-5.2.2/lib/active_record/connection_adapters/abstract/transaction.rb:236:in `within_new_transaction'
        48: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/2.5.0/monitor.rb:226:in `mon_synchronize'
        47: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/activerecord-5.2.2/lib/active_record/connection_adapters/abstract/transaction.rb:252:in `block in within_new_transaction'
        46: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/activerecord-5.2.2/lib/active_record/connection_adapters/abstract/transaction.rb:213:in `commit_transaction'
        45: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/2.5.0/monitor.rb:226:in `mon_synchronize'
        44: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/activerecord-5.2.2/lib/active_record/connection_adapters/abstract/transaction.rb:223:in `block in commit_transaction'
        43: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/activerecord-5.2.2/lib/active_record/connection_adapters/abstract/transaction.rb:128:in `commit_records'
        42: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/activerecord-5.2.2/lib/active_record/transactions.rb:346:in `committed!'
        41: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/activesupport-5.2.2/lib/active_support/callbacks.rb:816:in `_run_commit_callbacks'
        40: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/activesupport-5.2.2/lib/active_support/callbacks.rb:133:in `run_callbacks'
        39: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/activesupport-5.2.2/lib/active_support/callbacks.rb:517:in `invoke_after'
        38: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/activesupport-5.2.2/lib/active_support/callbacks.rb:517:in `each'
        37: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/activesupport-5.2.2/lib/active_support/callbacks.rb:517:in `block in invoke_after'
        36: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/activesupport-5.2.2/lib/active_support/callbacks.rb:261:in `block in conditional'
        35: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/activesupport-5.2.2/lib/active_support/callbacks.rb:426:in `block in make_lambda'
        34: from /Users/jamie/searchkick_forked/lib/searchkick/model.rb:78:in `reindex'
        33: from /Users/jamie/searchkick_forked/lib/searchkick/record_indexer.rb:51:in `reindex'
        32: from /Users/jamie/searchkick_forked/lib/searchkick/record_indexer.rb:74:in `reindex_record'
        31: from /Users/jamie/searchkick_forked/lib/searchkick/logging.rb:27:in `store'
        30: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/activesupport-5.2.2/lib/active_support/notifications.rb:168:in `instrument'
        29: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/activesupport-5.2.2/lib/active_support/notifications/instrumenter.rb:23:in `instrument'
        28: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/activesupport-5.2.2/lib/active_support/notifications.rb:168:in `block in instrument'
        27: from /Users/jamie/searchkick_forked/lib/searchkick/logging.rb:28:in `block in store'
        26: from /Users/jamie/searchkick_forked/lib/searchkick/index.rb:125:in `store'
        25: from /Users/jamie/searchkick_forked/lib/searchkick/bulk_indexer.rb:43:in `bulk_index'
        24: from /Users/jamie/searchkick_forked/lib/searchkick/indexer.rb:11:in `queue'
        23: from /Users/jamie/searchkick_forked/lib/searchkick/logging.rb:126:in `perform'
        22: from /Users/jamie/searchkick_forked/lib/searchkick/indexer.rb:18:in `perform'
        21: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/elasticsearch-api-6.1.0/lib/elasticsearch/api/actions/bulk.rb:95:in `bulk'
        20: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/elasticsearch-transport-6.1.0/lib/elasticsearch/transport/client.rb:131:in `perform_request'
        19: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/elasticsearch-transport-6.1.0/lib/elasticsearch/transport/transport/http/faraday.rb:20:in `perform_request'
        18: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/elasticsearch-transport-6.1.0/lib/elasticsearch/transport/transport/base.rb:266:in `perform_request'
        17: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/elasticsearch-transport-6.1.0/lib/elasticsearch/transport/transport/http/faraday.rb:23:in `block in perform_request'
        16: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/faraday-0.15.4/lib/faraday/connection.rb:387:in `run_request'
        15: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/faraday-0.15.4/lib/faraday/rack_builder.rb:143:in `build_response'
        14: from /Users/jamie/searchkick_forked/lib/searchkick/middleware.rb:9:in `call'
        13: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/faraday_middleware-aws-sigv4-0.2.4/lib/faraday_middleware/request/aws_sigv4.rb:15:in `call'
        12: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/faraday-0.15.4/lib/faraday/adapter/net_http.rb:38:in `call'
        11: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/faraday-0.15.4/lib/faraday/adapter/net_http.rb:92:in `with_net_http_connection'
        10: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/faraday-0.15.4/lib/faraday/adapter/net_http.rb:43:in `block in call'
         9: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/faraday-0.15.4/lib/faraday/adapter/net_http.rb:87:in `perform_request'
         8: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/2.5.0/net/http.rb:1455:in `request'
         7: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/2.5.0/net/http.rb:909:in `start'
         6: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/2.5.0/net/http.rb:920:in `do_start'
         5: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/2.5.0/net/http.rb:935:in `connect'
         4: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/2.5.0/timeout.rb:103:in `timeout'
         3: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/2.5.0/timeout.rb:93:in `block in timeout'
         2: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/2.5.0/net/http.rb:937:in `block in connect'
         1: from /Users/jamie/.rbenv/versions/2.5.3/lib/ruby/2.5.0/net/http.rb:937:in `open'
/Users/jamie/.rbenv/versions/2.5.3/lib/ruby/2.5.0/net/http.rb:937:in `initialize': execution expired (Faraday::ConnectionFailed)

Same code in rails console results:

irb(main):017:0>drug_to_change.update(package_insert: package.to_json)
   (17.2ms)  BEGIN
   (0.3ms)  COMMIT
  Drug Store (30237.8ms)  {"id":1,"exception":["Faraday::ConnectionFailed","execution expired"],"exception_object":"execution expired"}
Traceback (most recent call last):
        1: from (irb):17
Faraday::ConnectionFailed (execution expired)

I am guessing the problem is due to mysql commit taking too long. How can I solve this issue? Thanks in advance.

SHOW CREATE TABLE drugs;


问:
Which one is preferable? np.where or .loc?
I found two forms of replacing some values of a data frame based on a condition:

.loc

```<code>mask = df['param'].isnull()
df.loc[mask, 'param'] = 'new_value'
</code>```

np.where()

```<code>mask = df['param'].isnull()
df['param'] = np.where(mask, 'new_value', df['param'])
</code>```

Both forms work well, but which is the preferred one? And in relation to the question, when should I use .loc and when np.where?

答:
Well, not a throughout test, but here's a sample. In each run (loc, np.where), the data is reset to the original random with seed.

toy data 1

Here, there are more np.nan than valid values. Also, the column is of float type.

```<code>np.random.seed(1)
df = pd.DataFrame({'param': np.random.choice((1, np.nan), 1000000, p=(0.3,0.7))})

# loc
%%timeit
mask = df['param'].isnull()
df.loc[mask, 'param'] = 'new_value'
# 46.7 ms ± 177 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

# np.where
%%timeit
mask = df['param'].isnull()
df['param'] = np.where(mask, 'new_value', df['param'])
# 86.8 ms ± 2.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
</code>```

toy data 2:

Here there are less np.nan than valid values, and the column is of object type:

```<code>np.random.seed(1)
df = pd.DataFrame({'param': np.random.choice(("1", np.nan), 1000000, p=(0.7,0.3))})
</code>```

same story:

```<code>df.loc[mask, 'param'] = 'new_value'
# 47.8 ms ± 350 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

df['param'] = np.where(mask, 'new_value', df['param'])
# 58.9 ms ± 1.72 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
</code>```

So contrary to @cs95's comment, loc seems to outperform np.where.

Body:
I found two forms of replacing some values of a data frame based on a condition:

.loc

mask = df['param'].isnull()
df.loc[mask, 'param'] = 'new_value'

np.where()

mask = df['param'].isnull()
df['param'] = np.where(mask, 'new_value', df['param'])

Both forms work well, but which is the preferred one? And in relation to the question, when should I use .loc and when np.where?

Body:
Well, not a throughout test, but here's a sample. In each run (loc, np.where), the data is reset to the original random with seed.

toy data 1

Here, there are more np.nan than valid values. Also, the column is of float type.

np.random.seed(1)
df = pd.DataFrame({'param': np.random.choice((1, np.nan), 1000000, p=(0.3,0.7))})

# loc
%%timeit
mask = df['param'].isnull()
df.loc[mask, 'param'] = 'new_value'
# 46.7 ms ± 177 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

# np.where
%%timeit
mask = df['param'].isnull()
df['param'] = np.where(mask, 'new_value', df['param'])
# 86.8 ms ± 2.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

toy data 2:

Here there are less np.nan than valid values, and the column is of object type:

np.random.seed(1)
df = pd.DataFrame({'param': np.random.choice(("1", np.nan), 1000000, p=(0.7,0.3))})

same story:

df.loc[mask, 'param'] = 'new_value'
# 47.8 ms ± 350 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

df['param'] = np.where(mask, 'new_value', df['param'])
# 58.9 ms ± 1.72 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

So contrary to @cs95's comment, loc seems to outperform np.where.


问:
How to add in assembly?
I am trying to make a calculator in assembly. You introduce two variables and then you choose the operation. Now the operation is only addition. I am working only with BIOS interrupts, no DOS. Can someone explain to me how to make it? I have two problems and I am stuck with them:

The first problem is when I add 5+6 for example it returns
59(48+11) in ASCII. I think a solution would be to print in decimal but I found nothing on the internet using only BIOS interrupts.

The second problem is that when I add 49+59 it returns 9, so
it adds the first characters only.

Code:

```<code>    firstVariableKeyboard: ;store in var1 first variable
        mov ah,0x0
        int 16h ;keyboard interrupt

        cmp al,0x0d
        je returnEnter

        mov ah,0eh ;tty mode
        int 10h

        mov byte [var1 + bx],al
        inc bx

        jmp firstVariableKeyboard

    secondVariableKeyboard: ;store in var2 second variable
        mov ah,0x0
        int 16h

        cmp al,0x0d
        je returnEnter

        mov ah,0eh
        int 10h

        mov byte [var2 + bx],al
        inc bx

        jmp secondVariableKeyboard

   equalMath:
        ;introduce first variable
        mov si,math_description0
        call printString

        mov bx,0
        call firstVariableKeyboard
        mov dl,[var1]
        ;conversion from ascii to decimal
        sub dl, '0'

        ;new line
        mov si,newLine
        call printString

        ;introduce second variable
        mov si,math_description1
        call printString

        mov bx,0
        call secondVariableKeyboard
        mov dh,[var2]
        ;conversion from ascii to decimal
        sub dh, '0'

        ;new line
        mov si,newLine
        call printString

        ;the result
        mov si,math_description2
        call printString

        ;adding
        add dl, dh
        ;conversion from decimal to ascii
        add dl, '0'

        mov byte [result], dl
        mov si,result
        call printString

        ;new line
        mov si,newLine
        call printString

        jmp mainLoop

printString:
    push ax                   ; save ax to stack

    mov ah, 0x0e              ; call tty function
    call printChar

    pop ax                    ; take ax out of the stack
    ret
printChar:
    mov al, [si]              ; load symbol

    cmp al, 0                 ; if si empty then jump
    jz ifZero

    int 0x10                  ; if not print al
    inc si                    ; increment si

    jmp printChar       ;again untill stack empty
ifZero:
    ret

    var1: times 64 db 0
    var2: times 64 db 0
    result:  times 64 db 0
</code>```

5+6=11 example

two char + two char example

答:
The two issues are almost the same. You are trying to represent a number containing 2 digits with 1 ASCII byte. You need to loop over your input AND over your output. Let me explain. I apologise in advance that the example is 64-bit ... you didn't post your complete code so I just ran with what I knew best to write this answer.

You're essentially doing this: (53 - 48) + (54 - 48). This gives us the value 11. So far so good. What is the ASCII value for representing 11 as a single character?

There isn't one. What you need, is to print the character '1', twice (to form the string "11").

What you need then, is a way to convert a number that has more than 1 digit into a string. Perhaps something like the itoa function in the C standard library would be sufficient.

Essentially you need to loop over the number and convert each digit into a character to form a string you can print. You can do this by dividing the number by 10 each iteration and checking the remainder. Here is an example running on IDEOne

The core of the itoa example is the division loop:

```<code>.divloop:
    xor rdx,rdx         ; Zero out rdx (where our remainder goes after idiv)
    idiv rcx            ; divide rax (the number) by 10 (the remainder is placed in rdx)
    add rdx,0x30        ; add 0x30 to the remainder so we get the correct ASCII value
    dec rdi             ; move the pointer backwards in the buffer
    mov byte [rdi],dl   ; move the character into the buffer
    inc dword [rbp-4]   ; increase the length

    cmp rax,0           ; was the quotient zero?
    jnz .divloop        ; no it wasn't, keep looping
</code>```

Let's run the number 59 from your second example through this step by step:

Current buffer:

```<code>[0][0][0][0][0][0][0][0][0][0]
</code>```

First iteration:

```<code>59 / 10 = 5 remainder 9
9 + 48 = 57 (the ASCII value of '9')

[0][0][0][0][0][0][0][0][0][57]
                            ^ place the ASCII value in the buffer, decrease the pointer and update the number to be the quotient from the idiv instruction
</code>```

So if we print this now, we'd get the number 9. The quotient wasn't zero though so we loop around again:

```<code>5 / 10 = 0 remainder 5
5 + 48 = 53 (the ASCII value of '5')

[0][0][0][0][0][0][0][0][53][57]
                          ^ place the ASCII value in the buffer, decrease the pointer and update the number to be the quotient from the idiv instruction
</code>```

The quotient is zero from this last iteration, and so we don't loop and exit the function.

These two bytes in the buffer are now 53 and 57 which are the ASCII values of the characters 5 and 9 respectively. If you were to print this buffer to your stdout, it would produce the string "59" (this example function also returns the length of the resulting string so that it can be printed correctly).

There is a similar issue with your input. You are passing in the strings "49" and "59" and only reading the very first character. You need to loop over this string and convert it to an integer. This should be fairly straight forward so I will leave that as an exercise for you.

The reason the second example "works" (it prints a number you somewhat expect) is because of the bug above. You're only adding 4 and 5 together which results in 9 - a number that has a single digit.

I hope that helps.

Title: How to add in assembly?

Body:
I am trying to make a calculator in assembly. You introduce two variables and then you choose the operation. Now the operation is only addition. I am working only with BIOS interrupts, no DOS. Can someone explain to me how to make it? I have two problems and I am stuck with them:

The first problem is when I add 5+6 for example it returns
59(48+11) in ASCII. I think a solution would be to print in decimal but I found nothing on the internet using only BIOS interrupts.

The second problem is that when I add 49+59 it returns 9, so
it adds the first characters only.

Code:

    firstVariableKeyboard: ;store in var1 first variable
        mov ah,0x0
        int 16h ;keyboard interrupt

        cmp al,0x0d
        je returnEnter

        mov ah,0eh ;tty mode
        int 10h

        mov byte [var1 + bx],al
        inc bx

        jmp firstVariableKeyboard

    secondVariableKeyboard: ;store in var2 second variable
        mov ah,0x0
        int 16h

        cmp al,0x0d
        je returnEnter

        mov ah,0eh
        int 10h

        mov byte [var2 + bx],al
        inc bx

        jmp secondVariableKeyboard

   equalMath:
        ;introduce first variable
        mov si,math_description0
        call printString

        mov bx,0
        call firstVariableKeyboard
        mov dl,[var1]
        ;conversion from ascii to decimal
        sub dl, '0'

        ;new line
        mov si,newLine
        call printString

        ;introduce second variable
        mov si,math_description1
        call printString

        mov bx,0
        call secondVariableKeyboard
        mov dh,[var2]
        ;conversion from ascii to decimal
        sub dh, '0'

        ;new line
        mov si,newLine
        call printString

        ;the result
        mov si,math_description2
        call printString

        ;adding
        add dl, dh
        ;conversion from decimal to ascii
        add dl, '0'

        mov byte [result], dl
        mov si,result
        call printString

        ;new line
        mov si,newLine
        call printString

        jmp mainLoop

printString:
    push ax                   ; save ax to stack

    mov ah, 0x0e              ; call tty function
    call printChar

    pop ax                    ; take ax out of the stack
    ret
printChar:
    mov al, [si]              ; load symbol

    cmp al, 0                 ; if si empty then jump
    jz ifZero

    int 0x10                  ; if not print al
    inc si                    ; increment si

    jmp printChar       ;again untill stack empty
ifZero:
    ret

    var1: times 64 db 0
    var2: times 64 db 0
    result:  times 64 db 0

5+6=11 example

two char + two char example

Body:
The two issues are almost the same. You are trying to represent a number containing 2 digits with 1 ASCII byte. You need to loop over your input AND over your output. Let me explain. I apologise in advance that the example is 64-bit ... you didn't post your complete code so I just ran with what I knew best to write this answer.

You're essentially doing this: (53 - 48) + (54 - 48). This gives us the value 11. So far so good. What is the ASCII value for representing 11 as a single character?

There isn't one. What you need, is to print the character '1', twice (to form the string "11").

What you need then, is a way to convert a number that has more than 1 digit into a string. Perhaps something like the itoa function in the C standard library would be sufficient.

Essentially you need to loop over the number and convert each digit into a character to form a string you can print. You can do this by dividing the number by 10 each iteration and checking the remainder. Here is an example running on IDEOne

The core of the itoa example is the division loop:

.divloop:
    xor rdx,rdx         ; Zero out rdx (where our remainder goes after idiv)
    idiv rcx            ; divide rax (the number) by 10 (the remainder is placed in rdx)
    add rdx,0x30        ; add 0x30 to the remainder so we get the correct ASCII value
    dec rdi             ; move the pointer backwards in the buffer
    mov byte [rdi],dl   ; move the character into the buffer
    inc dword [rbp-4]   ; increase the length

    cmp rax,0           ; was the quotient zero?
    jnz .divloop        ; no it wasn't, keep looping

Let's run the number 59 from your second example through this step by step:

Current buffer:

[0][0][0][0][0][0][0][0][0][0]

First iteration:

59 / 10 = 5 remainder 9
9 + 48 = 57 (the ASCII value of '9')

[0][0][0][0][0][0][0][0][0][57]
                            ^ place the ASCII value in the buffer, decrease the pointer and update the number to be the quotient from the idiv instruction

So if we print this now, we'd get the number 9. The quotient wasn't zero though so we loop around again:

5 / 10 = 0 remainder 5
5 + 48 = 53 (the ASCII value of '5')

[0][0][0][0][0][0][0][0][53][57]
                          ^ place the ASCII value in the buffer, decrease the pointer and update the number to be the quotient from the idiv instruction

The quotient is zero from this last iteration, and so we don't loop and exit the function.

These two bytes in the buffer are now 53 and 57 which are the ASCII values of the characters 5 and 9 respectively. If you were to print this buffer to your stdout, it would produce the string "59" (this example function also returns the length of the resulting string so that it can be printed correctly).

There is a similar issue with your input. You are passing in the strings "49" and "59" and only reading the very first character. You need to loop over this string and convert it to an integer. This should be fairly straight forward so I will leave that as an exercise for you.

The reason the second example "works" (it prints a number you somewhat expect) is because of the bug above. You're only adding 4 and 5 together which results in 9 - a number that has a single digit.

I hope that helps.


问:
Browser doesn't set cookie even if it is present in response headers
My response  has a set-cookie header present but the browser doesn't seem to store it (in postman it works like a charm). My API is written in .NET Core, and im using axios (React) on the client. The client requests are, however, proxied through an express server for SSR purposes.

I have tried multiple solutions posted here. From the basics of setting withCredentials to true in axios to setting the MinimumSameSitePolicy on the server to none which can be seen in the code.

Server

```<code>services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => false;
                options.MinimumSameSitePolicy = SameSiteMode.None;
                options.ConsentCookie.HttpOnly = false;
            });
..........
 app.UseCookiePolicy(new CookiePolicyOptions
            {
                MinimumSameSitePolicy = SameSiteMode.None,
                HttpOnly = HttpOnlyPolicy.None
            });
</code>```

Client

```<code>const axiosInstance = axios.create({
  baseURL: '/api',
  withCredentials: true,
  headers: {
    'Access-Control-Allow-Origin': 'http://localhost:3000/',
    'Content-Type': 'application/json'
  }
});
</code>```

Proxy

```<code>app.use(
  '/api',
  proxy('https://localhost:44364/', {
    proxyReqOptDecorator(opts) {
      opts.rejectUnauthorized = false;
      opts.headers['x-forwarded-host'] = 'localhost:3000';
      return opts;
    },
    proxyReqPathResolver(req) {
      return `/api${req.url}`;
    }
  })
);
</code>```

The response with cookie:

```<code>HTTP/1.1 200 OK
x-powered-by: ASP.NET
cache-control: no-cache
pragma: no-cache
content-type: text/plain; charset=utf-8
expires: Thu, 01 Jan 1970 00:00:00 GMT
server: Kestrel
set-cookie: .AspNetCore.Cookies=CfDJ8KvV0sFM8_FJqzJkoUey_LvYSADPHUA20Mq40db0KYSbL9Q2ZjS2JW87G8CzcTDBIpG1H6mZ_nuThzOniga7oRpguIgi3xIFCjkY5D0DXwT98ZVejY7nzLaCmV9rGLMkkqqADbr0zzwUkzXQqtWMtubY0cdHXPskTWFucMjjYk0BU4eCuWOjRzooL-QtwYtDClP720LVetm8lZGvAS6jfYpk-HWZIQiDo1ERKqhyIWKYqSFBEN0nV4ykL6KhfqEjcK8URzTEnBxdV7dCpk287smjAzTvOziRWfO6BtpxXC2tZ9NBeTLLqitn_CaAypewt9qMnjMi75zazo6yicRlTsDp-i3LT0OkD_ls1celSeG1VPlTg0OMVm0nADpZurMT9LSrijsSrcFT0wvNSTeW9vE; path=/; secure; samesite=lax; httponly
x-sourcefiles: =?UTF-8?B?QzpcVXNlcnNcTWFrYWxhXERlc2t0b3BcUm91dG9yaWFsXFJvdXRvcmlhbEFQSVxSb3V0b3JpYWxBUElcUm91dG9yaWFsQVBJXGFwaVxhY2NvdW50XGxvZ2luU3VibWl0?=
date: Sun, 26 May 2019 15:47:32 GMT
connection: close
Content-Length: 6
ETag: W/"6-+3OfqLi6+pGCkKvbVPPQANDiBD4"
</code>```

答:
Thanks @Xing Zou! Your answer was close and made me think in the right direction.
The CookiePolicyOptions were not working at all and didn't seem to override the default options.
Instead, I used

```<code>services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
        .AddCookie(options =>
        {
             options.Cookie.SameSite = SameSiteMode.None;
             options.Cookie.HttpOnly = true;
             options.Cookie.SecurePolicy = CookieSecurePolicy.None;
        });
</code>```

in ConfigureServices and

```<code> app.UseAuthentication();
</code>```

in Configure.

The browser wasnt setting the cookie when it had the secure flag so it had to be disabled
with

```<code>options.Cookie.SecurePolicy = CookieSecurePolicy.None;
</code>```

Body:
My response  has a set-cookie header present but the browser doesn't seem to store it (in postman it works like a charm). My API is written in .NET Core, and im using axios (React) on the client. The client requests are, however, proxied through an express server for SSR purposes.

I have tried multiple solutions posted here. From the basics of setting withCredentials to true in axios to setting the MinimumSameSitePolicy on the server to none which can be seen in the code.

Server

services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => false;
                options.MinimumSameSitePolicy = SameSiteMode.None;
                options.ConsentCookie.HttpOnly = false;
            });
..........
 app.UseCookiePolicy(new CookiePolicyOptions
            {
                MinimumSameSitePolicy = SameSiteMode.None,
                HttpOnly = HttpOnlyPolicy.None
            });

Client

const axiosInstance = axios.create({
  baseURL: '/api',
  withCredentials: true,
  headers: {
    'Access-Control-Allow-Origin': 'http://localhost:3000/',
    'Content-Type': 'application/json'
  }
});

Proxy

app.use(
  '/api',
  proxy('https://localhost:44364/', {
    proxyReqOptDecorator(opts) {
      opts.rejectUnauthorized = false;
      opts.headers['x-forwarded-host'] = 'localhost:3000';
      return opts;
    },
    proxyReqPathResolver(req) {
      return `/api${req.url}`;
    }
  })
);

The response with cookie:

HTTP/1.1 200 OK
x-powered-by: ASP.NET
cache-control: no-cache
pragma: no-cache
content-type: text/plain; charset=utf-8
expires: Thu, 01 Jan 1970 00:00:00 GMT
server: Kestrel
set-cookie: .AspNetCore.Cookies=CfDJ8KvV0sFM8_FJqzJkoUey_LvYSADPHUA20Mq40db0KYSbL9Q2ZjS2JW87G8CzcTDBIpG1H6mZ_nuThzOniga7oRpguIgi3xIFCjkY5D0DXwT98ZVejY7nzLaCmV9rGLMkkqqADbr0zzwUkzXQqtWMtubY0cdHXPskTWFucMjjYk0BU4eCuWOjRzooL-QtwYtDClP720LVetm8lZGvAS6jfYpk-HWZIQiDo1ERKqhyIWKYqSFBEN0nV4ykL6KhfqEjcK8URzTEnBxdV7dCpk287smjAzTvOziRWfO6BtpxXC2tZ9NBeTLLqitn_CaAypewt9qMnjMi75zazo6yicRlTsDp-i3LT0OkD_ls1celSeG1VPlTg0OMVm0nADpZurMT9LSrijsSrcFT0wvNSTeW9vE; path=/; secure; samesite=lax; httponly
x-sourcefiles: =?UTF-8?B?QzpcVXNlcnNcTWFrYWxhXERlc2t0b3BcUm91dG9yaWFsXFJvdXRvcmlhbEFQSVxSb3V0b3JpYWxBUElcUm91dG9yaWFsQVBJXGFwaVxhY2NvdW50XGxvZ2luU3VibWl0?=
date: Sun, 26 May 2019 15:47:32 GMT
connection: close
Content-Length: 6
ETag: W/"6-+3OfqLi6+pGCkKvbVPPQANDiBD4"

Body:
Thanks @Xing Zou! Your answer was close and made me think in the right direction.
The CookiePolicyOptions were not working at all and didn't seem to override the default options.
Instead, I used

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
        .AddCookie(options =>
        {
             options.Cookie.SameSite = SameSiteMode.None;
             options.Cookie.HttpOnly = true;
             options.Cookie.SecurePolicy = CookieSecurePolicy.None;
        });

in ConfigureServices and

 app.UseAuthentication();

in Configure.

The browser wasnt setting the cookie when it had the secure flag so it had to be disabled
with

options.Cookie.SecurePolicy = CookieSecurePolicy.None;


问:
What use are EJBs
I'm currently learning Jave-EE, having plenty of C++ experience and having learned Java SE. I don't understand the purpose of Enterprise Java Beans; can someone clarify this for me. I'm not interested in legacy uses: this is in the context of EJB-3.1 and Java-EE 6.

It seems that some people use them to contain the business logic, for implementing the business layer of the conventional 3-layer architecture. That separates the domain logic from the domain objects, leading to an anemic domain model. But that goes against all my OOD instincts; I agree with Martin Fowler that it is an anti-pattern. Should I relax my objections to an anemic domain model? Or do EJBs have other uses?

答:
As indicated by several other answers, EJBs are perfect for implementing the service layer. They are a very modern, lightweight kind of bean in Java EE. Despite the name you cannot compare them with the draconian heavy weight EJB2 beasts that were in J2EE. Everyone agrees those were a disaster, but it's not 2002 anymore.

Ever since EJB3 (2006), EJB beans have been a perfectly fine technology.

They help a lot here by providing declarative transactions (every entry method automatically starts a transaction if one is not already in progress, although this can be changed if desired), pooling, security, locking, remoting and then some. See the following answers for some additional details:

Frameworks for Layering reusable Architectures

In what situations are EJBs used ? Are they required in websites/ web-application development?

EJB 3 or Hibernate 3

@EJB injection vs lookup - performance issue

Transactions have been explained here, but to add to this: it's not something that's only needed for highly complex, highly secure systems. I would go as far to state it's a basic requirement even when only dealing with databases. If I process a simple order, I want that the inventory and the order are both updated or both not at all. This is as basic as having PKs and FKs in your database to ensure integrity.

EJBs make it trivial to manage transactions. Without EJBs there's a lot of boilerplate code for starting, committing or rolling-back the tx.

One should also not underestimate the benefits of pooling and stubs that EJB provides. It means a bean can have a lot of EJBs injected, and you don't have to worry about them being instantiated each and every time such a bean is created. This would otherwise especially be troublesome when not all EJBs would be used every time.

Because of pooling however, only very lightweight stubs are injected, which are more akin to a kind of URLs that point to an actual instance. These cost next to nothing in terms of memory or cpu overhead to inject.

EJBs also feature annotations to declare them being Singletons, arrange their locking behavior (write locks/read locks), declaring one should be initiated at startup, allow them to manage a so-called extended persistence context (a persistence context not scoped to a TX), etc.

These are all concerns you don't want in your slim entities. In many architectures, a User object for instance is a simple data entity that I want to send across layers. I don't want my User instance to have a sendMsg() method and have a JMS resource as a dependency, so that message sending can suddenly be done from some client. I'm not really sure why people think this is somehow 'natural' and 'OOP'.

In the real world I also don't invoke a sendMsg operation on my friend Joe whenever I want to send him a postcard. Instead, I address a card and bring it to the postoffice or put it in a postbox.

I also don't invoke a bake() operation on a cake. Instead, I put the cake in an oven, etc.

ContentLicense: CC BY-SA 2.5

Title: What use are EJBs


问:
How to create expandable panels using swing?
I would like to create a list of expandand/collapse panels, like on this image:

I haven't found any swing component for this, so I began to create something like this.
I tried to put buttons one under the other, which fill the available width, but doesn't really works. I can only see the last added one.

```<code>    JPanel panel = new JPanel();
    panel.setLayout(new BorderLayout());

    panel.add(new JButton("Delphi Projects"), BorderLayout.NORTH);
    panel.add(new JPanel(), BorderLayout.NORTH); // hidden panel
    panel.add(new JButton("Delphi Projects | Delphi Files"), BorderLayout.NORTH);
    panel.add(new JPanel(), BorderLayout.NORTH); // hidden panel
    panel.add(new JButton("Other Files"), BorderLayout.NORTH);
    panel.add(new JPanel(), BorderLayout.NORTH); // hidden panel
    panel.add(new JButton("C++ Builder Projects | C++ Builder Files"), BorderLayout.NORTH);
    panel.add(new JPanel(), BorderLayout.NORTH); // hidden panel

    JScrollPane scroll = new JScrollPane(panel);
</code>```

答: you have to put a grid panel in your layout panel. so in the "north" part in your layout panel, just add a grip panel of one column and the number of raw you want</p>

Body:
I would like to create a list of expandand/collapse panels, like on this image:

I haven't found any swing component for this, so I began to create something like this.
I tried to put buttons one under the other, which fill the available width, but doesn't really works. I can only see the last added one.

    JPanel panel = new JPanel();
    panel.setLayout(new BorderLayout());

    panel.add(new JButton("Delphi Projects"), BorderLayout.NORTH);
    panel.add(new JPanel(), BorderLayout.NORTH); // hidden panel
    panel.add(new JButton("Delphi Projects | Delphi Files"), BorderLayout.NORTH);
    panel.add(new JPanel(), BorderLayout.NORTH); // hidden panel
    panel.add(new JButton("Other Files"), BorderLayout.NORTH);
    panel.add(new JPanel(), BorderLayout.NORTH); // hidden panel
    panel.add(new JButton("C++ Builder Projects | C++ Builder Files"), BorderLayout.NORTH);
    panel.add(new JPanel(), BorderLayout.NORTH); // hidden panel

    JScrollPane scroll = new JScrollPane(panel);


问:
Create a Private App that adds orders to your Shopify Account
When i started this day i was sure this will be a very easy task:

Create a private app for my client's Shopify Store

Create orders for him to see, process fulfil etc...

I'm using nodejs.
Assuming i have all the relevant data to create an order, how can i send an order to my client's Shopify Admin Panel?

答:
Try using Google instead of Stack Overflow...

https://help.shopify.com/en/manual/orders/create-orders


问:
SCDF. WSDL Source : Spring Cloud Task or Spring Cloud Stream or any other solution?
We have requirements for getting data from a SOAP web service, where same records are going to be exposed. Then the record is transformed and written do the DB.
We are the acitve side and at the certain intervals we are going to check if a new record has appeared.

Our main goal are:

to have a scheduler for setting intervals

to have a mechanizm to retry if something goes wrong (eg. lost connection)

to have a visual control of the process - check the places where something stuck (like dashboard in SCDF)

Since there is no sample wsdl source app, I guess the Task (or Stream ?) should be written by ourself. But what to use for repeating and scheduling...

I Need your advice in choosing the right approach.

I'm not tied to the SCDF solution if any other are more suitable.

答:
If you intend to consume directly as SOAP messages from external services, you could either build a custom Spring Cloud Stream source or a simple Spring Batch/Spring Cloud Task application. Both the options provide the resiliency patterns, including retries.

However, if the upstream data is not real-time, you would choose the Task path because the streams are long-running and they never terminate. Tasks, on the other hand, run for a finite period of time, terminate, and free-up resources. There's also the option to use the platform-specific scheduler implementation to trigger to launch the Task on a recurring window periodically.

From the SCDF dashboard, you can design/build Composed Tasks, including the state transitions and the desired downstream operation.