问:
 in ASP.net MVC
I know that similar questions have been asked A LOT but none of the answers have been any help to me yet. Pretty much, I am working with an MVC project and a CL project someone else created from a former desktop app that was actually supposed to be a web app (long and frustrating story). He made it so an image generated programatically is stored on the User's C:/ drive and then later displayed, which works fine in a desktop app, but not so much in a web app.

I have tried the , but no luck. I know that I wouldn't be able to get to a file on a user's C:/ drive directly and should upload the image to the server and then go from there, but I have no idea how to go about that, and was hoping that someone could point me in the right direction.

答:
Assuming you store your image as:

```<code>public byte[] MyImage { get; set; }
</code>```

You can pass it to the view:

```<code>public ActionResult Index()
{
    ViewBag.MyImage = Convert.ToBase64String(MyImage);
    return View();
}
</code>```

In your view display it like:

```<code><img src="data:image/png;base64,@ViewBag.MyImage" />
</code>```

Title: <img src="C:/Some_File"> in ASP.net MVC

Body:
Assuming you store your image as:

public byte[] MyImage { get; set; }

You can pass it to the view:

public ActionResult Index()
{
    ViewBag.MyImage = Convert.ToBase64String(MyImage);
    return View();
}

In your view display it like:

<img src="data:image/png;base64,@ViewBag.MyImage" />


来源: stackexchange

问:
Knuth Morris Pratt algorithm implementation
I'm trying to implement KMP algorithm. Part "if (W[i] == S[m + i])" returns index out of range exception and I can't get it to work.

I was following example on Wikipedia: https://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm

```<code>static int[] KMPTable(string W)
    {
        int[] T = new int[W.Length];
        int pos = 2;
        int cnd = 0;

        T[0] = -1;
        T[1] = 0;

        while (pos < W.Length)
        {
            if (W[pos - 1] == W[cnd])
            {
                T[pos] = cnd + 1;
                cnd = cnd + 1;
                pos = pos + 1;
            }
            else
                if (cnd > 0)
                {
                    cnd = T[cnd];
                }
                else
                {
                    T[pos] = 0;
                    pos = pos + 1;
                }
        }

        return T;
    }

    static int[] KMPSearch(string S, string W)
    {
        int m = 0;
        int i = 0;
        int[] kmpNext = KMPTable(S);
        List<int> result = new List<int>();

        while (m + i < S.Length)
        {
            if (W[i] == S[m + i])
            {
                if (i == W.Length - 1)
                {
                    result.Add(m);
                }
                    i = i + 1;
            }
            else
            {
                m = m + i - kmpNext[i];
                if (kmpNext[i] > -1)
                    i = kmpNext[i];
                else
                    i = 0;
            }
        }
        return result.ToArray();
    }
</code>```

答: When m + i < S.Length, then it might be W[i] that is out of its index. Try checking with a step-by-step debug.</p>

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to implement KMP algorithm. Part "if (W[i] == S[m + i])" returns index out of range exception and I can't get it to work.

I was following example on Wikipedia: https://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm

static int[] KMPTable(string W)
    {
        int[] T = new int[W.Length];
        int pos = 2;
        int cnd = 0;

        T[0] = -1;
        T[1] = 0;

        while (pos < W.Length)
        {
            if (W[pos - 1] == W[cnd])
            {
                T[pos] = cnd + 1;
                cnd = cnd + 1;
                pos = pos + 1;
            }
            else
                if (cnd > 0)
                {
                    cnd = T[cnd];
                }
                else
                {
                    T[pos] = 0;
                    pos = pos + 1;
                }
        }

        return T;
    }

    static int[] KMPSearch(string S, string W)
    {
        int m = 0;
        int i = 0;
        int[] kmpNext = KMPTable(S);
        List<int> result = new List<int>();

        while (m + i < S.Length)
        {
            if (W[i] == S[m + i])
            {
                if (i == W.Length - 1)
                {
                    result.Add(m);
                }
                    i = i + 1;
            }
            else
            {
                m = m + i - kmpNext[i];
                if (kmpNext[i] > -1)
                    i = kmpNext[i];
                else
                    i = 0;
            }
        }
        return result.ToArray();
    }


问:
Where to define C++ class member template function and functors that instantiate it?
I have a class Foo which is used in a small standalone project. It has a class definition in Foo.h with the implementation for the class' member functions in an implementation file Foo.cpp.

First question - one of the member functions of class Foo is a template method Foo::doSomething(), is it correct that the implementation of this method should appear with the declaration of the function in Foo.h ?

The template parameter which Foo::doSomething() will be instantiated with is one of two Functor types - class CalcA and CalcB.

Should I:

(A) put the defintion and implementation of the two Functor classes all together in Foo.cpp (where they are actually used by the implementation of other Foo member functions to call Foo::doSomething).

(B) put the definition and implementation of the two Functor classes in Foo.h.

(C) should I put split the definition and implementation of the two Functors across Foo.h and Foo.cpp as would be done with an ordinary class?

答:
General rule:

If foo::doSomething() is used outside foo.cpp (i.e. if it's public or protected, usually), it must go in the header.

If not, putting in in the cpp file is perfectly ok, and even a good idea (as it keeps the clutter away from the header file).

So, if the functors are only used in the cpp file, by all means put the template function there too. One can always refactor things later if this changes.

ContentLicense: CC BY-SA 2.5


问:
Testing if an Array is empty JUNIT
I wanna write a Method displaying a deck from a Game.
I initialized an Array with 98 Elements

```<code>private int [] cards = new int[98];
</code>```

I also created a get and a set method

```<code>public int[] getCards() {
    return cards;
}
</code>```

and

```<code>public void setCards(final int... cards) {
    this.cards = cards;
}
</code>```

The Method I wrote is called drawCard. If I use this method it should remove the first element out of the Array and return it.

```<code>public int drawCard() throws IndexOutOfBoundsException {
    if (getCards().length == 0) {
        throw new IndexOutOfBoundsException("No Cards Left!");
    }
    setCards(ArrayUtils.removeElement(getCards(), 0));
    return getCards()[0];
}
</code>```

And then I wrote the JUnit Test.
The test should remove all the 98 elements and then the array should be empty == 0.
But the test always stops at 1.

```<code>@Test
public void testDrawCard() {
    Deck deck = new Deck();
    assertThat(deck.getCards().length).isEqualTo(98);

    for(int x = 98; x >= 0; x--){
        deck.drawCard();
    }
    assertThat(deck.getCards().length).isEqualTo(0);
}
</code>```

Error message:

```<code>java.lang.ArrayIndexOutOfBoundsException: 0
at edu.hm.hafner.java2.thegame.Deck.drawCard(Deck.java:35)
</code>```

35=Return Line

```<code>at edu.hm.hafner.java2.thegame.DeckTest.testDrawCard(DeckTest.java:40)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:237)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
</code>```

Does somebody know what's wrong?

答:
@ajb is right, but when you want to normally iterate backwards, you start with length - 1 because indices start with 0. So in your style, the loop should be

```<code>for(int x = 98 - 1; x >= 0; x--)
</code>```

But however, you aren't using the x variable inside the loop, so the order should not matter as long as you are drawing exactly 98 elements.

Title: Testing if an Array is empty JUNIT

Body:
I wanna write a Method displaying a deck from a Game.
I initialized an Array with 98 Elements

private int [] cards = new int[98];

I also created a get and a set method

public int[] getCards() {
    return cards;
}

and

public void setCards(final int... cards) {
    this.cards = cards;
}

The Method I wrote is called drawCard. If I use this method it should remove the first element out of the Array and return it.

public int drawCard() throws IndexOutOfBoundsException {
    if (getCards().length == 0) {
        throw new IndexOutOfBoundsException("No Cards Left!");
    }
    setCards(ArrayUtils.removeElement(getCards(), 0));
    return getCards()[0];
}

And then I wrote the JUnit Test.
The test should remove all the 98 elements and then the array should be empty == 0.
But the test always stops at 1.

@Test
public void testDrawCard() {
    Deck deck = new Deck();
    assertThat(deck.getCards().length).isEqualTo(98);

    for(int x = 98; x >= 0; x--){
        deck.drawCard();
    }
    assertThat(deck.getCards().length).isEqualTo(0);
}

Error message:

java.lang.ArrayIndexOutOfBoundsException: 0
at edu.hm.hafner.java2.thegame.Deck.drawCard(Deck.java:35)

35=Return Line

at edu.hm.hafner.java2.thegame.DeckTest.testDrawCard(DeckTest.java:40)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:237)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

Does somebody know what's wrong?

Body:
@ajb is right, but when you want to normally iterate backwards, you start with length - 1 because indices start with 0. So in your style, the loop should be

for(int x = 98 - 1; x >= 0; x--)

But however, you aren't using the x variable inside the loop, so the order should not matter as long as you are drawing exactly 98 elements.


问:
How to pass a .txt file as an argument for a function in a different cpp
```<code>int main()
{
    fstream file;
    file.open("new_file.txt" , ios::app);
    if (!file.is_open()){
        cout << "File does not exist yet !\n";
        return 1;
    }
    string input;
    cout << "Add new line or edit? Write NEW or EDIT";
    cin >> input;
    if (input == "NEW")
    {
        add_new_info();
    }
    //.....
}
</code>```

In another cpp I have:

```<code>int add_new_info()
{
    string aux;
    int count;
    cout << "Add line ID \n";
    cin >> aux;
    file << aux << "; ";
    //...
}
</code>```

So basically I want to open the txt file in main and then pass it on to the add_new_info(). How do I pass a txt file as an argument to a function in another .cpp ?

答:
You can just pass a reference to the open file

```<code>int add_new_info(fstream& file)
{
    // add info to the file

}
</code>```

and at the call in main

```<code>add_new_info(file);
</code>```

And like zett42 mentions in the comments, if the function doesn't use anything specific to file streams, using a parameter std::ostream& would allow the use of the function for other types of streams as well, like add_new_info(cout); to display the info at the console.

Body:
int main()
{
    fstream file;
    file.open("new_file.txt" , ios::app);
    if (!file.is_open()){
        cout << "File does not exist yet !\n";
        return 1;
    }
    string input;
    cout << "Add new line or edit? Write NEW or EDIT";
    cin >> input;
    if (input == "NEW")
    {
        add_new_info();
    }
    //.....
}

In another cpp I have:

int add_new_info()
{
    string aux;
    int count;
    cout << "Add line ID \n";
    cin >> aux;
    file << aux << "; ";
    //...
}

So basically I want to open the txt file in main and then pass it on to the add_new_info(). How do I pass a txt file as an argument to a function in another .cpp ?

Body:
You can just pass a reference to the open file

int add_new_info(fstream& file)
{
    // add info to the file

}

and at the call in main

add_new_info(file);

And like zett42 mentions in the comments, if the function doesn't use anything specific to file streams, using a parameter std::ostream& would allow the use of the function for other types of streams as well, like add_new_info(cout); to display the info at the console.


问:
Javascript var vs let (de)optimization/slowdown issue in v8 and SpiderMonkey
During JavaScript code refactoring in my project I've found that some of my loops slowed down drastically. Searching for root cause I've found this SO question stating slowdown is caused by let statement inside for loop and closure creation.
To my surprise moving let and closure out of the for loop didn't help, and even using var instead of let for loop variable also does not help because slowdown is caused by let placed after thefor loop.
By removing extra details I've obtained this code snippet:

