问:
How to convert c++ for loop to Python?
I wrote a code in C++ and would like to convert it to Python3. How to do that?

```<code>int N = 1000
for (p=2; p*p<=N; p++)
    for (w=p*p; w<=N; w=w+p)
</code>```

I tried to change the first for loop to:

```<code>for p in range(2,N**0.5+1):
</code>```

But it doesn't work - TypeError: 'float' object cannot be interpreted as an integer

And what about the second for loop?

答:
```<code>int N = 1000
for (p=2; p*p<=N; p++)
    for (w=p*p; w<=N; w=w+p)
</code>```

In Python, the range() function takes in 3 parameters: int start, int stop, int step. Since your second argument is N**0.5, with 0.5 of type float, the result of that calculation is interpreted as of type float.

My suggestion is:

```<code>from math import sqrt
n = 1000
m = int(sqrt(n))
for p in range(2,m):
  for w in range(p*p, n+1, p)
    print(p,w)
</code>```

Does that solve your problem?

Title: How to convert c++ for loop to Python?

Body:
I wrote a code in C++ and would like to convert it to Python3. How to do that?

int N = 1000
for (p=2; p*p<=N; p++)
    for (w=p*p; w<=N; w=w+p)

I tried to change the first for loop to:

for p in range(2,N**0.5+1):

But it doesn't work - TypeError: 'float' object cannot be interpreted as an integer

And what about the second for loop?

Body:
int N = 1000
for (p=2; p*p<=N; p++)
    for (w=p*p; w<=N; w=w+p)

In Python, the range() function takes in 3 parameters: int start, int stop, int step. Since your second argument is N**0.5, with 0.5 of type float, the result of that calculation is interpreted as of type float.

My suggestion is:

from math import sqrt
n = 1000
m = int(sqrt(n))
for p in range(2,m):
  for w in range(p*p, n+1, p)
    print(p,w)

Does that solve your problem?


来源: stackexchange

问:
Windows forms: Graphics.Drawline doesnt work
So here is code i have in my Form class:

```<code>public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
 private void Form1_Load(object sender, EventArgs e)
        {
            BstTree tree = new BstTree();
            tree.addRoot(50);
            for (int i = 1; i < 50; i++)
            {
                int b = rnd.Next(1, 100);
                listBox1.Items.Add(b);
                tree.AddNode(tree.root, b);
            }
            tree.treeOutput(tree.root, this);
        }
        public void draw(Point prevPT, Point currentPT)
        {
            Graphics p = CreateGraphics();
            Pen pen = new Pen(Color.Red, 5);
            p.DrawLine(pen, prevPT, currentPT);
        }
    }
</code>```

And i have BstTree class and i call the draw method from there:

```<code>public Class BstTree
{
public void treeOutput(Node root, Form1 f)
        {
                Label node = new Label();
                node.AutoSize = true;
                node.Text = root.value.ToString();
                node.Location = pt;
                root.ancPT = pt;
                f.Controls.Add(node);
                f.draw(root.ancestor.ancPT, pt);
        }
}
</code>```

but it doesnt draw anything, have no idea how to solve this...

答:
Drawing in a bitmap is static and you can do so by using your own Graphics object; however, drawing in WinForms is very dynamic, as the drawing is very ephemeral. Minimizing a form, resizing a form, moving a form partly out of the visible screen area or opening another application on top of your form can destroy the drawn things. Therefore the Windows operating system implements a clever drawing mechanism by sending messages to the applications whenever a form, a control or parts of those must be redrawn. This raises paint events in the applications and means that the OS determines when things must be drawn (or redrawn). Therefore, your drawing routines must occur inside paint event handlers.

If you want to draw the tree nodes yourself, create your own tree control by deriving it from TreeView and change the DrawMode accordingly.

```<code>public class MyTreeView : TreeView
{
    public MyTreeView()
    {
        DrawMode = TreeViewDrawMode.OwnerDrawAll;
    }

    protected override void OnDrawNode(DrawTreeNodeEventArgs e)
    {
        if (e.Node.IsVisible) {
            // Draw background of node.
            if (e.Node == e.Node.TreeView.SelectedNode) {
                e.Graphics.FillRectangle(Brushes.LightBlue, e.Bounds);
            } else {
                e.Graphics.FillRectangle(Brushes.White, e.Bounds);
            }
            using (Pen p = new Pen(Color.Red, 5))
            {
                // TODO: Implement your drawing logic here
            }
            e.Graphics.DrawString(e.Node.Text, this.Font, Brushes.Black,
                                  e.Bounds.Left + delta, e.Bounds.Top + 1);
        }
    }
}
</code>```

This is only a raw sketch. You might have to consider other details like e.Node.IsExpanded and e.State.

ContentLicense: CC BY-SA 3.0

Body:
So here is code i have in my Form class:

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
 private void Form1_Load(object sender, EventArgs e)
        {
            BstTree tree = new BstTree();
            tree.addRoot(50);
            for (int i = 1; i < 50; i++)
            {
                int b = rnd.Next(1, 100);
                listBox1.Items.Add(b);
                tree.AddNode(tree.root, b);
            }
            tree.treeOutput(tree.root, this);
        }
        public void draw(Point prevPT, Point currentPT)
        {
            Graphics p = CreateGraphics();
            Pen pen = new Pen(Color.Red, 5);
            p.DrawLine(pen, prevPT, currentPT);
        }
    }

And i have BstTree class and i call the draw method from there:

public Class BstTree
{
public void treeOutput(Node root, Form1 f)
        {
                Label node = new Label();
                node.AutoSize = true;
                node.Text = root.value.ToString();
                node.Location = pt;
                root.ancPT = pt;
                f.Controls.Add(node);
                f.draw(root.ancestor.ancPT, pt);
        }
}

but it doesnt draw anything, have no idea how to solve this...

Body:
Drawing in a bitmap is static and you can do so by using your own Graphics object; however, drawing in WinForms is very dynamic, as the drawing is very ephemeral. Minimizing a form, resizing a form, moving a form partly out of the visible screen area or opening another application on top of your form can destroy the drawn things. Therefore the Windows operating system implements a clever drawing mechanism by sending messages to the applications whenever a form, a control or parts of those must be redrawn. This raises paint events in the applications and means that the OS determines when things must be drawn (or redrawn). Therefore, your drawing routines must occur inside paint event handlers.

If you want to draw the tree nodes yourself, create your own tree control by deriving it from TreeView and change the DrawMode accordingly.

public class MyTreeView : TreeView
{
    public MyTreeView()
    {
        DrawMode = TreeViewDrawMode.OwnerDrawAll;
    }

    protected override void OnDrawNode(DrawTreeNodeEventArgs e)
    {
        if (e.Node.IsVisible) {
            // Draw background of node.
            if (e.Node == e.Node.TreeView.SelectedNode) {
                e.Graphics.FillRectangle(Brushes.LightBlue, e.Bounds);
            } else {
                e.Graphics.FillRectangle(Brushes.White, e.Bounds);
            }
            using (Pen p = new Pen(Color.Red, 5))
            {
                // TODO: Implement your drawing logic here
            }
            e.Graphics.DrawString(e.Node.Text, this.Font, Brushes.Black,
                                  e.Bounds.Left + delta, e.Bounds.Top + 1);
        }
    }
}

This is only a raw sketch. You might have to consider other details like e.Node.IsExpanded and e.State.


问:
Group repeated elements of a list
I am trying to create a function that receives a list and return another list with the repeated elements.

For example for the input A = [2,2,1,1,3,2] (the list is not sorted) and the function would return result = [[1,1], [2,2,2]]. The result doesn't need to be sorted.

I already did it in Wolfram Mathematica but now I have to translate it to python3, Mathematica has some functions like Select, Map and Split that makes it very simple without using long loops with a lot of instructions.

答:
You could do this with a list comprehension:

```<code>A = [1,1,1,2,2,3,3,3]
B = []
[B.append([n]*A.count(n)) for n in A if B.count([n]*A.count(n)) == 0]
</code>```

outputs [[1,1,1],[2,2],[3,3,3]]

Or more pythonically:

```<code>A = [1,2,2,3,4,1,1,2,2,2,3,3,4,4,4]
B = []
for n in A:
    if B.count([n]*A.count(n)) == 0:
        B.append([n]*A.count(n))
</code>```

outputs [[1,1,1],[2,2,2,2,2],[3,3,3],[4,4,4,4]]

Works with sorted or unsorted list, if you need to sort the list before hand you can do for n in sorted(A)

Title: Group repeated elements of a list

Body:
You could do this with a list comprehension:

A = [1,1,1,2,2,3,3,3]
B = []
[B.append([n]*A.count(n)) for n in A if B.count([n]*A.count(n)) == 0]

outputs [[1,1,1],[2,2],[3,3,3]]

Or more pythonically:

A = [1,2,2,3,4,1,1,2,2,2,3,3,4,4,4]
B = []
for n in A:
    if B.count([n]*A.count(n)) == 0:
        B.append([n]*A.count(n))

outputs [[1,1,1],[2,2,2,2,2],[3,3,3],[4,4,4,4]]

Works with sorted or unsorted list, if you need to sort the list before hand you can do for n in sorted(A)


问:
JS Function Issues with array.filter()
So I have a JavaScript function I'm working on. I noticed that my editor is flagging an error on line 4 but the function works in every browser I've tested except for IE and Safari. I find this particularly weird.

Basic idea for the function is: take 'element' (the ID of a html element) and convert it to a string, define an array of all possible versions of 'element', remove 'element' from the array, and perform another function using the now-filtered array and 'element' as variables. This is what I have:

```<code>function thisFunction(element){
    var eStr=element.toString();
    var eArray=['element1', 'element2', 'element3'];
    var fArray=eArray.filter(e=>e!==eStr);
    fArray.forEach(doThis);
    function doThis(value){

        Now do this with 'fArray'....

        return false;
        doThis();
        }

    And do this with 'element'...

    return false;
    thisFunction();
    }
</code>```

The error is apparently something to do with the "var fArray" line, but I cant see a problem. The error when I click the link that is supposed to activate this function is "thisFunction is undefined" as well as the error on line 4.

答:
The problem on line 4 is that IE does not support the arrow function syntax you're using in the callback. Changing this line:

```<code>var fArray=eArray.filter(e=>e!==eStr);
</code>```

To something like:

```<code>var fArray=eArray.filter(function(e) { return e!==eStr; });
</code>```

Should fix things.

Details on which JS features are supported by which browsers can be found at https://kangax.github.io/compat-table/es6/

Title: JS Function Issues with array.filter()

Body:
So I have a JavaScript function I'm working on. I noticed that my editor is flagging an error on line 4 but the function works in every browser I've tested except for IE and Safari. I find this particularly weird.

Basic idea for the function is: take 'element' (the ID of a html element) and convert it to a string, define an array of all possible versions of 'element', remove 'element' from the array, and perform another function using the now-filtered array and 'element' as variables. This is what I have:

