问:
Does this implementation of merge sort use mutual recursion?
Does this mergeSort algorithm use mutual recursion?  I realize that mergeSort calls the merge function and it calls itself (mergeSort), but since merge does not call mergeSort is it not mutual recursion and simply just recursion?

```<code>function mergeSort(arr) {
    // split array
    ...
    return merge(mergSort(firstHalf), mergeSort(secondHalf));
}

function merge (array1, array2) {
    // merge both arrays
    ...
    return singleArray;
}
</code>```

答:
Correct: this is simple recursion.  Mutual recursion is also called indirect recursion: A calls B; B calls A.

Your analysis is exactly correct: were merge to call mergeSort, then you would have mutual recursion.  In the posted code, the call to merge is a simple parent-child link on the call tree.

Body:
Does this mergeSort algorithm use mutual recursion?  I realize that mergeSort calls the merge function and it calls itself (mergeSort), but since merge does not call mergeSort is it not mutual recursion and simply just recursion?

function mergeSort(arr) {
    // split array
    ...
    return merge(mergSort(firstHalf), mergeSort(secondHalf));
}

function merge (array1, array2) {
    // merge both arrays
    ...
    return singleArray;
}


来源: stackexchange

问:
Firefox driver won't connect using Serenity
I'm trying to run a simple test with Firefox, using Serenity.

This is my pom.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>serenity.test</groupId>
    <artifactId>firefox</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <serenity.version>1.4.0</serenity.version>
        <serenity.maven.version>1.4.0</serenity.maven.version>
        <webdriver.driver>firefox</webdriver.driver>

        <surefire.rerunFailingTestsCount>0</surefire.rerunFailingTestsCount>
    </properties>

    <build>
        <plugins>
            <plugin>
                <artifactId>maven-failsafe-plugin</artifactId>
                <version>2.18</version>
                <configuration>
                    <includes>
                        <include>**/features/**/*.java</include>
                    </includes>
                    <systemProperties>
                        <webdriver.driver>${webdriver.driver}</webdriver.driver>
                        <surefire.rerunFailingTestsCount>${surefire.rerunFailingTestsCount}</surefire.rerunFailingTestsCount>
                    </systemProperties>
                </configuration>
            </plugin>
            <plugin>
                <groupId>net.serenity-bdd.maven.plugins</groupId>
                <artifactId>serenity-maven-plugin</artifactId>
                <version>${serenity.maven.version}</version>
                <dependencies>
                    <dependency>
                        <groupId>net.serenity-bdd</groupId>
                        <artifactId>serenity-core</artifactId>
                        <version>${serenity.version}</version>
                    </dependency>
                </dependencies>
                <executions>
                    <execution>
                        <id>serenity-reports</id>
                        <phase>post-integration-test</phase>
                        <goals>
                            <goal>aggregate</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.20</version>
                <configuration>
                    <testFailureIgnore>true</testFailureIgnore>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <dependencies>
        <dependency>
            <groupId>net.serenity-bdd</groupId>
            <artifactId>serenity-core</artifactId>
            <version>${serenity.version}</version>
        </dependency>
        <dependency>
            <groupId>net.serenity-bdd</groupId>
            <artifactId>serenity-screenplay</artifactId>
            <version>${serenity.version}</version>
        </dependency>
        <dependency>
            <groupId>net.serenity-bdd</groupId>
            <artifactId>serenity-screenplay-webdriver</artifactId>
            <version>${serenity.version}</version>
        </dependency>
        <dependency>
            <groupId>net.serenity-bdd</groupId>
            <artifactId>serenity-junit</artifactId>
            <version>${serenity.version}</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
            <version>1.7.18</version>
        </dependency>
        <dependency>
            <groupId>com.google.inject</groupId>
            <artifactId>guice</artifactId>
            <version>3.0</version>
        </dependency>

        <dependency>
            <groupId>org.assertj</groupId>
            <artifactId>assertj-core</artifactId>
            <version>1.7.0</version>
            <scope>test</scope>
        </dependency>

    </dependencies>