"use strict"
console.log("=========================");
(function(){
    var itr = 0;
    function f(){++itr;}
    console.time('without_let');
    for(var i = 0; i < 50000000; ++i){
        f();
    }
    var totals = 0;
    console.timeEnd('without_let'); //chrome: 122ms, FF:102ms
})();

(function(){
    var itr = 0;
    function f(){++itr;}
    console.time('let_below');
    for(var i = 0; i < 50000000; ++i){
        f();
    }
    let totals = 0; // <--- notice let instead of var
    console.timeEnd('let_below'); //chrome: 411ms, FF:99ms
})();

(function(){
    let itr = 0;
    function f(){++itr;}
    console.time('let_above_and_in_loop');
    for(let i = 0; i < 50000000; ++i){
        f();
    }
    var totals = 0;
    console.timeEnd('let_above_and_in_loop'); //chrome: 153ms, FF:899ms
})();

(function(){
    var itr = 0;
    function f(){++itr;}
    console.time('let_in_loop');
    for(let i = 0; i < 50000000; ++i){
        f();
    }
    var totals = 0;
  console.timeEnd('let_in_loop'); //chrome: 137ms, FF:102ms
})();```
</div>
</div>
</p>

<p>(also on JS Fiddle Note: using JS Fiddle shows little bit different results but similar slowdown is still present in the same places)</p>

<p>Running this on Chrome produces following</p>

``` without_let: 122ms
 let_below: 411ms <----------- Slowdown for v8
 let_above_and_in_loop: 153ms
 let_in_loop: 137ms
```

<p>Some googling brought me to the article stating that <code>let</code> caused deoptimization prior to Chrome 56 / V8 5.6! but my chrome is 57.0.2987.133 (64-bit) and v8 ver 5.7.492.71.
More surprises trying to run this on Firefox 52.0.2 (32-bit). Here we have slowdown in another place, when variable created with <code>let</code> is used inside closure:</p>

``` without_let: 101.9ms
 let_below: 99ms
 let_above_and_in_loop: 899ms <----- Slowdown for SpiderMonkey
 let_in_loop: 102ms
```

<p>As I see the issue is somewhat related to so called "Temporal Dead Zone" feature, but still unclear:</p>

<ol>
<li><p>Why two major browsers (major JavaScript engines) still cannot optimize those (different) parts of the snippet?</p></li>
<li><p>Are there any workarounds to keep using <code>let</code> (<em>except</em> using Babel to turn let into var)? Assume I'm able to pass options to Chrome or even directly to v8 via <code>v8::V8::SetFlagsFromCommandLine(&argc, argv, true);</code></p></li>
</ol>

<p><strong>UPD:</strong>
In Chrome ver 58.0.3029.96, correspondng v8 version 5.8.283.37 (aconding to https://omahaproxy.appspot.com/) after enabling chrome://flags/#enable-v8-future as jmrk suggested below there is still slowdown for third case (now 2 times instead of 8 times)</p>

```without_let: 157.000ms
let_below: 155.000ms
let_above_and_in_loop: 304.000ms
let_in_loop: 201.000ms
```

<p>Firefox 53.0 (32bit)</p>

```without_let: 278.650ms
let_below: 310.290ms
let_above_and_in_loop: 848.325ms
let_in_loop: 275.495ms
```

答:
I can answer the V8 part of the question. The slowdown you're seeing is due to a limitation in the old optimizing compiler (known as "Crankshaft"). It hasn't been addressed in all this time because the team has been busy working on the new optimizing compiler ("Turbofan"), which is shipping in Chrome 59 (currently on the Canary and Dev channels, soon on Beta!).

In Chrome 58 (currently on Beta), you can already get a preview by setting the "Experimental JavaScript Compilation Pipeline" to "Enabled" (at chrome://flags/#enable-v8-future). Note that Chrome 59 will have a couple of additional performance improvements.

Side note: in an existing codebase, there isn't much benefit in migrating to let, so you could just keep using var.

Body:
During JavaScript code refactoring in my project I've found that some of my loops slowed down drastically. Searching for root cause I've found this SO question stating slowdown is caused by let statement inside for loop and closure creation.
To my surprise moving let and closure out of the for loop didn't help, and even using var instead of let for loop variable also does not help because slowdown is caused by let placed after thefor loop.
By removing extra details I've obtained this code snippet:

"use strict"
console.log("=========================");
(function(){
    var itr = 0;
    function f(){++itr;}
    console.time('without_let');
    for(var i = 0; i < 50000000; ++i){
        f();
    }
    var totals = 0;
    console.timeEnd('without_let'); //chrome: 122ms, FF:102ms
})();

(function(){
    var itr = 0;
    function f(){++itr;}
    console.time('let_below');
    for(var i = 0; i < 50000000; ++i){
        f();
    }
    let totals = 0; // <--- notice let instead of var
    console.timeEnd('let_below'); //chrome: 411ms, FF:99ms
})();

(function(){
    let itr = 0;
    function f(){++itr;}
    console.time('let_above_and_in_loop');
    for(let i = 0; i < 50000000; ++i){
        f();
    }
    var totals = 0;
    console.timeEnd('let_above_and_in_loop'); //chrome: 153ms, FF:899ms
})();

(function(){
    var itr = 0;
    function f(){++itr;}
    console.time('let_in_loop');
    for(let i = 0; i < 50000000; ++i){
        f();
    }
    var totals = 0;
  console.timeEnd('let_in_loop'); //chrome: 137ms, FF:102ms
})();

(also on JS Fiddle Note: using JS Fiddle shows little bit different results but similar slowdown is still present in the same places)

Running this on Chrome produces following

 without_let: 122ms
 let_below: 411ms <----------- Slowdown for v8
 let_above_and_in_loop: 153ms
 let_in_loop: 137ms

Some googling brought me to the article stating that let caused deoptimization prior to Chrome 56 / V8 5.6! but my chrome is 57.0.2987.133 (64-bit) and v8 ver 5.7.492.71.
More surprises trying to run this on Firefox 52.0.2 (32-bit). Here we have slowdown in another place, when variable created with let is used inside closure:

 without_let: 101.9ms
 let_below: 99ms
 let_above_and_in_loop: 899ms <----- Slowdown for SpiderMonkey
 let_in_loop: 102ms

As I see the issue is somewhat related to so called "Temporal Dead Zone" feature, but still unclear:

Why two major browsers (major JavaScript engines) still cannot optimize those (different) parts of the snippet?

Are there any workarounds to keep using let (except using Babel to turn let into var)? Assume I'm able to pass options to Chrome or even directly to v8 via v8::V8::SetFlagsFromCommandLine(&argc, argv, true);

UPD:
In Chrome ver 58.0.3029.96, correspondng v8 version 5.8.283.37 (aconding to https://omahaproxy.appspot.com/) after enabling chrome://flags/#enable-v8-future as jmrk suggested below there is still slowdown for third case (now 2 times instead of 8 times)

without_let: 157.000ms
let_below: 155.000ms
let_above_and_in_loop: 304.000ms
let_in_loop: 201.000ms

Firefox 53.0 (32bit)

without_let: 278.650ms
let_below: 310.290ms
let_above_and_in_loop: 848.325ms
let_in_loop: 275.495ms


问:
JavaScript loop through to check duplicate value
I am having troubles trying to check if the date exists in the array.

```<code> for(var i = 0; i< crisislist.length; i++){
        hazecounter = 1;
        if(crisislist[i].category == 1){
            if(crisislist[i].date != crisislist[i+1].date) {
                hazelabel.push(crisislist[i].date);
            }else{
                hazecounter++;
            }
            hazedata.push(hazecounter);
        }
 }