function thisFunction(element){
    var eStr=element.toString();
    var eArray=['element1', 'element2', 'element3'];
    var fArray=eArray.filter(e=>e!==eStr);
    fArray.forEach(doThis);
    function doThis(value){

        Now do this with 'fArray'....

        return false;
        doThis();
        }

    And do this with 'element'...

    return false;
    thisFunction();
    }

The error is apparently something to do with the "var fArray" line, but I cant see a problem. The error when I click the link that is supposed to activate this function is "thisFunction is undefined" as well as the error on line 4.

Body:
The problem on line 4 is that IE does not support the arrow function syntax you're using in the callback. Changing this line:

var fArray=eArray.filter(e=>e!==eStr);

To something like:

var fArray=eArray.filter(function(e) { return e!==eStr; });

Should fix things.

Details on which JS features are supported by which browsers can be found at https://kangax.github.io/compat-table/es6/


问:
How to setup Codeception with remote code coverage?

I have two repo on my machine

API

Codeception repo that tests API

In API repo I have added codeception+c3

```<code>"require-dev": {
    "codeception/codeception": "2.*",
    "codeception/c3": "2.*",
</code>```

I've also included c3.php inside index.php, but when trying to test it with --coverage I have this error

[PHPUnit_Framework_Exception]
  file_get_contents(http://local.api.codeception.com/c3/report/clear): fai
  led to open stream: HTTP request failed! HTTP/1.1 500 Internal Server Error

Is there ANY online example of remote codecoverage with Codeception?

答:
Here's my configuration for remote codecoverage with Codeception (Project on GitHub).

Steps for running up remote codecoverage collection

1. Make sure that xdebug installed and enabled.

2. Configure codeception.

File codeception.yml (GitHub):

```<code>coverage:
  enabled: true
  c3_url: 'http://%SERVICE_HOST%/index-test.php/'
  include:
  - web/*
  - config/*
  - src/*
</code>```

3. Enable coverage for the suits you need.

File acceptance.suite.yml (GitHub):

```<code>coverage:
  remote: true
</code>```

In my example its enabled only for acceptance tests.

4. Include c3.php file in your application bootstrap.

Application bootstrap file index-test.php (GitHub):

```<code>// Start the remote code coverage collection.
require_once __DIR__.'/../c3.php';

// autoloader, application running and etc
// ...
</code>```

5. Run coverage.

```<code>$ vendor/bin/codecept run --coverage --coverage-html
</code>```

By default you can find your reports in tests/_output directory.

Possible issues

1. Output directory not writable (tests/_output).

```<code>$ chmod 777 tests/_output
</code>```

2. Remote codecoverage not printed in console.

It should not be printed. From documentation:

```<code>coverage:
  remote: true
</code>```

In this case remote Code Coverage results won’t be merged with local ones, if this option is enabled. Merging is possible only in case a remote and local files have the same path. But in case of running tests on a remote server we are not sure of it.

3. Some other error.

Try to enable debug. If debug enabled, you can get your report or clear it.

```<code>curl -o codecoverage.tar "http://localhost:8080/index-test.php/c3/report/html"
</code>```

End

Sometimes it's not a trivial task. So I hope this will help!

Body:
I have two repo on my machine

API

Codeception repo that tests API

In API repo I have added codeception+c3

"require-dev": {
    "codeception/codeception": "2.*",
    "codeception/c3": "2.*",

I've also included c3.php inside index.php, but when trying to test it with --coverage I have this error

[PHPUnit_Framework_Exception]
  file_get_contents(http://local.api.codeception.com/c3/report/clear): fai
  led to open stream: HTTP request failed! HTTP/1.1 500 Internal Server Error

Is there ANY online example of remote codecoverage with Codeception?

Body:
Here's my configuration for remote codecoverage with Codeception (Project on GitHub).

Steps for running up remote codecoverage collection

1. Make sure that xdebug installed and enabled.

2. Configure codeception.

File codeception.yml (GitHub):

coverage:
  enabled: true
  c3_url: 'http://%SERVICE_HOST%/index-test.php/'
  include:
  - web/*
  - config/*
  - src/*

3. Enable coverage for the suits you need.

File acceptance.suite.yml (GitHub):

coverage:
  remote: true

In my example its enabled only for acceptance tests.

4. Include c3.php file in your application bootstrap.

Application bootstrap file index-test.php (GitHub):

// Start the remote code coverage collection.
require_once __DIR__.'/../c3.php';

// autoloader, application running and etc
// ...

5. Run coverage.

$ vendor/bin/codecept run --coverage --coverage-html

By default you can find your reports in tests/_output directory.

Possible issues

1. Output directory not writable (tests/_output).

$ chmod 777 tests/_output

2. Remote codecoverage not printed in console.

It should not be printed. From documentation:

coverage:
  remote: true

In this case remote Code Coverage results won’t be merged with local ones, if this option is enabled. Merging is possible only in case a remote and local files have the same path. But in case of running tests on a remote server we are not sure of it.

3. Some other error.

Try to enable debug. If debug enabled, you can get your report or clear it.

curl -o codecoverage.tar "http://localhost:8080/index-test.php/c3/report/html"

End

Sometimes it's not a trivial task. So I hope this will help!

ContentLicense: CC BY-SA 4.0


问:
Could not find com.android.tools.build:gradle:2.3.3
I am getting this error during gradle build in android studio. And I am unable to figure out what I am missing.

Error:Could not find com.android.tools.build:gradle:2.3.3. Searched in the
    following locations:
    file:/C:/Program Files/Android/Android
    Studio/gradle/m2repository/com/android/tools/build/gradle/2.3.3/gradle-2.3.3.pom

    file:/C:/Program Files/Android/Android
    Studio/gradle/m2repository/com/android/tools/build/gradle/2.3.3/gradle-2.3.3.jar

    https://maven.google.com/com/android/tools/build/gradle/2.3.3/gradle-2.3.3.pom

    https://maven.google.com/com/android/tools/build/gradle/2.3.3/gradle-2.3.3.jar

Here is my build.gradlefile configuration

```<code>`
all sub-projects/modules.
    allprojects {
        repositories {
            jcenter()
            maven {
                url "https://maven.google.com"
            }
            maven {
                url 'https://jitpack.io'
            }
        }
    }

    buildscript {
        dependencies {
            classpath 'com.android.tools.build:gradle:2.3.3'
        }
        repositories {
            maven {
                url 'https://maven.google.com/'
                name 'Google'
            }
        }
    }

    ext {
        supportlib_version = '26.0.2'
        gps_version = '11.2.0'
    }

    //Ensure that all dependencies use the same version of the Android Support library
    subprojects {
        project.configurations.all {
            resolutionStrategy.eachDependency { details ->
                if (details.requested.group == 'com.android.support'
                        && !details.requested.name.contains('multidex')) {
                    details.useVersion "$supportlib_version"
                }
                if (details.requested.group == 'com.google.android.gms'
                        && !details.requested.name.contains('multidex')) {
                    details.useVersion "$gps_version"
                }
            }
        }
    }

    allprojects {
        repositories {
            jcenter()
            maven {
                url 'https://maven.google.com/'
                name 'Google'
            }
        }
    }
`
</code>```

Could you help me what am I missing?

答:
Add jcenter() to buildscript repositories if you are using gradle plugin 2.x.

Here's a copy of build.gradle(Project) from my old project.

```<code>buildscript {
    repositories {
        // for 2.x
        jcenter()
    }
    dependencies {
        // classpath 'com.android.tools.build:gradle:2.2.0'
        classpath 'com.android.tools.build:gradle:2.3.3'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}
</code>```

If your gradle (the one distributed by Gradle) version is low,

also need to edit gradle-wrapper.properties.

Minimum version of Gradle is 3.3 for plugin 2.3.3.

Plugin version 2.3.0+ :

  Required Gradle version 3.3+

gradle-wrapper.properties sample:

```<code>distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
#distributionUrl=https\://services.gradle.org/distributions/gradle-2.14.1-all.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-3.3-all.zip
</code>```

Please see Update Gradle.  Available versions are listed in this page.

For information:

This exists (jcenter).

https://bintray.com/android/android-tools/com.android.tools.build.gradle/2.3.3

This does not exist (Google's Maven repository). It's from 3.0, I think.

https://maven.google.com/com/android/tools/build/gradle/2.3.3/gradle-2.3.3.pom

This exists

https://maven.google.com/com/android/tools/build/gradle/3.0.0/gradle-3.0.0.pom

For Gradle version >= 3.0.0

Please see Update the Android Plugin for Gradle
and Update Gradle.

Body:
I am getting this error during gradle build in android studio. And I am unable to figure out what I am missing.

Error:Could not find com.android.tools.build:gradle:2.3.3. Searched in the
    following locations:
    file:/C:/Program Files/Android/Android
    Studio/gradle/m2repository/com/android/tools/build/gradle/2.3.3/gradle-2.3.3.pom

    file:/C:/Program Files/Android/Android
    Studio/gradle/m2repository/com/android/tools/build/gradle/2.3.3/gradle-2.3.3.jar

    https://maven.google.com/com/android/tools/build/gradle/2.3.3/gradle-2.3.3.pom

    https://maven.google.com/com/android/tools/build/gradle/2.3.3/gradle-2.3.3.jar

Here is my build.gradlefile configuration

`
all sub-projects/modules.
    allprojects {
        repositories {
            jcenter()
            maven {
                url "https://maven.google.com"
            }
            maven {
                url 'https://jitpack.io'
            }
        }
    }

    buildscript {
        dependencies {
            classpath 'com.android.tools.build:gradle:2.3.3'
        }
        repositories {
            maven {
                url 'https://maven.google.com/'
                name 'Google'
            }
        }
    }

    ext {
        supportlib_version = '26.0.2'
        gps_version = '11.2.0'
    }

    //Ensure that all dependencies use the same version of the Android Support library
    subprojects {
        project.configurations.all {
            resolutionStrategy.eachDependency { details ->
                if (details.requested.group == 'com.android.support'
                        && !details.requested.name.contains('multidex')) {
                    details.useVersion "$supportlib_version"
                }
                if (details.requested.group == 'com.google.android.gms'
                        && !details.requested.name.contains('multidex')) {
                    details.useVersion "$gps_version"
                }
            }
        }
    }

    allprojects {
        repositories {
            jcenter()
            maven {
                url 'https://maven.google.com/'
                name 'Google'
            }
        }
    }
`

Could you help me what am I missing?

Body:
Add jcenter() to buildscript repositories if you are using gradle plugin 2.x.

Here's a copy of build.gradle(Project) from my old project.

buildscript {
    repositories {
        // for 2.x
        jcenter()
    }
    dependencies {
        // classpath 'com.android.tools.build:gradle:2.2.0'
        classpath 'com.android.tools.build:gradle:2.3.3'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

If your gradle (the one distributed by Gradle) version is low,

also need to edit gradle-wrapper.properties.

Minimum version of Gradle is 3.3 for plugin 2.3.3.

Plugin version 2.3.0+ :

  Required Gradle version 3.3+

gradle-wrapper.properties sample:

distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
#distributionUrl=https\://services.gradle.org/distributions/gradle-2.14.1-all.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-3.3-all.zip

Please see Update Gradle.  Available versions are listed in this page.

For information:

This exists (jcenter).

https://bintray.com/android/android-tools/com.android.tools.build.gradle/2.3.3

This does not exist (Google's Maven repository). It's from 3.0, I think.

https://maven.google.com/com/android/tools/build/gradle/2.3.3/gradle-2.3.3.pom

This exists

https://maven.google.com/com/android/tools/build/gradle/3.0.0/gradle-3.0.0.pom

For Gradle version >= 3.0.0

Please see Update the Android Plugin for Gradle
and Update Gradle.


问:
calculate average using onchange event handler
I need to calculate the average of 5 numbers using onchange event handler. I'm new to coding and don't fully understand how onchange works. I also am confused on how to have the return # for my calcAvg function displayin my in 'result' box</p>

```<code><! doctype html >

<html lang = "en">
<head>
<title> Calculate Average </title>
</head>

<body>
    Number 1:<input type="number" id="number 1" Value="0"
onchange="calcAvg()"> </br> //do I put anything in between the ()of
onchange?
    Number 2:<input type="number" id="number 2" Value="0"
onchange="calcAvg()"> </br>
    Number 3:<input type="number" id="number 3" Value="0"
onchange="calcAvg()"> </br>
    Number 4:<input type="number" id="number 4" Value="0"
onchange="calcAvg()"> </br>
    Number 5:<input type="number" id="number 5" Value="0"
onchange="calcAvg()"> </br>
    Result :<input type=" number" id="result"> </br>
    <input type= 'button' value='calculate' id= 'calculate'>
    <div id= "result"> </div>//

    <script>
        function calcAvg ( number 1, number 2 ,number 3, number 4, number 5)
{
        return ((number 1 + number 2 +number 3+ number 4+ number 5)/5)
        }
    </script>

</body>
</html>
</code>```

答:
This below code will give your expected output.

$(function(){
 var sum = 0;
 $('input[type=number]').on("change keyup mouseup", function(){
  $("#result").val(calcAvg());
 });
 $('#calculate').on("click", function(){
  $("#result").val(calcAvg());
 });

});
function calcAvg(){
 var s = $("input[type=number]");
 var sum = 0;
 for(var i=0;i<s.length;i++){
  sum += parseInt($(s[i]).val());
 }
 return sum/s.length;
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>input{
 display:block;
}</code>```

Number 1:<input type="number" id="number1" Value="0">
    Number 2:<input type="number" id="number2" Value="0">
    Number 3:<input type="number" id="number3" Value="0">
    Number 4:<input type="number" id="number4" Value="0">
    Number 5:<input type="number" id="number5" Value="0">
    Result :<input type=" number" id="result">
    <input type= 'button' value='calculate' id='calculate'>```

Body:
I need to calculate the average of 5 numbers using onchange event handler. I'm new to coding and don't fully understand how onchange works. I also am confused on how to have the return # for my calcAvg function displayin my in 'result' box

<! doctype html >

<title> Calculate Average </title>

    Number 1:<input type="number" id="number 1" Value="0"
onchange="calcAvg()">
 //do I put anything in between the ()of
onchange?
    Number 2:<input type="number" id="number 2" Value="0"
onchange="calcAvg()">

    Number 3:<input type="number" id="number 3" Value="0"
onchange="calcAvg()">

    Number 4:<input type="number" id="number 4" Value="0"
onchange="calcAvg()">

    Number 5:<input type="number" id="number 5" Value="0"
onchange="calcAvg()">

    Result :<input type=" number" id="result">

    <input type= 'button' value='calculate' id= 'calculate'>

//

Body:
This below code will give your expected output.

$(function(){
 var sum = 0;
 $('input[type=number]').on("change keyup mouseup", function(){
  $("#result").val(calcAvg());
 });
 $('#calculate').on("click", function(){
  $("#result").val(calcAvg());
 });

});
function calcAvg(){
 var s = $("input[type=number]");
 var sum = 0;
 for(var i=0;i<s.length;i++){
  sum += parseInt($(s[i]).val());
 }
 return sum/s.length;
}

input{
 display:block;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Number 1:<input type="number" id="number1" Value="0">
    Number 2:<input type="number" id="number2" Value="0">
    Number 3:<input type="number" id="number3" Value="0">
    Number 4:<input type="number" id="number4" Value="0">
    Number 5:<input type="number" id="number5" Value="0">
    Result :<input type=" number" id="result">
    <input type= 'button' value='calculate' id='calculate'>


问:
Wordpress wp-admin fatal error
I have just switched my website's hosting and it is giving me error in opening the wordpress admin panel page. Can any body help me out. Thankyou

Fatal error: Uncaught Error: Call to undefined function eregi() in
  /home/atifchat/public_html/pakistanivoicechat.com/wp-content/plugins/google-bot-bling/google-bot-bling.php:59
  Stack trace: #0
  /home/atifchat/public_html/pakistanivoicechat.com/wp-includes/class-wp-hook.php(298):
  thisismyurl_google_bot_bling_init_code('') #1
  /home/atifchat/public_html/pakistanivoicechat.com/wp-includes/class-wp-hook.php(323):
  WP_Hook->apply_filters(NULL, Array) #2
  /home/atifchat/public_html/pakistanivoicechat.com/wp-includes/plugin.php(453):
  WP_Hook->do_action(Array) #3
  /home/atifchat/public_html/pakistanivoicechat.com/wp-settings.php(448):
  do_action('init') #4
  /home/atifchat/public_html/pakistanivoicechat.com/wp-config.php(104):
  require_once('/home/atifchat/...') #5
  /home/atifchat/public_html/pakistanivoicechat.com/wp-load.php(37):
  require_once('/home/atifchat/...') #6
  /home/atifchat/public_html/pakistanivoicechat.com/wp-admin/admin.php(31):
  require_once('/home/atifchat/...') #7
  /home/atifchat/public_html/pakistanivoicechat.com/wp-admin/in in
  /home/atifchat/public_html/pakistanivoicechat.com/wp-content/plugins/google-bot-bling/google-bot-bling.php
  on line 59

答:
What hosting did you switch from as well as what hosting did you switch it to? A lot of hosts for WordPress will give you support for this kind of thing especially if you just switched to their services so I would probably call support and give them the URL so that they can see the error and it is likely that they will give you some help. If they don't, try this article: http://www.wpbeginner.com/plugins/how-to-deactivate-all-plugins-when-not-able-to-access-wp-admin/
I remember migrating a site and having to FTP in to rename the plugins folder to plugins.hold or something and then I could login then I went back and renamed it again. But just to be safe I would follow the article and not my words.</p>

Title: Wordpress wp-admin fatal error


问:
Filtering Nothing from a List with foldr/foldl
I'm trying to implement catMaybes with List folding but have no clue how i should start.

My general idea is to use foldl and use a case to filter for Nothing and Just. After that the same function has to concat the found parts together my code this far looks like this:

```<code>{-# LANGUAGE LambdaCase #-}
catMaybes :: [Maybe a] -> [a]
catMaybes xs = foldl((++) \case Nothing -> []; Just y -> y) [] xs
</code>```

I'm getting alot of errors when compiling...
I think i need a push in the right direction to solve this. Thank you for your help!

答:
```<code>Just y -> y
</code>```

If this needs to unify with [] then you should have said [Maybe [a]] in the function type signature.  That or perhaps you meant Just y -> [y].

```<code>(++) \case Nothing -> []; Just y -> y
</code>```

That's just syntacticly nonsense.  I think you want 1. function composition 2. partial application of the first argument:

```<code>\b -> (b ++) . \case Nothing -> []; Just y -> y
</code>```

Body:
I'm trying to implement catMaybes with List folding but have no clue how i should start.

My general idea is to use foldl and use a case to filter for Nothing and Just. After that the same function has to concat the found parts together my code this far looks like this:

{-# LANGUAGE LambdaCase #-}
catMaybes :: [Maybe a] -> [a]
catMaybes xs = foldl((++) \case Nothing -> []; Just y -> y) [] xs

I'm getting alot of errors when compiling...
I think i need a push in the right direction to solve this. Thank you for your help!

Body:
Just y -> y

If this needs to unify with [] then you should have said [Maybe [a]] in the function type signature.  That or perhaps you meant Just y -> [y].

(++) \case Nothing -> []; Just y -> y

That's just syntacticly nonsense.  I think you want 1. function composition 2. partial application of the first argument:

\b -> (b ++) . \case Nothing -> []; Just y -> y


问:
tensorflow input pipeline returns multiple values
I'm trying to make an input pipeline in tensorflow for image classification, therefore I want to make batches of images and corresponding labels. The Tensorflow document suggests that we can use tf.train.batch to make batches of inputs:

```<code>train_batch, train_label_batch = tf.train.batch(
[train_image, train_image_label],
batch_size=batch_size,
num_threads=1,
capacity=10*batch_size,
enqueue_many=False,
shapes=[[224,224,3], [len(labels),]],
allow_smaller_final_batch=True
)
</code>```

However, I'm thinking would it be a problem if I feed in the graph like this:

```<code>cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=train_label_batch, logits=Model(train_batch)))
</code>```

The question is does the operation in the cost function dequeues images and their corresponding labels, or it returns them separately? Therefore causing the training with wrong images and labels.

答:
There are several things you need to consider to preserve the ordering of images and labels.

let's say we need a function that gives us images and labels.

```<code>def _get_test_images(_train=False):

"""
Gets the test images and labels as a batch

Inputs:
======
_train      : Boolean if images are from training set
random_crop     : Boolean if random cropping is allowed
random_flip         : Boolean if random horizontal flip is allowed
distortion      : Boolean if distortions are allowed

Outputs:
========
images_batch    : Batch of images containing BATCH_SIZE images at a time
label_batch     : Batch of labels corresponding to the images in images_batch
idx         : Batch of indexes of images
"""

#get images and labels
_,_img_names,_img_class,index= _get_list(_train = _train)

#total number of distinct images used for train will be equal to the images
#fed in tf.train.slice_input_producer as _img_names

img_path,label,idx = tf.train.slice_input_producer([_img_names,_img_class,index],shuffle=False)

img_path,label,idx = tf.convert_to_tensor(img_path),tf.convert_to_tensor(label),tf.convert_to_tensor(idx)
img_path = tf.cast(img_path,dtype=tf.string)

#read file
image_file = tf.read_file(img_path)

#decode jpeg/png/bmp
#tf.image.decode_image won't give shape out. So it will give error while resizing
image = tf.image.decode_jpeg(image_file)

#image preprocessing
image = tf.image.resize_images(image, [IMG_DIM,IMG_DIM])

float_image = tf.cast(image,dtype=tf.float32)

#subtracting mean and divide by standard deviation
float_image = tf.image.per_image_standardization(float_image)

#set the shape
float_image.set_shape(IMG_SIZE)
labels_original = tf.cast(label,dtype=tf.int32)
img_index = tf.cast(idx,dtype=tf.int32)

#parameters for shuffle
batch_size = BATCH_SIZE
min_fraction_of_examples_in_queue = 0.3
num_preprocess_threads = 1
num_examples_per_epoch = MAX_TEST_EXAMPLE
min_queue_examples = int(num_examples_per_epoch *
                       min_fraction_of_examples_in_queue)

images_batch, label_batch,idx = tf.train.batch(
        [float_image,label,img_index],
        batch_size=batch_size,
        num_threads=num_preprocess_threads,
        capacity=min_queue_examples + 3 * batch_size)

# Display the training images in the visualizer.
tf.summary.image('images', images_batch)

return images_batch, label_batch,idx
</code>```

Here,tf.train.slice_input_producer([_img_names,_img_class,index],shuffle=False) is an interesting thing to look at where if you put shuffle=True it will shuffle all three arrays in coordination.

Second thing is, num_preprocess_threads. As long as you are using single threads for dequeue operation, batches will come out in a deterministic way. But more than one threads will shuffle the arrays randomly. for example for image 0001.jpg if True label is 1 you might get 2 or 4. Once its dequeue it is in tensor form. tf.nn.softmax_cross_entropy_with_logits shouldn't have problem with such tensors.

Body:
I'm trying to make an input pipeline in tensorflow for image classification, therefore I want to make batches of images and corresponding labels. The Tensorflow document suggests that we can use tf.train.batch to make batches of inputs:

train_batch, train_label_batch = tf.train.batch(
[train_image, train_image_label],
batch_size=batch_size,
num_threads=1,
capacity=10*batch_size,
enqueue_many=False,
shapes=[[224,224,3], [len(labels),]],
allow_smaller_final_batch=True
)

However, I'm thinking would it be a problem if I feed in the graph like this:

cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=train_label_batch, logits=Model(train_batch)))

The question is does the operation in the cost function dequeues images and their corresponding labels, or it returns them separately? Therefore causing the training with wrong images and labels.

Body:
There are several things you need to consider to preserve the ordering of images and labels.

let's say we need a function that gives us images and labels.

def _get_test_images(_train=False):

"""
Gets the test images and labels as a batch

Inputs:
======
_train      : Boolean if images are from training set
random_crop     : Boolean if random cropping is allowed
random_flip         : Boolean if random horizontal flip is allowed
distortion      : Boolean if distortions are allowed

Outputs:
========
images_batch    : Batch of images containing BATCH_SIZE images at a time
label_batch     : Batch of labels corresponding to the images in images_batch
idx         : Batch of indexes of images
"""

#get images and labels
_,_img_names,_img_class,index= _get_list(_train = _train)

#total number of distinct images used for train will be equal to the images
#fed in tf.train.slice_input_producer as _img_names

img_path,label,idx = tf.train.slice_input_producer([_img_names,_img_class,index],shuffle=False)

img_path,label,idx = tf.convert_to_tensor(img_path),tf.convert_to_tensor(label),tf.convert_to_tensor(idx)
img_path = tf.cast(img_path,dtype=tf.string)

#read file
image_file = tf.read_file(img_path)

#decode jpeg/png/bmp
#tf.image.decode_image won't give shape out. So it will give error while resizing
image = tf.image.decode_jpeg(image_file)

#image preprocessing
image = tf.image.resize_images(image, [IMG_DIM,IMG_DIM])

float_image = tf.cast(image,dtype=tf.float32)

#subtracting mean and divide by standard deviation
float_image = tf.image.per_image_standardization(float_image)

#set the shape
float_image.set_shape(IMG_SIZE)
labels_original = tf.cast(label,dtype=tf.int32)
img_index = tf.cast(idx,dtype=tf.int32)

#parameters for shuffle
batch_size = BATCH_SIZE
min_fraction_of_examples_in_queue = 0.3
num_preprocess_threads = 1
num_examples_per_epoch = MAX_TEST_EXAMPLE
min_queue_examples = int(num_examples_per_epoch *
                       min_fraction_of_examples_in_queue)

images_batch, label_batch,idx = tf.train.batch(
        [float_image,label,img_index],
        batch_size=batch_size,
        num_threads=num_preprocess_threads,
        capacity=min_queue_examples + 3 * batch_size)

# Display the training images in the visualizer.
tf.summary.image('images', images_batch)

return images_batch, label_batch,idx

Here,tf.train.slice_input_producer([_img_names,_img_class,index],shuffle=False) is an interesting thing to look at where if you put shuffle=True it will shuffle all three arrays in coordination.

Second thing is, num_preprocess_threads. As long as you are using single threads for dequeue operation, batches will come out in a deterministic way. But more than one threads will shuffle the arrays randomly. for example for image 0001.jpg if True label is 1 you might get 2 or 4. Once its dequeue it is in tensor form. tf.nn.softmax_cross_entropy_with_logits shouldn't have problem with such tensors.


问:
What is the purpose of the AuthenticatorInterface::supports() method?
In Symfony 4, the AuthenticatorInterface::supports() method has the following comment:

```<code>interface AuthenticatorInterface extends AuthenticationEntryPointInterface
{
    /**
     * Does the authenticator support the given Request?
     *
     * If this returns false, the authenticator will be skipped.
     *
     * @param Request $request
     *
     * @return bool
     */
    public function supports(Request $request);
</code>```

I find the phrasing confusing. My first instinct when I tried implementing this was to return true if the request contains a username and password field, but then I remembered that all the requests I am receiving are getting authenticated, even if i am not using the login form.

Is the supports() method a way to override the security.firewalls.myFirewall.pattern argument? Is it a thing that handles the flow between multiple authenticators?

How should I use this interface?

答:
I agree this feature isn't that well documented (yet). The only thing I can find is this:

How to Create a Custom Authentication System with Guard

supports(Request $request)

This will be called on every request and
your job is to decide if the authenticator should be used for this
request (return true) or if it should be skipped (return false).

For example: you can use the Request to check if it is a XMLHttpRequest (AJAX), so you can have dedicated AjaxAuthenticator.

A similar feature (VoterInterface::support()) is documented at How to Use Voters to Check User Permissions.

Body:
In Symfony 4, the AuthenticatorInterface::supports() method has the following comment:

interface AuthenticatorInterface extends AuthenticationEntryPointInterface
{
    /**
     * Does the authenticator support the given Request?
     *
     * If this returns false, the authenticator will be skipped.
     *
     * @param Request $request
     *
     * @return bool
     */
    public function supports(Request $request);

I find the phrasing confusing. My first instinct when I tried implementing this was to return true if the request contains a username and password field, but then I remembered that all the requests I am receiving are getting authenticated, even if i am not using the login form.

Is the supports() method a way to override the security.firewalls.myFirewall.pattern argument? Is it a thing that handles the flow between multiple authenticators?

How should I use this interface?


问:
How to parse long hexadecimal string into uint
I'm pulling in data that is in long hexadecimal string form which I need to convert into decimal notation, truncate 18 decimal places, and then serve up in JSON.

For example I may have the hex string:

```<code>"0x00000000000000000000000000000000000000000000d3c21bcecceda1000000"
</code>```

At first I was attempting to use ParseUint(), however since the highest it supports is int64, my number ends up being way too big.

This example after conversion and truncation results in 10^6.
However there are instances where this number can be up to 10^12 (meaning pre truncation 10^30!).

What is the best strategy to attack this?

答:
Use math/big for working with numbers larger than 64 bits.

From the Int.SetString example:

```<code>s := "d3c21bcecceda1000000"
i := new(big.Int)
i.SetString(s, 16)
fmt.Println(i)
</code>```

https://play.golang.org/p/vf31ce93vA

The math/big types also support the encoding.TextMarshaler and fmt.Scanner interfaces.

For example

```<code>i := new(big.Int)
fmt.Sscan("0x000000d3c21bcecceda1000000", i)
</code>```

Or

```<code>i := new(big.Int)
fmt.Sscanf("0x000000d3c21bcecceda1000000", "0x%x", i)
</code>```

Body:
I'm pulling in data that is in long hexadecimal string form which I need to convert into decimal notation, truncate 18 decimal places, and then serve up in JSON.

For example I may have the hex string:

"0x00000000000000000000000000000000000000000000d3c21bcecceda1000000"

At first I was attempting to use ParseUint(), however since the highest it supports is int64, my number ends up being way too big.

This example after conversion and truncation results in 10^6.
However there are instances where this number can be up to 10^12 (meaning pre truncation 10^30!).

What is the best strategy to attack this?

Body:
Use math/big for working with numbers larger than 64 bits.

From the Int.SetString example:

s := "d3c21bcecceda1000000"
i := new(big.Int)
i.SetString(s, 16)
fmt.Println(i)

https://play.golang.org/p/vf31ce93vA

The math/big types also support the encoding.TextMarshaler and fmt.Scanner interfaces.

For example

i := new(big.Int)
fmt.Sscan("0x000000d3c21bcecceda1000000", i)

Or

i := new(big.Int)
fmt.Sscanf("0x000000d3c21bcecceda1000000", "0x%x", i)


问:
StrSQL Insert into throwing an error in VBA
I am trying to Insert some new records in to an access database.

Here is my code,

```<code>' OPEN ACCESS APPLICATION
    Set objAccess = CreateObject("Access.Application")
    objAccess.OpenCurrentDatabase DatabasePath

 ' OPEN INTERNAL DATABASE
    Set db = objAccess.CurrentDb

BuName = Ws.Sheets("Config").Range("T1").Value
RepName = Ws.Sheets("Config").Range("T2").Value
NumberofUniqueSheets = Ws.Sheets("Config").Range("T3").Value

For i = 1 To NumberofUniqueSheets

    CmpValue = Ws.Sheets("Config").Range("U1").Value
    ShtNamedec = Split(CmpValue, "$")(0)
    HeadRow = Split(CmpValue, "$")(1)
    AddInfo = Split(CmpValue, "$")(2)
    DateInfo = Split(CmpValue, "$")(3)

    ' PREPARE STATEMENT
    strSQL = "PARAMETERS [BusinessUnitparam] TEXT(255), [ReportNameparam] TEXT(255),[SheetNameparam] TEXT(255), [HeaderRowparam] INTEGER, [AdditionalInfoparam] TEXT(255), [DateRequiredinfoparam] TEXT(255);" _
               & "INSERT INTO ReportTypes ([BusinessUnit], [ReportName], [SheetName], [HeaderRow], [AdditionalInfo], [DateRequiredinfo]);"

    ' BUILD TEMP QUERYDEF
    Set qdef = db.CreateQueryDef("", strSQL)

    ' BIND PARAMS TO VARIABLES
    qdef!BusinessUnitparam = BuName
    qdef!ReportNameparam = RepName
    qdef!SheetNameparam = ShtNamedec
    qdef!HeaderRowparam = HeadRow
    qdef!AdditionalInfoparam = AddInfo
    qdef!DateRequiredinfoparam = DateInfo

    ' EXECUTE ACTION QUERY
    qdef.Execute

Next

    Set qdef = Nothing
    Set db = Nothing
    Set objAccess = Nothing
</code>```

I am facing an error in the Build Temp QueryDef Statement and the error says `

Syntax error in Insert into Statement.

`
I added the Values into the Insert Into the statement like below

```<code>strSQL = "PARAMETERS [BusinessUnitparam] TEXT(255), [ReportNameparam] TEXT(255),[SheetNameparam] TEXT(255), [HeaderRowparam] INTEGER, [AdditionalInfoparam] TEXT(255), [DateRequiredinfoparam] TEXT(255);" _
               & "INSERT INTO ReportTypes ([BusinessUnit], [ReportName], [SheetName], [HeaderRow], [AdditionalInfo], [DateRequiredinfo]) VALUES (BuName, RepName, ShtNamedec, HeadRow, AddInfo, DateInfo);"
</code>```

But it gives another on Execute Action Query statement saying too few parameters expected 12. Here is the Table structure for reference -

答:
This query works with parameters for your data table design:</p>

```<code>strSQL = "PARAMETERS [BusinessUnitparam] TEXT(255), [ReportNameparam] TEXT(255),[SheetNameparam] TEXT(255), [HeaderRowparam] INTEGER, [AdditionalInfoparam] TEXT(255), [DateRequiredinfoparam] TEXT(255);" _
           & "INSERT INTO ReportTypes ([BusinessUnit], [ReportName], [SheetName], [HeaderRow], [AdditionalInfo], [DateRequiredinfo])" _
           & "SELECT BusinessUnitparam AS Expr1, ReportNameparam AS Expr2, SheetNameparam AS Expr3, HeaderRowparam AS Expr4, AdditionalInfoparam AS Expr5, DateRequiredInfoparam as Expr6;"
</code>```

Body:
I am trying to Insert some new records in to an access database.

Here is my code,

' OPEN ACCESS APPLICATION
    Set objAccess = CreateObject("Access.Application")
    objAccess.OpenCurrentDatabase DatabasePath

 ' OPEN INTERNAL DATABASE
    Set db = objAccess.CurrentDb

BuName = Ws.Sheets("Config").Range("T1").Value
RepName = Ws.Sheets("Config").Range("T2").Value
NumberofUniqueSheets = Ws.Sheets("Config").Range("T3").Value

For i = 1 To NumberofUniqueSheets

    CmpValue = Ws.Sheets("Config").Range("U1").Value
    ShtNamedec = Split(CmpValue, "$")(0)
    HeadRow = Split(CmpValue, "$")(1)
    AddInfo = Split(CmpValue, "$")(2)
    DateInfo = Split(CmpValue, "$")(3)

    ' PREPARE STATEMENT
    strSQL = "PARAMETERS [BusinessUnitparam] TEXT(255), [ReportNameparam] TEXT(255),[SheetNameparam] TEXT(255), [HeaderRowparam] INTEGER, [AdditionalInfoparam] TEXT(255), [DateRequiredinfoparam] TEXT(255);" _
               & "INSERT INTO ReportTypes ([BusinessUnit], [ReportName], [SheetName], [HeaderRow], [AdditionalInfo], [DateRequiredinfo]);"

    ' BUILD TEMP QUERYDEF
    Set qdef = db.CreateQueryDef("", strSQL)

    ' BIND PARAMS TO VARIABLES
    qdef!BusinessUnitparam = BuName
    qdef!ReportNameparam = RepName
    qdef!SheetNameparam = ShtNamedec
    qdef!HeaderRowparam = HeadRow
    qdef!AdditionalInfoparam = AddInfo
    qdef!DateRequiredinfoparam = DateInfo

    ' EXECUTE ACTION QUERY
    qdef.Execute

Next

    Set qdef = Nothing
    Set db = Nothing
    Set objAccess = Nothing

I am facing an error in the Build Temp QueryDef Statement and the error says `

Syntax error in Insert into Statement.

`
I added the Values into the Insert Into the statement like below

strSQL = "PARAMETERS [BusinessUnitparam] TEXT(255), [ReportNameparam] TEXT(255),[SheetNameparam] TEXT(255), [HeaderRowparam] INTEGER, [AdditionalInfoparam] TEXT(255), [DateRequiredinfoparam] TEXT(255);" _
               & "INSERT INTO ReportTypes ([BusinessUnit], [ReportName], [SheetName], [HeaderRow], [AdditionalInfo], [DateRequiredinfo]) VALUES (BuName, RepName, ShtNamedec, HeadRow, AddInfo, DateInfo);"

But it gives another on Execute Action Query statement saying too few parameters expected 12. Here is the Table structure for reference -

Body:
This query works with parameters for your data table design:

strSQL = "PARAMETERS [BusinessUnitparam] TEXT(255), [ReportNameparam] TEXT(255),[SheetNameparam] TEXT(255), [HeaderRowparam] INTEGER, [AdditionalInfoparam] TEXT(255), [DateRequiredinfoparam] TEXT(255);" _
           & "INSERT INTO ReportTypes ([BusinessUnit], [ReportName], [SheetName], [HeaderRow], [AdditionalInfo], [DateRequiredinfo])" _
           & "SELECT BusinessUnitparam AS Expr1, ReportNameparam AS Expr2, SheetNameparam AS Expr3, HeaderRowparam AS Expr4, AdditionalInfoparam AS Expr5, DateRequiredInfoparam as Expr6;"


问:
Create new sheet and organize result
I am creating a report from Cognos which is generating the result below in Excel format:

The problem with the code is everything I have hardcoded the values based on line numbers and which I want to make dynamic, so that if I have to generate a report for the previous 2 weeks, then I won't have to change my macro code every time.

Currently I am showing the value for name = "PO" and id = 28. But there will be other name and id also. For every name and id there will be 4 column values as for RR, DD, EE and FF. I have to group them based on name and id and create new sheet which will have results like below:

答:
Andrew: What version of Excel do you have? If you have Excel 2013 or later, you can use the new functionality under the 'Get and Transform' tab to do this really easily. It was previously a separate add-in called PowerQuery, and is now bulk standard in Excel.

There's many excellent walkthroughs on the internet showing this exact type of activity. Google "PowerQuery"  and put a date filter on your results to show just the last year, as the functionality is constantly being updated. Add "Ken Puls" to your search term, and see what bubbles to the top. Then replace Ken "Mike Girvin" or "ExcelIsFun" and you should see like a zillion excellent tutorials on PowerQuery. Try "ExcelCampus" too, as Jon has great tutorials, as does "Chandoo". Also replace PowerQuery with "Get and Transform" and repeat those same searches.

PowerQuery is simple to learn, and lets you do stuff just by "muddling through" that would otherwise take a year or more to learn if you wanted to pick up VBA.

It acts like a user-friendly macro recorder, only unlike the macro recorder it spits out reusable code that doesn't have hard coded references in it.

Title: Create new sheet and organize result


问:
How can I schedule an email to be sent at some point in the future in django?
I want to schedule an email to be sent to a user upon a specific action.
However, if the user takes another action I want to cancel that email and have it not send.

How would I do that in django or python?

答: I would set up a cron job which could handle everything you want to do...</p>

ContentLicense: CC BY-SA 2.5


问:
Solve differential equation in Python when I don't know the derivative analytically
I'm trying to solve a first-order ODE in Python:

where Gamma and u are square matrices.
I don't explicitly know u(t) at all times, but I do know it at discrete timesteps from doing an earlier calculation.

Every example I found of Python's solvers online (e.g. this one for scipy.integrate.odeint and scipy.integrate.ode) know the expression for the derivative analytically as a function of time.

Is there a way to call these (or other differential equation solvers) without knowing an analytic expression for the derivative?

For now, I've written my own Runge-Kutta solver and jitted it with numba.

答:
Is there a way to call these (or other differential equation solvers) without knowing an analytic expression for the derivative?

Yes, none of the solvers you mentioned (nor most other solvers) require an analytic expression for the derivative. Instead they call a function you supply that has to evaluate the derivative for a given time and state. So, your code would roughly look something like:

```<code>def my_derivative(time,flat_Gamma):
    Gamma = flat_Gamma.reshape(dim_1,dim_2)
    u = get_u_from_time(time)
    dGamma_dt = u.dot(Gamma)
    return dGamma_dt.flatten()

from scipy.integrate import ode
my_integrator = ode(my_derivative)
…
</code>```

The difficulty in your situation is rather that you have to ensure that get_u_from_time provides an appropriate result for every time with which it is called. Probably the most robust and easy solution is to use interpolation (see the other answer).

You can also try to match your integration steps to the data you have, but at least for scipy.integrate.odeint and scipy.integrate.ode this will be very tedious as all the integrators use internal steps that are inconvenient for this purpose. For example, the fifth-order Dormand–Prince method (DoPri5) uses internal steps of 1/5, 3/10, 4/5, 8/9, and 1. This means that if you have temporally equidistant data for u, you would need 90 data points for each integration step (as 1/90 is the greatest common divisor of the internal steps). The only integrator that could make this remotely feasible is the Bogacki–Shampine integrator (RK23) from cipy.integrate.solve_ivp with internal steps of 1/2, 3/4, and 1.

Body:
Is there a way to call these (or other differential equation solvers) without knowing an analytic expression for the derivative?

Yes, none of the solvers you mentioned (nor most other solvers) require an analytic expression for the derivative. Instead they call a function you supply that has to evaluate the derivative for a given time and state. So, your code would roughly look something like:

def my_derivative(time,flat_Gamma):
    Gamma = flat_Gamma.reshape(dim_1,dim_2)
    u = get_u_from_time(time)
    dGamma_dt = u.dot(Gamma)
    return dGamma_dt.flatten()

from scipy.integrate import ode
my_integrator = ode(my_derivative)
…

The difficulty in your situation is rather that you have to ensure that get_u_from_time provides an appropriate result for every time with which it is called. Probably the most robust and easy solution is to use interpolation (see the other answer).

You can also try to match your integration steps to the data you have, but at least for scipy.integrate.odeint and scipy.integrate.ode this will be very tedious as all the integrators use internal steps that are inconvenient for this purpose. For example, the fifth-order Dormand–Prince method (DoPri5) uses internal steps of 1/5, 3/10, 4/5, 8/9, and 1. This means that if you have temporally equidistant data for u, you would need 90 data points for each integration step (as 1/90 is the greatest common divisor of the internal steps). The only integrator that could make this remotely feasible is the Bogacki–Shampine integrator (RK23) from cipy.integrate.solve_ivp with internal steps of 1/2, 3/4, and 1.


问:
Why is this SQL Query causing an "Ambiguous column name" error?
I have a SQL query which fails to execute:

```<code>select p.PersonID, CreatedDate, * from dbo.Person p
join dbo.PotentiallyFraudulentPeople pfp on p.PersonID= pfp.PersonID
order by CreatedDate
</code>```

The Person table has a PK of PersonID (int). The PotentiallyFraudulentPeople view is a query of the Person table joined with some other tables to decide if we trust a person or not. The PotentiallyFraudulentPeople view only has one column: PersonID.

When I try to execute this query, I get this error:

Msg 209, Level 16, State 1, Line 3

  Ambiguous column name 'CreatedDate'.

I understand that this error is telling me that the CreatedDate column name is ambiguous and I need to preface it with my table's alias, 'p'.

This query works:

```<code>select p.PersonID, CreatedDate, * from dbo.Person p
join dbo.PotentiallyFraudulentPeople pfp on p.PersonID= pfp.PersonID
order by p.CreatedDate
</code>```

What I don't understand is why I need to use the 'p' alias in the ORDER BY statement and not in the SELECT column list. Also, I don't understand why I need to use the table alias at all since the PotentiallyFraudulentPeople view doesn't even have a CreatedDate column.

Can anyone explain this odd behavior?

I am using SQL Server 2008 and SSMS to execute the query.

UPDATE

Also, I tried removing the CreatedDate column from my SELECT column list and then the query no longer requires the 'p' alias in the ORDER BY. So this query works as well:

```<code>select p.PersonID, * from dbo.Person p
join dbo.PotentiallyFraudulentPeople pfp on p.PersonID= pfp.PersonID
order by CreatedDate
</code>```

答:
You can add an alias to "CreatedDate" and sort it using the alias</p>

```<code>select
    p.PersonID,
    CreatedDate [create_date],
    *
from
    dbo.Person p join
    dbo.PotentiallyFraudulentPeople pfp on p.PersonID= pfp.PersonID
order by
    [create_date]
</code>```

Body:
I have a SQL query which fails to execute:

select p.PersonID, CreatedDate, * from dbo.Person p
join dbo.PotentiallyFraudulentPeople pfp on p.PersonID= pfp.PersonID
order by CreatedDate

The Person table has a PK of PersonID (int). The PotentiallyFraudulentPeople view is a query of the Person table joined with some other tables to decide if we trust a person or not. The PotentiallyFraudulentPeople view only has one column: PersonID.

When I try to execute this query, I get this error:

Msg 209, Level 16, State 1, Line 3

  Ambiguous column name 'CreatedDate'.

I understand that this error is telling me that the CreatedDate column name is ambiguous and I need to preface it with my table's alias, 'p'.

This query works:

select p.PersonID, CreatedDate, * from dbo.Person p
join dbo.PotentiallyFraudulentPeople pfp on p.PersonID= pfp.PersonID
order by p.CreatedDate

What I don't understand is why I need to use the 'p' alias in the ORDER BY statement and not in the SELECT column list. Also, I don't understand why I need to use the table alias at all since the PotentiallyFraudulentPeople view doesn't even have a CreatedDate column.

Can anyone explain this odd behavior?

I am using SQL Server 2008 and SSMS to execute the query.

UPDATE

Also, I tried removing the CreatedDate column from my SELECT column list and then the query no longer requires the 'p' alias in the ORDER BY. So this query works as well:

select p.PersonID, * from dbo.Person p
join dbo.PotentiallyFraudulentPeople pfp on p.PersonID= pfp.PersonID
order by CreatedDate

Body:
You can add an alias to "CreatedDate" and sort it using the alias

select
    p.PersonID,
    CreatedDate [create_date],
    *
from
    dbo.Person p join
    dbo.PotentiallyFraudulentPeople pfp on p.PersonID= pfp.PersonID
order by
    [create_date]


问:
Using UTF-8 codes for use in intToUtf8() in R?
I'm trying to use UTF-8 code to put a symbol in some text in an R figure. If I wanted a black circle, I could use the code intToUtf8(9679). Where can I find a database that lists the values for other symbols? I want to find the code to create a red circle (i.e., pch=16, col="red"), but I can't find a list of what all of the unicode values are for specific symbols.

```<code># example R code
x <- 1:10
y1 <- rnorm(10, x*2, 0.5)
y2 <- rnorm(10, x, 0.5)
plot(x, y1, xlab='x-value', ylab='', pch=16)
points(x, y2, pch=16, col='red')
mtext(paste0('value for y1 (', intToUtf8(9679), ') and y2 (',    intToUtf8(9679), ')'), side=2, line=2)
# except that I want the second black circle in the axis label to be a red circle
</code>```

Thank you for your help,
Mikey

答:
Here is the solution I ended up using. It's not the most efficient, but it works:

```<code>x <- 1:10
y1 <- rnorm(10, x*2, 0.5)
y2 <- rnorm(10, x, 0.5)
plot(x, y1, xlab='x-value', ylab='', pch=16)
points(x, y2, pch=16, col='red')
mtext('value for y1 (\u25CF) and y2 (  )', side=2, line=2)
mtext('                                   \u25CF', side=2, line=2, col='red')

# alternatively, the following would also work in place of line 6
mtext(paste0('value for y1 (', intToUtf8(9679),' and y2 (  )'), side=2, line=2)
</code>```

If you want to find more unicode character information for your specific symbol, you can look here.

Thank you lukeA for your help with this.

Body:
I'm trying to use UTF-8 code to put a symbol in some text in an R figure. If I wanted a black circle, I could use the code intToUtf8(9679). Where can I find a database that lists the values for other symbols? I want to find the code to create a red circle (i.e., pch=16, col="red"), but I can't find a list of what all of the unicode values are for specific symbols.

# example R code
x <- 1:10
y1 <- rnorm(10, x*2, 0.5)
y2 <- rnorm(10, x, 0.5)
plot(x, y1, xlab='x-value', ylab='', pch=16)
points(x, y2, pch=16, col='red')
mtext(paste0('value for y1 (', intToUtf8(9679), ') and y2 (',    intToUtf8(9679), ')'), side=2, line=2)
# except that I want the second black circle in the axis label to be a red circle

Thank you for your help,
Mikey

Body:
Here is the solution I ended up using. It's not the most efficient, but it works:

x <- 1:10
y1 <- rnorm(10, x*2, 0.5)
y2 <- rnorm(10, x, 0.5)
plot(x, y1, xlab='x-value', ylab='', pch=16)
points(x, y2, pch=16, col='red')
mtext('value for y1 (\u25CF) and y2 (  )', side=2, line=2)
mtext('                                   \u25CF', side=2, line=2, col='red')

# alternatively, the following would also work in place of line 6
mtext(paste0('value for y1 (', intToUtf8(9679),' and y2 (  )'), side=2, line=2)

If you want to find more unicode character information for your specific symbol, you can look here.

Thank you lukeA for your help with this.


问:
Is there anyway to check if a function return nothing in Scheme?
Is there anyway to check if a function return nothing in Scheme?

For example:

```<code>(define (f1)
  (if #f #f)
)
</code>```

or

```<code>(define (f2) (values) )
</code>```

or

```<code>(define (f3) (define var 10))
</code>```

How can I check if f return nothing?

Thanks in advance.

答:
In GNU Guile the function for checking this is unspecified?:

```<code>(unspecified? (if #f #f)); returns #t
(unspecified? '()); returns #f
</code>```

Body:
Is there anyway to check if a function return nothing in Scheme?

For example:

(define (f1)
  (if #f #f)
)

or

(define (f2) (values) )

or

(define (f3) (define var 10))

How can I check if f return nothing?

Thanks in advance.

Body:
In GNU Guile the function for checking this is unspecified?:

(unspecified? (if #f #f)); returns #t
(unspecified? '()); returns #f


问:
Drag and Drop Inventory for Game in Jquery
I'm creating a game inventory for a browser based game in Ruby Rails. Now, i was trying to find some good resources on the topic but i'm unable to locate some good examples. I would like to find something about drag, drop, lock and stuff like ajax refreshing when i drag an element out of the inventory.

Do you happen to know of any good resources, or even a ready made plugin for that ?

答:
http://jqueryui.com — Drag and drop goodness, complete with all the events you need to do what you want with making AJAX calls when an item is dragged out of inventory.

AJAX is baked right into jQuery. All you need is your Rails app…


问:
Find folder of specific file
I am trying to find the folder location of a specific file, for this example libgfortran.so.

What I've tried so far is:

```<code>find 2>/dev/null / -name libgfortran.so
</code>```

... which will output something like the following to stdout (redirecting stderr to /dev/null):

```<code>/usr/lib/gcc/x86_64-linux-gnu/4.8/libgfortran.so
</code>```

From this I want to extract just the folder (without a trailing /):

```<code>/usr/lib/gcc/x86_64-linux-gnu/4.8
</code>```

I've got as far as trying something like:

```<code>find 2>/dev/null / -name libgfortran.so | sed 's/\(\/.*\/\)/\1/'
</code>```

... which I was hoping would capture what is between the first and last / (I would then need to remove the last /), but the output I get is still:

```<code>/usr/lib/gcc/x86_64-linux-gnu/4.8/libgfortran.so
</code>```

How do I achieve what I want?

答:
you can achieve this in a simpler fashion using grep:</p>

```<code>find 2>/dev/null / -name libgfortran.so | grep -o '\/.*\/'
</code>```

Title: Find folder of specific file

Body:
I am trying to find the folder location of a specific file, for this example libgfortran.so.

What I've tried so far is:

find 2>/dev/null / -name libgfortran.so

... which will output something like the following to stdout (redirecting stderr to /dev/null):

/usr/lib/gcc/x86_64-linux-gnu/4.8/libgfortran.so

From this I want to extract just the folder (without a trailing /):

/usr/lib/gcc/x86_64-linux-gnu/4.8

I've got as far as trying something like:

find 2>/dev/null / -name libgfortran.so | sed 's/\(\/.*\/\)/\1/'

... which I was hoping would capture what is between the first and last / (I would then need to remove the last /), but the output I get is still:

/usr/lib/gcc/x86_64-linux-gnu/4.8/libgfortran.so

How do I achieve what I want?

Body:
you can achieve this in a simpler fashion using grep:

find 2>/dev/null / -name libgfortran.so | grep -o '\/.*\/'


问:
Javascript Copy Text not working
I try to implement the following javascript example on my own:

https://jsfiddle.net/bt3v3rst/

I have created 2 files:

index.html

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
    <head>
        <title>Test</title>
        <script type="text/javascript" src="1.js"></script>
    </head>
    <body>
        <p>hello</p>
        <button id="copy">Copy</button>
        <button onclick="myFunction()">Click me</button>
    </body>
</html>
</code>```

1.js

```<code>// Copies a string to the clipboard. Must be called from within an event handler such as click.
// May return false if it failed, but this is not always
// possible. Browser support for Chrome 43+, Firefox 42+, Edge and IE 10+.
// No Safari support, as of (Nov. 2015). Returns false.
// IE: The clipboard feature may be disabled by an adminstrator. By default a prompt is
// shown the first time the clipboard is used (per session).
function copyToClipboard(text) {
    if (window.clipboardData && window.clipboardData.setData) {
        // IE specific code path to prevent textarea being shown while dialog is visible.
        return clipboardData.setData("Text", text);

    } else if (document.queryCommandSupported && document.queryCommandSupported("copy")) {
        var textarea = document.createElement("textarea");
        textarea.textContent = text;
        textarea.style.position = "fixed";  // Prevent scrolling to bottom of page in MS Edge.
        document.body.appendChild(textarea);
        textarea.select();
        try {
            return document.execCommand("copy");  // Security exception may be thrown by some browsers.
        } catch (ex) {
            console.warn("Copy to clipboard failed.", ex);
            return false;
        } finally {
            document.body.removeChild(textarea);
        }
    }
}

document.querySelector("#copy").onclick = function() {
    var result = copyToClipboard("longlonglongtext");
    console.log("copied?", result);
};

function myFunction()
{
    alert("Hello");
}
</code>```

The second button alert which displays "Hello" on the screen is working, the first one does not, which suppose to copy "longlonglongtext" to the keyboard.

This is not a browser issue since the example from jsfiddle works perfectly with my firefox 47.

What can be the problem?

答:
Problem: The way you are trying to define event handler for "copy" button  in javascript (1.js file) before element is rendered or available.

```<code>document.querySelector("#copy").onclick = function() {
    var result = copyToClipboard("longlonglongtext");
    console.log("copied?", result);
};
</code>```

You can solve this problem different ways.

Solution 1: Move script tag which references 1.js file before the end of body tag.

```<code><script type="text/javascript" src="1.js"></script>
</code>```

e.g.

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
    <head>
        <title>Test</title>
    </head>
    <body>
        <p>hello</p>
        <button id="copy">Copy</button>
        <button onclick="myFunction()">Click me</button>
        <script type="text/javascript" src="1.js"></script>
    </body>
</html>
</code>```

Solution 2: Make use of "DOMContentLoaded" event listner

e.g.

```<code>document.addEventListener("DOMContentLoaded", function(event) {
    document.querySelector("#copy").onclick = function() {
        var result = copyToClipboard("longlonglongtext");
        console.log("copied?", result);
    };
})
</code>```

Title: Javascript Copy Text not working

Body:
I try to implement the following javascript example on my own:

https://jsfiddle.net/bt3v3rst/

I have created 2 files:

index.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

        <title>Test</title>

hello

        <button id="copy">Copy</button>
        <button onclick="myFunction()">Click me</button>

1.js

// Copies a string to the clipboard. Must be called from within an event handler such as click.
// May return false if it failed, but this is not always
// possible. Browser support for Chrome 43+, Firefox 42+, Edge and IE 10+.
// No Safari support, as of (Nov. 2015). Returns false.
// IE: The clipboard feature may be disabled by an adminstrator. By default a prompt is
// shown the first time the clipboard is used (per session).
function copyToClipboard(text) {
    if (window.clipboardData && window.clipboardData.setData) {
        // IE specific code path to prevent textarea being shown while dialog is visible.
        return clipboardData.setData("Text", text);

    } else if (document.queryCommandSupported && document.queryCommandSupported("copy")) {
        var textarea = document.createElement("textarea");
        textarea.textContent = text;
        textarea.style.position = "fixed";  // Prevent scrolling to bottom of page in MS Edge.
        document.body.appendChild(textarea);
        textarea.select();
        try {
            return document.execCommand("copy");  // Security exception may be thrown by some browsers.
        } catch (ex) {
            console.warn("Copy to clipboard failed.", ex);
            return false;
        } finally {
            document.body.removeChild(textarea);
        }
    }
}

document.querySelector("#copy").onclick = function() {
    var result = copyToClipboard("longlonglongtext");
    console.log("copied?", result);
};

function myFunction()
{
    alert("Hello");
}

The second button alert which displays "Hello" on the screen is working, the first one does not, which suppose to copy "longlonglongtext" to the keyboard.

This is not a browser issue since the example from jsfiddle works perfectly with my firefox 47.

What can be the problem?

Body:
Problem: The way you are trying to define event handler for "copy" button  in javascript (1.js file) before element is rendered or available.

document.querySelector("#copy").onclick = function() {
    var result = copyToClipboard("longlonglongtext");
    console.log("copied?", result);
};

You can solve this problem different ways.

Solution 1: Move script tag which references 1.js file before the end of body tag.

<script type="text/javascript" src="1.js"></script>

e.g.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
    <head>
        <title>Test</title>
    </head>
    <body>
        <p>hello</p>
        <button id="copy">Copy</button>
        <button onclick="myFunction()">Click me</button>
        <script type="text/javascript" src="1.js"></script>
    </body>
</html>

Solution 2: Make use of "DOMContentLoaded" event listner

e.g.

document.addEventListener("DOMContentLoaded", function(event) {
    document.querySelector("#copy").onclick = function() {
        var result = copyToClipboard("longlonglongtext");
        console.log("copied?", result);
    };
})


问:
pyodbc not committing changes to db2 database
I am trying to update my db2 database using pyodbc in python. The sql statement runs normally without errors on the database directly. when I run the code below, I get no errors and the code executes successfully but when I query the database, the changes did not save.

```<code>try:
    conn2 = pyodbc.connect("DRIVER={iSeries Access ODBC Driver};SYSTEM="+ Config_Main.iseriesServer +";DATABASE="+ Config_Main.iseriesDB +";UID="+ Config_Main.iseriesUser +";PWD=" + Config_Main.iseriesPass)
    db2 = conn2.cursor()

    for row in encludeData:
        count = len(str(row[2]))
        srvid = row[2]
        if count < 10:
            sql3 = "UPDATE SVCEN2DEV.SRVMAST SET svbrch = ? WHERE svtype != '*DCS-' AND svacct = ? AND svcid LIKE '%?' and svbrch = ?"
            db2.execute(sql3, (row[4],row[1],"%" + str(srvid),row[5]))
        else:
            sql3 = "UPDATE SVCEN2DEV.SRVMAST SET svbrch = ? WHERE svtype != '*DCS-' AND svacct = ? AND svcid = ? and svbrch = ?"
            db2.execute(sql3, (row[4],row[1],srvid,row[5]))
        conn2.commit()
except pyodbc.Error as e:
    logging.error(e)
</code>```

I have tried setting conn2.autocommit = True. and I have also tried moving the conn2.commit() inside of the for loop to commit after each iteration. I also tried a different driver {IBM i Access ODBC Driver}

EDIT:

Sample of encludeData

```<code>['4567890001','4567890001','1234567890','1234567890','foo','bar']
</code>```

After changing the except statement to grab general errors, the code above now produces this error:

IntegrityError('23000', '[23000] [IBM][System i Access ODBC Driver][DB2 for i5/OS]SQL0803 - Duplicate key value specified. (-803) (SQLExecDirectW)')

答:
As OP found out, the application layer language, Python, may not raise specific database exceptions such as duplicate index or foreign key issues and hence will silently fail or will be logged on server side. Usually errors that affect actual SQL queries to run like incorrect identifiers and syntax errors will raise an error on client side.

Therefore, as best practice in programming it is necessary to use exception handling like Python's try/except/finally or the equivalent in other general purpose languages that interface with any external API like database connections in order to catch and properly handle runtime issues.

Below will print any exception on statements raised in the try block including connection and query execution. And regardless of success or fail will run the finally statements.

```<code>try:
    conn2 = pyodbc.connect(...)
    db2 = conn2.cursor()

    sql = "..."
    db2.execute(sql, params)
    conn2.commit()

except Exception as e:
    print(e)

finally:
    db2.close()
    conn2.close()
</code>```

Body:
I am trying to update my db2 database using pyodbc in python. The sql statement runs normally without errors on the database directly. when I run the code below, I get no errors and the code executes successfully but when I query the database, the changes did not save.

try:
    conn2 = pyodbc.connect("DRIVER={iSeries Access ODBC Driver};SYSTEM="+ Config_Main.iseriesServer +";DATABASE="+ Config_Main.iseriesDB +";UID="+ Config_Main.iseriesUser +";PWD=" + Config_Main.iseriesPass)
    db2 = conn2.cursor()

    for row in encludeData:
        count = len(str(row[2]))
        srvid = row[2]
        if count < 10:
            sql3 = "UPDATE SVCEN2DEV.SRVMAST SET svbrch = ? WHERE svtype != '*DCS-' AND svacct = ? AND svcid LIKE '%?' and svbrch = ?"
            db2.execute(sql3, (row[4],row[1],"%" + str(srvid),row[5]))
        else:
            sql3 = "UPDATE SVCEN2DEV.SRVMAST SET svbrch = ? WHERE svtype != '*DCS-' AND svacct = ? AND svcid = ? and svbrch = ?"
            db2.execute(sql3, (row[4],row[1],srvid,row[5]))
        conn2.commit()
except pyodbc.Error as e:
    logging.error(e)

I have tried setting conn2.autocommit = True. and I have also tried moving the conn2.commit() inside of the for loop to commit after each iteration. I also tried a different driver {IBM i Access ODBC Driver}

EDIT:

Sample of encludeData

['4567890001','4567890001','1234567890','1234567890','foo','bar']

After changing the except statement to grab general errors, the code above now produces this error:

IntegrityError('23000', '[23000] [IBM][System i Access ODBC Driver][DB2 for i5/OS]SQL0803 - Duplicate key value specified. (-803) (SQLExecDirectW)')

Body:
As OP found out, the application layer language, Python, may not raise specific database exceptions such as duplicate index or foreign key issues and hence will silently fail or will be logged on server side. Usually errors that affect actual SQL queries to run like incorrect identifiers and syntax errors will raise an error on client side.

Therefore, as best practice in programming it is necessary to use exception handling like Python's try/except/finally or the equivalent in other general purpose languages that interface with any external API like database connections in order to catch and properly handle runtime issues.

Below will print any exception on statements raised in the try block including connection and query execution. And regardless of success or fail will run the finally statements.

try:
    conn2 = pyodbc.connect(...)
    db2 = conn2.cursor()

    sql = "..."
    db2.execute(sql, params)
    conn2.commit()

except Exception as e:
    print(e)

finally:
    db2.close()
    conn2.close()


问:
WiX Upgrade without uninstallation of existing version
The MajorUpgrade element in WiX seems to be uninstalling the existing version. But I have a requirement wherein I have to upgrade from 1.0.0 to 2.0.0 without uninstalling 1.0.0. But this doesn't mean, it will have both 1.0.0 and 2.0.0 showing in the Add/Remove Programs. My 1.0.0 version has a file, a registry entry, a custom windows service and so on. My 2.0.0 essentially, will modify an existing file and add a new file. In our case, it is possible to make only changes like these and still increment the major version. But for this, I don't want to uninstall and reinstall the services and so on. But if it's a fresh install, all the components will have to be installed. For example, if a customer has 7.9.0 version installed and wants to upgrade to 8.0.0 (This technically might be a major upgrade because major version is updated or minor upgrade because there may be only incremental changes going from 7.9.0 to 8.0.0?), uninstalling 7.9.0 completely may lead to issues like loss of data and so on. Is there a way to achieve this? If so, can anyone please provide some steps / examples or provide some links showing this? Note: I am not talking about Patch. I am able to get a patch working. But I am also confused between Minor upgrade and Small update.

FireGiant's Tutorial talks about using <Upgrade> element whereas there are many other articles which talk about using <MajorUpgrade> element.

答:
jbudreau is correct. There are two different types of major upgrades. The early major upgrade uninstalls the existing version prior to installing the new version. This is the behavior you explain in your post.

Look at the execute sequence table and move the RemoveExistingProducts action to after InstallFinalize and this will now become the late upgrade, where it overwrites existing files using component rules and then remove any files that should be removed.


问:
How can I give access to certain objects in Firebase database based on id
I have this data structure:

The red arrows points at animal IDs, and the blue arrow points at user IDs. Every user have one or many animals.

I have tried different methods for showing only the animals that have id that is stored in the current user node.

Example: If I have UID = 48onHXIxgDP465j5WW16oo7psNm2 (the first one in "users") I want to show the data from: "dog2" and "dog3".

Now iIhave the following code that gets snapshot from the "animals" node in the database, and then gets data from every child.

```<code>     myAnimalRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            list = new ArrayList<AnimalCard>();
            for(DataSnapshot dataSnapshot1 :dataSnapshot.getChildren()){

                AnimalCard value = dataSnapshot1.getValue(AnimalCard.class);
                AnimalCard animal = new AnimalCard();
                String name = value.getName();
                int age = value.getAge();
                String url = value.getUrl();
                animal.setName(name);
                animal.setAge(age);
                animal.setUrl(url);
                list.add(animal);

            }
            recyclerViewSetAdapter();
            progressDialog.dismiss();

        }
        @Override
        public void onCancelled(DatabaseError databaseError) {
            Log.d(TAG1, "failed to read value: " + databaseError.toException());
        }
    });
</code>```

How can get my code to filter out every animal that does not have their ID in the user node?

The reason I want to make the user get access with an UID stored in the database is because later on I want to make it so that multiple users can get access to the same animal.

答:
I ended up taking Alex Mamo's answer and tweak with a litte bit.

This is the code i'am using:

```<code>       uid = currentUser.getUid();
    mRootRef = FirebaseDatabase.getInstance().getReference();
    final DatabaseReference myUserRef = mRootRef.child("users").child(uid);

    Log.d(TAG1, uid);

    myUserRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            list = new ArrayList<AnimalCard>();
            for(DataSnapshot ds : dataSnapshot.getChildren()){
                String aid = ds.getKey();

                DatabaseReference myAnimalRef = mRootRef.child("animals");

                Query query = myAnimalRef.orderByKey().equalTo(aid);
                query.addValueEventListener(new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {
                        for (DataSnapshot ds2 : dataSnapshot.getChildren()){

                            AnimalCard value = ds2.getValue(AnimalCard.class);
                            AnimalCard animal = new AnimalCard();
                            String name = value.getName();
                            int age = value.getAge();
                            String url = value.getUrl();
                            animal.setName(name);
                            animal.setAge(age);
                            animal.setUrl(url);
                            list.add(animal);

                        }
                        recyclerViewSetAdapter();
                        progressDialog.dismiss();
                    }
                    @Override
                    public void onCancelled(DatabaseError databaseError) {

                    }
                });
            }

        }
        @Override
        public void onCancelled(DatabaseError databaseError) {
        }

    });