</project>
</code>```

And this is my test class:

```<code>public class FirefoxTest {

    @Managed
    WebDriver driver;

    private Actor actor;

    @Before
    public void setup(){
        actor = Actor.named("Firefox user");
        actor.can(BrowseTheWeb.with(driver));
    }

    @Test
    public void open_browser(){
        actor.attemptsTo(Open.url("www.google.com"));
    }
}
</code>```

Running "mvn verify" I get the following log:

```<code>[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building firefox 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ firefox ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 0 resource
[INFO]
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ firefox ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ firefox ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory C:\work\verso3\src\test\resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ firefox ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-surefire-plugin:2.20:test (default-test) @ firefox ---
[INFO]
[INFO] -------------------------------------------------------
[INFO]  T E S T S
[INFO] -------------------------------------------------------
[INFO] Running features.FirefoxTest
[ERROR] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.629 s <<< FAILURE! - in features.FirefoxTest
[ERROR] open_browser(features.FirefoxTest)  Time elapsed: 0.58 s  <<< ERROR!
java.lang.NullPointerException
    at features.FirefoxTest.open_browser(FirefoxTest.java:31)

[INFO]
[INFO] Results:
[INFO]
[ERROR] Errors:
[ERROR]   FirefoxTest.open_browser:31 » NullPointer
[INFO]
[ERROR] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0
[INFO]
[ERROR] There are test failures.

Please refer to C:\work\verso3\target\surefire-reports for the individual test results.
Please refer to dump files (if any exist) [date]-jvmRun[N].dump, [date].dumpstream and [date]-jvmRun[N].dumpstream.
[INFO]
[INFO] --- maven-jar-plugin:2.4:jar (default-jar) @ firefox ---
[INFO] Building jar: C:\work\verso3\target\firefox-1.0-SNAPSHOT.jar
[INFO]
[INFO] --- serenity-maven-plugin:1.4.0:aggregate (serenity-reports) @ firefox ---
[INFO] current_project.base.dir: C:\work\verso3
[INFO] Generating test results for 0 tests
[INFO] 0 requirements loaded after 27 ms
[INFO] 0 related requirements found after 27 ms
[INFO] Generating test outcome reports: false
[INFO] Starting generating reports: 38 ms
[INFO] Configured report threads: 80
[INFO] Finished generating test results for 0 tests after 316 ms
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 5.337 s
[INFO] Finished at: 2017-06-08T13:20:18+03:00
[INFO] Final Memory: 17M/274M
[INFO] ------------------------------------------------------------------------

Process finished with exit code 0
</code>```

So what's going on here? Why am I getting that null pointer exception? What am I doing wrong here?

The Firefox version I'm using is 53.0.3 (64-bit).

答: It is probably an incompatible version of Firefox or gecko. But why are you managing the WebDriver instance yourself?</p>

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to run a simple test with Firefox, using Serenity.

This is my pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>serenity.test</groupId>
    <artifactId>firefox</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <serenity.version>1.4.0</serenity.version>
        <serenity.maven.version>1.4.0</serenity.maven.version>
        <webdriver.driver>firefox</webdriver.driver>

        <surefire.rerunFailingTestsCount>0</surefire.rerunFailingTestsCount>
    </properties>

    <build>
        <plugins>
            <plugin>
                <artifactId>maven-failsafe-plugin</artifactId>
                <version>2.18</version>
                <configuration>
                    <includes>
                        <include>**/features/**/*.java</include>
                    </includes>
                    <systemProperties>
                        <webdriver.driver>${webdriver.driver}</webdriver.driver>
                        <surefire.rerunFailingTestsCount>${surefire.rerunFailingTestsCount}</surefire.rerunFailingTestsCount>
                    </systemProperties>
                </configuration>
            </plugin>
            <plugin>
                <groupId>net.serenity-bdd.maven.plugins</groupId>
                <artifactId>serenity-maven-plugin</artifactId>
                <version>${serenity.maven.version}</version>
                <dependencies>
                    <dependency>
                        <groupId>net.serenity-bdd</groupId>
                        <artifactId>serenity-core</artifactId>
                        <version>${serenity.version}</version>
                    </dependency>
                </dependencies>
                <executions>
                    <execution>
                        <id>serenity-reports</id>
                        <phase>post-integration-test</phase>
                        <goals>
                            <goal>aggregate</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.20</version>
                <configuration>
                    <testFailureIgnore>true</testFailureIgnore>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <dependencies>
        <dependency>
            <groupId>net.serenity-bdd</groupId>
            <artifactId>serenity-core</artifactId>
            <version>${serenity.version}</version>
        </dependency>
        <dependency>
            <groupId>net.serenity-bdd</groupId>
            <artifactId>serenity-screenplay</artifactId>
            <version>${serenity.version}</version>
        </dependency>
        <dependency>
            <groupId>net.serenity-bdd</groupId>
            <artifactId>serenity-screenplay-webdriver</artifactId>
            <version>${serenity.version}</version>
        </dependency>
        <dependency>
            <groupId>net.serenity-bdd</groupId>
            <artifactId>serenity-junit</artifactId>
            <version>${serenity.version}</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
            <version>1.7.18</version>
        </dependency>
        <dependency>
            <groupId>com.google.inject</groupId>
            <artifactId>guice</artifactId>
            <version>3.0</version>
        </dependency>

        <dependency>
            <groupId>org.assertj</groupId>
            <artifactId>assertj-core</artifactId>
            <version>1.7.0</version>
            <scope>test</scope>
        </dependency>

    </dependencies>

</project>

And this is my test class:

public class FirefoxTest {

    @Managed
    WebDriver driver;

    private Actor actor;

    @Before
    public void setup(){
        actor = Actor.named("Firefox user");
        actor.can(BrowseTheWeb.with(driver));
    }

    @Test
    public void open_browser(){
        actor.attemptsTo(Open.url("www.google.com"));
    }
}

Running "mvn verify" I get the following log:

[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building firefox 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ firefox ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 0 resource
[INFO]
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ firefox ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ firefox ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory C:\work\verso3\src\test\resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ firefox ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-surefire-plugin:2.20:test (default-test) @ firefox ---
[INFO]
[INFO] -------------------------------------------------------
[INFO]  T E S T S
[INFO] -------------------------------------------------------
[INFO] Running features.FirefoxTest
[ERROR] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.629 s <<< FAILURE! - in features.FirefoxTest
[ERROR] open_browser(features.FirefoxTest)  Time elapsed: 0.58 s  <<< ERROR!
java.lang.NullPointerException
    at features.FirefoxTest.open_browser(FirefoxTest.java:31)

[INFO]
[INFO] Results:
[INFO]
[ERROR] Errors:
[ERROR]   FirefoxTest.open_browser:31 » NullPointer
[INFO]
[ERROR] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0
[INFO]
[ERROR] There are test failures.

Please refer to C:\work\verso3\target\surefire-reports for the individual test results.
Please refer to dump files (if any exist) [date]-jvmRun[N].dump, [date].dumpstream and [date]-jvmRun[N].dumpstream.
[INFO]
[INFO] --- maven-jar-plugin:2.4:jar (default-jar) @ firefox ---
[INFO] Building jar: C:\work\verso3\target\firefox-1.0-SNAPSHOT.jar
[INFO]
[INFO] --- serenity-maven-plugin:1.4.0:aggregate (serenity-reports) @ firefox ---
[INFO] current_project.base.dir: C:\work\verso3
[INFO] Generating test results for 0 tests
[INFO] 0 requirements loaded after 27 ms
[INFO] 0 related requirements found after 27 ms
[INFO] Generating test outcome reports: false
[INFO] Starting generating reports: 38 ms
[INFO] Configured report threads: 80
[INFO] Finished generating test results for 0 tests after 316 ms
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 5.337 s
[INFO] Finished at: 2017-06-08T13:20:18+03:00
[INFO] Final Memory: 17M/274M
[INFO] ------------------------------------------------------------------------

Process finished with exit code 0

So what's going on here? Why am I getting that null pointer exception? What am I doing wrong here?

The Firefox version I'm using is 53.0.3 (64-bit).


问:
Recursively checking for odd or even
In this code:

```<code>def is_even(x):
  if x == 0:
    return True
  else:
    return is_odd(x-1)

def is_odd(x):
  return not is_even(x)

print(is_even(2))
print(is_odd(2))
</code>```

I keep going through this in my head and wondering how it's working.  It seems to me that eventually x in is_even(x) will return True every time.  However, when I run the code, it works perfectly fine and returns True and False appropriately.  Can someone explain how that's happening?

I understand the basic concept of recursion and fully understand how the famous factorial example works.  However, this one is hard for me to wrap my head around.

Feeling inept right now...

答: I think that all the other answers are great but potentially the easiest way to understand the problem is how many times the answer will get "not"ed. Every time it passes through the is_odd function a not will be added on to the final answer. True will always be returned but for even numbers, there will always be an even number of nots which cancel each other out, but for odd numbers they will always have an odd number of nots and therefore return false.</p>

Title: Recursively checking for odd or even

Body:
In this code:

def is_even(x):
  if x == 0:
    return True
  else:
    return is_odd(x-1)

def is_odd(x):
  return not is_even(x)

print(is_even(2))
print(is_odd(2))

I keep going through this in my head and wondering how it's working.  It seems to me that eventually x in is_even(x) will return True every time.  However, when I run the code, it works perfectly fine and returns True and False appropriately.  Can someone explain how that's happening?

I understand the basic concept of recursion and fully understand how the famous factorial example works.  However, this one is hard for me to wrap my head around.

Feeling inept right now...


问:
Showing a Modal view
In my application, I need to show two Modal view one after the other. Tap on one screen will show a Modal and then a button on this Modal view will show another Modal.

Both my Modal view also contains a top bar with two buttons.

What is the best way to showing these Modal views. Should I use Navigation controller to control these Modal views or a simple view controller?

答:
I'd just have them set up using a view controller.  Just do this to present the view when it's needed, and just implement a "Done" or "Save" UIBarButton depending on what you need it for.</p>

```<code>YourViewController *yourView = [[YourViewController alloc] init];
yourView.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
[self presentModalViewController:yourView animated:YES];
</code>```

ContentLicense: CC BY-SA 2.5

Title: Showing a Modal view

Body:
I'd just have them set up using a view controller.  Just do this to present the view when it's needed, and just implement a "Done" or "Save" UIBarButton depending on what you need it for.

YourViewController *yourView = [[YourViewController alloc] init];
yourView.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
[self presentModalViewController:yourView animated:YES];


问:
How to change style or add CSS in $mdDialog in AngularJs?
I have used the below code for showing a dialog, but I want to change the default style of the dialog.

Here's my code:

$scope.LocationRejectModal = function (msg) {
  var PersonName= msg.from.local;
  var confirm = $mdDialog.confirm()
    .title('Location')
    .textContent(PersonName+' has Rejected Location sharing Request.')
    .targetEvent(event)
    .ok('Ok')
  $mdDialog.show(confirm).then(function() {
      //some code
  }, function() {
      //some code
    });
  };
```

How can this be done?

答:
I had a similar situation where I wanted to add custom button styles instead of the default because it was hard to see.

this.$rootScope.isErrorDialogOpen = true;
var confirm = this.$mdDialog.confirm({
  onComplete: function afterShowAnimation() {
    var $dialog = angular.element(document.querySelector('md-dialog'));
    var $actionsSection = $dialog.find('md-dialog-actions');
    var $cancelButton = $actionsSection.children()[0];
    var $confirmButton = $actionsSection.children()[1];
    angular.element($confirmButton).addClass('md-raised md-accent');
    angular.element($cancelButton).addClass('md-raised');
  }
})
  .title('Session Timeout')
  .textContent('Would you like to stay logged into the application?')
  .ok('Yes')
  .cancel('No');
this.$mdDialog.show(confirm).then(() => {
  // Your code goes here
}, () => {
  // Your code goes here
}
```

ContentLicense: CC BY-SA 4.0

Body:
I have used the below code for showing a dialog, but I want to change the default style of the dialog.

Here's my code:

$scope.LocationRejectModal = function (msg) {
  var PersonName= msg.from.local;
  var confirm = $mdDialog.confirm()
    .title('Location')
    .textContent(PersonName+' has Rejected Location sharing Request.')
    .targetEvent(event)
    .ok('Ok')
  $mdDialog.show(confirm).then(function() {
      //some code
  }, function() {
      //some code
    });
  };

How can this be done?


问:
How to read an input value from atmega32 pin?
I'm trying to read a value from an avr pin but it doesn't work.

I'm trying to read a value that is coming from a push button and this button is connected to 5V DC cell.

When I press the button the 5V should go to the atmega32 and reads it as 1, then the if statement becomes true and the led goes on.

However, when the value becomes true the led will turn on but its not.

bit 1 is the button
bit 0 is the led

Code

```<code>#define DDRA (*((volatile unsigned char *)0x3A))
#define PORTA (*((volatile unsigned char *)0x3B))
#define PINA (*((volatile unsigned char *)0x39))

int main(void) {
   DDRA |= 0b00000001;         // pin 0 output

    while (1) {
        if ((PINA&0b00000010) == 1) {  // button pressed
            PORTA |= 0b00000001;   // turn led on
        }
    }
}
</code>```

答:
Just to make sure, your button has to have a pull-up / pull-down resistor connected to ground. Without it, you can't correctly read whether the pin is on or off.

https://learn.sparkfun.com/tutorials/pull-up-resistors

Body:
I'm trying to read a value from an avr pin but it doesn't work.

I'm trying to read a value that is coming from a push button and this button is connected to 5V DC cell.

When I press the button the 5V should go to the atmega32 and reads it as 1, then the if statement becomes true and the led goes on.

However, when the value becomes true the led will turn on but its not.

bit 1 is the button
bit 0 is the led

Code

#define DDRA (*((volatile unsigned char *)0x3A))
#define PORTA (*((volatile unsigned char *)0x3B))
#define PINA (*((volatile unsigned char *)0x39))

int main(void) {
   DDRA |= 0b00000001;         // pin 0 output

    while (1) {
        if ((PINA&0b00000010) == 1) {  // button pressed
            PORTA |= 0b00000001;   // turn led on
        }
    }
}


问:
React-native and react dependency conflicts
Currently I'm using React Native 0.42.0 with React 15.4.2, and there is a bugfix: Fix crash if native code tries to update the size of a modal view after JS has removed it in the 0.44.0 which is the latest release of the React Native. I wanted to update for the latest version but it's require 16.0.0-alpha.6 React version. There is problems, because the other npm packages don't support the alpha version of the React and they require the 15.x.x version.

What is the proper solution for this problem?

There is my related part of the package.json:

```<code>  "dependencies": {
    "axios": "^0.16.1",
    "lodash": "^4.17.4",
    "querystring": "^0.2.0",
    "react": "16.0.0-alpha.6",
    "react-addons-pure-render-mixin": "^15.4.2",
    "react-native": "0.44.0",
    "react-native-cookies": "^3.1.0",
    "react-native-device-info": "^0.10.2",
    "react-native-lazyload": "^1.1.0",
    "react-native-router-flux": "^3.38.0",
    "react-native-swiper": "^1.5.4",
    "react-native-vector-icons": "^4.0.0",
    "react-navigation": "^1.0.0-beta.7",
    "react-redux": "^5.0.3",
    "redux": "^3.6.0",
    "redux-thunk": "^2.2.0"
  },
</code>```

答:
I don't know if this can be taken as a response but in my case having the same problem i only updated into the latest version possible without depending on the alpha version of react (0.42), and we'll need to wait until the next React.js versions comes out.

The official explain that i heard was that react-native take some React Fiber considerations that are not included on React.js for now

Body:
Currently I'm using React Native 0.42.0 with React 15.4.2, and there is a bugfix: Fix crash if native code tries to update the size of a modal view after JS has removed it in the 0.44.0 which is the latest release of the React Native. I wanted to update for the latest version but it's require 16.0.0-alpha.6 React version. There is problems, because the other npm packages don't support the alpha version of the React and they require the 15.x.x version.

What is the proper solution for this problem?

There is my related part of the package.json:

  "dependencies": {
    "axios": "^0.16.1",
    "lodash": "^4.17.4",
    "querystring": "^0.2.0",
    "react": "16.0.0-alpha.6",
    "react-addons-pure-render-mixin": "^15.4.2",
    "react-native": "0.44.0",
    "react-native-cookies": "^3.1.0",
    "react-native-device-info": "^0.10.2",
    "react-native-lazyload": "^1.1.0",
    "react-native-router-flux": "^3.38.0",
    "react-native-swiper": "^1.5.4",
    "react-native-vector-icons": "^4.0.0",
    "react-navigation": "^1.0.0-beta.7",
    "react-redux": "^5.0.3",
    "redux": "^3.6.0",
    "redux-thunk": "^2.2.0"
  },


问:
Javascript ES6 onclick load module...can it be done?
I have created a few es6 modules:

```<code>module1.js
module2.js
</code>```

These modules will load content into a div with id="root"

```<code><div id="root"></div>

document.getElementById('root').innerHTML = (results);
</code>```

My question is ...

Is is possible to load modules from as onclick event for example:

```<code><li onclick="loadModule('module1')">Load Module 1</li> //load module1.js
<li onclick="loadModule('module2')">Load Module 2</li> //load module2.js
</code>```

If so, how can I do this?

答:
In the following case I am using libraries that you can get through http and then append the html with a script that points to that library you asked to be required. If the module is local, then you just use the filepath of those modules. I assume that those modules are transpiled into some sort of built folder along with the html, so you can access if from there.

function loadModule(module) {
  var script = {
    'jquery': 'https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js',
    'knockout': 'https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js'
  }[module];
  document.body.innerHTML += `<script src=${script} type='text/javascript'><\/script>`;
  console.log(module + ' module loaded');
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button onclick="loadModule('jquery')">Load jquery </button>
<button onclick="loadModule('knockout')">Load knockout.js </button></code>```

Body:
I have created a few es6 modules:

module1.js
module2.js

These modules will load content into a div with id="root"

document.getElementById('root').innerHTML = (results);

My question is ...

Is is possible to load modules from as onclick event for example:

Load Module 1
 //load module1.js

Load Module 2
 //load module2.js

If so, how can I do this?

Body:
In the following case I am using libraries that you can get through http and then append the html with a script that points to that library you asked to be required. If the module is local, then you just use the filepath of those modules. I assume that those modules are transpiled into some sort of built folder along with the html, so you can access if from there.

function loadModule(module) {
  var script = {
    'jquery': 'https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js',
    'knockout': 'https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js'
  }[module];
  document.body.innerHTML += `<script src=${script} type='text/javascript'><\/script>`;
  console.log(module + ' module loaded');
}

<button onclick="loadModule('jquery')">Load jquery </button>
<button onclick="loadModule('knockout')">Load knockout.js </button>


问:
Excel: Protect password not compatible with VBA password?
I know of the 2 possible ways to password-protect sheets in Excel -

Manual Password protect

Password protect using VBA

This is where I'm stumped. I have password-protected a sheet using VBA and then tried to unprotect it manually with the same password used in VBA. But Excel throws an error saying that the password provided is incorrect. I tried the opposite as well - Protected the file manually and then tried to unprotect using VBA providing the right password in the code; same error. Any ideas why this is happening?

答:
After some analysis, I figured out what the issue is in my code -

```<code>ActiveWorkbook.Protect Password = "xyz", Structure:=True, Windows:=False
</code>```

The password option was assigned with an "=" sign instead of a ":=". This code still protects the sheet but with an empty password. When I use a similar Unprotect code like,

```<code>ActiveWorkbook.Unprotect Password = "xyz"
</code>```

the unprotect code is passing on an empty password. Hence, if I try a manual password of "xyz" it throws an error.

The correct code that solves the issue is

```<code>ActiveWorkbook.Protect Password:= "xyz", Structure:=True, Windows:=False
ActiveWorkbook.Unprotect Password:= "xyz
</code>```

Body:
After some analysis, I figured out what the issue is in my code -

ActiveWorkbook.Protect Password = "xyz", Structure:=True, Windows:=False

The password option was assigned with an "=" sign instead of a ":=". This code still protects the sheet but with an empty password. When I use a similar Unprotect code like,

ActiveWorkbook.Unprotect Password = "xyz"

the unprotect code is passing on an empty password. Hence, if I try a manual password of "xyz" it throws an error.

The correct code that solves the issue is

ActiveWorkbook.Protect Password:= "xyz", Structure:=True, Windows:=False
ActiveWorkbook.Unprotect Password:= "xyz


问:
Best way to output ajax data from a Magento Admin Extension
I'm writing a Magento Admin extension that has some ajax callbacks in it.  Up until now I've been echoing the json I'm feeding back through the ajax call with a simple echo statement in the controller.  It "works" but I get a bunch of errors like this in my log file:

2010-12-14T15:37:05+00:00 DEBUG (7): HEADERS ALREADY SENT: ```[0] /home/simplifiedsafety/www/store/app/code/core/Mage/Core/Controller/Response/Http.php:44
[1] /home/simplifiedsafety/www/store/lib/Zend/Controller/Response/Abstract.php:727
[2] /home/simplifiedsafety/www/store/app/code/core/Mage/Core/Controller/Response/Http.php:75
[3] /home/simplifiedsafety/www/store/app/code/core/Mage/Core/Controller/Varien/Front.php:188
[4] /home/simplifiedsafety/www/store/app/code/core/Mage/Core/Model/App.php:304
[5] /home/simplifiedsafety/www/store/app/Mage.php:599
[6] /home/simplifiedsafety/www/store/index.php:104
```

I think to avoid this I need to push it out through some sort of block.  Can someone give me a little guidance on this?

Body:
I'm writing a Magento Admin extension that has some ajax callbacks in it.  Up until now I've been echoing the json I'm feeding back through the ajax call with a simple echo statement in the controller.  It "works" but I get a bunch of errors like this in my log file:

2010-12-14T15:37:05+00:00 DEBUG (7): HEADERS ALREADY SENT:
[0] /home/simplifiedsafety/www/store/app/code/core/Mage/Core/Controller/Response/Http.php:44
[1] /home/simplifiedsafety/www/store/lib/Zend/Controller/Response/Abstract.php:727
[2] /home/simplifiedsafety/www/store/app/code/core/Mage/Core/Controller/Response/Http.php:75
[3] /home/simplifiedsafety/www/store/app/code/core/Mage/Core/Controller/Varien/Front.php:188
[4] /home/simplifiedsafety/www/store/app/code/core/Mage/Core/Model/App.php:304
[5] /home/simplifiedsafety/www/store/app/Mage.php:599
[6] /home/simplifiedsafety/www/store/index.php:104

I think to avoid this I need to push it out through some sort of block.  Can someone give me a little guidance on this?

Body: $this->getResponse()->setBody($output)


问:
Insert elements in numpy array given X and Y index
I have the following code:

```
import numpy as np

b = np.full([20, 20], 0)

x = [3, 6, 3, 6]
y = [18, 18, 19, 19]

print(b)
for _x, _y in zip(y, x):
    b[_x][_y] = 1
    pass

print('\n')

print(b)```

However, I don't understand some of the things in there, such as the x and y coordinates. Why are they flipped?
Is there any cleaner way to implement this using a built-in numpy function?

Body:
I have the following code:

import numpy as np

b = np.full([20, 20], 0)

x = [3, 6, 3, 6]
y = [18, 18, 19, 19]

print(b)
for _x, _y in zip(y, x):
    b[_x][_y] = 1
    pass

print('\n')

print(b)

However, I don't understand some of the things in there, such as the x and y coordinates. Why are they flipped?
Is there any cleaner way to implement this using a built-in numpy function?

Body:
for _x, _y in zip(y, x):

is borked, zip 'em in the order you intend to use them

for _x, _y in zip(x,y):

then

print(*b, sep='\n')
[ 0.  0.  0. ...,  0.  0.  0.]
[ 0.  0.  0. ...,  0.  0.  0.]
[ 0.  0.  0. ...,  0.  0.  0.]
[ 0.  0.  0. ...,  0.  1.  1.]
[ 0.  0.  0. ...,  0.  0.  0.]
[ 0.  0.  0. ...,  0.  0.  0.]
[ 0.  0.  0. ...,  0.  1.  1.]
[ 0.  0.  0. ...,  0.  0.  0.]


问:
Silently POST a URL in PHP?
I need to trigger an alarm using a specific URL.
Alarm script should start/stop/start/off the alarm for 5 seconds. I don't want users to be redirected from the page.

This script should start/stop the alarm (using those special local host URL strings). Would this work?

?php

/* start alarm for 5 seconds */
echo file_get_contents('http://localhost/cgi-bin/controller.cgi?target=2&control=1');

/* note to user that alarm is on */
echo 'Alarm started...' "
";
echo date('h:i:s') . "
";

/* alarm off for 5 seconds */
sleep(5);
echo file_get_contents('http://localhost/cgi-bin/controller.cgi?target=2&control=0');

/* alarm on for 5 seconds */
echo date('h:i:s');
echo file_get_contents('http://localhost/cgi-bin/controller.cgi?target=2&control=1');

/* alarm off for 5 seconds */

echo file_get_contents('http://localhost/cgi-bin/controller.cgi?target=2&control=0');

?>
```

<p>EDIT:</p>

<p>Sorry, I forgot to add that echo file_get_contents should load this whole XML thing which I don't want to printed on the page. </p>

<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>URL</key>
    <string>http://localhost/cgi-bin/controller.cgi?target=2&control=1</string>
</dict>
</plist>
</code>```

答: If I'm understanding correctly, you may want to look at clientside ajax post methods (the clientside would be a small amount of Js that would call out to the server side without refreshing the page)</p>

Title: Silently POST a URL in PHP?

Body:
I need to trigger an alarm using a specific URL.
Alarm script should start/stop/start/off the alarm for 5 seconds. I don't want users to be redirected from the page.

This script should start/stop the alarm (using those special local host URL strings). Would this work?

?php

/* start alarm for 5 seconds */
echo file_get_contents('http://localhost/cgi-bin/controller.cgi?target=2&control=1');

/* note to user that alarm is on */
echo 'Alarm started...' "
";
echo date('h:i:s') . "
";

/* alarm off for 5 seconds */
sleep(5);
echo file_get_contents('http://localhost/cgi-bin/controller.cgi?target=2&control=0');

/* alarm on for 5 seconds */
echo date('h:i:s');
echo file_get_contents('http://localhost/cgi-bin/controller.cgi?target=2&control=1');

/* alarm off for 5 seconds */

echo file_get_contents('http://localhost/cgi-bin/controller.cgi?target=2&control=0');

?>

EDIT:

Sorry, I forgot to add that echo file_get_contents should load this whole XML thing which I don't want to printed on the page.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>URL</key>
    <string>http://localhost/cgi-bin/controller.cgi?target=2&control=1</string>
</dict>
</plist>


问:
perl goto&Name vs return
I came accross a piece of perl code recently. The code looks like below

```<code>package CODE;

sub _doJob
{
    $result = JOB->new(@_)->doIt();
    return $result;
}

sub _doFirstJob
{
    unshift @_, '1';
    goto &_doJob;
}

sub _doSecondJob
{
    unshift @_, '2';
    goto &_doJob;
}

sub _doThirdJob
{
    unshift @_, '3';
    goto &_doJob;
}
</code>```

and then calling the functions like

```<code>$result = CODE::_doFirstJob($a);
$result = CODE::_doSecondJob($a);
$result = CODE::_doThirdJob($a);
</code>```

Question is what is the significance of goto here? If I write similar function calls with return, like below, what would be the problem?

```<code>package CODE;

sub _doJob
{
    $result = JOB->new(@_)->doIt();
    return $result;
}

sub _doFirstJob
{
    unshift @_, '1';
    return &_doJob(@_);
}

sub _doSecondJob
{
    unshift @_, '2';
    return &_doJob(@_)
}

sub _doThirdJob
{
    unshift @_, '3';
    return &_doJob(@_)
}
</code>```

I could still call these functions in same way

```<code>$result = CODE::_doFirstJob($a);
$result = CODE::_doSecondJob($a);
$result = CODE::_doThirdJob($a);
</code>```

I know that goto &NAME actually makes perl to exit from current function and replace it with the new function in call stack. But how am I being benefited by this here?

答: Unfortunately the tail call myth is only a myth. A goto still creates a new stack frame and is not faster than recursion. I experimented with eliminating this cost with cperl, doing real tail recursion, overwriting the stack values, but I don't think I've properly solved it yet. The whole ABI is highly deoptimized. And it would only work with cperl signatures as only those use the stack ABI as XS. With pure perl5 you are in the same mess as python.</p>

Title: perl goto&Name vs return

Body:
I came accross a piece of perl code recently. The code looks like below

package CODE;

sub _doJob
{
    $result = JOB->new(@_)->doIt();
    return $result;
}

sub _doFirstJob
{
    unshift @_, '1';
    goto &_doJob;
}

sub _doSecondJob
{
    unshift @_, '2';
    goto &_doJob;
}

sub _doThirdJob
{
    unshift @_, '3';
    goto &_doJob;
}

and then calling the functions like

$result = CODE::_doFirstJob($a);
$result = CODE::_doSecondJob($a);
$result = CODE::_doThirdJob($a);

Question is what is the significance of goto here? If I write similar function calls with return, like below, what would be the problem?

package CODE;

sub _doJob
{
    $result = JOB->new(@_)->doIt();
    return $result;
}

sub _doFirstJob
{
    unshift @_, '1';
    return &_doJob(@_);
}

sub _doSecondJob
{
    unshift @_, '2';
    return &_doJob(@_)
}

sub _doThirdJob
{
    unshift @_, '3';
    return &_doJob(@_)
}

I could still call these functions in same way

$result = CODE::_doFirstJob($a);
$result = CODE::_doSecondJob($a);
$result = CODE::_doThirdJob($a);

I know that goto &NAME actually makes perl to exit from current function and replace it with the new function in call stack. But how am I being benefited by this here?


问:
how to call a method from a menu of methods?
I am learning about methods and am trying to make a menu of methods that do simple conversions. I don't know how to call a method from the menu and make it do the function. I would like to know how to call a method AND make it run with inputs not using the scanner class except in main.

```<code>public static void main(String[] args) {
    displayMenu();
    Scanner keyboard = new Scanner(System.in);
    int selection = keyboard.nextInt();
    switch(selection) {
    case 1:
        FahrToCel();
        break;
    case 2:
        CelToFahr();
        break;
    case 3:
        LbToKilo();
        break;
    case 4:
        KiloToLb();
        break;
   }

}

public static void displayMenu() {
    System.out.println("Enter 1 for Fahrenheit to Celsius" );
    System.out.println("Enter 2 for Celsius to Fahrenheit");
    System.out.println("Enter 3 for lb to kg");
    System.out.println("Enter 4 for kg to lb");
    return;

public static double FahrToCel() {

    double Fahrenheit = ???;
    double Celsius = 5 * (Fahrenheit - 32) / 9;

    return Celsius;

}

public static double CelToFahr() {
    double Celsius = ???;
    double Fahrenheit = (9 * Celsius / 5) + 32;
    return Fahrenheit;

}

public static double LbtoKilo() {
    double pounds = ???;
    double factor = 0.454;
    double Kilogram = pounds * factor;

    return Kilogram;

}
public static double KiloToLb() {
    double kilograms = ???;
    double factor = 0.454;
    double Pound = kilograms / factor;
    return Pound;

}
</code>```

the ??? are the variables that i want to get user input, but idk how to do that without making a new Scanner in each method.

idk how to get the inputs in the methods either.

When I run the code, I get the displayMenu options and i can input 1,2,3,4 but then nothing happens after that

答:
I just went and made the menu a bit purdy :)</p>

```<code>package com.boeing.tbng.ddm.ms;

import java.util.Scanner;

public class StackOverflow {

    private static final int FACTOR_FARENHEIT = 32;
    private static final double FACTOR = 0.454;

    public static void main(String[] args) {
        StackOverflow so = new StackOverflow();
        int selection;

        Scanner keyboard = new Scanner(System.in);

        do{
            /* request user input */
            so.displayMenu();

            /* read input */
            selection = keyboard.nextInt();

            System.out.print(selection + ") ");
            /* choose path based on selection */
            switch(selection) {
                case 1:
                    so.FahrToCel(keyboard);
                    break;
                case 2:
                    so.CelToFahr(keyboard);
                    break;
                case 3:
                    so.LbToKilo(keyboard);
                    break;
                case 4:
                    so.KiloToLb(keyboard);
                    break;
                case 9:
                    System.out.println("Quitting Program...");
                    break;
            }
        }while (selection != 9);

    }

    private void displayMenu() {
        System.out.println("");
        System.out.println("===================");
        System.out.println("Select an Option:");
        System.out.println("1) for Fahrenheit to Celsius");
        System.out.println("2) for Celsius to Fahrenheit");
        System.out.println("3) for lb to kg");
        System.out.println("4) for kg to lb");
        System.out.println("9) to quit");
        System.out.println("===================");
    }

    private double askForNextInput(Scanner keyboard, String unit){
        System.out.println("Enter how many " + unit + " you want to convert");
        double userInput = keyboard.nextDouble();
        return userInput;
    }

    private double FahrToCel(Scanner keyboard) {
        double Fahrenheit = askForNextInput(keyboard, "Farenheit");
        double Celsius = 5 * (Fahrenheit - FACTOR_FARENHEIT) / 9;

        System.out.println( "In Celcius, that's: " + Celsius);
        return Celsius;
    }

    private double CelToFahr(Scanner keyboard) {
        double Celsius = askForNextInput(keyboard, "Celsius");
        double Fahrenheit = (9 * Celsius / 5) + FACTOR_FARENHEIT;
        System.out.println( "In Fahrenheit, that's: " + Fahrenheit);
        return Fahrenheit;

    }

    private double LbToKilo(Scanner keyboard) {
        double pounds = askForNextInput(keyboard, "Pounds");
        double Kilogram = pounds * FACTOR;

        System.out.println( "In Kilograms, that's: " + Kilogram);
        return Kilogram;

    }

    private double KiloToLb(Scanner keyboard) {
        double kilograms = askForNextInput(keyboard, "Kilograms");
        double Pound = kilograms / FACTOR;

        System.out.println( "In Pounds, that's: " + Pound);
        return Pound;
    }
}
</code>```

Body:
I am learning about methods and am trying to make a menu of methods that do simple conversions. I don't know how to call a method from the menu and make it do the function. I would like to know how to call a method AND make it run with inputs not using the scanner class except in main.

public static void main(String[] args) {
    displayMenu();
    Scanner keyboard = new Scanner(System.in);
    int selection = keyboard.nextInt();
    switch(selection) {
    case 1:
        FahrToCel();
        break;
    case 2:
        CelToFahr();
        break;
    case 3:
        LbToKilo();
        break;
    case 4:
        KiloToLb();
        break;
   }

}

public static void displayMenu() {
    System.out.println("Enter 1 for Fahrenheit to Celsius" );
    System.out.println("Enter 2 for Celsius to Fahrenheit");
    System.out.println("Enter 3 for lb to kg");
    System.out.println("Enter 4 for kg to lb");
    return;

public static double FahrToCel() {

    double Fahrenheit = ???;
    double Celsius = 5 * (Fahrenheit - 32) / 9;

    return Celsius;

}

public static double CelToFahr() {
    double Celsius = ???;
    double Fahrenheit = (9 * Celsius / 5) + 32;
    return Fahrenheit;

}

public static double LbtoKilo() {
    double pounds = ???;
    double factor = 0.454;
    double Kilogram = pounds * factor;

    return Kilogram;

}
public static double KiloToLb() {
    double kilograms = ???;
    double factor = 0.454;
    double Pound = kilograms / factor;
    return Pound;

}

the ??? are the variables that i want to get user input, but idk how to do that without making a new Scanner in each method.

idk how to get the inputs in the methods either.

When I run the code, I get the displayMenu options and i can input 1,2,3,4 but then nothing happens after that

Body:
I just went and made the menu a bit purdy :)

package com.boeing.tbng.ddm.ms;

import java.util.Scanner;

public class StackOverflow {

    private static final int FACTOR_FARENHEIT = 32;
    private static final double FACTOR = 0.454;

    public static void main(String[] args) {
        StackOverflow so = new StackOverflow();
        int selection;

        Scanner keyboard = new Scanner(System.in);

        do{
            /* request user input */
            so.displayMenu();

            /* read input */
            selection = keyboard.nextInt();

            System.out.print(selection + ") ");
            /* choose path based on selection */
            switch(selection) {
                case 1:
                    so.FahrToCel(keyboard);
                    break;
                case 2:
                    so.CelToFahr(keyboard);
                    break;
                case 3:
                    so.LbToKilo(keyboard);
                    break;
                case 4:
                    so.KiloToLb(keyboard);
                    break;
                case 9:
                    System.out.println("Quitting Program...");
                    break;
            }
        }while (selection != 9);

    }

    private void displayMenu() {
        System.out.println("");
        System.out.println("===================");
        System.out.println("Select an Option:");
        System.out.println("1) for Fahrenheit to Celsius");
        System.out.println("2) for Celsius to Fahrenheit");
        System.out.println("3) for lb to kg");
        System.out.println("4) for kg to lb");
        System.out.println("9) to quit");
        System.out.println("===================");
    }

    private double askForNextInput(Scanner keyboard, String unit){
        System.out.println("Enter how many " + unit + " you want to convert");
        double userInput = keyboard.nextDouble();
        return userInput;
    }

    private double FahrToCel(Scanner keyboard) {
        double Fahrenheit = askForNextInput(keyboard, "Farenheit");
        double Celsius = 5 * (Fahrenheit - FACTOR_FARENHEIT) / 9;

        System.out.println( "In Celcius, that's: " + Celsius);
        return Celsius;
    }

    private double CelToFahr(Scanner keyboard) {
        double Celsius = askForNextInput(keyboard, "Celsius");
        double Fahrenheit = (9 * Celsius / 5) + FACTOR_FARENHEIT;
        System.out.println( "In Fahrenheit, that's: " + Fahrenheit);
        return Fahrenheit;

    }

    private double LbToKilo(Scanner keyboard) {
        double pounds = askForNextInput(keyboard, "Pounds");
        double Kilogram = pounds * FACTOR;

        System.out.println( "In Kilograms, that's: " + Kilogram);
        return Kilogram;

    }

    private double KiloToLb(Scanner keyboard) {
        double kilograms = askForNextInput(keyboard, "Kilograms");
        double Pound = kilograms / FACTOR;

        System.out.println( "In Pounds, that's: " + Pound);
        return Pound;
    }
}


问:
How to know if I am using Rails 2.3 in production?
I have a client that is running a Linux VPS with a Ruby on Rails site. There is a way to prove that the site is not running rails 2.3.14 without enter to the VPS? Something like to see if have turbolinks for example. Because turbolinks not exist in rails 2.3.14. </p>

答:
The way you determine the version of a Rails application is by examining the sourcecode. There is no other way that you can depend on.

Also, if the VPS contains the only copy of the source you have larger problems to consider than what version of Rails it is.


问:
Create SDDL failed, Error: 1332
I'm trying to use IIS Express with Visual Studio 2010 SP1.

I'm following this tutorial. When I run this command.

```<code>netsh http add urlacl url=https://Melnibone:443/ user=everyone
</code>```

I get this message:

```<code>Create SDDL failed, Error: 1332
</code>```

What's happening?

答: I recently ran into this issue.  The solution for me was to run the command prompt as an administrator.</p>

Title: Create SDDL failed, Error: 1332

Body:
I'm trying to use IIS Express with Visual Studio 2010 SP1.

I'm following this tutorial. When I run this command.

netsh http add urlacl url=https://Melnibone:443/ user=everyone

I get this message:

Create SDDL failed, Error: 1332

What's happening?


问:
Play JSON serialize/deserialize
I'm trying to go create some formats for this:

```<code>  case class Work[T](todo: Seq[T], failed: Seq[T], success: Seq[T])

  object Work {
    implicit def format[T](implicit r: Reads[T], w: Writes[T]): Format[Work[T]] = Json.format[Work[T]]
  }

  object InternalMessage {
    implicit def format[D, R](implicit
                              rD: Reads[D],
                              wD: Writes[D],
                              rR: Reads[R],
                              wR: Writes[R]
                             ): Format[InternalMessage[D, R]] = Json.format[InternalMessage[D, R]]

  }

  case class InternalMessage[D, R](
                                    download: List[Work[D]],
                                    refine: List[Work[R]],
                                    numberOfTries: Int
                                  )
</code>```

This doesn't work and I don't understand why. The error is

```<code>[error] /home/oleber/develop/data-platform/modules/importerTemplate/src/main/scala/template/TemplateModel.scala:46: No apply function found matching unapply parameters
[error]     implicit def format[T](implicit r: Reads[T], w: Writes[T]): Format[Work[T]] = Json.format[Work[T]]
[error]                                                                                ^
[error] /home/oleber/develop/data-platform/modules/importerTemplate/src/main/scala/template/TemplateModel.scala:55: No apply function found matching unapply parameters
[error]                              ): Format[InternalMessage[D, R]] = Json.format[InternalMessage[D, R]]
</code>```

Thanks for any help

答:
AFAIU you can't generate JSON Format for such data types using Play 2.5 macros. What is limiting you is that you use Seq[T] i.e. you want JSON serialization for a generic class that has fields that use some complex type built from that generic type rather than just raw generic T. Relevant code seems to be in the JsMacroImpl lines 135-141. In those lines inside paramsMatch inner method of maybeApply calculation the macro checks if there are an apply and unapply methods with matching (complement) signatures:

```<code>val maybeApply = applies.collectFirst {
  case (apply: MethodSymbol) if hasVarArgs && {
    // Option[List[c.universe.Type]]
    val someApplyTypes = apply.paramLists.headOption.map(_.map(_.asTerm.typeSignature))
    val someInitApply = someApplyTypes.map(_.init)
    val someApplyLast = someApplyTypes.map(_.last)
    val someInitUnapply = unapplyReturnTypes.map(_.init)
    val someUnapplyLast = unapplyReturnTypes.map(_.last)
    val initsMatch = someInitApply == someInitUnapply
    val lastMatch = (for {
      lastApply <- someApplyLast
      lastUnapply <- someUnapplyLast
    } yield lastApply <:< lastUnapply).getOrElse(false)
    initsMatch && lastMatch
  } => apply

  case (apply: MethodSymbol) if {
    val applyParams = apply.paramLists.headOption.
      toList.flatten.map(_.typeSignature)
    val unapplyParams = unapplyReturnTypes.toList.flatten

    def paramsMatch = (applyParams, unapplyParams).zipped.forall {
      case (TypeRef(NoPrefix, applyParam, _),
        TypeRef(NoPrefix, unapplyParam, _)) => // for generic parameter
        applyParam.fullName == unapplyParam.fullName

      case (applyParam, unapplyParam) => applyParam =:= unapplyParam
    }

    (applyParams.size == unapplyParams.size && paramsMatch)
  } => apply
}
</code>```

As you can see in the relevant (non-hasVarArgs branch), this code only handles two cases: when the types in apply and unapply match exactly or when the same raw generic type is used. Your case of Seq[T] (as well as other complex generic types) is not handled here and the error you get is generated just a few lines down when maybeApply is empty:

```<code>val (tparams, params) = maybeApply match {
  case Some(apply) => {
    apply.typeParams -> apply.paramLists.head
    // assume there is a single parameter group
  }

  case None => c.abort(c.enclosingPosition, "No apply function found matching unapply parameters")
}
</code>```

In Play-JSON 2.6 this code was significantly re-worked and now it seems to support your case as well (see conforms inner method).

If upgrading to (not released yet) Play-JSON 2.6 is not acceptable, you can create Formats object(s) yourself using JSON Reads/Writes/Format Combinators doc. Something like this should work for you:

```<code>  implicit def format[T](implicit r: Reads[T], w: Writes[T]): Format[Work[T]] = {
    val workReads = (
      (JsPath \ "todo").read[Seq[T]] and
        (JsPath \ "failed").read[Seq[T]] and
        (JsPath \ "success").read[Seq[T]]
      ) (Work.apply[T] _)

    val workWrites = (
      (JsPath \ "todo").write[Seq[T]] and
        (JsPath \ "failed").write[Seq[T]] and
        (JsPath \ "success").write[Seq[T]]
      ) (unlift(Work.unapply[T]))

    new Format[Work[T]] {
      override def reads(json: JsValue): JsResult[Work[T]] = workReads.reads(json)

      override def writes(o: Work[T]): JsValue = workWrites.writes(o)
    }
  }
</code>```

Title: Play JSON serialize/deserialize

Body:
I'm trying to go create some formats for this:

  case class Work[T](todo: Seq[T], failed: Seq[T], success: Seq[T])

  object Work {
    implicit def format[T](implicit r: Reads[T], w: Writes[T]): Format[Work[T]] = Json.format[Work[T]]
  }

  object InternalMessage {
    implicit def format[D, R](implicit
                              rD: Reads[D],
                              wD: Writes[D],
                              rR: Reads[R],
                              wR: Writes[R]
                             ): Format[InternalMessage[D, R]] = Json.format[InternalMessage[D, R]]

  }

  case class InternalMessage[D, R](
                                    download: List[Work[D]],
                                    refine: List[Work[R]],
                                    numberOfTries: Int
                                  )

This doesn't work and I don't understand why. The error is

[error] /home/oleber/develop/data-platform/modules/importerTemplate/src/main/scala/template/TemplateModel.scala:46: No apply function found matching unapply parameters
[error]     implicit def format[T](implicit r: Reads[T], w: Writes[T]): Format[Work[T]] = Json.format[Work[T]]
[error]                                                                                ^
[error] /home/oleber/develop/data-platform/modules/importerTemplate/src/main/scala/template/TemplateModel.scala:55: No apply function found matching unapply parameters
[error]                              ): Format[InternalMessage[D, R]] = Json.format[InternalMessage[D, R]]