</code>```

The sample data for the date is:

```<code>["01-02-2017", "22-03-2017", "22-03-2017", "07-08-2017"]
</code>```

And the expected output for hazelabel, hazedata should be:

hazelabel: ["01-02-2017", "22-03-2017", "07-08-2017"]
   hazedata: [1,2,1]

With the code above, when I check until the last element in the array and trying to make a comparison, it throw me an error message:

```<code>Uncaught TypeError: Cannot read property 'date' of undefined
</code>```

I think this is because when I reach the last element of array, and I try to find crisislist[I+1].date, it could not found and thus the error message.

Any idea how to fix this? Thanks in advance!

答:
Your if statement is going to be a problem.

```<code>if(crisislist[i].date != crisislist[i+1].date) {
</code>```

You are accessing crisislist[i+1] in a loop that goes to < crisislist.length. That means that if you have an array of size 4, your loop will go until i = 3, but you are accessing i+1 from the array (crisislist[4]), which will be undefined.

Try changing your for loop to go to crisis.length-1

Body:
I am having troubles trying to check if the date exists in the array.

 for(var i = 0; i< crisislist.length; i++){
        hazecounter = 1;
        if(crisislist[i].category == 1){
            if(crisislist[i].date != crisislist[i+1].date) {
                hazelabel.push(crisislist[i].date);
            }else{
                hazecounter++;
            }
            hazedata.push(hazecounter);
        }
 }

The sample data for the date is:

["01-02-2017", "22-03-2017", "22-03-2017", "07-08-2017"]

And the expected output for hazelabel, hazedata should be:

hazelabel: ["01-02-2017", "22-03-2017", "07-08-2017"]
   hazedata: [1,2,1]

With the code above, when I check until the last element in the array and trying to make a comparison, it throw me an error message:

Uncaught TypeError: Cannot read property 'date' of undefined

I think this is because when I reach the last element of array, and I try to find crisislist[I+1].date, it could not found and thus the error message.

Any idea how to fix this? Thanks in advance!

Body:
Your if statement is going to be a problem.

if(crisislist[i].date != crisislist[i+1].date) {

You are accessing crisislist[i+1] in a loop that goes to < crisislist.length. That means that if you have an array of size 4, your loop will go until i = 3, but you are accessing i+1 from the array (crisislist[4]), which will be undefined.

Try changing your for loop to go to crisis.length-1


问:
Why we need Fault Contracts in WCF
I have been getting my hands Dirty in WCF. Now one of the question which comes to my mind is regarding Fault Contracts in WCF.

I would like to know why we would be needing it. Consider a Sample Application where I am adding 2 Numbers.

So in the Response I have like 2 Fields

Result - Success/Error

Error - Error Details (Code + Text)

Now if my WCF service had any Exception I can catch it in the catch block and assign values to Response object

Result - Success/Error

Error - Error Details (Code + Text)

So where does Fault Contract come into the picture?

答:
This is a old question, but I still wish to post some answers for future readers.

Found this website http://www.c-sharpcorner.com/UploadFile/aravindbenator/wcf-exception-handling-best-ways/.

The Author said, if we do not use Fault Contract, the response data (from service to client) will include some sensitive data.

If we do not have Fault Contract, in  WCF app.config or web.config, and we still want Fault Exceptions or Web Fault Exceptions, we will set as:
<serviceDebug includeExceptionDetailInFaults="true" />, however, if we set <serviceDebug includeExceptionDetailInFaults="false" />, we must have Fault Contract above service operations.

Title: Why we need Fault Contracts in WCF


问:
Jquery Tabs Cookies
I am trying to use the Jquery cookie plugin to remember the last selected tab.

I can't seem to get it to work.Do i need anything else apart from the jquery lib and cookie plugin???

This is the code:

```<code>  <script type="text/javascript">
    $(document).ready(function() {
       $("#tabletabscampaigns > ul").tabs({ remote: true, cache: true });
$("#tabletabscampaigns").tabs({selected: 0, cookie: { expires: 30}  });
    });
</script>

<div id="tabletabscampaigns" style="float:left; width:895px; margin-top:20px;">
</code>```

答: in the plugin documention it states not to use selected with cookie plugin.</p>

Title: Jquery Tabs Cookies


问:
Achieve error differentiation in Promises

Background

I have a REST API using MongoDB, Node.js and Express that makes a request to my NoSQL DB and depending on different results, I want to differentiate which error I send the customer.

Problem

The current version of my code has a generic error handler and always sends the same error message to the client:

```<code>api.post("/Surveys/", (req, res) => {
        const surveyJSON = req.body;
        const sender = replyFactory(res);

        Survey.findOne({_id: surveyJSON.id})
            .then(doc => {
                if(doc !== null)
                    throw {reason: "ObjectRepeated"};

                //do stuff
                return new Survey(surveyJSON).save();
            })
            .then(() => sender.replySuccess("Object saved with success!"))
            .catch(error => {
                /*
                 * Here I don't know if:
                 * 1. The object is repeated
                 * 2. There was an error while saving (eg. validation failed)
                 * 3. Server had a hiccup (500)
                 */
                sender.replyBadRequest(error);
            });
    });
</code>```

This is a problem, because the client will always get the same error message, no matter what and I need error differentiation!

Research

I found a possible solution, based on the division of logic and error/response handling:

Handling multiple catches in promise chain

However, I don't understand a few things:

I don't see how, at least in my example, I can separate the logic from the response. The response will depend on the logic after all!

I would like to avoid error sub-classing and hierarchy. First because I don't use bluebird, and I can't subclass the error class the answer suggests, and second because I don't want my code with a billion different error classes with brittle hierarchies that will change in the future.

My idea, that I don't really like either

With this structure, if I want error differentiation, the only thing I can do is to detect an error occurred, build an object with that information and then throw it:

```<code>.then(doc => {
    if(doc === null)
        throw {reason: "ObjectNotFound"};

    //do stuff
    return doc.save();
})
.catch(error => {
    if(error.reason === "ObjectNotFound")
        sendJsonResponse(res, 404, err);
    else if(error.reason === "Something else ")
        sendJsonResponse(/*you get the idea*/);
    else //if we don't know the reasons, its because the server likely crashed
        sendJsonResponse(res, 500, err);
});
</code>```

I personally don't find this solution particularly attractive because it means I will have a huge if then else chain of statements in my catch block.

Also, as mentioned in the previous post, generic error handlers are usually frowned upon (and for a good reason imo).

Questions

How can I improve this code?

答:
I think a good improvement would be creating an error utility method that takes the error message as a parameter, then does all your ifs to try to parse the error (logic that does have to happen somewhere) and returns a formatted error.</p>

```<code>function errorFormatter(errMsg) {
   var formattedErr = {
    responseCode: 500,
    msg: 'Internal Server Error'
};

  switch (true) {
     case errMsg.includes('ObjectNotFound'):
      formattedErr.responseCode = 404;
      formattedErr.msg = 'Resource not found';
      break;
  }
  return formattedErr;
}
</code>```

Body:
Background

I have a REST API using MongoDB, Node.js and Express that makes a request to my NoSQL DB and depending on different results, I want to differentiate which error I send the customer.

Problem

The current version of my code has a generic error handler and always sends the same error message to the client:

api.post("/Surveys/", (req, res) => {
        const surveyJSON = req.body;
        const sender = replyFactory(res);

        Survey.findOne({_id: surveyJSON.id})
            .then(doc => {
                if(doc !== null)
                    throw {reason: "ObjectRepeated"};

                //do stuff
                return new Survey(surveyJSON).save();
            })
            .then(() => sender.replySuccess("Object saved with success!"))
            .catch(error => {
                /*
                 * Here I don't know if:
                 * 1. The object is repeated
                 * 2. There was an error while saving (eg. validation failed)
                 * 3. Server had a hiccup (500)
                 */
                sender.replyBadRequest(error);
            });
    });

This is a problem, because the client will always get the same error message, no matter what and I need error differentiation!

Research

I found a possible solution, based on the division of logic and error/response handling:

Handling multiple catches in promise chain

However, I don't understand a few things:

I don't see how, at least in my example, I can separate the logic from the response. The response will depend on the logic after all!

I would like to avoid error sub-classing and hierarchy. First because I don't use bluebird, and I can't subclass the error class the answer suggests, and second because I don't want my code with a billion different error classes with brittle hierarchies that will change in the future.

My idea, that I don't really like either

With this structure, if I want error differentiation, the only thing I can do is to detect an error occurred, build an object with that information and then throw it:

.then(doc => {
    if(doc === null)
        throw {reason: "ObjectNotFound"};

    //do stuff
    return doc.save();
})
.catch(error => {
    if(error.reason === "ObjectNotFound")
        sendJsonResponse(res, 404, err);
    else if(error.reason === "Something else ")
        sendJsonResponse(/*you get the idea*/);
    else //if we don't know the reasons, its because the server likely crashed
        sendJsonResponse(res, 500, err);
});

I personally don't find this solution particularly attractive because it means I will have a huge if then else chain of statements in my catch block.

Also, as mentioned in the previous post, generic error handlers are usually frowned upon (and for a good reason imo).

Questions

How can I improve this code?

Body:
I think a good improvement would be creating an error utility method that takes the error message as a parameter, then does all your ifs to try to parse the error (logic that does have to happen somewhere) and returns a formatted error.

function errorFormatter(errMsg) {
   var formattedErr = {
    responseCode: 500,
    msg: 'Internal Server Error'
};

  switch (true) {
     case errMsg.includes('ObjectNotFound'):
      formattedErr.responseCode = 404;
      formattedErr.msg = 'Resource not found';
      break;
  }
  return formattedErr;
}


问:
How to add an anchor text in Oracle Apex 5.0
I want to create a login page where below the "Login" button I want to create a html text saying "Do not have an account? Click here to register." Here "Click here" will be an anchor text and when user clicks "Click here" it will redirect the user to the registration page.

I have searched for a whole day to achieve this but could not find any solution. I am new to oracle apex. Could anyone help me explaining the procedure?

答:
One way would be to create a Display As Text item with the source:

```<code>Do not have an account? <a href="f?p=whatever">Click here</a> to register.
</code>```

Set Escape HTML to "No"so that the link is displayed properly.

Body:
One way would be to create a Display As Text item with the source:

Do not have an account? <a href="f?p=whatever">Click here</a> to register.

Set Escape HTML to "No"so that the link is displayed properly.


答:
You must access crisislist[i+1].date only when i doesn't point to the last element.

Also notice that to get the desired result, you need to move the hazedata.push inside the if block and put the initialisation of hazecounter in front of the loop.

```<code>var hazecounter = 1;
for (var i = 0; i< crisislist.length; i++) {
    if (crisislist[i].category == 1) {
        if (i == crisislist.length-1 || crisislist[i].date != crisislist[i+1].date) {
            hazelabel.push(crisislist[i].date);
            hazedata.push(hazecounter);
            hazeCounter = 1;
        } else {
            hazecounter++;
        }
    }
}
</code>```

Title: JavaScript loop through to check duplicate value

Body:
You must access crisislist[i+1].date only when i doesn't point to the last element.

Also notice that to get the desired result, you need to move the hazedata.push inside the if block and put the initialisation of hazecounter in front of the loop.

var hazecounter = 1;
for (var i = 0; i< crisislist.length; i++) {
    if (crisislist[i].category == 1) {
        if (i == crisislist.length-1 || crisislist[i].date != crisislist[i+1].date) {
            hazelabel.push(crisislist[i].date);
            hazedata.push(hazecounter);
            hazeCounter = 1;
        } else {
            hazecounter++;
        }
    }
}


问:
Using ifelse to determine point size in r ggplot, works until legend is added
I am trying to set up a graph where the size of the point is smaller if n == 0 than n > 0.  The code works until I add a legend.  Here is my code that works:

```<code>ggplot(len.oo, aes(x = TCL, y = n, colour = worm, shape = worm)) + ylim(0, 20) +
  geom_point(size = ifelse(len.oo$n == 0, 2, 4)) +
  theme_bw() + xlab(expression(~italic("O. obscurus")~"TCL (mm)")) + ylab("Abundance") +
  theme(legend.title=element_blank(), legend.position="none")
</code>```

that gives me:

as soon as i add a legend it gives me an error.  code with legend:

```<code>ggplot(len.oo, aes(x = TCL, y = n, colour = worm, shape = worm)) + ylim(0, 20) +
  geom_point(size = ifelse(len.oo$n == 0, 2, 4)) +
  theme_bw() + xlab(expression(~italic("O. obscurus")~"TCL (mm)")) + ylab("Abundance") +
  theme(legend.title=element_blank(), legend.position=c(0.2, 0.8)) + guides(size=FALSE)
</code>```

gives me the error:

Error: Aesthetics must be either length 1 or the same as the data (3):
  size

I've also tried position = "top" and the like to have the legend outside the plot and without the guides(size=FALSE)

I could easily make the graph without the legend and then make the legend without the size difference and use other software to copy and paste the legend on the image, but I would like to do all this in R.

答:
The problem lies here: geom_point(size = ifelse(len.oo$n == 0, 2, 4))

I can't give you a direct solution because no data was provided, but I'd suggest adding a variable in your len.oo dataframe so that this variable (let's say you call it size_n) is either a 2 or a 4 if n is equal to 0 and then change the ggplot layer to geom_point(aes(size = size_n)).

You can create this new variable with the following code:

```<code>library(dplyr)
len.oo <- mutate(len.oo, size_n = ifelse(n == 0, 2, 4))
</code>```

Body:
I am trying to set up a graph where the size of the point is smaller if n == 0 than n > 0.  The code works until I add a legend.  Here is my code that works:

ggplot(len.oo, aes(x = TCL, y = n, colour = worm, shape = worm)) + ylim(0, 20) +
  geom_point(size = ifelse(len.oo$n == 0, 2, 4)) +
  theme_bw() + xlab(expression(~italic("O. obscurus")~"TCL (mm)")) + ylab("Abundance") +
  theme(legend.title=element_blank(), legend.position="none")

that gives me:

as soon as i add a legend it gives me an error.  code with legend:

ggplot(len.oo, aes(x = TCL, y = n, colour = worm, shape = worm)) + ylim(0, 20) +
  geom_point(size = ifelse(len.oo$n == 0, 2, 4)) +
  theme_bw() + xlab(expression(~italic("O. obscurus")~"TCL (mm)")) + ylab("Abundance") +
  theme(legend.title=element_blank(), legend.position=c(0.2, 0.8)) + guides(size=FALSE)

gives me the error:

Error: Aesthetics must be either length 1 or the same as the data (3):
  size

I've also tried position = "top" and the like to have the legend outside the plot and without the guides(size=FALSE)

I could easily make the graph without the legend and then make the legend without the size difference and use other software to copy and paste the legend on the image, but I would like to do all this in R.

Body:
The problem lies here: geom_point(size = ifelse(len.oo$n == 0, 2, 4))

I can't give you a direct solution because no data was provided, but I'd suggest adding a variable in your len.oo dataframe so that this variable (let's say you call it size_n) is either a 2 or a 4 if n is equal to 0 and then change the ggplot layer to geom_point(aes(size = size_n)).

You can create this new variable with the following code:

library(dplyr)
len.oo <- mutate(len.oo, size_n = ifelse(n == 0, 2, 4))


问:
Button view with drawableLeft
I need to add drawable to my button and added drawableLeft to it. If button's width is set to wrap_content, then everything is fine and looks good. But if I set custom width to my button then drawableLeft image goes away from button's caption to left edge of the button. Is this somekind of a design bug in android? How can I fix this to let button look the same on custom width?

Regards,
evilone

答:
I had this problem just right now, but I found out that you just need to set android:padding to the button. That way you push the picture away from left side of the button. Check this code:

```<code>`<Button
        android:id="@+id/button1"
        android:layout_width="170dp"
        android:layout_height="50dp"
        android:layout_below="@+id/txt1"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="12dp"
        android:background="@drawable/button"
        android:drawableLeft="@drawable/icon"
        android:drawablePadding="20dp"
        android:minHeight="40dp"
        android:onClick="onClick"
        android:padding="40dp"
        android:text="@string/string1"
        android:textSize="16sp" />`
</code>```

Title: Button view with drawableLeft

Body:
I had this problem just right now, but I found out that you just need to set android:padding to the button. That way you push the picture away from left side of the button. Check this code:

`<Button
        android:id="@+id/button1"
        android:layout_width="170dp"
        android:layout_height="50dp"
        android:layout_below="@+id/txt1"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="12dp"
        android:background="@drawable/button"
        android:drawableLeft="@drawable/icon"
        android:drawablePadding="20dp"
        android:minHeight="40dp"
        android:onClick="onClick"
        android:padding="40dp"
        android:text="@string/string1"
        android:textSize="16sp" />`


问:
How to remove an data/models from nltk dowloader?
I installed some NLTK-packages in python3 NLTK (via nltk.download()), tried them and -not needing them- want to remove them now.

How can I remove for example the package large_grammars from my NLTK-installation? (I do not want to remove the complete NLTK-installation!)

答:
By default NLTK packages/data are saved in the nltk_data directory.

First, you have to find where the directory might be:

```<code>>>> import nltk
>>> nltk.data.path
['/home/alvas/nltk_data', '/usr/share/nltk_data', '/usr/local/share/nltk_data', '/usr/lib/nltk_data', '/usr/local/lib/nltk_data']
</code>```

Check the exact location of nltk_data:

```<code>>>> import os
>>> next(p for p in nltk.data.path if os.path.exists(p))
'/home/alvas/nltk_data'
</code>```

On linux, simply go to the directory on the command line:

```<code>$ cd /home/alvas/nltk_data/
$ ls
corpora  grammars  tokenizers
$ cd grammars/
$ ls
large_grammars  large_grammars.zip
$ rm -rf large_grammars
$ rm large_grammars.zip
</code>```

Body:
By default NLTK packages/data are saved in the nltk_data directory.

First, you have to find where the directory might be:

>>> import nltk
>>> nltk.data.path
['/home/alvas/nltk_data', '/usr/share/nltk_data', '/usr/local/share/nltk_data', '/usr/lib/nltk_data', '/usr/local/lib/nltk_data']

Check the exact location of nltk_data:

>>> import os
>>> next(p for p in nltk.data.path if os.path.exists(p))
'/home/alvas/nltk_data'

On linux, simply go to the directory on the command line:

$ cd /home/alvas/nltk_data/
$ ls
corpora  grammars  tokenizers
$ cd grammars/
$ ls
large_grammars  large_grammars.zip
$ rm -rf large_grammars
$ rm large_grammars.zip


问:
iOS - Save array of struct in CoreData
I have a struct like this:

```<code>     struct list
{

         var userId: Int = 0
         var id: Int = 0
         var title: String = ""
         var body: String = ""

}
</code>```

In another part of my program, I declare an array of struct and I enter information through a JSON files downloaded from the internet.

```<code>var array = [list]()
</code>```

Now my problem is to save and recuperar this array of struct in CoreData. I do not know how to go forward, would you give me a hand?

答:
I think you best choice is to go with Binary Data type.

1.Create a toDictionary() method on your struct model:

```<code>func toDictionary() -> [String: Any] {
    return ["userId: self.userId, "id": self.id, ...]
}
</code>```

2.Then add a NSData property on your core data model, which represents your struct list:

@NSManaged var list: NSData?

3.Access that list property with a class helper:

```<code>func listDictionary() -> [String: Any]? {
    guard let listData = self.list as? Data else { return nil }
    let dict = NSKeyedUnarchiver.unarchiveObject(with: listData) as? [String: Any]
    return dict
}
</code>```

4.Create a fromDictionary() -> list on your list object which will build a model from dictionary

Title: iOS - Save array of struct in CoreData

Body:
I have a struct like this:

     struct list
{

         var userId: Int = 0
         var id: Int = 0
         var title: String = ""
         var body: String = ""

}

In another part of my program, I declare an array of struct and I enter information through a JSON files downloaded from the internet.

var array = [list]()

Now my problem is to save and recuperar this array of struct in CoreData. I do not know how to go forward, would you give me a hand?

Body:
I think you best choice is to go with Binary Data type.

1.Create a toDictionary() method on your struct model:

func toDictionary() -> [String: Any] {
    return ["userId: self.userId, "id": self.id, ...]
}

2.Then add a NSData property on your core data model, which represents your struct list:

@NSManaged var list: NSData?

3.Access that list property with a class helper:

func listDictionary() -> [String: Any]? {
    guard let listData = self.list as? Data else { return nil }
    let dict = NSKeyedUnarchiver.unarchiveObject(with: listData) as? [String: Any]
    return dict
}

4.Create a fromDictionary() -> list on your list object which will build a model from dictionary


问:
I'm trying to make a program that produces a receipt
I would like for my code to write to a receipt file, the product and price of each barcode entered and then print that file, however, at the moment it stops writing to the file once the first barcode has been entered but continues to ask the questions (it also stops asking for the quantity of products).

The CSV:

```<code>34512340,bread,2.50,0
98981236,flour,1.79,0
56756777,pasta,1.49,0
90673412,milk,0.89,0
</code>```

The output:

```<code>Output of code:

Enter a Barcode? (Yes/No):  yes
Enter Barcode:  56756777
Enter quantity of products:  7
Enter a Barcode? (Yes/No):  yes
Enter Barcode:  98981236
Enter a Barcode? (Yes/No):  no
Here is your Receipt:
56756777    10.43

Total: 10.43
</code>```

答:
Your file pointer moves to the end after one read from the file. The minimum change you can do to make it work is add:

```<code>f.seek(0)
</code>```

before

```<code>for column in f:
</code>```

seek moves the file pointer to the desired position. Here we are moving it into the start of the file after every time we start checking for the products.

A better way can be to read the file locally and use it to search for your products.

Body:
I would like for my code to write to a receipt file, the product and price of each barcode entered and then print that file, however, at the moment it stops writing to the file once the first barcode has been entered but continues to ask the questions (it also stops asking for the quantity of products).

The CSV:

34512340,bread,2.50,0
98981236,flour,1.79,0
56756777,pasta,1.49,0
90673412,milk,0.89,0

The output:

Output of code:

Enter a Barcode? (Yes/No):  yes
Enter Barcode:  56756777
Enter quantity of products:  7
Enter a Barcode? (Yes/No):  yes
Enter Barcode:  98981236
Enter a Barcode? (Yes/No):  no
Here is your Receipt:
56756777    10.43

Total: 10.43

Body:
Your file pointer moves to the end after one read from the file. The minimum change you can do to make it work is add:

f.seek(0)

before

for column in f:

seek moves the file pointer to the desired position. Here we are moving it into the start of the file after every time we start checking for the products.

A better way can be to read the file locally and use it to search for your products.


问:
Wagtail: Passing Django form to WagtailAdmin (Sidebar: Forms)
I have a very interesting task.

Wagtail Form with a FileField - For image upload (I guess this is not possible yet)

From the point that this is not possible yet in Wagtail I've tried another thing.

A Django Form (from this example django form in wagtail) that has actually a FileField.

Generate the link to uploaded image (let's say '/media/pics/image_example.jpg')

Somehow pass this link (a text field) to Wagtail Form and auto-submit it.

So at the end, we have the Form Submissions in WagtailAdmin that has a field with the direct url to the uploaded image.

But.. I don't really understand how this must work. Any ideas? Maybe there are better solutions for my problem.

答:
Have a method as mentioned below

```<code>def content_file_name(instance, filename):

    import random
    import string

    # random_str length will be 16 which will be combination of (4 digits + 4 characters + 4 digits + 4 characters)
    random_str =  "".join([random.choice(string.uppercase) for i in range(0,4)]) + "".join([random.choice(string.digits) for i in range(0,4)]) + \
                    "".join([random.choice(string.lowercase) for i in range(0,4)]) + "".join([random.choice(string.digits) for i in range(0,4)])

    # return string seperated by hyphen eg:
    random_str =  random_str[:4] + "-" + random_str[4:8] + "-" + random_str[8:12] + "-" + random_str[12:]
    filetype = filename.split(".")[-1].lower()
    filename = random_str +"." +  filetype
    path = "yourapp/uploads/" + str(datetime.datetime.now().year) + "/" + str(datetime.datetime.now().month) + "/" + str(datetime.datetime.now().day) + "/"
    os_path = os.path.join(path, filename)
return os_path
</code>```

Now add the above method into your model field which is having attachment
EX:-

```<code>atachement = models.FileField(upload_to=content_file_name, blank=True, null=True, verbose_name='Attachment')
</code>```

WagtailForm.save()
will save your data.

Body:
Have a method as mentioned below

def content_file_name(instance, filename):

    import random
    import string

    # random_str length will be 16 which will be combination of (4 digits + 4 characters + 4 digits + 4 characters)
    random_str =  "".join([random.choice(string.uppercase) for i in range(0,4)]) + "".join([random.choice(string.digits) for i in range(0,4)]) + \
                    "".join([random.choice(string.lowercase) for i in range(0,4)]) + "".join([random.choice(string.digits) for i in range(0,4)])

    # return string seperated by hyphen eg:
    random_str =  random_str[:4] + "-" + random_str[4:8] + "-" + random_str[8:12] + "-" + random_str[12:]
    filetype = filename.split(".")[-1].lower()
    filename = random_str +"." +  filetype
    path = "yourapp/uploads/" + str(datetime.datetime.now().year) + "/" + str(datetime.datetime.now().month) + "/" + str(datetime.datetime.now().day) + "/"
    os_path = os.path.join(path, filename)
return os_path

Now add the above method into your model field which is having attachment
EX:-

atachement = models.FileField(upload_to=content_file_name, blank=True, null=True, verbose_name='Attachment')

WagtailForm.save()
will save your data.


问:
NumPy in-place operations with overlapping slices
Consider this out-of-place operation:

```<code>>>> b = numpy.asarray([1, 2, 3])
>>> b[1:] = b[1:] - b[:-1]
>>> b
array([1, 1, 1])
</code>```

Now consider the in-place operation:

```<code>>>> a = numpy.asarray([1, 2, 3])
>>> a[1:] -= a[:-1]
>>> a
array([1, 1, 2])
</code>```

They give different results, which I did not expect.

Update: It seems this behavior changed; now they give the same result.

I would have assumed NumPy would have done the subtraction in the correct order (backward) so that they would give equivalent results to the out-of-place subtraction.

My question is: is this intended behavior on NumPy's part, or is it a bug, or is the result undefined?

答:
Undefined, or at least hard-to-understand, may be best answer.  Another SO answer claims

```<code>a[1:] -= a[:-1]
</code>```

gets translated, by the interpreter, into something like

```<code>a.__setitem__(slice(1,None), a.__getitem__(slice(1,None)).
   __isub__(a.__getitem__(slice(None,-1))))

In [171]: a=np.arange(10)
In [172]: a[1:] -= a[:-1]
In [173]: a
Out[173]: array([0, 1, 1, 2, 2, 3, 3, 4, 4, 5])
</code>```

evaluates the same as:

```<code>In [175]: for i in range(9):
     ...:     a[i+1] = a[i+1]-a[i]
</code>```

I can sort of see how it gets this from the nested __setitem__ etc expression.  I'm try to replicate it with np.nditer.

the  reverse that you mention would be

```<code>In [178]: for i in range(8,-1,-1):
     ...:     a[i+1] = a[i+1]-a[i]
</code>```

I don't there's any way that numpy could deduce that such a reverse iteration is required.  The 2nd argument to __setitem__ evaluates just fine with forward iteration.  Buffering that term is the only simple solution.

The .at ufunc method was introduced as a way to get around buffering issues in expressions like a[idx] += b. In particular when idx has dupicates.  Should the effect on a be cumulative or should just the last instance apply.

In your example if behaves just like a[1:] - a[:-1]:

```<code>In [165]: a=np.arange(10)
In [166]: idx=np.arange(1,10)
In [167]: np.add.at(a, idx, -a[:-1])
In [168]: a
Out[168]: array([0, 1, 1, 1, 1, 1, 1, 1, 1, 1])
</code>```

That's because 3rd argument to add.at is fully evaluated before being used.  It's a temporary copy.  I know from other tests that add.at is slower than the ordinary a[idx] +=.  [I'm a little confused as to what 'buffering' add.at is bypassing; how that's different from the apparent lack of buffering that is giving problems here?]

Why use the += notation?  Just to make the code more compact?  or in hopes of making it faster?  But if speed is the goal, do we want numpy throw in some extra buffering, just to make it safer?

An nditer equivalent of the a[1:] -= a[:-1]

```<code>In [190]: a=np.arange(10)
In [191]: it = np.nditer([a[1:],a[1:],a[:-1]], op_flags=['readwrite'])
In [192]: for i,j,k in it:
     ...:     print(i,j,k)
     ...:     i[...] = j-k
     ...:     print(i)

1 1 0
1
2 2 1
1
3 3 1
2
4 4 2
2
5 5 2
3
6 6 3
...
</code>```

The iteration can be simplified

```<code>In [197]: it = np.nditer([a[1:],a[:-1]], op_flags=['readwrite'])
In [198]: for i,j in it:
     ...:     i[...] -= j
</code>```

Because it's a view the iterated value from a[:-1] will reflect changes made in the previous loop.

I'm not sure that c version of nditer is being using in the array += expression, but the intention of nditer was to consolidate the iteration coding into one unified framework.

Another interesting observation is that if I define

```<code>idx = array([1, 2, 3, 4, 5, 6, 7, 8, 9])
</code>```

then

```<code>a[idx] -= a[:-1]
a[1:] -= a[idx-1]
a[idx] -= a[idx-1]
</code>```

all give the desired array([0, 1, 1, 1, 1, 1, 1, 1, 1, 1]).  In other words both sides of the -= have to be 'views/slices'.  That must be the buffering that add.at bypasses.  That a[idx-1] is a copy is obvious.  That a[idx]-= throws in a buffer, while a[1:]-= does not, is not so obvious.

ContentLicense: CC BY-SA 4.0

Body:
Consider this out-of-place operation:

>>> b = numpy.asarray([1, 2, 3])
>>> b[1:] = b[1:] - b[:-1]
>>> b
array([1, 1, 1])

Now consider the in-place operation:

>>> a = numpy.asarray([1, 2, 3])
>>> a[1:] -= a[:-1]
>>> a
array([1, 1, 2])

They give different results, which I did not expect.

Update: It seems this behavior changed; now they give the same result.

I would have assumed NumPy would have done the subtraction in the correct order (backward) so that they would give equivalent results to the out-of-place subtraction.

My question is: is this intended behavior on NumPy's part, or is it a bug, or is the result undefined?

Body:
Undefined, or at least hard-to-understand, may be best answer.  Another SO answer claims

a[1:] -= a[:-1]

gets translated, by the interpreter, into something like

a.__setitem__(slice(1,None), a.__getitem__(slice(1,None)).
   __isub__(a.__getitem__(slice(None,-1))))

In [171]: a=np.arange(10)
In [172]: a[1:] -= a[:-1]
In [173]: a
Out[173]: array([0, 1, 1, 2, 2, 3, 3, 4, 4, 5])

evaluates the same as:

In [175]: for i in range(9):
     ...:     a[i+1] = a[i+1]-a[i]

I can sort of see how it gets this from the nested __setitem__ etc expression.  I'm try to replicate it with np.nditer.

the  reverse that you mention would be

In [178]: for i in range(8,-1,-1):
     ...:     a[i+1] = a[i+1]-a[i]

I don't there's any way that numpy could deduce that such a reverse iteration is required.  The 2nd argument to __setitem__ evaluates just fine with forward iteration.  Buffering that term is the only simple solution.

The .at ufunc method was introduced as a way to get around buffering issues in expressions like a[idx] += b. In particular when idx has dupicates.  Should the effect on a be cumulative or should just the last instance apply.

In your example if behaves just like a[1:] - a[:-1]:

In [165]: a=np.arange(10)
In [166]: idx=np.arange(1,10)
In [167]: np.add.at(a, idx, -a[:-1])
In [168]: a
Out[168]: array([0, 1, 1, 1, 1, 1, 1, 1, 1, 1])

That's because 3rd argument to add.at is fully evaluated before being used.  It's a temporary copy.  I know from other tests that add.at is slower than the ordinary a[idx] +=.  [I'm a little confused as to what 'buffering' add.at is bypassing; how that's different from the apparent lack of buffering that is giving problems here?]

Why use the += notation?  Just to make the code more compact?  or in hopes of making it faster?  But if speed is the goal, do we want numpy throw in some extra buffering, just to make it safer?

An nditer equivalent of the a[1:] -= a[:-1]

In [190]: a=np.arange(10)
In [191]: it = np.nditer([a[1:],a[1:],a[:-1]], op_flags=['readwrite'])
In [192]: for i,j,k in it:
     ...:     print(i,j,k)
     ...:     i[...] = j-k
     ...:     print(i)

1 1 0
1
2 2 1
1
3 3 1
2
4 4 2
2
5 5 2
3
6 6 3
...

The iteration can be simplified

In [197]: it = np.nditer([a[1:],a[:-1]], op_flags=['readwrite'])
In [198]: for i,j in it:
     ...:     i[...] -= j

Because it's a view the iterated value from a[:-1] will reflect changes made in the previous loop.

I'm not sure that c version of nditer is being using in the array += expression, but the intention of nditer was to consolidate the iteration coding into one unified framework.

Another interesting observation is that if I define

idx = array([1, 2, 3, 4, 5, 6, 7, 8, 9])

then

a[idx] -= a[:-1]
a[1:] -= a[idx-1]
a[idx] -= a[idx-1]

all give the desired array([0, 1, 1, 1, 1, 1, 1, 1, 1, 1]).  In other words both sides of the -= have to be 'views/slices'.  That must be the buffering that add.at bypasses.  That a[idx-1] is a copy is obvious.  That a[idx]-= throws in a buffer, while a[1:]-= does not, is not so obvious.


问:
Unzip vs explicit loop
what's the difference between the two ways to unzip two zipped lists?

```<code>assert isinstance(X, list)
assert isinstance(X[0], tuple)
assert isinstance(X[0][0], list)
assert isinstance(X[0][0][0], dict)

X_model = []
X_synth = []
for row in X:
    X_model.append(row[0])
    X_synth.append(row[1])
</code>```

X_model is now a list of list of dict

```<code>X_model, X_synth, = zip(*X)
</code>```

X_model is a tuple of list of dicts
shouldn't the results be the same?

答:
The equivalent to zip() would be:

```<code>X_model = tuple(x for x, _ in X)
X_synth = tuple(x for _, x in X)
</code>```

But this isn't very efficient as it cycles X twice.
Note: tuples are immutable, so you can't efficiently do it in a loop as you would be creating a new tuple each time.

Title: Unzip vs explicit loop

Body:
what's the difference between the two ways to unzip two zipped lists?

assert isinstance(X, list)
assert isinstance(X[0], tuple)
assert isinstance(X[0][0], list)
assert isinstance(X[0][0][0], dict)

X_model = []
X_synth = []
for row in X:
    X_model.append(row[0])
    X_synth.append(row[1])

X_model is now a list of list of dict

X_model, X_synth, = zip(*X)

X_model is a tuple of list of dicts
shouldn't the results be the same?

Body:
The equivalent to zip() would be:

X_model = tuple(x for x, _ in X)
X_synth = tuple(x for _, x in X)

But this isn't very efficient as it cycles X twice.
Note: tuples are immutable, so you can't efficiently do it in a loop as you would be creating a new tuple each time.


问:
hash table copy can't find word using find function
I am building a hash table that uses linear probing as its collision resolution method, and I am stuck on one last check. the copied to table can't find a key that should be there, as it was removed from the original hash table prior to the check.</p>

```<code>template <class TYPE>
LPTable<TYPE>::LPTable(const LPTable<TYPE>& other){

    max_ = other.max_;
    LargerMax = other.LargerMax;
    size_ = other.size_;

    if (other.size_)
    {
            records_ = new Record*[other.LargerMax];

            for (int i = 0; i < other.size_; i++) // chasnged size from larger max
            {

                    if (other.records_[i] != nullptr)
                    {
                            records_[i] = new Record();    //throws exception after this loop

                            records_[i]->key_ = other.records_[i]->key_;
                            records_[i]->data_ = other.records_[i]->data_;
                            records_[i]->isDeleted = other.records_[i]->isDeleted;

                    }
            }
    }
    else
            size_ = 0;

}
</code>```

答:
The records_ field of the LPTable class need not be a pointer to a pointer; a pointer would have sufficed and this is very likely the source of your problem. Moreover, you should very likely prefer a vector for this task.

The strange behavior you're seeing is because of a mistake in the copy constructor of the LPTable. You're allocating an array of pointers, then iterating through the other and copying the pointers.

In other words, you're not copying the Record instance to which the pointer refers.

Corresponding pointers in the records_ array  of the "copied from" and "copied to" LPTable refer to the same instance of the Record class. As a result, when you modify an entry in the "copied from" hash table, those changes are reflected in the "copied to" hash table

Body:
I am building a hash table that uses linear probing as its collision resolution method, and I am stuck on one last check. the copied to table can't find a key that should be there, as it was removed from the original hash table prior to the check.

template <class TYPE>
LPTable<TYPE>::LPTable(const LPTable<TYPE>& other){

    max_ = other.max_;
    LargerMax = other.LargerMax;
    size_ = other.size_;

    if (other.size_)
    {
            records_ = new Record*[other.LargerMax];

            for (int i = 0; i < other.size_; i++) // chasnged size from larger max
            {

                    if (other.records_[i] != nullptr)
                    {
                            records_[i] = new Record();    //throws exception after this loop

                            records_[i]->key_ = other.records_[i]->key_;
                            records_[i]->data_ = other.records_[i]->data_;
                            records_[i]->isDeleted = other.records_[i]->isDeleted;

                    }
            }
    }
    else
            size_ = 0;

}


问:
NHibernate sets Foreign Key in secondary update rather than on initial insert violating Not-Null Constrain on key column
I am having a problem with what should be a fairly simple (I would think) NHibernate use case.

I have a classic Parent and a Child entity like so:

```<code>public class Parent
{
    public virtual int ParentId { get; set; }
    public virtual string Name { get; set; }
    public virtual IList<Child> Children { get; set; }
}

public class Child
{
    public virtual int ChildId { get; set; }
    public virtual Parent Parent { get; set; }
    public virtual string Name { get; set; }
}
</code>```

And mappings as follows:

```<code>public class ParentMap : ClassMap<Parent>
{
    public ParentMap()
    {
        Id(x => x.ParentId).GeneratedBy.Native();
        Map(x => x.Name);
        HasMany(x => x.Children).KeyColumn("ParentId").Cascade.SaveUpdate();
    }
}

public class ChildMap : ClassMap<Child>
{
    public ChildMap()
    {
        Id(x => x.ChildId).GeneratedBy.Native();
        Map(x => x.Name);
        References(x => x.Parent).Column("ParentId").ReadOnly().Not.Nullable();
    }
}
</code>```

Lastly, I have a simple tests:

```<code>   [Test]
    public void Test_save_family()
    {
        var parent = new Parent();
        var child = new Child {Parent = parent};
        parent.Children = new List<Child>{child};

        SessionManager.WithSession(
            session =>
                {
                    session.Save(parent);
                    session.Flush();
                });

    }
</code>```

The test fails with a System.Data.SqlClient.SqlException : Cannot insert the value NULL into column 'ParentId'.  This is correct in that the column is non-nullable but why is it inserting null?

If I remove the null constraint, the save works because NHibernate first inserts the parent, then inserts the child, then updates the ParentId column on the child record as shown in this output:

```<code>NHibernate: INSERT INTO [Parent] (Name) VALUES (@p0); select SCOPE_IDENTITY();@p0 = NULL
NHibernate: INSERT INTO [Child] (Name) VALUES (@p0); select SCOPE_IDENTITY();@p0 = NULL
NHibernate: UPDATE [Child] SET ParentId = @p0 WHERE ChildId = @p1;@p0 = 2, @p1 = 1
</code>```

This seems bizarre to me as in almost all cases foreign key columns of this sort are declared non-nullable and hence the foreign key must be provided at insert.  So why is NHibernate not setting the foreign key on the initial insert of the child row and how to I fix this?

答:
A few problems with your mapping... You have a bidirectional relationship and NHibernate needs to know which way to update it. In the OO world, references only go one way and there is no way for NHibernate to know that Parent->Children is the same FK as Child->Parent. Right now you have Child->Parent set to ReadOnly(). This is telling NHibernate not to update this property. So it tries to insert the Child (with a null parent) and then update the FK from the Parent side. This isn't working if you have a not null constraint on your FK. The usual way to map this is to use Inverse=true on the parent side and let the child worry about persistence. (It's your job in the OO model to ensure that the Parent->Children collection contains the same set of references as the set of Child->Parent relationships.)

```<code>public class ParentMap : ClassMap<Parent>
{
    public ParentMap()
    {
        Id(x => x.ParentId).GeneratedBy.Native();
        Map(x => x.Name);
        HasMany(x => x.Children).KeyColumn("ParentId").Inverse().Cascade.SaveUpdate();
    }
}

public class ChildMap : ClassMap<Child>
{
    public ChildMap()
    {
        Id(x => x.ChildId).GeneratedBy.Native();
        Map(x => x.Name);
        References(x => x.Parent).Column("ParentId").Not.Nullable();  // Removed ReadOnly()
    }
}
</code>```

The SQL statements sent to the database when saving are now:

```<code>INSERT INTO [Parent]
           (Name)
VALUES     ('P1' /* @p0 */)
select SCOPE_IDENTITY()

INSERT INTO [Child]
           (Name,
            ParentId)
VALUES     ('C1' /* @p0 */,
            1 /* @p1 */)
select SCOPE_IDENTITY()
</code>```

Body:
I am having a problem with what should be a fairly simple (I would think) NHibernate use case.

I have a classic Parent and a Child entity like so:

public class Parent
{
    public virtual int ParentId { get; set; }
    public virtual string Name { get; set; }
    public virtual IList<Child> Children { get; set; }
}

public class Child
{
    public virtual int ChildId { get; set; }
    public virtual Parent Parent { get; set; }
    public virtual string Name { get; set; }
}

And mappings as follows:

public class ParentMap : ClassMap<Parent>
{
    public ParentMap()
    {
        Id(x => x.ParentId).GeneratedBy.Native();
        Map(x => x.Name);
        HasMany(x => x.Children).KeyColumn("ParentId").Cascade.SaveUpdate();
    }
}

public class ChildMap : ClassMap<Child>
{
    public ChildMap()
    {
        Id(x => x.ChildId).GeneratedBy.Native();
        Map(x => x.Name);
        References(x => x.Parent).Column("ParentId").ReadOnly().Not.Nullable();
    }
}

Lastly, I have a simple tests:

   [Test]
    public void Test_save_family()
    {
        var parent = new Parent();
        var child = new Child {Parent = parent};
        parent.Children = new List<Child>{child};

        SessionManager.WithSession(
            session =>
                {
                    session.Save(parent);
                    session.Flush();
                });

    }

The test fails with a System.Data.SqlClient.SqlException : Cannot insert the value NULL into column 'ParentId'.  This is correct in that the column is non-nullable but why is it inserting null?

If I remove the null constraint, the save works because NHibernate first inserts the parent, then inserts the child, then updates the ParentId column on the child record as shown in this output:

NHibernate: INSERT INTO [Parent] (Name) VALUES (@p0); select SCOPE_IDENTITY();@p0 = NULL
NHibernate: INSERT INTO [Child] (Name) VALUES (@p0); select SCOPE_IDENTITY();@p0 = NULL
NHibernate: UPDATE [Child] SET ParentId = @p0 WHERE ChildId = @p1;@p0 = 2, @p1 = 1

This seems bizarre to me as in almost all cases foreign key columns of this sort are declared non-nullable and hence the foreign key must be provided at insert.  So why is NHibernate not setting the foreign key on the initial insert of the child row and how to I fix this?

Body:
A few problems with your mapping... You have a bidirectional relationship and NHibernate needs to know which way to update it. In the OO world, references only go one way and there is no way for NHibernate to know that Parent->Children is the same FK as Child->Parent. Right now you have Child->Parent set to ReadOnly(). This is telling NHibernate not to update this property. So it tries to insert the Child (with a null parent) and then update the FK from the Parent side. This isn't working if you have a not null constraint on your FK. The usual way to map this is to use Inverse=true on the parent side and let the child worry about persistence. (It's your job in the OO model to ensure that the Parent->Children collection contains the same set of references as the set of Child->Parent relationships.)

public class ParentMap : ClassMap<Parent>
{
    public ParentMap()
    {
        Id(x => x.ParentId).GeneratedBy.Native();
        Map(x => x.Name);
        HasMany(x => x.Children).KeyColumn("ParentId").Inverse().Cascade.SaveUpdate();
    }
}

public class ChildMap : ClassMap<Child>
{
    public ChildMap()
    {
        Id(x => x.ChildId).GeneratedBy.Native();
        Map(x => x.Name);
        References(x => x.Parent).Column("ParentId").Not.Nullable();  // Removed ReadOnly()
    }
}

The SQL statements sent to the database when saving are now:

INSERT INTO [Parent]
           (Name)
VALUES     ('P1' /* @p0 */)
select SCOPE_IDENTITY()

INSERT INTO [Child]
           (Name,
            ParentId)
VALUES     ('C1' /* @p0 */,
            1 /* @p1 */)
select SCOPE_IDENTITY()


问:
Retrieving token on Swagger
I need to retrieve token from link.
But when I enter valid username and password I do not see any token. Also I tried to retrieve it in my C# Android program.

```<code>`var client = new RestClient("https://networkrail-uk-qa.traffilog.com/swagger/ui/index#!/User/User_LoginData");
request.AddParameter("username", login);
request.AddParameter("password", password);
IRestResponse response = client.Execute(request);
var content = response.Content;`
</code>```

There are a lot of data in output but there is no token. How can I get deal with it?

答:
The request URL is wrong.

```<code>https://networkrail-uk-qa.traffilog.com/swagger/ui/index#!/User/User_LoginData
</code>```

is just a documentation page (aka Swagger UI), not the actual request URL.

To find out the actual URL, use Swagger UI's "Try it out" feature: fill out the operation parameters and click "Try it out". It looks like the correct URL is

```<code>https://networkrail-uk-qa.traffilog.com/UK/api/User/Login?username={login}&password={password}
</code>```

where the login and password need to be URL-encoded.

Also note the request HTTP method (POST), and that the parameters need to be passed in the query string. With all that in mind, your code should be:

```<code>var client = new RestClient("https://networkrail-uk-qa.traffilog.com");
var request = new RestRequest("UK/api/User/Login", Method.POST);
request.AddQueryParameter("username", login);
request.AddQueryParameter("password", password);

IRestResponse response = client.Execute(request);
</code>```

Title: Retrieving token on Swagger

Body:
I need to retrieve token from link.
But when I enter valid username and password I do not see any token. Also I tried to retrieve it in my C# Android program.

`var client = new RestClient("https://networkrail-uk-qa.traffilog.com/swagger/ui/index#!/User/User_LoginData");
request.AddParameter("username", login);
request.AddParameter("password", password);
IRestResponse response = client.Execute(request);
var content = response.Content;`

There are a lot of data in output but there is no token. How can I get deal with it?

Body:
The request URL is wrong.

https://networkrail-uk-qa.traffilog.com/swagger/ui/index#!/User/User_LoginData

is just a documentation page (aka Swagger UI), not the actual request URL.

To find out the actual URL, use Swagger UI's "Try it out" feature: fill out the operation parameters and click "Try it out". It looks like the correct URL is

https://networkrail-uk-qa.traffilog.com/UK/api/User/Login?username={login}&password={password}

where the login and password need to be URL-encoded.

Also note the request HTTP method (POST), and that the parameters need to be passed in the query string. With all that in mind, your code should be:

var client = new RestClient("https://networkrail-uk-qa.traffilog.com");
var request = new RestRequest("UK/api/User/Login", Method.POST);
request.AddQueryParameter("username", login);
request.AddQueryParameter("password", password);

IRestResponse response = client.Execute(request);


问:
c# private boolean error inside method
Sorry for the noobish question and there is probably a very easy fix to this, but I am making an application and I am trying to return a boolean to be used in another method when a checkbox is ticked. Though here I receive an error after the first { saying } expected. Thanks in advance, P

```<code>    private void CheckImgur_Checked(object sender, RoutedEventArgs e)
    {
        private bool imgurChecked = true;
    }
</code>```

答:
You cannot declare variables with access modifiers (-> private) inside of a method. Further if you'd want to return the bool, this is done with the return keyword.

Keep in mind that a method that returns a value of a specific class needs to have this and not void as a return type.

Title: c# private boolean error inside method

Body:
Sorry for the noobish question and there is probably a very easy fix to this, but I am making an application and I am trying to return a boolean to be used in another method when a checkbox is ticked. Though here I receive an error after the first { saying } expected. Thanks in advance, P

    private void CheckImgur_Checked(object sender, RoutedEventArgs e)
    {
        private bool imgurChecked = true;
    }


问:
How to add suffix and prefix to all columns in python/pyspark dataframe
I have a data frame in pyspark with more than 100 columns. What I want to do is for all the column names I would like to add back ticks(`) at the start of the column name and end of column name.

For example:

```<code>column name  is testing user. I want `testing user`
</code>```

Is there a method to do this in pyspark/python. when we apply the code it should return a data frame.

答:
You can use withColumnRenamed method of dataframe in combination with na to create new dataframe

```<code>df.na.withColumnRenamed('testing user', '`testing user`')
</code>```

edit : suppose you have  list of columns, you can do like -

```<code>old = "First Last Age"
new = ["`"+field+"`" for field in old.split()]
df.rdd.toDF(new)
</code>```

output :

```<code>DataFrame[`First`: string, `Last`: string, `Age`: string]
</code>```

Body:
I have a data frame in pyspark with more than 100 columns. What I want to do is for all the column names I would like to add back ticks(`) at the start of the column name and end of column name.

For example:

column name  is testing user. I want `testing user`

Is there a method to do this in pyspark/python. when we apply the code it should return a data frame.

Body:
You can use withColumnRenamed method of dataframe in combination with na to create new dataframe

df.na.withColumnRenamed('testing user', '`testing user`')

edit : suppose you have  list of columns, you can do like -

old = "First Last Age"
new = ["`"+field+"`" for field in old.split()]
df.rdd.toDF(new)

output :

DataFrame[`First`: string, `Last`: string, `Age`: string]


问:
How to add css style to the all children of element at the same time?
Such as:

```<code><div class="mostOut">
    <div class="a">
        <h3 class="b"></h3>
        <div class="d"></div>
    </div>
</div>
</code>```

And how can I apply css style to the children of "moustOut" at the same time.E.g:

with one click event.the css('opacity',1) could apply to the "a","b","d" at the same time.Or ,exclude "b" .

答:
This might be a dirty solution, but it should work:

```<code>$('.mostOut').click(function()
{
  $(this).find('*').each(function()
  {
    $(this).css('opacity', 1);
  });
});
</code>```

For excluding all but the b element, try this:

```<code>$('.mostOut').click(function()
{
  $(this).find('*').not('.b').each(function()
  {
    $(this).css('opacity', 1);
  });
});
</code>```

Play with the code, as I just typed this off of the top of my head, so I'm not guaranteeing that it will work.

Good luck!

Body:
Such as:

And how can I apply css style to the children of "moustOut" at the same time.E.g:

with one click event.the css('opacity',1) could apply to the "a","b","d" at the same time.Or ,exclude "b" .

Body:
This might be a dirty solution, but it should work:

$('.mostOut').click(function()
{
  $(this).find('*').each(function()
  {
    $(this).css('opacity', 1);
  });
});

For excluding all but the b element, try this:

$('.mostOut').click(function()
{
  $(this).find('*').not('.b').each(function()
  {
    $(this).css('opacity', 1);
  });
});

Play with the code, as I just typed this off of the top of my head, so I'm not guaranteeing that it will work.

Good luck!


问:
Puzzler: How To Group Rows By A Particular Sum of a Particular Column
How to burst the following rows into 3 groups where the sum of "dollars" is 10. All rows must be used and none more than once.

```<code>row|dollars
1|1
2|1
3|1
4|1
5|1
6|1
7|3
8|4
9|7
10|10
</code>```

One (of many possible) desired outcomes would be...

```<code>Row Group 1 = 10
Row Group 2 = 7,9
Row Group 3 = 1,2,3,4,5,6,8
</code>```

Extra Credit:
When it's not mathematically possible to get a sum of exactly $10 in each group, is there a formula for getting us closest to that?

I though maybe " HAVING sum(dollar) = 10 " or, for a close solution, just sorting and distributing one row to one group, but that didn't get me close.

Group Row By Sum of Specific Column equal to Specific Value sort of touches on this, but, assuming their could be millions of rows, there would be performance issues.
I'm stumped.

If it helps, I'm using php and mysql. A sql-only solution would be ideal, but some combination would be great too. Thanks for any suggestions.

Edit: If I wasn't clear, I want to return the rows that make this possible, not just "group by" them.

答:
I don't think you could do it with just sql, but it could certainly help out. I'd start by having a query like select * from data where dollars <= 10 order by dollars desc and then make an algorithm in php that went through the results and added up dollars until it found three sets that add up to 10.

It would start out adding from larger to smaller until it found a correct sum, then store it, remove those items from the list and start again, three times. I'm on my phone, but will update the answer with a working example when I get to my computer.

EDIT: got to my computer. This is very messy code, but it should lead you in the right direction.

```<code>$dataset = [10,7,4,3,1,1,1,1,1,1];
$results = [];

function add_to_ten(&$data) {
    $sum = 0;
    $results = [];

    foreach ($data as $index => &$datum) {
        if ($datum == 0) {
            continue;
        }
        if ($sum + $datum <= 10) {
            $sum += $datum;
            $results[] = $index;
            $datum = 0;
        }
        if ($sum == 10) {
            return $results;
        }
    }
}

print_r(add_to_ten($dataset));
print_r(add_to_ten($dataset));
print_r(add_to_ten($dataset));
</code>```

Body:
How to burst the following rows into 3 groups where the sum of "dollars" is 10. All rows must be used and none more than once.

row|dollars
1|1
2|1
3|1
4|1
5|1
6|1
7|3
8|4
9|7
10|10

One (of many possible) desired outcomes would be...

Row Group 1 = 10
Row Group 2 = 7,9
Row Group 3 = 1,2,3,4,5,6,8

Extra Credit:
When it's not mathematically possible to get a sum of exactly $10 in each group, is there a formula for getting us closest to that?

I though maybe " HAVING sum(dollar) = 10 " or, for a close solution, just sorting and distributing one row to one group, but that didn't get me close.

Group Row By Sum of Specific Column equal to Specific Value sort of touches on this, but, assuming their could be millions of rows, there would be performance issues.
I'm stumped.

If it helps, I'm using php and mysql. A sql-only solution would be ideal, but some combination would be great too. Thanks for any suggestions.

Edit: If I wasn't clear, I want to return the rows that make this possible, not just "group by" them.

Body:
I don't think you could do it with just sql, but it could certainly help out. I'd start by having a query like select * from data where dollars <= 10 order by dollars desc and then make an algorithm in php that went through the results and added up dollars until it found three sets that add up to 10.

It would start out adding from larger to smaller until it found a correct sum, then store it, remove those items from the list and start again, three times. I'm on my phone, but will update the answer with a working example when I get to my computer.

EDIT: got to my computer. This is very messy code, but it should lead you in the right direction.

$dataset = [10,7,4,3,1,1,1,1,1,1];
$results = [];

function add_to_ten(&$data) {
    $sum = 0;
    $results = [];

    foreach ($data as $index => &$datum) {
        if ($datum == 0) {
            continue;
        }
        if ($sum + $datum <= 10) {
            $sum += $datum;
            $results[] = $index;
            $datum = 0;
        }
        if ($sum == 10) {
            return $results;
        }
    }
}

print_r(add_to_ten($dataset));
print_r(add_to_ten($dataset));
print_r(add_to_ten($dataset));


问:
Vertical lines for Bode plots in Matlab
I have graphed a Bode plot for my transfer function, and I was wondering if there is some way to insert either horizontal or vertical lines to show a specific value for the gain/phase angle or frequency?

I have found with the following code I can draw a horizontal line on the phase angle graph:

```<code>x = linspace(10^-1,10^2,100);

for bleh = 1:length(x)
      y(bleh) = -30.9638;
end

bode(num, den)
hold on
plot(x,y)
</code>```

But this does not seem to apply in the gain graph, nor does my limited knowledge (and only way that makes sense to me) of vertical lines. I tried:

```<code>y1 = get(gca,'ylim');
w1 = 1.2;

bode(num, den)
hold on

plot(x,y,[w1 w1],y1)
</code>```

But I only get the one horizontal line as was done from the above code.
Is this a possibility?

(Using R2017a, if that matters.)

答:
I'm not sure I've understood you question, nevertheless, I propose the following.

When there are more one axes in a figure, as it is the case of the bode diagram, if you want to add something in a specific axes (or in all) you have to specify, in the call to plot the handle of the axes.

So, to add lines in the bode diagram, you have first to identify the handles of the two axes: you can do it in, at least two way:

using the findobj function: ax=findobj(gcf,'type','axes')

extract them as the Children of the figure: ax=get(gcf,'children')

Once you have the handles of the axes, you can get their XLim and YLim that you can use to limit the extent of the line you want to add.

In the following example, I've used the above proposed approach to add two lines in each graph.

The horizontal and vertical lines are added in the middle point of the X and Y axes (problably this point does not have a relevant meaning, but it is ... just an example).

```<code>% Define a transfer function
H = tf([1 0.1 7.5],[1 0.12 9 0 0]);
% PLot the bode diagram
bode(H)
% Get the handles of the axes
ax=findobj(gcf,'type','axes')
phase_ax=ax(1)
mag_ax=ax(2)
% Get the X axis limits (it is the same for both the plot
ax_xlim=phase_ax.XLim
% Get the Y axis limits
phase_ylim=phase_ax.YLim
mag_ylim=mag_ax.YLim
%
% Define some points to be used in the plot
%    middle point of the X and Y axes of the two plots
%
mid_x=(ax_xlim(1)+ax_xlim(2))/2
mid_phase_y=(phase_ylim(1)+phase_ylim(2))/2
mid_mag_y=(mag_ylim(1)+mag_ylim(2))/2
% Set hold to on to add the line
hold(phase_ax,'on')
% Add a vertical line in the Phase plot
plot(phase_ax,[mid_x mid_x],[phase_ylim(1) phase_ylim(2)])
% Add an horizontal line in the Phase plot
plot(phase_ax,[ax_xlim(1), ax_xlim(2)],[mid_phase_y mid_phase_y])
% Set hold to on to add the line
hold(mag_ax,'on')
% Add a vertical line in the Magnitide plot
plot(mag_ax,[mid_x mid_x],[mag_ylim(1) mag_ylim(2)])
% Add an Horizontal line in the Magnitide plot
plot(mag_ax,[ax_xlim(1), ax_xlim(2)],[mid_mag_y mid_mag_y])
</code>```

Hope this helps,

Qapla'

Title: Vertical lines for Bode plots in Matlab

Body:
I have graphed a Bode plot for my transfer function, and I was wondering if there is some way to insert either horizontal or vertical lines to show a specific value for the gain/phase angle or frequency?

I have found with the following code I can draw a horizontal line on the phase angle graph:

x = linspace(10^-1,10^2,100);

for bleh = 1:length(x)
      y(bleh) = -30.9638;
end

bode(num, den)
hold on
plot(x,y)

But this does not seem to apply in the gain graph, nor does my limited knowledge (and only way that makes sense to me) of vertical lines. I tried:

y1 = get(gca,'ylim');
w1 = 1.2;

bode(num, den)
hold on

plot(x,y,[w1 w1],y1)

But I only get the one horizontal line as was done from the above code.
Is this a possibility?

(Using R2017a, if that matters.)

Body:
I'm not sure I've understood you question, nevertheless, I propose the following.

When there are more one axes in a figure, as it is the case of the bode diagram, if you want to add something in a specific axes (or in all) you have to specify, in the call to plot the handle of the axes.

So, to add lines in the bode diagram, you have first to identify the handles of the two axes: you can do it in, at least two way:

using the findobj function: ax=findobj(gcf,'type','axes')

extract them as the Children of the figure: ax=get(gcf,'children')

Once you have the handles of the axes, you can get their XLim and YLim that you can use to limit the extent of the line you want to add.

In the following example, I've used the above proposed approach to add two lines in each graph.

The horizontal and vertical lines are added in the middle point of the X and Y axes (problably this point does not have a relevant meaning, but it is ... just an example).

% Define a transfer function
H = tf([1 0.1 7.5],[1 0.12 9 0 0]);
% PLot the bode diagram
bode(H)
% Get the handles of the axes
ax=findobj(gcf,'type','axes')
phase_ax=ax(1)
mag_ax=ax(2)
% Get the X axis limits (it is the same for both the plot
ax_xlim=phase_ax.XLim
% Get the Y axis limits
phase_ylim=phase_ax.YLim
mag_ylim=mag_ax.YLim
%
% Define some points to be used in the plot
%    middle point of the X and Y axes of the two plots
%
mid_x=(ax_xlim(1)+ax_xlim(2))/2
mid_phase_y=(phase_ylim(1)+phase_ylim(2))/2
mid_mag_y=(mag_ylim(1)+mag_ylim(2))/2
% Set hold to on to add the line
hold(phase_ax,'on')
% Add a vertical line in the Phase plot
plot(phase_ax,[mid_x mid_x],[phase_ylim(1) phase_ylim(2)])
% Add an horizontal line in the Phase plot
plot(phase_ax,[ax_xlim(1), ax_xlim(2)],[mid_phase_y mid_phase_y])
% Set hold to on to add the line
hold(mag_ax,'on')
% Add a vertical line in the Magnitide plot
plot(mag_ax,[mid_x mid_x],[mag_ylim(1) mag_ylim(2)])
% Add an Horizontal line in the Magnitide plot
plot(mag_ax,[ax_xlim(1), ax_xlim(2)],[mid_mag_y mid_mag_y])

Hope this helps,

Qapla'


问:
Running Four Queries on Three Database in PHP
I'm fairly new to PHP and MySQL and going on things i've read in various places I've managed to chop together this script, unfortunately the output isn't quite what I expected, I get lots of:

```<code>Buffer Status 2H: Notice: Undefined variable: row in /var/www/secretbit/allbuff.php on line 53 0 records. <br />
Buffer Status TC: Notice: Undefined variable: row in /var/www/secretbit/allbuff.php on line 54 0 records. <br />
Buffer Status ST: Notice: Undefined variable: row in /var/www/secretbit/allbuff.php on line 55 0 records. <br />
Buffer Status 3C: Notice: Undefined variable: row in /var/www/secretbit/allbuff.php on line 56 0 records <br />
</code>```

And here is the code I've used to compile this monster:

```<code> <?php

 error_reporting(-1);
 ini_set('display_errors', true);

 $con = mysqli_connect(
   '192.168.20.10',
   'root2',
   'password',
   'contaque'
 );

 $con2 = mysqli_connect(
   '192.168.20.222',
   'root2',
   'password',
   'contaque'
 );

 $con3 = mysqli_connect(
   '192.168.20.8',
   'root2',
   'password',
   'contaque'
 );

 $res = mysqli_query(
 $con,
  "SELECT COUNT(*) AS 'total1' FROM contaque_hopper WHERE  campaign_id = 'CLOSERUK';"
 );

 $res = mysqli_query(
 $con2,
  "SELECT COUNT(*) AS 'total2' FROM contaque_hopper WHERE  campaign_id = 'CLOSERTC';"
 );

 $res = mysqli_query(
 $con2,
  "SELECT COUNT(*) AS 'total3' FROM contaque_hopper WHERE  campaign_id = 'CLOSERST';"
 );

 $res = mysqli_query(
 $con3,
  "SELECT COUNT(*) AS 'total4' FROM contaque_hopper WHERE  campaign_id = 'CLOSER3C';"
 );

 echo 'Buffer Status 2H: ', (int)$row['total1'], ' records. <br />';
 echo 'Buffer Status TC: ', (int)$row['total2'], ' records. <br />';
 echo 'Buffer Status ST: ', (int)$row['total3'], ' records. <br />';
 echo 'Buffer Status 3C: ', (int)$row['total4'], ' records. <br />';

 ?>
</code>```

答: Well it looks like $row is undefined. I think you probably need to use the method mysqli_fetch_assoc() to get the results of the queries.

Body:
I'm fairly new to PHP and MySQL and going on things i've read in various places I've managed to chop together this script, unfortunately the output isn't quite what I expected, I get lots of:

Buffer Status 2H: Notice: Undefined variable: row in /var/www/secretbit/allbuff.php on line 53 0 records.

Buffer Status TC: Notice: Undefined variable: row in /var/www/secretbit/allbuff.php on line 54 0 records.

Buffer Status ST: Notice: Undefined variable: row in /var/www/secretbit/allbuff.php on line 55 0 records.

Buffer Status 3C: Notice: Undefined variable: row in /var/www/secretbit/allbuff.php on line 56 0 records

And here is the code I've used to compile this monster:

 <?php

 error_reporting(-1);
 ini_set('display_errors', true);

 $con = mysqli_connect(
   '192.168.20.10',
   'root2',
   'password',
   'contaque'
 );

 $con2 = mysqli_connect(
   '192.168.20.222',
   'root2',
   'password',
   'contaque'
 );

 $con3 = mysqli_connect(
   '192.168.20.8',
   'root2',
   'password',
   'contaque'
 );

 $res = mysqli_query(
 $con,
  "SELECT COUNT(*) AS 'total1' FROM contaque_hopper WHERE  campaign_id = 'CLOSERUK';"
 );

 $res = mysqli_query(
 $con2,
  "SELECT COUNT(*) AS 'total2' FROM contaque_hopper WHERE  campaign_id = 'CLOSERTC';"
 );

 $res = mysqli_query(
 $con2,
  "SELECT COUNT(*) AS 'total3' FROM contaque_hopper WHERE  campaign_id = 'CLOSERST';"
 );

 $res = mysqli_query(
 $con3,
  "SELECT COUNT(*) AS 'total4' FROM contaque_hopper WHERE  campaign_id = 'CLOSER3C';"
 );

 echo 'Buffer Status 2H: ', (int)$row['total1'], ' records.
';
 echo 'Buffer Status TC: ', (int)$row['total2'], ' records.
';
 echo 'Buffer Status ST: ', (int)$row['total3'], ' records.
';
 echo 'Buffer Status 3C: ', (int)$row['total4'], ' records.
';

 ?>


问:
How to Forward Values using excel formula
I am making one excel drawsheet for tennis.

As you can see Federer has won 6-2 against opponent, so as I update score player whose value is max should be moved forward to where I have written formula goes here.

I also want the formula to check if the opponent value is Bye. Then the player should be moved to next round as in case 2 Nadal should be forwarded.

I am trying from past 3 days, but I am still not able to get the solution.

Please help.

答:
An appropriate formula for D4 would be:

```<code>=IF(B3="Bye",B6,IF(B6="Bye",B3,IF(C4="","",IF(C4>C5,B3,B6))))
</code>```

That will first check the two players' names for the word "Bye" and use the other player's name if appropriate.

Having determined it isn't a bye, it then checks to see whether the game is yet to be played and, if so, sets the winner's name to blank (as there isn't a winner until there is a score).

Once it is determined that the game has been played, it picks the name of whoever had the highest score.  (Note: It does not allow for a draw - I'm not sure whether the game you are scoring allows for "draws" or not.)

Body:
An appropriate formula for D4 would be:

=IF(B3="Bye",B6,IF(B6="Bye",B3,IF(C4="","",IF(C4>C5,B3,B6))))

That will first check the two players' names for the word "Bye" and use the other player's name if appropriate.

Having determined it isn't a bye, it then checks to see whether the game is yet to be played and, if so, sets the winner's name to blank (as there isn't a winner until there is a score).

Once it is determined that the game has been played, it picks the name of whoever had the highest score.  (Note: It does not allow for a draw - I'm not sure whether the game you are scoring allows for "draws" or not.)


问:
Why am I getting 401 UnauthorizedError when getting a list of events using the SocialTables API?
I am trying to use the API Console to get access to event information. When I use https://api.socialtables.com/4.0/events/ I get a 401 response code, where I expect to see a list of events that I have created.

I am the owner on the account, and other calls in the API Console are working. I can query https://api.socialtables.com/4.0/users/ with my user id and https://api.socialtables.com/4.0/accounts/ with my account id.

I get the same behavior when calling the API from Postman.

Update

I was able to find my team id by inspecting the URL. It appeared to be an legacy numeric id, so I tried one of the legacy endpoints:

https://api.socialtables.com/4.0/legacyvm3/teams/[TEAM-ID]/events

That works, and returns the list of events that I expected. However, it only returns the legacy id values. I'd prefer to strictly use the newer ids and API endpoints.

答:
Thanks for using our API.  I couldn't reproduce the 401 unauthorized issue, but I noticed our trial signup put you in the 3.0 version, which is why you see your 3.0 events. Our trial process is currently being revised to put people in our latest version, and will do that soon.

In the meantime I went ahead and migrated your account to 4.0 and created a test v4 event.

Using this curl gives me the expected result:

```<code>curl --request GET \
>   --url https://api.socialtables.com/4.0/events \
>   --header 'authorization: Bearer XXXXXXXXXXXXXXXXXXXXXXXXXXXXade8'
</code>```

If you have further questions I'd be happy to assist.

Body:
Thanks for using our API.  I couldn't reproduce the 401 unauthorized issue, but I noticed our trial signup put you in the 3.0 version, which is why you see your 3.0 events. Our trial process is currently being revised to put people in our latest version, and will do that soon.

In the meantime I went ahead and migrated your account to 4.0 and created a test v4 event.

Using this curl gives me the expected result:

curl --request GET \
>   --url https://api.socialtables.com/4.0/events \
>   --header 'authorization: Bearer XXXXXXXXXXXXXXXXXXXXXXXXXXXXade8'

If you have further questions I'd be happy to assist.


问:
Using setImageDrawable dynamically to set image in an ImageView
I am generating a string from database dynamically which has the same name of image in drawable folder.

Now I want to set that value for ImageView using setImageDrawable(R.id.StringGenerated) dynamically.

Any Suggestions..

答:
All the answers posted do not apply today. For example, getDrawable() is deprecated. Here is an updated answer, cheers!

```<code>ContextCompat.getDrawable(mContext, drawable)
</code>```

From documented method

public static final android.graphics.drawable.Drawable
  getDrawable(@NotNull android.content.Context context,

  @android.support.annotation.DrawableRes int id

Body:
All the answers posted do not apply today. For example, getDrawable() is deprecated. Here is an updated answer, cheers!

ContextCompat.getDrawable(mContext, drawable)

From documented method

public static final android.graphics.drawable.Drawable
  getDrawable(@NotNull android.content.Context context,

  @android.support.annotation.DrawableRes int id