</code>```

The main difference is that i'am using a query to filter out every Animal that does not have the aID that the currentUser have.

Body:
I have this data structure:

The red arrows points at animal IDs, and the blue arrow points at user IDs. Every user have one or many animals.

I have tried different methods for showing only the animals that have id that is stored in the current user node.

Example: If I have UID = 48onHXIxgDP465j5WW16oo7psNm2 (the first one in "users") I want to show the data from: "dog2" and "dog3".

Now iIhave the following code that gets snapshot from the "animals" node in the database, and then gets data from every child.

     myAnimalRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            list = new ArrayList<AnimalCard>();
            for(DataSnapshot dataSnapshot1 :dataSnapshot.getChildren()){

                AnimalCard value = dataSnapshot1.getValue(AnimalCard.class);
                AnimalCard animal = new AnimalCard();
                String name = value.getName();
                int age = value.getAge();
                String url = value.getUrl();
                animal.setName(name);
                animal.setAge(age);
                animal.setUrl(url);
                list.add(animal);

            }
            recyclerViewSetAdapter();
            progressDialog.dismiss();

        }
        @Override
        public void onCancelled(DatabaseError databaseError) {
            Log.d(TAG1, "failed to read value: " + databaseError.toException());
        }
    });

How can get my code to filter out every animal that does not have their ID in the user node?

The reason I want to make the user get access with an UID stored in the database is because later on I want to make it so that multiple users can get access to the same animal.

Body:
I ended up taking Alex Mamo's answer and tweak with a litte bit.

This is the code i'am using:

       uid = currentUser.getUid();
    mRootRef = FirebaseDatabase.getInstance().getReference();
    final DatabaseReference myUserRef = mRootRef.child("users").child(uid);

    Log.d(TAG1, uid);

    myUserRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            list = new ArrayList<AnimalCard>();
            for(DataSnapshot ds : dataSnapshot.getChildren()){
                String aid = ds.getKey();

                DatabaseReference myAnimalRef = mRootRef.child("animals");

                Query query = myAnimalRef.orderByKey().equalTo(aid);
                query.addValueEventListener(new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {
                        for (DataSnapshot ds2 : dataSnapshot.getChildren()){

                            AnimalCard value = ds2.getValue(AnimalCard.class);
                            AnimalCard animal = new AnimalCard();
                            String name = value.getName();
                            int age = value.getAge();
                            String url = value.getUrl();
                            animal.setName(name);
                            animal.setAge(age);
                            animal.setUrl(url);
                            list.add(animal);

                        }
                        recyclerViewSetAdapter();
                        progressDialog.dismiss();
                    }
                    @Override
                    public void onCancelled(DatabaseError databaseError) {

                    }
                });
            }

        }
        @Override
        public void onCancelled(DatabaseError databaseError) {
        }

    });

The main difference is that i'am using a query to filter out every Animal that does not have the aID that the currentUser have.


问:
Entity Framework: Select new attributes inside include
Let's say, I have an Entity called Solutions which has multiple multimedia. I want to query Solutions and retrieve their list of multimedia, but I also want to Select only some fields and infer others from each of those multimedia such as follow:

```<code>IQueryable<Solution> result = db.Solutions
                .Include(s => s.Multimedia.Select(m => new MultimediaViewModel(){
                    ID = m.ID,
                    Name = m.Name,
                    Path = m.Path,
                    Preview = MultimediasController.ConvertVideo(m),
                    Extension = MultimediasController.GetExtension(m),
                    Type = m.Type
                }))