Thanks for any help

Body:
AFAIU you can't generate JSON Format for such data types using Play 2.5 macros. What is limiting you is that you use Seq[T] i.e. you want JSON serialization for a generic class that has fields that use some complex type built from that generic type rather than just raw generic T. Relevant code seems to be in the JsMacroImpl lines 135-141. In those lines inside paramsMatch inner method of maybeApply calculation the macro checks if there are an apply and unapply methods with matching (complement) signatures:

val maybeApply = applies.collectFirst {
  case (apply: MethodSymbol) if hasVarArgs && {
    // Option[List[c.universe.Type]]
    val someApplyTypes = apply.paramLists.headOption.map(_.map(_.asTerm.typeSignature))
    val someInitApply = someApplyTypes.map(_.init)
    val someApplyLast = someApplyTypes.map(_.last)
    val someInitUnapply = unapplyReturnTypes.map(_.init)
    val someUnapplyLast = unapplyReturnTypes.map(_.last)
    val initsMatch = someInitApply == someInitUnapply
    val lastMatch = (for {
      lastApply <- someApplyLast
      lastUnapply <- someUnapplyLast
    } yield lastApply <:< lastUnapply).getOrElse(false)
    initsMatch && lastMatch
  } => apply

  case (apply: MethodSymbol) if {
    val applyParams = apply.paramLists.headOption.
      toList.flatten.map(_.typeSignature)
    val unapplyParams = unapplyReturnTypes.toList.flatten

    def paramsMatch = (applyParams, unapplyParams).zipped.forall {
      case (TypeRef(NoPrefix, applyParam, _),
        TypeRef(NoPrefix, unapplyParam, _)) => // for generic parameter
        applyParam.fullName == unapplyParam.fullName

      case (applyParam, unapplyParam) => applyParam =:= unapplyParam
    }

    (applyParams.size == unapplyParams.size && paramsMatch)
  } => apply
}

As you can see in the relevant (non-hasVarArgs branch), this code only handles two cases: when the types in apply and unapply match exactly or when the same raw generic type is used. Your case of Seq[T] (as well as other complex generic types) is not handled here and the error you get is generated just a few lines down when maybeApply is empty:

val (tparams, params) = maybeApply match {
  case Some(apply) => {
    apply.typeParams -> apply.paramLists.head
    // assume there is a single parameter group
  }

  case None => c.abort(c.enclosingPosition, "No apply function found matching unapply parameters")
}

In Play-JSON 2.6 this code was significantly re-worked and now it seems to support your case as well (see conforms inner method).

If upgrading to (not released yet) Play-JSON 2.6 is not acceptable, you can create Formats object(s) yourself using JSON Reads/Writes/Format Combinators doc. Something like this should work for you:

  implicit def format[T](implicit r: Reads[T], w: Writes[T]): Format[Work[T]] = {
    val workReads = (
      (JsPath \ "todo").read[Seq[T]] and
        (JsPath \ "failed").read[Seq[T]] and
        (JsPath \ "success").read[Seq[T]]
      ) (Work.apply[T] _)

    val workWrites = (
      (JsPath \ "todo").write[Seq[T]] and
        (JsPath \ "failed").write[Seq[T]] and
        (JsPath \ "success").write[Seq[T]]
      ) (unlift(Work.unapply[T]))

    new Format[Work[T]] {
      override def reads(json: JsValue): JsResult[Work[T]] = workReads.reads(json)

      override def writes(o: Work[T]): JsValue = workWrites.writes(o)
    }
  }