</code>```

The following gives the System.ArgumentException exception with the message: "The Include path expression must refer to a navigation property defined on the type. Use dotted paths for reference navigation properties and the Select operator for collection navigation properties."

How is this achievable?

expected response would be something like this:

```<code>[
    {
        "id": 2,
        "title": "Example",
        "subTitle": "Example 1",
        "multimedia": [
            {
                "id": 27,
                "name": "teste",
                "path": "/Upload_Public/Solution/27_.mp4",
                "preview": "/Upload_Public/Solution/27_preview.jpg",
                "extension": "mp4",
                "type": 0,
            }
        ],
    }
]
</code>```

答:
You do not need to use .Include for this. Just create an anonymous object and select off the properties you want.

```<code>IQueryable<Solution> result = db.Solutions
    .Select(s => new {
        s.Id,
        s.Title,
        s.Subtitle,
        Multimedia = new
        {
            s.Multimedia.ID,
            s.Multimedia.Name,
            s.Multimedia.Path,
            Preview = MultimediasController.ConvertVideo(m),
            Extension = MultimediasController.GetExtension(m),
            s.Multimedia.Type,
        }
    });
</code>```

However, the method calls will likely result in a run-time error because the whole statement needs to be evaluated in the database. I'm not sure what those methods do, but you may have to bring back raw data and then extract the required info once the data is on the client.

Body:
Let's say, I have an Entity called Solutions which has multiple multimedia. I want to query Solutions and retrieve their list of multimedia, but I also want to Select only some fields and infer others from each of those multimedia such as follow:

IQueryable<Solution> result = db.Solutions
                .Include(s => s.Multimedia.Select(m => new MultimediaViewModel(){
                    ID = m.ID,
                    Name = m.Name,
                    Path = m.Path,
                    Preview = MultimediasController.ConvertVideo(m),
                    Extension = MultimediasController.GetExtension(m),
                    Type = m.Type
                }))

The following gives the System.ArgumentException exception with the message: "The Include path expression must refer to a navigation property defined on the type. Use dotted paths for reference navigation properties and the Select operator for collection navigation properties."

How is this achievable?

expected response would be something like this:

[
    {
        "id": 2,
        "title": "Example",
        "subTitle": "Example 1",
        "multimedia": [
            {
                "id": 27,
                "name": "teste",
                "path": "/Upload_Public/Solution/27_.mp4",
                "preview": "/Upload_Public/Solution/27_preview.jpg",
                "extension": "mp4",
                "type": 0,
            }
        ],
    }
]

Body:
You do not need to use .Include for this. Just create an anonymous object and select off the properties you want.

IQueryable<Solution> result = db.Solutions
    .Select(s => new {
        s.Id,
        s.Title,
        s.Subtitle,
        Multimedia = new
        {
            s.Multimedia.ID,
            s.Multimedia.Name,
            s.Multimedia.Path,
            Preview = MultimediasController.ConvertVideo(m),
            Extension = MultimediasController.GetExtension(m),
            s.Multimedia.Type,
        }
    });

However, the method calls will likely result in a run-time error because the whole statement needs to be evaluated in the database. I'm not sure what those methods do, but you may have to bring back raw data and then extract the required info once the data is on the client.


问:
NHibernate Linq .Where(x => x.Kind == (byte)criteria.Value) does not work
The fallowing was working with NHibernate 2.1. Now with NHibernate 3 it doesn't.
I have a Table with Column Kind, which has the fallowing Mapping:

Now, when I try do with Linq

.Where(x => x.Kind == (byte)criteria.Value)

where criteria.Value is a byte-Value, I get a InvalidCastException:(could not execute query
[ select ... from ProjectType projecttyp0_ where projecttyp0_.Kind=? order by projecttyp0_.Name asc ]
  Name:p1 - Value:0 ) --->

bei NHibernate.Type.ByteType.Set(IDbCommand cmd, Object value, Int32 index) in d:\CSharp\NH\nhibernate\src\NHibernate\Type\ByteType.cs:Zeile 44.
   bei NHibernate.Type.NullableType.NullSafeSet(IDbCommand cmd, Object value, Int32 index) in d:\CSharp\NH\nhibernate\src\NHibernate\Type\NullableType.cs:Zeile 180.
   bei NHibernate.Type.NullableType.NullSafeSet(IDbCommand st, Object value, Int32 index, ISessionImplementor session) in d:\CSharp\NH\nhibernate\src\NHibernate\Type\NullableType.cs:Zeile 139.
   bei NHibernate.Engine.QueryParameters.BindParameters(IDbCommand command, Int32 start, ISessionImplementor session) in d:\CSharp\NH\nhibernate\src\NHibernate\Engine\QueryParameters.cs:Zeile 638.

Does I have to change something?

Thanks for your help.

Best Regards, Thomas

答:
What type is criteria.Value?

Try replacing (byte)criteria.Value with Convert.ToByte(criteria.Value)