问:
How to get the number of tweets from a given hashtag
I'm using the library tweepy. My objective is obtain the number of tweets of a given hashtag related with films of the spanish cinema.

I use the function 'search' with the input parameter: the title of the film.

I would like obtain the hashtag related to this title, and then the number of tweets that was in it.

Can you help me?

Thanks!!

答: you might want to use the Cursor class: http://docs.tweepy.org/en/v3.5.0/cursor_tutorial.html


问:
Trying to understand inline assembly code in C
So I have some code

```<code>#define umul_ppmm(w1, w0, u, v)                         \
  asm ("mulq %3"                                        \
       : "=a" (w0), "=d" (w1)                           \
       : "0" ((uint64_t)(u)), "rm" ((uint64_t)(v)))
</code>```

I'm trying to debug it and understand how it works.

Currently, I am looking at This pdf for reference on mulq.

My understanding so far is that it is multiplying two 64 bit numbers together which would be w0 and u. Then it stores the result of that multiplication in w0 and w1.

My main questions are:

According to This GCC assembly guide on Simple Constraints 'a' and 'd' in "=a" and "=d" are address and data registers respectively. How does that play in here and what exactly does that mean?

What does "0" mean in this case? That same guide says that "An operand that matches the specified operand number is allowed." What would be the matching operand here?

How does v come into play? If at all?

Printing out the variables before and after the function call results in

w1         w0           u                    v

2097147    549755813889 17179869183          4611684961865433149

4294966311 17179869183  13835060159816138691 4611684961865433149

答:
The mulq instruction implicitly produces result in the a and d registers (normally known as rax and rdx)

Operands are indexed from zero. "0" thus means same place as the first operand, which is w0. mulq implicitly uses rax as one of the input operands, hence the matching constraint. Could have written it out as "a" again.

v is the operand %3 which is the only explicit operand referenced in the mulq instruction. The code multiplies u and v so of course it "comes into play".

You printed the registers wrong, on the second line you swapped w0 and u, as u and v are unchanged input operands.
u*v=w1*2^64+w0, that is 17179869183*4611684961865433149=4294966311*2^64+13835060159816138691

Body:
So I have some code

#define umul_ppmm(w1, w0, u, v)                         \
  asm ("mulq %3"                                        \
       : "=a" (w0), "=d" (w1)                           \
       : "0" ((uint64_t)(u)), "rm" ((uint64_t)(v)))

I'm trying to debug it and understand how it works.

Currently, I am looking at This pdf for reference on mulq.

My understanding so far is that it is multiplying two 64 bit numbers together which would be w0 and u. Then it stores the result of that multiplication in w0 and w1.

My main questions are:

According to This GCC assembly guide on Simple Constraints 'a' and 'd' in "=a" and "=d" are address and data registers respectively. How does that play in here and what exactly does that mean?

What does "0" mean in this case? That same guide says that "An operand that matches the specified operand number is allowed." What would be the matching operand here?

How does v come into play? If at all?

Printing out the variables before and after the function call results in

w1         w0           u                    v

2097147    549755813889 17179869183          4611684961865433149

4294966311 17179869183  13835060159816138691 4611684961865433149


问:
Servlet + Tomcat 6: referencing javaScript library
I'm writting a small JSP page, which should use a JavaScript library, but I have problem with resolving this library. To test the issue I created a simple web app and added the following HTML-file:

```<code><html>
<head>
    <script type="text/javascript" src="scripts/jquery.js"></script>
    <script type="text/javascript" src="scripts/jquery.cookie.js"></script>
    <script type="text/javascript" src="scripts/jquery.hotkeys.js"></script>
    <script type="text/javascript" src="http://static.jstree.com/v.1.0rc2/jquery.jstree.js"></script>
</head>
<body>
    <div id="demo1" class="demo">
        <ul>
            <li id="phtml_1">
                <a href="#">Root node 1</a>
                <ul>
                    <li id="phtml_2" class="jstree-checked">
                        <a href="#">Child node 1</a>
                    </li>
                    <li id="phtml_3">
                        <a href="#">Child node 2</a>
                    </li>
                </ul>
            </li>
            <li id="phtml_4">
                <a href="#">Root node 2</a>
            </li>
        </ul>
    </div>
    <script type="text/javascript" class="source">
        $(function () {
            $("#demo1").jstree({
                "plugins" : [ "themes", "html_data", "checkbox" ]
            });
        });
    </script>
</body>
</code>```

This works fine, but it doesn't work if I replace "http://static.jstree.com/v.1.0rc2/jquery.jstree.js" with "scripts/jquery.jstree.js", though all libraries are in the same scripts folder (src/main/webapp/scripts).

Any idea what is going wrong?

Regards,
Florian

答:
I found the problem: I didn't copy the themes to my project :-/

Thanks anyway.

Body:
I'm writting a small JSP page, which should use a JavaScript library, but I have problem with resolving this library. To test the issue I created a simple web app and added the following HTML-file:

                Root node 1

                        Child node 1

                        Child node 2

                Root node 2

This works fine, but it doesn't work if I replace "http://static.jstree.com/v.1.0rc2/jquery.jstree.js" with "scripts/jquery.jstree.js", though all libraries are in the same scripts folder (src/main/webapp/scripts).

Any idea what is going wrong?

Regards,
Florian


问:
efficient way to split temporal Numpy vector automatically
I have a temporal vector as in the following image:

Numpy vector:
https://drive.google.com/file/d/0B4Jac-wNMDxHS3BnUzBoUkdmOGs/view?usp=sharing

I would like to know an efficient way to split the vector in numpy, and extract the 5 chunks of the signals that drop in amplitude significantly.

I could separate them by considering the amplitude 2.302 as the cut off amplitude and separate them by the initial index when the signal drops bellow this value and the final index when the signal goes above this value.

Any efficient way to do this in numpy?

答:
So I've programmed the solution in pure python and lists:

```<code>vec = np.load('vector_numpy.npy')
# plt.plot(vec)
# plt.show()
print vec.shape

temporal_vec = []
flag = 0
flag_start = 0
flag_end = 0

all_vectors = []
all_index = []

count = -1
for element in vec:
    count = count+1
    #print element
    if element < 2.302:
        if flag_start ==0:
            all_index.append(count)
            flag_start=1
        temporal_vec.append(element)
        flag = 1
    if flag == 1:
        if element >= 2.302:
            if flag_start==1:
                all_index.append(count)
                flag_start=0
            all_vectors.append(temporal_vec)
            temporal_vec = []
            flag = 0

print(all_vectors)

for element in all_vectors:
    print(len(element))
    plt.plot(element)
    plt.show()

print(all_index)
</code>```

Any fancier way in Numpy or better/shorter python code?

Body:
So I've programmed the solution in pure python and lists:

vec = np.load('vector_numpy.npy')
# plt.plot(vec)
# plt.show()
print vec.shape

temporal_vec = []
flag = 0
flag_start = 0
flag_end = 0

all_vectors = []
all_index = []

count = -1
for element in vec:
    count = count+1
    #print element
    if element < 2.302:
        if flag_start ==0:
            all_index.append(count)
            flag_start=1
        temporal_vec.append(element)
        flag = 1
    if flag == 1:
        if element >= 2.302:
            if flag_start==1:
                all_index.append(count)
                flag_start=0
            all_vectors.append(temporal_vec)
            temporal_vec = []
            flag = 0

print(all_vectors)

for element in all_vectors:
    print(len(element))
    plt.plot(element)
    plt.show()

print(all_index)

Any fancier way in Numpy or better/shorter python code?


问:
tensorflow configure error: Unexpected error reading .blazerc file '%workspace%/.tf_configure.bazelrc'
I use ubuntu 14.04, cuda 8.0 cudnn 5.1
when I config tensorflow, some errors show as follow:

Unexpected error reading .blazerc file '%workspace%/.tf_configure.bazelrc'

答: You have to change .bazelrc to replace %workspace% with the path to .tf_configure.bazelrc.


问:
Access container url using Azure Blob Emulator
I'm trying to use a Azure Emulator to create a container, but I think is not working:

Emulator Endpoint :

```<code>BlobEndpoint: http://127.0.0.1:10000/
</code>```

App.config :

```<code><appSettings>
  <add key="StorageConnectionString" value="UseDevelopmentStorage=true;" />
</appSettings>
</code>```

And the code :

```<code>CloudStorageAccount storageAccount =
                   CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString"));

        CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

        CloudBlobContainer container = blobClient.GetContainerReference("mycontainer");
await container.CreateIfNotExistsAsync();
</code>```

But when I try to access http://127.0.0.1:10000/mycontainer I got :

```<code>The requested URI does not represent any resource on the server.
</code>```

答: The correct container URI should be http://127.0.0.1:10000/devstoreaccount1/mycontainer, how did you try to access it? I don't think opening it in browser directly is feasible.</p>

Body:
I'm trying to use a Azure Emulator to create a container, but I think is not working:

Emulator Endpoint :

BlobEndpoint: http://127.0.0.1:10000/

App.config :

<appSettings>
  <add key="StorageConnectionString" value="UseDevelopmentStorage=true;" />
</appSettings>

And the code :

CloudStorageAccount storageAccount =
                   CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString"));

        CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

        CloudBlobContainer container = blobClient.GetContainerReference("mycontainer");
await container.CreateIfNotExistsAsync();

But when I try to access http://127.0.0.1:10000/mycontainer I got :

The requested URI does not represent any resource on the server.


问:
Not all code paths return a value in case of a recursive algorithm
I've just designed a recursive algorithm and implemented in C# encountering not all code paths return a value error. Here is the code:

```<code>public List<List<Event>> CollectPaths(IEnumerable<string[]> transitions, State q_r, State q_s, List<State> Q_T, ref List<Event> tempPath)
        {
            if (!Q_T.Any())
            {
                pathCollection.Add(tempPath);
                return pathCollection;
            }

            else
            {
                List<State> Q_O = new List<State>();
                Q_O = Get_Q_O(q_r, transitions);

                State qq = new State("");

                foreach (State q in Q_O)
                {
                    List<Event> S_O = new List<Event>();
                    List<Event> S_OO = new List<Event>();
                    S_O = Get_S_O(q_r, q, transitions);
                    S_OO = Get_S_OO(q_r, q, S_O, transitions);

                    if (q.ID == q_s.ID)
                    {
                        tempPath.AddRange(S_O);
                        pathCollection.Add(tempPath);
                        Q_T.Remove(q);
                        if (!Q_T.Any())
                            return pathCollection;
                        else
                            continue; /////////////Note 1
                    }

                    else
                    {
                        foreach(Event sigma in S_O)
                        {
                            if (AFC_1(S_OO) ||
                             AFC_2(S_OO) ||
                             (AFC_3_1(S_OO, S_O) && AFC_3_2(GetC_S_OO(S_OO), GetU_S_OO(S_OO)))
                            )
                            {
                                tempPath.AddRange(S_O);
                                Q_T.Remove(q);
                                CollectPaths(transitions, q, q_s, Q_T, ref tempPath);
                            }

                            else
                            {
                                Q_T.Remove(q);
                                if (!Q_T.Any())
                                    return pathCollection;
                                else
                                    continue; /////////////Note 2
                            }
                        }
                    }
                }
            }
        }
</code>```

There are many conditional branches, and I've done my best to make algorithm return the pathCollection, finally.

Some Remarks:

Note 1 and Note 2: the continue continues the foreach for the other values of q. Then, either it will get rid of the if and execute the else; or Q_T (a global variable which can be changed by all instantiations of the function) will become empty and pathCollection returns.

But I can't figure out what's wrong with this code!

Could you please give me some advice about it?

答:
If you are positive that the function is going to safely return a value, just add a return statement above your last bracket.

However, I would recommend trying to refactor your code to catch this sort of thing (adding exceptions, etc) to make sure this very confusing algorithm is operating correctly.

Body:
I've just designed a recursive algorithm and implemented in C# encountering not all code paths return a value error. Here is the code:

public List<List<Event>> CollectPaths(IEnumerable<string[]> transitions, State q_r, State q_s, List<State> Q_T, ref List<Event> tempPath)
        {
            if (!Q_T.Any())
            {
                pathCollection.Add(tempPath);
                return pathCollection;
            }

            else
            {
                List<State> Q_O = new List<State>();
                Q_O = Get_Q_O(q_r, transitions);

                State qq = new State("");

                foreach (State q in Q_O)
                {
                    List<Event> S_O = new List<Event>();
                    List<Event> S_OO = new List<Event>();
                    S_O = Get_S_O(q_r, q, transitions);
                    S_OO = Get_S_OO(q_r, q, S_O, transitions);

                    if (q.ID == q_s.ID)
                    {
                        tempPath.AddRange(S_O);
                        pathCollection.Add(tempPath);
                        Q_T.Remove(q);
                        if (!Q_T.Any())
                            return pathCollection;
                        else
                            continue; /////////////Note 1
                    }

                    else
                    {
                        foreach(Event sigma in S_O)
                        {
                            if (AFC_1(S_OO) ||
                             AFC_2(S_OO) ||
                             (AFC_3_1(S_OO, S_O) && AFC_3_2(GetC_S_OO(S_OO), GetU_S_OO(S_OO)))
                            )
                            {
                                tempPath.AddRange(S_O);
                                Q_T.Remove(q);
                                CollectPaths(transitions, q, q_s, Q_T, ref tempPath);
                            }

                            else
                            {
                                Q_T.Remove(q);
                                if (!Q_T.Any())
                                    return pathCollection;
                                else
                                    continue; /////////////Note 2
                            }
                        }
                    }
                }
            }
        }

There are many conditional branches, and I've done my best to make algorithm return the pathCollection, finally.

Some Remarks:

Note 1 and Note 2: the continue continues the foreach for the other values of q. Then, either it will get rid of the if and execute the else; or Q_T (a global variable which can be changed by all instantiations of the function) will become empty and pathCollection returns.

But I can't figure out what's wrong with this code!

Could you please give me some advice about it?


问:
How to get backorder status from product information programmatically in Magento 2
How to get backorder status from product information programmatically?

Now the product information is ready as $_product, also we can get inventory status by this code.

```<code><?php $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
     $StockState = $objectManager->get('\Magento\CatalogInventory\Api\StockStateInterface');
     $product_is_stock = $StockState->getStockQty($_product->getId(), $_product->getStore()->getWebsiteId()); ?>
</code>```

Also, backorder feature was settled so we can add the out stock products on cart.

答:
I had tried to get result by full searching whole channels, but I didn't get proper solution.

After debugging and investigating vendor API structures on several hours, I got the correct answers myself.
This is proved answers on Magento 2.1.5, 2.1.7.

```<code>$obj = \Magento\Framework\App\ObjectManager::getInstance();
$stockRegistry = $obj->get('Magento\CatalogInventory\Api\StockRegistryInterface');
$stockitem = $stockRegistry->getStockItem($_product->getId(),$_product->getStore()->getWebsiteId());
echo "Backorder: "; echo $stockitem->getBackorders(); echo '<br>';
</code>```

I added this part on

```<code>app\design\frontend\[vendor]\[theme]\Amasty_Cart\templates\rightside\cart.phtml
app\design\frontend\[vendor]\[theme]\Magento_Checkout\templates\cart\form.phtml
</code>```

which I should determine backorderable products status.

Finally, I could get 0, 1, 2 values according to the 3 status of backorders.

```<code>0: "No Backorders"
1: "Allow Qty Below 0 "
2: "Allow Qty Below 0 and Notify Customer"
</code>```

This will help many developers who create new modules or customize themes with its efficiency.

Body:
How to get backorder status from product information programmatically?

Now the product information is ready as $_product, also we can get inventory status by this code.

<?php $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
     $StockState = $objectManager->get('\Magento\CatalogInventory\Api\StockStateInterface');
     $product_is_stock = $StockState->getStockQty($_product->getId(), $_product->getStore()->getWebsiteId()); ?>

Also, backorder feature was settled so we can add the out stock products on cart.

Body:
I had tried to get result by full searching whole channels, but I didn't get proper solution.

After debugging and investigating vendor API structures on several hours, I got the correct answers myself.
This is proved answers on Magento 2.1.5, 2.1.7.

$obj = \Magento\Framework\App\ObjectManager::getInstance();
$stockRegistry = $obj->get('Magento\CatalogInventory\Api\StockRegistryInterface');
$stockitem = $stockRegistry->getStockItem($_product->getId(),$_product->getStore()->getWebsiteId());
echo "Backorder: "; echo $stockitem->getBackorders(); echo '<br>';

I added this part on

app\design\frontend\[vendor]\[theme]\Amasty_Cart\templates\rightside\cart.phtml
app\design\frontend\[vendor]\[theme]\Magento_Checkout\templates\cart\form.phtml

which I should determine backorderable products status.

Finally, I could get 0, 1, 2 values according to the 3 status of backorders.

0: "No Backorders"
1: "Allow Qty Below 0 "
2: "Allow Qty Below 0 and Notify Customer"

This will help many developers who create new modules or customize themes with its efficiency.


问:
Recursively checking for odd or even
In this code:

```<code>def is_even(x):
  if x == 0:
    return True
  else:
    return is_odd(x-1)

def is_odd(x):
  return not is_even(x)

print(is_even(2))
print(is_odd(2))
</code>```

I keep going through this in my head and wondering how it's working.  It seems to me that eventually x in is_even(x) will return True every time.  However, when I run the code, it works perfectly fine and returns True and False appropriately.  Can someone explain how that's happening?

I understand the basic concept of recursion and fully understand how the famous factorial example works.  However, this one is hard for me to wrap my head around.

Feeling inept right now...

答:
Add a couple of print statements and you will see what it is doing:

```<code>from __future__ import print_function

def is_even(x):
    if x == 0:
        print('True')
        return True
    else:
        return is_odd(x-1)

def is_odd(x):
    print('not', end=' ')
    return not is_even(x)

>>> is_even(5)
not not not not not True
False
>>> is_odd(5)
not not not not not not True
True
</code>```

Title: Recursively checking for odd or even

Body:
In this code:

def is_even(x):
  if x == 0:
    return True
  else:
    return is_odd(x-1)

def is_odd(x):
  return not is_even(x)

print(is_even(2))
print(is_odd(2))

I keep going through this in my head and wondering how it's working.  It seems to me that eventually x in is_even(x) will return True every time.  However, when I run the code, it works perfectly fine and returns True and False appropriately.  Can someone explain how that's happening?

I understand the basic concept of recursion and fully understand how the famous factorial example works.  However, this one is hard for me to wrap my head around.

Feeling inept right now...

Body:
Add a couple of print statements and you will see what it is doing:

from __future__ import print_function

def is_even(x):
    if x == 0:
        print('True')
        return True
    else:
        return is_odd(x-1)

def is_odd(x):
    print('not', end=' ')
    return not is_even(x)

>>> is_even(5)
not not not not not True
False
>>> is_odd(5)
not not not not not not True
True


问:
How to read an input value from atmega32 pin?
I'm trying to read a value from an avr pin but it doesn't work.

I'm trying to read a value that is coming from a push button and this button is connected to 5V DC cell.

When I press the button the 5V should go to the atmega32 and reads it as 1, then the if statement becomes true and the led goes on.

However, when the value becomes true the led will turn on but its not.

bit 1 is the button
bit 0 is the led

Code

```<code>#define DDRA (*((volatile unsigned char *)0x3A))
#define PORTA (*((volatile unsigned char *)0x3B))
#define PINA (*((volatile unsigned char *)0x39))

int main(void) {
   DDRA |= 0b00000001;         // pin 0 output

    while (1) {
        if ((PINA&0b00000010) == 1) {  // button pressed
            PORTA |= 0b00000001;   // turn led on
        }
    }
}
</code>```

答:
I find one logic error here:

```<code>if ((PINA&0b00000010) == 1)  // button pressed
</code>```

when the bit 1 is set, (PINA&0b00000010) == 2.
Normally, when you do bit check, just do this:

```<code>if (PINA&0b00000010)  // button pressed
</code>```

Body:
I'm trying to read a value from an avr pin but it doesn't work.

I'm trying to read a value that is coming from a push button and this button is connected to 5V DC cell.

When I press the button the 5V should go to the atmega32 and reads it as 1, then the if statement becomes true and the led goes on.

However, when the value becomes true the led will turn on but its not.

bit 1 is the button
bit 0 is the led

Code

#define DDRA (*((volatile unsigned char *)0x3A))
#define PORTA (*((volatile unsigned char *)0x3B))
#define PINA (*((volatile unsigned char *)0x39))

int main(void) {
   DDRA |= 0b00000001;         // pin 0 output

    while (1) {
        if ((PINA&0b00000010) == 1) {  // button pressed
            PORTA |= 0b00000001;   // turn led on
        }
    }
}

Body:
I find one logic error here:

if ((PINA&0b00000010) == 1)  // button pressed

when the bit 1 is set, (PINA&0b00000010) == 2.
Normally, when you do bit check, just do this:

if (PINA&0b00000010)  // button pressed


问:
SQL ignore rows based on other rows
On Microsoft SQL I run a query that will return tons of rows with a name and a state (plus lots of other columns), like so:

```<code>Name  | State
------|------------
Bob   | In Progress
Bob   | In Progress
Sally | Complete
Sally | Not Started
Sally | In Progress
Bob   | Not Started
</code>```

Every row will have one of those three states, and the rows may appear in any order.  More annoyingly, rows may repeat. If somebody is 'In Progress' then I don't want to see any rows for them of 'Not Started', and if they are 'Complete' then I don't want to see 'In Progress' or 'Not Started'.

So for the above data I'd just want to see

```<code>Name  | State
------|------------
Bob   | In Progress
Sally | Complete
</code>```

Is this possible with a SQL query?

Here's the actual query I'm using right now, but I still get entries where the name appears with more than one state.

答:
You seem to want the "maximum" state.  Here is one method:</p>

```<code>select name, state
from (select name, state
             row_number() over (partition by name
                                order by (case when State = 'Not Started' then 1
                                               when State = 'In Progress' then 2
                                               when State = 'Complete' then 3
                                               else 0
                                          end) desc
                                ) as seqnum
      from t
     ) t
where seqnum = 1;
</code>```

Title: SQL ignore rows based on other rows

Body:
On Microsoft SQL I run a query that will return tons of rows with a name and a state (plus lots of other columns), like so:

Name  | State
------|------------
Bob   | In Progress
Bob   | In Progress
Sally | Complete
Sally | Not Started
Sally | In Progress
Bob   | Not Started

Every row will have one of those three states, and the rows may appear in any order.  More annoyingly, rows may repeat. If somebody is 'In Progress' then I don't want to see any rows for them of 'Not Started', and if they are 'Complete' then I don't want to see 'In Progress' or 'Not Started'.

So for the above data I'd just want to see

Name  | State
------|------------
Bob   | In Progress
Sally | Complete

Is this possible with a SQL query?

Here's the actual query I'm using right now, but I still get entries where the name appears with more than one state.

Body:
You seem to want the "maximum" state.  Here is one method:

select name, state
from (select name, state
             row_number() over (partition by name
                                order by (case when State = 'Not Started' then 1
                                               when State = 'In Progress' then 2
                                               when State = 'Complete' then 3
                                               else 0
                                          end) desc
                                ) as seqnum
      from t
     ) t
where seqnum = 1;


问:
Calculating averages based on adjustable, non-overlapping averaging period (4, 7, 30, 42 days) while aggregating (grouping) based multiple variables
I’d like to apply a distinct (not rolling) seven day averaging period to a set of data, but the seven day window does not start until a sample is "found" and is not based on calendar weeks.

I’ve tried the following code but problem with this code is that it gives a rolling averaged sample for every sample in the data set.  Instead I need to aggregate all samples that appear within the averaging period into a single sample.

```<code>library(plyr)
library(dplyr)
library(lubridate)

Analyte<-c("Copper", "Copper", "Copper", "Copper", "Nickel", "Nickel", "Nickel")
Date<-mdy(c("1/1/2015", "1/3/2015", "1/12/2015", "1/15/2015", "1/3/2015", "1/6/2015", "1/8/2015"))
Matrix<-c("Water", "Water", "Water", "Water", "Water", "Water", "Water")
Fraction<-c("Total", "Total", "Total", "Total", "Dissolved", "Dissolved", "Dissolved")
Result<-c(0.6, 0.3, 0.5, 0.6, 0.1, 0.9, 1.0)
d<-cbind.data.frame(Analyte, Date, Matrix, Fraction, Result)

d$Date2<-d$Date
d$dateinterval<-interval(d$Date2-days(7), d$Date2+days(7))

d2<-ddply(d, c("Analyte", "Matrix", "Fraction"),function(df){
  SevenDayResultMean<-rep(NA, length(df$Date))
  SevenDayN<-rep(NA, length(df$Date))

  for(i in 1:length(df$Date)){
    SevenDayResultMean[i]<-mean(df$Result[df$Date2%within%df$dateinterval[i]], na.rm=T)
    SevenDayN[i]<-length(df$Result[df$Date2%within%df$dateinterval[i]])
  }
  return(data.frame(SevenDayResultMean=SevenDayResultMean, Date=as.character(df$Date), SevenDayN=SevenDayN))
}
)
</code>```

The above code returns the table below which is a rolling average and not what I need.  In the table below, the first nickel sample is averaged with the following two nickel samples.  Then the second sample is averaged with the first and last sample, and so on.

```<code>Analyte     Matrix     Fraction    SevenDayResultMean   Date       SevenDayN

Copper      Water      Total       0.45                 2015-01-01        2
Copper      Water      Total       0.3                  2015-01-03        2
Copper      Water      Total       0.55                 2015-01-12        2
Copper      Water      Total       0.6                  2015-01-15        2
Nickel      Water      Dissolved   0.67                 2015-01-03        3
Nickel      Water      Dissolved   0.95                 2015-01-06        3
Nickel      Water      Dissolved   1.0                  2015-01-08        3
</code>```

Ideally, I would define an averaging period then group all other variables by like values.  I would need to get a table like the following:

```<code>Analyte    Date       Matrix     Fraction     Result

Copper     1/1/2015   Water      Total        0.45
Copper     1/12/2015  Water      Total        0.55
Nickel     1/3/2015   Water      Dissolved    0.67
</code>```

Here, the first two samples were averaged because there were within seven days of the first sample, had the same fraction, matrix, and analyte and became the first entry in the result table.  The same for the next 2 samples of copper and all of the nickel samples were averaged for the same reasons.  The date applied to the sample in the result table doesn’t really matter as long as the date is within the seven day period that was averaged.

答:
With dplyr we can do:

library(dplyr)

d %>%
  group_by(Analyte, Matrix, Fraction) %>%
  mutate(interval = cumsum(Date - lag(Date, default = min(Date)) >= 7)) %>%
  group_by(interval, add = TRUE) %>%
  summarise(Date = min(Date), Result = mean(Result)) %>%
  select(Analyte, Date, Matrix, Fraction, Result)

#> Source: local data frame [3 x 5]
#> Groups: Analyte, Matrix, Fraction [2]
#>
#>   Analyte       Date Matrix  Fraction    Result
#>    <fctr>     <date> <fctr>    <fctr>     <dbl>
#> 1  Copper 2015-01-01  Water     Total 0.4500000
#> 2  Copper 2015-01-12  Water     Total 0.5500000
#> 3  Nickel 2015-01-03  Water Dissolved 0.6666667
```

<p>Data: </p>

<pre class="lang-r prettyprint-override"><code>library(lubridate)

Analyte <- c("Copper", "Copper", "Copper", "Copper", "Nickel", "Nickel", "Nickel")
Date <- mdy(c("1/1/2015", "1/3/2015", "1/12/2015", "1/15/2015", "1/3/2015", "1/6/2015", "1/8/2015"))
Matrix <- c("Water", "Water", "Water", "Water", "Water", "Water", "Water")
Fraction <- c("Total", "Total", "Total", "Total", "Dissolved", "Dissolved", "Dissolved")
Result <- c(0.6, 0.3, 0.5, 0.6, 0.1, 0.9, 1.0)
d <- data.frame(Analyte, Date, Matrix, Fraction, Result)
</code>```

Body:
I’d like to apply a distinct (not rolling) seven day averaging period to a set of data, but the seven day window does not start until a sample is "found" and is not based on calendar weeks.

I’ve tried the following code but problem with this code is that it gives a rolling averaged sample for every sample in the data set.  Instead I need to aggregate all samples that appear within the averaging period into a single sample.

library(plyr)
library(dplyr)
library(lubridate)

Analyte<-c("Copper", "Copper", "Copper", "Copper", "Nickel", "Nickel", "Nickel")
Date<-mdy(c("1/1/2015", "1/3/2015", "1/12/2015", "1/15/2015", "1/3/2015", "1/6/2015", "1/8/2015"))
Matrix<-c("Water", "Water", "Water", "Water", "Water", "Water", "Water")
Fraction<-c("Total", "Total", "Total", "Total", "Dissolved", "Dissolved", "Dissolved")
Result<-c(0.6, 0.3, 0.5, 0.6, 0.1, 0.9, 1.0)
d<-cbind.data.frame(Analyte, Date, Matrix, Fraction, Result)

d$Date2<-d$Date
d$dateinterval<-interval(d$Date2-days(7), d$Date2+days(7))

d2<-ddply(d, c("Analyte", "Matrix", "Fraction"),function(df){
  SevenDayResultMean<-rep(NA, length(df$Date))
  SevenDayN<-rep(NA, length(df$Date))

  for(i in 1:length(df$Date)){
    SevenDayResultMean[i]<-mean(df$Result[df$Date2%within%df$dateinterval[i]], na.rm=T)
    SevenDayN[i]<-length(df$Result[df$Date2%within%df$dateinterval[i]])
  }
  return(data.frame(SevenDayResultMean=SevenDayResultMean, Date=as.character(df$Date), SevenDayN=SevenDayN))
}
)

The above code returns the table below which is a rolling average and not what I need.  In the table below, the first nickel sample is averaged with the following two nickel samples.  Then the second sample is averaged with the first and last sample, and so on.

Analyte     Matrix     Fraction    SevenDayResultMean   Date       SevenDayN

Copper      Water      Total       0.45                 2015-01-01        2
Copper      Water      Total       0.3                  2015-01-03        2
Copper      Water      Total       0.55                 2015-01-12        2
Copper      Water      Total       0.6                  2015-01-15        2
Nickel      Water      Dissolved   0.67                 2015-01-03        3
Nickel      Water      Dissolved   0.95                 2015-01-06        3
Nickel      Water      Dissolved   1.0                  2015-01-08        3

Ideally, I would define an averaging period then group all other variables by like values.  I would need to get a table like the following:

Analyte    Date       Matrix     Fraction     Result

Copper     1/1/2015   Water      Total        0.45
Copper     1/12/2015  Water      Total        0.55
Nickel     1/3/2015   Water      Dissolved    0.67

Here, the first two samples were averaged because there were within seven days of the first sample, had the same fraction, matrix, and analyte and became the first entry in the result table.  The same for the next 2 samples of copper and all of the nickel samples were averaged for the same reasons.  The date applied to the sample in the result table doesn’t really matter as long as the date is within the seven day period that was averaged.

Body:
With dplyr we can do:

library(dplyr)

d %>%
  group_by(Analyte, Matrix, Fraction) %>%
  mutate(interval = cumsum(Date - lag(Date, default = min(Date)) >= 7)) %>%
  group_by(interval, add = TRUE) %>%
  summarise(Date = min(Date), Result = mean(Result)) %>%
  select(Analyte, Date, Matrix, Fraction, Result)

#> Source: local data frame [3 x 5]
#> Groups: Analyte, Matrix, Fraction [2]
#>
#>   Analyte       Date Matrix  Fraction    Result
#>    <fctr>     <date> <fctr>    <fctr>     <dbl>
#> 1  Copper 2015-01-01  Water     Total 0.4500000
#> 2  Copper 2015-01-12  Water     Total 0.5500000
#> 3  Nickel 2015-01-03  Water Dissolved 0.6666667

Data:

library(lubridate)

Analyte <- c("Copper", "Copper", "Copper", "Copper", "Nickel", "Nickel", "Nickel")
Date <- mdy(c("1/1/2015", "1/3/2015", "1/12/2015", "1/15/2015", "1/3/2015", "1/6/2015", "1/8/2015"))
Matrix <- c("Water", "Water", "Water", "Water", "Water", "Water", "Water")
Fraction <- c("Total", "Total", "Total", "Total", "Dissolved", "Dissolved", "Dissolved")
Result <- c(0.6, 0.3, 0.5, 0.6, 0.1, 0.9, 1.0)
d <- data.frame(Analyte, Date, Matrix, Fraction, Result)


问:
How do you embedded your sql queries in php scripts (coding-style)?
how do you embed your sql scripts in php? Do you just write them in a string or a heredoc or do you outsource them to a sql file? Are there any best practices when to outsource them ? Is there an elegant way to organize this?</p>

答: You could use an ORM or an sql string builder, but some complex queries necessitate writing sql. When writing sql, as Michał Słaby illustrates, use query bindings. Query bindings prevent sql injection and maintain readability. As for where to put your queries: use model classes.</p>

OwnerDisplayName: rick


问:
Historic Maps in R
Being concerned with a spatial data analysis with data ranging from 1950 to 2016 I would like to plot some nice features in a world map in R. However, as the political landscape has changed with time, the actual implementations (e.g. the R package rworldmap) give the recent countries (Although, not long ago that was not true for all packages: Updated world map for R "maps" package?).

Hence my question is, whether there is some package with historic maps or otherwise some online-source for shapefiles or polygons for worldmaps, beginning in 1950.

答:
Try the package cshapes from CRAN:

R Package for CShapes, a GIS dataset of country boundaries
  (1946-2015). Includes functions for data extraction and the
  computation of weights matrices.

It lets you extract a dataset for a chosen time, which you can then also use with any mapping tool you prefer.

Title: Historic Maps in R