问:
Help with a leaky function
```<code>-(void)determineClosestLocationToUser:(NSArray *)allLocations
                                locationOfUser:(MapLocation *)userLocationIn
{
    // Determine how many objects you have in the array (incase you'e too lazy to count, or changed the
    // code to enter locations dynamically
    NSUInteger counter = [allLocations count];

    // set this value to the first item in the array, so it has something to compare to
    closestLocationFound = [allLocations objectAtIndex:0];

    // run a for loop to compare each of the locations in the array against the user location to determine
    // which location is the closest
    for(NSUInteger i = 0; i < counter; i++)
    {
        // setup 2 variables to hold the distances between the user and both locations for comparison
        CLLocationDistance distance1 = 0;
        CLLocationDistance distance2 = 0;

        // create a CLLocation variable using the values from our MapLocation variable
        // in order to utilize the getDistanceFrom function
        CLLocation *user = [[CLLocation alloc] initWithLatitude:userLocationIn.coordinate.latitude longitude:userLocationIn.coordinate.longitude];
        CLLocation *closest = [[CLLocation alloc] initWithLatitude:closestLocationFound.coordinate.latitude longitude:closestLocationFound.coordinate.longitude];

        // create a variable to hold the values stores in the array
        // (this should be accessed directly from the array, but I'm not sure how to do it yet - CHANGE THIS)
        MapLocation *tempLoc = [[MapLocation alloc] init];
        tempLoc = [allLocations objectAtIndex:i];

        // create a CLLocation variable to hold the coordinates for each object in the array
        // (has to be CLLocation for the getDistance from function to work)
        CLLocation *check = [[CLLocation alloc] initWithLatitude:tempLoc.coordinate.latitude longitude:tempLoc.coordinate.longitude];

        // get the distance from the current closest location
        distance1 = [user getDistanceFrom:closest];
        // now get the distance from the next location in the array
        distance2 = [user getDistanceFrom:check];

        // if the location we just checked is closer than the location we're currently storing
        if(distance2 < distance1)
        {
            // declare that location the closest
            closestLocationFound = [allLocations objectAtIndex:i];
        }

        // clean up
        [user release];
        [tempLoc release];
        [check release];
        [closest release];
    }
}
</code>```

I checked my code with the Leaks performance tool and it shows my app only has one leak (category:MapLocation , eventType: Malloc, size: 48, responsibleCaller:( ^ the above function) ) When I double click on the function it takes me to this line.

```<code>distance1 = [user getDistanceFrom:closest];
</code>```

Any ideas or suggestions? Thanks in advance.

答:
```<code>MapLocation *tempLoc = [[MapLocation alloc] init];
</code>```

That's the line. You're alloc/init'ing a new MapLocation, and then immediately throwing it out

```<code>tempLoc = [allLocations objectAtIndex:i];
</code>```

When this line executes, the original value of tempLoc is leaked. That first line is useless and these should be combined in to

```<code>MapLocation *tempLoc = [allLocations objectAtIndex:i];
</code>```

Title: Help with a leaky function

Body:
-(void)determineClosestLocationToUser:(NSArray *)allLocations
                                locationOfUser:(MapLocation *)userLocationIn
{
    // Determine how many objects you have in the array (incase you'e too lazy to count, or changed the
    // code to enter locations dynamically
    NSUInteger counter = [allLocations count];

    // set this value to the first item in the array, so it has something to compare to
    closestLocationFound = [allLocations objectAtIndex:0];

    // run a for loop to compare each of the locations in the array against the user location to determine
    // which location is the closest
    for(NSUInteger i = 0; i < counter; i++)
    {
        // setup 2 variables to hold the distances between the user and both locations for comparison
        CLLocationDistance distance1 = 0;
        CLLocationDistance distance2 = 0;

        // create a CLLocation variable using the values from our MapLocation variable
        // in order to utilize the getDistanceFrom function
        CLLocation *user = [[CLLocation alloc] initWithLatitude:userLocationIn.coordinate.latitude longitude:userLocationIn.coordinate.longitude];
        CLLocation *closest = [[CLLocation alloc] initWithLatitude:closestLocationFound.coordinate.latitude longitude:closestLocationFound.coordinate.longitude];

        // create a variable to hold the values stores in the array
        // (this should be accessed directly from the array, but I'm not sure how to do it yet - CHANGE THIS)
        MapLocation *tempLoc = [[MapLocation alloc] init];
        tempLoc = [allLocations objectAtIndex:i];

        // create a CLLocation variable to hold the coordinates for each object in the array
        // (has to be CLLocation for the getDistance from function to work)
        CLLocation *check = [[CLLocation alloc] initWithLatitude:tempLoc.coordinate.latitude longitude:tempLoc.coordinate.longitude];

        // get the distance from the current closest location
        distance1 = [user getDistanceFrom:closest];
        // now get the distance from the next location in the array
        distance2 = [user getDistanceFrom:check];

        // if the location we just checked is closer than the location we're currently storing
        if(distance2 < distance1)
        {
            // declare that location the closest
            closestLocationFound = [allLocations objectAtIndex:i];
        }

        // clean up
        [user release];
        [tempLoc release];
        [check release];
        [closest release];
    }
}

I checked my code with the Leaks performance tool and it shows my app only has one leak (category:MapLocation , eventType: Malloc, size: 48, responsibleCaller:( ^ the above function) ) When I double click on the function it takes me to this line.

distance1 = [user getDistanceFrom:closest];

Any ideas or suggestions? Thanks in advance.

Body:
MapLocation *tempLoc = [[MapLocation alloc] init];

That's the line. You're alloc/init'ing a new MapLocation, and then immediately throwing it out

tempLoc = [allLocations objectAtIndex:i];

When this line executes, the original value of tempLoc is leaked. That first line is useless and these should be combined in to

MapLocation *tempLoc = [allLocations objectAtIndex:i];


来源: stackexchange

问:
How does select work when multiple channels are involved?
I found when using select on multiple non buffered channels like

```<code>select {
case <- chana:
case <- chanb:
}
</code>```

Even when both channels have data, but when processing this select,
the call that falls in case chana and case chanb is not balanced.

```<code>package main

import (
    "fmt"
    _ "net/http/pprof"
    "sync"
    "time"
)

func main() {
    chana := make(chan int)
    chanb := make(chan int)

    go func() {
        for i := 0; i < 1000; i++ {
            chana <- 100 * i
        }
    }()

    go func() {
        for i := 0; i < 1000; i++ {
            chanb <- i
        }
    }()

    time.Sleep(time.Microsecond * 300)

    acount := 0
    bcount := 0
    wg := sync.WaitGroup{}
    wg.Add(1)
    go func() {
        for {
            select {
            case <-chana:
                acount++
            case <-chanb:
                bcount++
            }
            if acount == 1000 || bcount == 1000 {
                fmt.Println("finish one acount, bcount", acount, bcount)
                break
            }
        }
        wg.Done()
    }()

    wg.Wait()
}
</code>```

Run this demo, when one of the chana,chanb finished read/write, the other may remain 999-1 left.

Is there any method to ensure the balance?

found related topic

golang-channels-select-statement

答:
The Go select statement is not biased toward any (ready) cases. Quoting from the spec:

If one or more of the communications can proceed, a single one that can proceed is chosen via a uniform pseudo-random selection. Otherwise, if there is a default case, that case is chosen. If there is no default case, the "select" statement blocks until at least one of the communications can proceed.

If multiple communications can proceed, one is selected randomly. This is not a perfect random distribution, and the spec does not guarantee that, but it's random.

What you experience is the result of the Go Playground having GOMAXPROCS=1 (which you can verify here) and the goroutine scheduler not being preemptive. What this means is that by default goroutines are not executed parallel. A goroutine is put in park if a blocking operation is encountered (e.g. reading from the network, or attempting to receive from or send on a channel that is blocking), and another one ready to run continues.

And since there is no blocking operation in your code, goroutines may not be put in park and it may be only one of your "producer" goroutines will run, and the other may not get scheduled (ever).

Running your code on my local computer where GOMAXPROCS=4, I have very "realistic" results. Running it a few times, the output:

```<code>finish one acount, bcount 1000 901
finish one acount, bcount 1000 335
finish one acount, bcount 1000 872
finish one acount, bcount 427 1000
</code>```

If you need to prioritize a single case, check out this answer: Force priority of go select statement

The default behavior of select does not guarantee equal priority, but on average it will be close to it. If you need guaranteed equal priority, then you should not use select, but you could do a sequence of 2 non-blocking receive from the 2 channels, which could look something like this:

```<code>for {
    select {
    case <-chana:
        acount++
    default:
    }
    select {
    case <-chanb:
        bcount++
    default:
    }
    if acount == 1000 || bcount == 1000 {
        fmt.Println("finish one acount, bcount", acount, bcount)
        break
    }
}
</code>```

The above 2 non-blocking receive will drain the 2 channels at equal speed (with equal priority) if both supply values, and if one does not, then the other is constantly received from without getting delayed or blocked.

One thing to note about this is that if none of the channels provide any values to receive, this will be basically a "busy" loop and hence consume computational power. To avoid this, we may detect that none of the channels were ready, and then use a select statement with both of the receives, which then will block until one of them is ready to receive from, not wasting any CPU resources:

```<code>for {
    received := 0
    select {
    case <-chana:
        acount++
        received++
    default:
    }
    select {
    case <-chanb:
        bcount++
        received++
    default:
    }

    if received == 0 {
        select {
        case <-chana:
            acount++
        case <-chanb:
            bcount++
        }
    }

    if acount == 1000 || bcount == 1000 {
        fmt.Println("finish one acount, bcount", acount, bcount)
        break
    }
}
</code>```

For more details about goroutine scheduling, see these questions:

Number of threads used by Go runtime

Goroutines 8kb and windows OS thread 1 mb

Why does it not create many threads when many goroutines are blocked in writing file in golang?

ContentLicense: CC BY-SA 4.0

Body:
I found when using select on multiple non buffered channels like

select {
case <- chana:
case <- chanb:
}

Even when both channels have data, but when processing this select,
the call that falls in case chana and case chanb is not balanced.

package main

import (
    "fmt"
    _ "net/http/pprof"
    "sync"
    "time"
)

func main() {
    chana := make(chan int)
    chanb := make(chan int)

    go func() {
        for i := 0; i < 1000; i++ {
            chana <- 100 * i
        }
    }()

    go func() {
        for i := 0; i < 1000; i++ {
            chanb <- i
        }
    }()

    time.Sleep(time.Microsecond * 300)

    acount := 0
    bcount := 0
    wg := sync.WaitGroup{}
    wg.Add(1)
    go func() {
        for {
            select {
            case <-chana:
                acount++
            case <-chanb:
                bcount++
            }
            if acount == 1000 || bcount == 1000 {
                fmt.Println("finish one acount, bcount", acount, bcount)
                break
            }
        }
        wg.Done()
    }()

    wg.Wait()
}

Run this demo, when one of the chana,chanb finished read/write, the other may remain 999-1 left.

Is there any method to ensure the balance?

found related topic

golang-channels-select-statement

Body:
The Go select statement is not biased toward any (ready) cases. Quoting from the spec:

If one or more of the communications can proceed, a single one that can proceed is chosen via a uniform pseudo-random selection. Otherwise, if there is a default case, that case is chosen. If there is no default case, the "select" statement blocks until at least one of the communications can proceed.

If multiple communications can proceed, one is selected randomly. This is not a perfect random distribution, and the spec does not guarantee that, but it's random.

What you experience is the result of the Go Playground having GOMAXPROCS=1 (which you can verify here) and the goroutine scheduler not being preemptive. What this means is that by default goroutines are not executed parallel. A goroutine is put in park if a blocking operation is encountered (e.g. reading from the network, or attempting to receive from or send on a channel that is blocking), and another one ready to run continues.

And since there is no blocking operation in your code, goroutines may not be put in park and it may be only one of your "producer" goroutines will run, and the other may not get scheduled (ever).

Running your code on my local computer where GOMAXPROCS=4, I have very "realistic" results. Running it a few times, the output:

finish one acount, bcount 1000 901
finish one acount, bcount 1000 335
finish one acount, bcount 1000 872
finish one acount, bcount 427 1000

If you need to prioritize a single case, check out this answer: Force priority of go select statement

The default behavior of select does not guarantee equal priority, but on average it will be close to it. If you need guaranteed equal priority, then you should not use select, but you could do a sequence of 2 non-blocking receive from the 2 channels, which could look something like this:

for {
    select {
    case <-chana:
        acount++
    default:
    }
    select {
    case <-chanb:
        bcount++
    default:
    }
    if acount == 1000 || bcount == 1000 {
        fmt.Println("finish one acount, bcount", acount, bcount)
        break
    }
}

The above 2 non-blocking receive will drain the 2 channels at equal speed (with equal priority) if both supply values, and if one does not, then the other is constantly received from without getting delayed or blocked.

One thing to note about this is that if none of the channels provide any values to receive, this will be basically a "busy" loop and hence consume computational power. To avoid this, we may detect that none of the channels were ready, and then use a select statement with both of the receives, which then will block until one of them is ready to receive from, not wasting any CPU resources:

for {
    received := 0
    select {
    case <-chana:
        acount++
        received++
    default:
    }
    select {
    case <-chanb:
        bcount++
        received++
    default:
    }

    if received == 0 {
        select {
        case <-chana:
            acount++
        case <-chanb:
            bcount++
        }
    }

    if acount == 1000 || bcount == 1000 {
        fmt.Println("finish one acount, bcount", acount, bcount)
        break
    }
}

For more details about goroutine scheduling, see these questions:

Number of threads used by Go runtime

Goroutines 8kb and windows OS thread 1 mb

Why does it not create many threads when many goroutines are blocked in writing file in golang?


问:
Array of strings: Segmentation fault(core dumped)
I'm trying to write a code that sorts an array of strings in alphabetical or reverse alphabetical order, depending on the command line argument given.

"-o a" for alphabetic.

"-o r" for reverse.

This is my code so far.

```<code>#include<stdio.h>
#include<string.h>

int string_compare(char *str1,char *str2){
    int ret;

    ret=strcmp(str1,str2);

    if(ret < 0) {
      return 0;
    }
    else if(ret > 0) {
      return 1;
    }
    else {
      return -1;
    }
}

void swap(char *str1, char *str2)
{
  char *temp = str1;
  str1 = str2;
  str2 = temp;
}

int main(int argc,char *argv[]){
    char *planets[9]={"Mercury","Venus","Earth","Mars","Jupiter","Saturn","Uranus","Neptune","Pluto"};
    int i,j;
    int a_ret=strcmp(argv[2],"a");
    int r_ret=strcmp(argv[2],"r");
    int cmp;

    for(i=0;i=8;i++){
        for(j=8;j=(i+1);j--){
            cmp=string_compare(planets[j],planets[j-1]);
            if(a_ret==0){
                if(cmp==0){
                    swap(planets[j],planets[j-1]);
                }
            }
            else if(r_ret==0){
                if(cmp==1){
                    swap(planets[j],planets[j-1]);
                }
            }
        }
    }
    printf("%s",planets[0]);
   return 0;
}
</code>```

The program is supposed to work something like this:

```<code>./planets –o a
The planets in alphabetical order are: Earth, Jupiter, Mars, Mercury, Neptune, Pluto, Saturn, Uranus, Venus
</code>```

or this:

```<code>./planets –o r
The planets in reverse alphabetical order are: Venus, Uranus, Saturn, Pluto, Neptune, Mercury, Mars, Jupiter, Earth
</code>```

The program compiles without error, but when I run it I get

```<code>Segmentation fault(core dumped)
</code>```

I'm new to C, and I don't quite fully understand how to manipulate the memory allocation. Any help or advice is much appreciated.

答:
I fixed the logic errors that were pointed out and the swap function, and the program runs without crashing. The results are mostly right except for "Mercury".

Current program:

```<code>#include<stdio.h>
#include<string.h>

int string_compare(char *str1,char *str2){
    int ret;

    ret=strcmp(str1,str2);

    if(ret < 0) {
      return 0;
    }
    else if(ret > 0) {
      return 1;
    }
    else {
      return -1;
    }
}

void swap(char** s1, char** s2)
{
    char* temp = *s1;
    *s1 = *s2;
    *s2 = temp;
}

int main(int argc,char *argv[]){
    char *planets[9]={"Mercury","Venus","Earth","Mars","Jupiter","Saturn","Uranus","Neptune","Pluto"};
    int i,j;
    int a_ret=strcmp(argv[2],"a");
    int r_ret=strcmp(argv[2],"r");
    int cmp;

    for(i=0;i<8;i++){
        for(j=i+1;j<=8;j++){
            cmp=string_compare(planets[j-1],planets[j]);
            if(a_ret==0){
                if(cmp==1){
                    swap(&planets[j-1],&planets[j]);
                }
            }
            else if(r_ret==0){
                if(cmp==0){
                    swap(&planets[j-1],&planets[j]);
                }
            }
        }
    }
    for(int k=0;k<=8;k++){
        printf("%s,",planets[k]);

    }
    printf("\n");
return 0;
}
</code>```

Result with command line argument -o a:

```<code>Mercury,Earth,Jupiter,Mars,Neptune,Pluto,Saturn,Uranus,Venus,
</code>```

It seems the program skips the first string in the array.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to write a code that sorts an array of strings in alphabetical or reverse alphabetical order, depending on the command line argument given.

"-o a" for alphabetic.

"-o r" for reverse.

This is my code so far.

#include<stdio.h>
#include<string.h>

int string_compare(char *str1,char *str2){
    int ret;

    ret=strcmp(str1,str2);

    if(ret < 0) {
      return 0;
    }
    else if(ret > 0) {
      return 1;
    }
    else {
      return -1;
    }
}

void swap(char *str1, char *str2)
{
  char *temp = str1;
  str1 = str2;
  str2 = temp;
}

int main(int argc,char *argv[]){
    char *planets[9]={"Mercury","Venus","Earth","Mars","Jupiter","Saturn","Uranus","Neptune","Pluto"};
    int i,j;
    int a_ret=strcmp(argv[2],"a");
    int r_ret=strcmp(argv[2],"r");
    int cmp;

    for(i=0;i=8;i++){
        for(j=8;j=(i+1);j--){
            cmp=string_compare(planets[j],planets[j-1]);
            if(a_ret==0){
                if(cmp==0){
                    swap(planets[j],planets[j-1]);
                }
            }
            else if(r_ret==0){
                if(cmp==1){
                    swap(planets[j],planets[j-1]);
                }
            }
        }
    }
    printf("%s",planets[0]);
   return 0;
}

The program is supposed to work something like this:

./planets –o a
The planets in alphabetical order are: Earth, Jupiter, Mars, Mercury, Neptune, Pluto, Saturn, Uranus, Venus

or this:

./planets –o r
The planets in reverse alphabetical order are: Venus, Uranus, Saturn, Pluto, Neptune, Mercury, Mars, Jupiter, Earth

The program compiles without error, but when I run it I get

Segmentation fault(core dumped)

I'm new to C, and I don't quite fully understand how to manipulate the memory allocation. Any help or advice is much appreciated.

Body:
I fixed the logic errors that were pointed out and the swap function, and the program runs without crashing. The results are mostly right except for "Mercury".

Current program:

#include<stdio.h>
#include<string.h>

int string_compare(char *str1,char *str2){
    int ret;

    ret=strcmp(str1,str2);

    if(ret < 0) {
      return 0;
    }
    else if(ret > 0) {
      return 1;
    }
    else {
      return -1;
    }
}

void swap(char** s1, char** s2)
{
    char* temp = *s1;
    *s1 = *s2;
    *s2 = temp;
}

int main(int argc,char *argv[]){
    char *planets[9]={"Mercury","Venus","Earth","Mars","Jupiter","Saturn","Uranus","Neptune","Pluto"};
    int i,j;
    int a_ret=strcmp(argv[2],"a");
    int r_ret=strcmp(argv[2],"r");
    int cmp;

    for(i=0;i<8;i++){
        for(j=i+1;j<=8;j++){
            cmp=string_compare(planets[j-1],planets[j]);
            if(a_ret==0){
                if(cmp==1){
                    swap(&planets[j-1],&planets[j]);
                }
            }
            else if(r_ret==0){
                if(cmp==0){
                    swap(&planets[j-1],&planets[j]);
                }
            }
        }
    }
    for(int k=0;k<=8;k++){
        printf("%s,",planets[k]);

    }
    printf("\n");
return 0;
}

Result with command line argument -o a:

Mercury,Earth,Jupiter,Mars,Neptune,Pluto,Saturn,Uranus,Venus,

It seems the program skips the first string in the array.


问:
Update a field of document using DSL query
I am working on generating logs and then from those logs generating an index. I have generated an index from the logs but now I need to modify a field of all the documents having that field.

Technically there is a field in my document named as status which tells the status of the transaction, In my logstash configuration file I have given a status "Transaction posted on POS" but now I want to change that to "Transaction completed on POS"

It's more like a find and replace query, any idea how can I achieve this using DSL query?

答:
This sounds like something you could do with the update by query API.

You call that API with an Elasticsearch query to pick which documents to update (which can simply be a match-all if you want to update all documents) and a Painless script that actually changes the data in those documents.


问:
Errors defining templated class functions
I'm working on a template assignment for class and my code is giving me errors at these specific lines. "'T' is not a valid template type argument for parameter 'T'"

It's real confusing for me because I've never worked with namespaces before. Nor have I worked with an .inl. Could someone help correct my code? I've inserted comments at where the compiler is giving me errors, they're the functions that return a Node*. My code is not finished either.

BST.hpp

```<code>#ifndef BST_HPP
#define BST_HPP

namespace Tree{
    template<class T>
    class BST {
    public:
        BST();//default constructor
        BST(T rootkey);//constructor with 1 parameter for root key
        ~BST();//destructor
        void insert(T value); //function named insert with 1 parameter(key value to insert)
        Node* remove(class Node* troot,T value);//function named remove with 1 parameter (key value to remove)
        Node* min(class Node* mini);
    private:
        class Node {
        public:
            Node();//default constructor
            Node(T k);//constructor with 1 parameter (key value)
            ~Node(); //destructor
            Node* getP(); //parent accessor
            Node* getL();//left accessor
            Node* getR();//right accessor
            parent mutator
            left mutator
            right mutator
            operator <
            operator ==
            operator !=
            operator <<
        private:
            T key;
            Node *parent;
            Node *left;
            Node *right;
        };
        Node *root;
        void destroy(Node* r);

    };

};

#include "BST.inl"
#endif
</code>```

BST.inl

```<code>#include "BST.hpp"
template<class T>
inline Tree::BST<T>::BST(T rootkey)
{
    root = new Node(rootkey);
    root->setP(0);
}

template<class T>
inline Tree::BST<T>::BST()
{
    root = new Node();
}

template<class T>
inline Tree::BST<T>::~BST()
{
    delete root;
}

template<class T>
inline void Tree::BST<T>::insert(T value)
{
    Node *temp = root;
    Node *prev;
    do
    {
        if (value < temp->getK())
        {
            prev = temp;
            temp = temp->getL();
        }
        else if (value >= temp->getK())
        {
            prev = temp;
            temp = temp->getR();
        }
    } while (temp != NULL);
    temp = new Node(value);
    temp->setP(prev);
    if (temp->getK() > prev->getK())
    {
        prev->setR(temp);
    }
    else
    {
        prev->setL(temp);
    }
}

template<class T>
inline Node * Tree::BST<T>::remove(Node *troot, T value)//ERROR
{
    Node *temp;
    if (troot == NULL)
    {
        return troot;
    }
    else if (value > troot->getK())
    {
        return remove(troot->getR(), value)
    }
    else if (value < troot->getK())
    {
        return remove(troot->getL(), value)
    }
    else
    {
        if (troot->getL() == NULL && troot->getR() == NULL)
        {
            delete troot;
            troot = NULL;
            return troot;
        }
        else if (troot->getR() == NULL)
        {
            temp = troot;
            troot = troot->getL();
            return troot;
        }
        else if (troot->getL() == NULL)
        {
            temp = troot;
            troot = troot->getR();
            return troot;
        }
        else
        {
            temp = min(troot->getR());
            troot->setK(temp->getK());
            troot->getR() = remove(troot->getR, temp->getK());
        }
    }
    return troot;
}

template<class T>
inline Node * Tree::BST<T>::min(Node * mini)//ERROR
{
    if (mini->getL() != NULL)
    {
        mini = mini->getL();
    }
    else
        return mini;
}

template<class T>
inline Tree::BST<T>::Node::Node()
{
    key = 0;
}

template<class T>
inline Tree::BST<T>::Node::Node(T k)
{
    key = k;
}

template<class T>
inline Tree::BST<T>::Node::~Node()
{
    delete getL();
    delete getR();
}

template<class T>
inline Node * Tree::BST<T>::Node::getP()//ERROR
{
    return parent;
}

template<class T>
inline Node * Tree::BST<T>::Node::getL()//ERROR
{
    return left;
}
</code>```

答:
In this line:

```<code>template<class T>
inline Node * Tree::BST<T>::Node::getP() {
</code>```

There is no Node class at global scope for you to return. That's the only thing Node can refer to so far, since the compiler is still not inside BST<T>'s scope to find the internal Node. There are two ways to fix this:

Fully qualify the Node (works since C++98):

```<code>template<class T>
inline Tree::BST<T>::Node * Tree::BST<T>::Node::getP() {
</code>```

This fully qualifies the scope where Node is.

Use a trailing return type (my personal preference, C++11 and onward):

```<code>template<class T>
inline auto Tree::BST<T>::Node::getP() -> Node* {
</code>```

This delays the lookup of Node until it may begin inside the scope of the class.

Body:
I'm working on a template assignment for class and my code is giving me errors at these specific lines. "'T' is not a valid template type argument for parameter 'T'"

It's real confusing for me because I've never worked with namespaces before. Nor have I worked with an .inl. Could someone help correct my code? I've inserted comments at where the compiler is giving me errors, they're the functions that return a Node*. My code is not finished either.

BST.hpp

#ifndef BST_HPP
#define BST_HPP

namespace Tree{
    template<class T>
    class BST {
    public:
        BST();//default constructor
        BST(T rootkey);//constructor with 1 parameter for root key
        ~BST();//destructor
        void insert(T value); //function named insert with 1 parameter(key value to insert)
        Node* remove(class Node* troot,T value);//function named remove with 1 parameter (key value to remove)
        Node* min(class Node* mini);
    private:
        class Node {
        public:
            Node();//default constructor
            Node(T k);//constructor with 1 parameter (key value)
            ~Node(); //destructor
            Node* getP(); //parent accessor
            Node* getL();//left accessor
            Node* getR();//right accessor
            parent mutator
            left mutator
            right mutator
            operator <
            operator ==
            operator !=
            operator <<
        private:
            T key;
            Node *parent;
            Node *left;
            Node *right;
        };
        Node *root;
        void destroy(Node* r);

    };

};

#include "BST.inl"
#endif

BST.inl

#include "BST.hpp"
template<class T>
inline Tree::BST<T>::BST(T rootkey)
{
    root = new Node(rootkey);
    root->setP(0);
}

template<class T>
inline Tree::BST<T>::BST()
{
    root = new Node();
}

template<class T>
inline Tree::BST<T>::~BST()
{
    delete root;
}

template<class T>
inline void Tree::BST<T>::insert(T value)
{
    Node *temp = root;
    Node *prev;
    do
    {
        if (value < temp->getK())
        {
            prev = temp;
            temp = temp->getL();
        }
        else if (value >= temp->getK())
        {
            prev = temp;
            temp = temp->getR();
        }
    } while (temp != NULL);
    temp = new Node(value);
    temp->setP(prev);
    if (temp->getK() > prev->getK())
    {
        prev->setR(temp);
    }
    else
    {
        prev->setL(temp);
    }
}

template<class T>
inline Node * Tree::BST<T>::remove(Node *troot, T value)//ERROR
{
    Node *temp;
    if (troot == NULL)
    {
        return troot;
    }
    else if (value > troot->getK())
    {
        return remove(troot->getR(), value)
    }
    else if (value < troot->getK())
    {
        return remove(troot->getL(), value)
    }
    else
    {
        if (troot->getL() == NULL && troot->getR() == NULL)
        {
            delete troot;
            troot = NULL;
            return troot;
        }
        else if (troot->getR() == NULL)
        {
            temp = troot;
            troot = troot->getL();
            return troot;
        }
        else if (troot->getL() == NULL)
        {
            temp = troot;
            troot = troot->getR();
            return troot;
        }
        else
        {
            temp = min(troot->getR());
            troot->setK(temp->getK());
            troot->getR() = remove(troot->getR, temp->getK());
        }
    }
    return troot;
}

template<class T>
inline Node * Tree::BST<T>::min(Node * mini)//ERROR
{
    if (mini->getL() != NULL)
    {
        mini = mini->getL();
    }
    else
        return mini;
}

template<class T>
inline Tree::BST<T>::Node::Node()
{
    key = 0;
}

template<class T>
inline Tree::BST<T>::Node::Node(T k)
{
    key = k;
}

template<class T>
inline Tree::BST<T>::Node::~Node()
{
    delete getL();
    delete getR();
}

template<class T>
inline Node * Tree::BST<T>::Node::getP()//ERROR
{
    return parent;
}

template<class T>
inline Node * Tree::BST<T>::Node::getL()//ERROR
{
    return left;
}

Body:
In this line:

template<class T>
inline Node * Tree::BST<T>::Node::getP() {

There is no Node class at global scope for you to return. That's the only thing Node can refer to so far, since the compiler is still not inside BST<T>'s scope to find the internal Node. There are two ways to fix this:

Fully qualify the Node (works since C++98):

template<class T>
inline Tree::BST<T>::Node * Tree::BST<T>::Node::getP() {

This fully qualifies the scope where Node is.

Use a trailing return type (my personal preference, C++11 and onward):

template<class T>
inline auto Tree::BST<T>::Node::getP() -> Node* {

This delays the lookup of Node until it may begin inside the scope of the class.


问:
Mysql forcibly order by exact value
Need help with mysql request.

I make a request and I want to order result by the field ID.

ID for exemple: 1,2,3,4,5,6,7,8,9

But I need that it would be ordered like this: 6,3,1,2,4,5,7,8,9

Is there any solution in mysql  to forcibly put ID=6 in 1st place, ID=3 in 2nd...?

or I want the impossible)

答:
Use CASE expression in ORDER BY clause.

Query

```<code>select * from `your_table_name`
order by case `id` when 6 then 1 when 3 then 2 else 3 end, `id`;
</code>```

Find a demo here

Title: Mysql forcibly order by exact value

Body:
Use CASE expression in ORDER BY clause.

Query

select * from `your_table_name`
order by case `id` when 6 then 1 when 3 then 2 else 3 end, `id`;

Find a demo here


问:
Select Student list which is not in another table with date difference and aggregate function
I have three table i.e. "tblStudents", "tblStudentFee", "tblTransaction". table design is

tblStudents

```<code>StudID
Name
FatherName
MobileNO
ClassID
</code>```

tblStudentFee

```<code>StFeeID
StudID
SessionID
FeesID
FeeAmount
Discount
</code>```

tblTransaction

```<code>TransactionID
StFeeID
StudID
TransDate
Amount
</code>```

Now I want to join these table in a way that final table after join should have student fee data where tblTransaction.TransDate is 30 days old from today and I also want student who is not present in tblTransaction

答:
try this</p>

```<code>SELECT
tsf.*
FROM tblStudentFee tsf
inner join tblStudents ts
 on tsf.StudID = ts.StudID
left join tblTransaction tt
 on tt.StudID = ts.StudID
  and tt.StFeeID = ts.StFeeID
where
(
 tt.TransactionID is null
 or
 DATEDIFF(day,TransDate,getdate())=30
)
</code>```

Body:
I have three table i.e. "tblStudents", "tblStudentFee", "tblTransaction". table design is

tblStudents

StudID
Name
FatherName
MobileNO
ClassID

tblStudentFee

StFeeID
StudID
SessionID
FeesID
FeeAmount
Discount

tblTransaction

TransactionID
StFeeID
StudID
TransDate
Amount

Now I want to join these table in a way that final table after join should have student fee data where tblTransaction.TransDate is 30 days old from today and I also want student who is not present in tblTransaction

Body:
try this

SELECT
tsf.*
FROM tblStudentFee tsf
inner join tblStudents ts
 on tsf.StudID = ts.StudID
left join tblTransaction tt
 on tt.StudID = ts.StudID
  and tt.StFeeID = ts.StFeeID
where
(
 tt.TransactionID is null
 or
 DATEDIFF(day,TransDate,getdate())=30
)


问:
FCM and Typescript Async Await: Network Timing Out
I'm new to Typescript and I'm trying to use the async and await functionality. I'm getting some fcm network timeouts every once in a while and I believe it has to do with not returning my promises correctly.

Here is my cloud function for sending a push notification. The two functions that are using the await keyword are incrementBadgeCount, and sendPushNotification:

```<code>export const pushNotification = functions.firestore
  .document('company/{companyId}/message/{messageId}/chat/{chatId}')
  .onCreate(async event => {

const message = event.data.data();
const recipients = event.data.data().read;
const messageId = event.params.messageId;

const ids = [];
for (const key of Object.keys(recipients)) {
    const val = recipients[key];
    if (val === false) {
        ids.push(key);
    }
}

return await Promise.all(ids.map(async (id) => {
    const memberPayload = await incrementBadgeCount(id);
    const memberBadgeNumberString =
      memberPayload.getBadgeCount().toString();

    const senderName = message.sender.name;
    const senderId = message.sender.id;
    const senderMemberName = message.senderMember.name;
    const toId = message.receiver.id;
    const text = message.text;
    const photoURL = message.photoURL;
    const videoURL = message.videoURL;
    const dealId = message.dealId;
    const dealName = message.dealName;

    const payload = {
        notification: {
          title: `${senderName}`,
          click_action: 'exchange.booth.message',
          sound: 'default',
          badge: memberBadgeNumberString
        },
        data: { senderId, toId, messageId }
    };

    const options = {
        contentAvailable: true
    }

    ........

    const deviceIDs = memberPayload.getDeviceID()
    return await sendPushNotification(id, deviceIDs, payload, options);
  }));
});
</code>```

Here is the incrementBadgeCount function that increases the badge count for the payload and returns some info for the payload:

```<code>async function incrementBadgeCount(memberID: string):
  Promise<MemberPushNotificaitonInfo> {
const fs = admin.firestore();
const trans = await fs.runTransaction(async transaction => {
    const docRef = fs.doc(`member/${memberID}`);
    return transaction.get(docRef).then(doc => {
            let count: number = doc.get('badgeCount') || 0;
            const ids: Object = doc.get('deviceToken');
            transaction.update(docRef, {badgeCount: ++count});
            const memberPayload = new MemberPushNotificaitonInfo(count, ids);
            return Promise.resolve(memberPayload);
    });
});
return trans
}
</code>```

And finally the sendPushNotification function that interfaces with FCM and sends the payload off and cleans up bad device tokens:

```<code>async function sendPushNotification(memberID: string, deviceIDs: string[], payload: any, options: any) {
if (typeof deviceIDs === 'undefined') {
    console.log("member does not have deviceToken");
    return Promise.resolve();
}

const response = await admin.messaging().sendToDevice(deviceIDs, payload, options);
const tokensToRemove = [];
response.results.forEach((result, index) => {
    const error = result.error;
    const success = result.messageId;
    if (success) {
        console.log("success messageID:", success);
        return
    }
    if (error) {
        const failureDeviceID = deviceIDs[index];
        console.error(`error with ID: ${failureDeviceID}`, error);

        if (error.code === 'messaging/invalid-registration-token' ||
            error.code === 'messaging/registration-token-not-registered') {
            const doc = admin.firestore().doc(`member/${memberID}`);
             tokensToRemove.push(doc.update({
                deviceToken: {
                    failureDeviceID: FieldValue.delete()
                }
            }));
        }
    }
});

return Promise.all(tokensToRemove);
}
</code>```

I would appreciate some help on tightening this typescript up :)

答:
This is because you are opening too many http connections to send push notifications, ideally you should create batch of 5,10 .. to send push.

Try changing,

```<code>return await Promise.all(ids.map(async (id) => { ... });
</code>```

to,

```<code>while(ids.length) {
    var batch = ids.splice(0, ids.length >= 5 ? 5 : ids.length);
    await Promise.all(batch.map( async (id) => { ... });
}
</code>```

Body:
I'm new to Typescript and I'm trying to use the async and await functionality. I'm getting some fcm network timeouts every once in a while and I believe it has to do with not returning my promises correctly.

Here is my cloud function for sending a push notification. The two functions that are using the await keyword are incrementBadgeCount, and sendPushNotification:

export const pushNotification = functions.firestore
  .document('company/{companyId}/message/{messageId}/chat/{chatId}')
  .onCreate(async event => {

const message = event.data.data();
const recipients = event.data.data().read;
const messageId = event.params.messageId;

const ids = [];
for (const key of Object.keys(recipients)) {
    const val = recipients[key];
    if (val === false) {
        ids.push(key);
    }
}

return await Promise.all(ids.map(async (id) => {
    const memberPayload = await incrementBadgeCount(id);
    const memberBadgeNumberString =
      memberPayload.getBadgeCount().toString();

    const senderName = message.sender.name;
    const senderId = message.sender.id;
    const senderMemberName = message.senderMember.name;
    const toId = message.receiver.id;
    const text = message.text;
    const photoURL = message.photoURL;
    const videoURL = message.videoURL;
    const dealId = message.dealId;
    const dealName = message.dealName;

    const payload = {
        notification: {
          title: `${senderName}`,
          click_action: 'exchange.booth.message',
          sound: 'default',
          badge: memberBadgeNumberString
        },
        data: { senderId, toId, messageId }
    };

    const options = {
        contentAvailable: true
    }

    ........

    const deviceIDs = memberPayload.getDeviceID()
    return await sendPushNotification(id, deviceIDs, payload, options);
  }));
});

Here is the incrementBadgeCount function that increases the badge count for the payload and returns some info for the payload:

async function incrementBadgeCount(memberID: string):
  Promise<MemberPushNotificaitonInfo> {
const fs = admin.firestore();
const trans = await fs.runTransaction(async transaction => {
    const docRef = fs.doc(`member/${memberID}`);
    return transaction.get(docRef).then(doc => {
            let count: number = doc.get('badgeCount') || 0;
            const ids: Object = doc.get('deviceToken');
            transaction.update(docRef, {badgeCount: ++count});
            const memberPayload = new MemberPushNotificaitonInfo(count, ids);
            return Promise.resolve(memberPayload);
    });
});
return trans
}

And finally the sendPushNotification function that interfaces with FCM and sends the payload off and cleans up bad device tokens:

async function sendPushNotification(memberID: string, deviceIDs: string[], payload: any, options: any) {
if (typeof deviceIDs === 'undefined') {
    console.log("member does not have deviceToken");
    return Promise.resolve();
}

const response = await admin.messaging().sendToDevice(deviceIDs, payload, options);
const tokensToRemove = [];
response.results.forEach((result, index) => {
    const error = result.error;
    const success = result.messageId;
    if (success) {
        console.log("success messageID:", success);
        return
    }
    if (error) {
        const failureDeviceID = deviceIDs[index];
        console.error(`error with ID: ${failureDeviceID}`, error);

        if (error.code === 'messaging/invalid-registration-token' ||
            error.code === 'messaging/registration-token-not-registered') {
            const doc = admin.firestore().doc(`member/${memberID}`);
             tokensToRemove.push(doc.update({
                deviceToken: {
                    failureDeviceID: FieldValue.delete()
                }
            }));
        }
    }
});

return Promise.all(tokensToRemove);
}

I would appreciate some help on tightening this typescript up :)

Body:
This is because you are opening too many http connections to send push notifications, ideally you should create batch of 5,10 .. to send push.

Try changing,

return await Promise.all(ids.map(async (id) => { ... });

to,

while(ids.length) {
    var batch = ids.splice(0, ids.length >= 5 ? 5 : ids.length);
    await Promise.all(batch.map( async (id) => { ... });
}


问:
difference between str(dict) and json.dumps(dict)
What is the difference between the output of str(a dictionary) and json.dumps(a dictionary)? If I print them, they look the same. Their attributes (as per dir) also seem to be identical (see below). Yet I know there must be a difference. Could you please explain it to me?

```<code>import json

aDictionary= {"first": 42, "second":21}
s = str(aDictionary)
j = json.dumps(aDictionary)
s == j # returns false
dir(s) == dir(j) # returns true
</code>```

答:
str(aDictionary) (as well as repr(aDictionary)) produces a Python representation of your dictionary. This representation is helpful for debugging and nothing more. For the built-in types such as dictionaries and strings, you'll be given a representation that is valid Python syntax. Python syntax and JSON syntax may look similar, but are not the same thing.

Python uses single and double quotes for string literals. JSON only allows double quotes.

Python Unicode strings use \<single letter>, \xhh, \uhhhh and \Uhhhhhhhh escape sequences to encode Unicode codepoints; the latter form is used for non-BMP codepoints. JSON uses a smaller range of \<single letter> escapes as well as the \uhhhh form, and encodes UTF-16 surrogate pairs for non-BMP codepoints (so two \uhhhh sequences per codepoint).

Python uses None objects, JSON uses null to as a special "doesn't exist" sentinel value.

Python uses True and False as boolean values, JSON uses true and false.

Python dictionary keys can be any hashable type, JSON only supports strings.

So str(dictionary) will not produce valid JSON output, most of the time; only if all your keys and values are BMP strings with at least one single quote in the value could you end up with a document that can also be parsed as valid JSON.

In terms of your specific example, note that str(aDictionary) produces a document with single quotes; json.loads() can't load this document as that's not valid JSON:

```<code>>>> import json
>>> aDictionary = {"first": 42, "second":21}
>>> str(aDictionary)
"{'first': 42, 'second': 21}"
>>> json.loads(str(aDictionary))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/mjpieters/Development/Library/buildout.python/parts/opt/lib/python3.6/json/__init__.py", line 354, in loads
    return _default_decoder.decode(s)
  File "/Users/mjpieters/Development/Library/buildout.python/parts/opt/lib/python3.6/json/decoder.py", line 339, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/Users/mjpieters/Development/Library/buildout.python/parts/opt/lib/python3.6/json/decoder.py", line 355, in raw_decode
    obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
</code>```

Never use str(pythonobject) as a serialisation. Although the ast.literal_eval() function can load a reasonable number of Python built-in types from a string representation, it is a lot slower than using JSON for the same job, or a more sophisticated data persistence format if JSON doesn't fit your needs.

Body:
What is the difference between the output of str(a dictionary) and json.dumps(a dictionary)? If I print them, they look the same. Their attributes (as per dir) also seem to be identical (see below). Yet I know there must be a difference. Could you please explain it to me?

import json

aDictionary= {"first": 42, "second":21}
s = str(aDictionary)
j = json.dumps(aDictionary)
s == j # returns false
dir(s) == dir(j) # returns true

Body:
str(aDictionary) (as well as repr(aDictionary)) produces a Python representation of your dictionary. This representation is helpful for debugging and nothing more. For the built-in types such as dictionaries and strings, you'll be given a representation that is valid Python syntax. Python syntax and JSON syntax may look similar, but are not the same thing.

Python uses single and double quotes for string literals. JSON only allows double quotes.

Python Unicode strings use \<single letter>, \xhh, \uhhhh and \Uhhhhhhhh escape sequences to encode Unicode codepoints; the latter form is used for non-BMP codepoints. JSON uses a smaller range of \<single letter> escapes as well as the \uhhhh form, and encodes UTF-16 surrogate pairs for non-BMP codepoints (so two \uhhhh sequences per codepoint).

Python uses None objects, JSON uses null to as a special "doesn't exist" sentinel value.

Python uses True and False as boolean values, JSON uses true and false.

Python dictionary keys can be any hashable type, JSON only supports strings.

So str(dictionary) will not produce valid JSON output, most of the time; only if all your keys and values are BMP strings with at least one single quote in the value could you end up with a document that can also be parsed as valid JSON.

In terms of your specific example, note that str(aDictionary) produces a document with single quotes; json.loads() can't load this document as that's not valid JSON:

>>> import json
>>> aDictionary = {"first": 42, "second":21}
>>> str(aDictionary)
"{'first': 42, 'second': 21}"
>>> json.loads(str(aDictionary))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/mjpieters/Development/Library/buildout.python/parts/opt/lib/python3.6/json/__init__.py", line 354, in loads
    return _default_decoder.decode(s)
  File "/Users/mjpieters/Development/Library/buildout.python/parts/opt/lib/python3.6/json/decoder.py", line 339, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/Users/mjpieters/Development/Library/buildout.python/parts/opt/lib/python3.6/json/decoder.py", line 355, in raw_decode
    obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)

Never use str(pythonobject) as a serialisation. Although the ast.literal_eval() function can load a reasonable number of Python built-in types from a string representation, it is a lot slower than using JSON for the same job, or a more sophisticated data persistence format if JSON doesn't fit your needs.


问:
Draw cirle to fit grid in xaml
I have this grid:

```<code><UserControl
x:Class="Test.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Test"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" Background="#FF341616">

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
    <Ellipse
        Name="Red"
        Grid.Row="0"
        Margin="10,10,10,10"
        Grid.Column="0"
        Fill="#73b43c"/>
</Grid>
</UserControl>
</code>```

but when it scales, it distortes.

How can I fix it? I don't want to replace it with an image.

答:
If you want something to scale without distorting, put it inside of a Viewbox:

```<code><Viewbox Grid.Row="0" Grid.Column="0" Margin="10,10,10,10">
    <Ellipse Name="Red" Width="100" Height="100" Fill="#73b43c"/>
</Viewbox>
</code>```

The Stretch property of the Viewbox can be set various values, depending on how you want the content to stretch. You probably want Uniform, which would look like this:

Title: Draw cirle to fit grid in xaml

Body:
I have this grid:

<UserControl
x:Class="Test.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Test"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" Background="#FF341616">

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
    <Ellipse
        Name="Red"
        Grid.Row="0"
        Margin="10,10,10,10"
        Grid.Column="0"
        Fill="#73b43c"/>
</Grid>
</UserControl>

but when it scales, it distortes.

How can I fix it? I don't want to replace it with an image.

Body:
If you want something to scale without distorting, put it inside of a Viewbox:

<Viewbox Grid.Row="0" Grid.Column="0" Margin="10,10,10,10">
    <Ellipse Name="Red" Width="100" Height="100" Fill="#73b43c"/>
</Viewbox>

The Stretch property of the Viewbox can be set various values, depending on how you want the content to stretch. You probably want Uniform, which would look like this:


问:
Pasting xml to console
I  need to get data SHILS_V from XML file. I read .xml

XML code for example:

```<code><SVED_PR_GS>
          <ZGLV>
            <VERSION>99</VERSION>
            <DATA>9999</DATA>
            <FILENAME>1234</FILENAME>
            <FIRSTNAME>1234</FIRSTNAME>
          </ZGLV>
          <SVD>
            <CODE></CODE>
            <YEAR></YEAR>
            <MONTH></MONTH>
          </SVD>
          <SV_PR_GS>
            <OBSV>
              <N_ZAP>1</N_ZAP>
              <MO_SV_V>12345</MO_SV_V>
              <SNILS_V>123456789</SNILS_V>
            </OBSV>
          </SV_PR_GS>
</SVED_PR_GS>
</code>```

My code to read xml:

```<code>XmlDocument xml = new XmlDocument();
xml.Load(filename);
Console.WriteLine("this");
XmlNodeList nodes = xml.GetElementsByTagName("SVED_PR_GS/SV_PR_GS");

foreach (XmlNode n in nodes)
{
    Console.WriteLine("in loop");
    XmlNode snils_v = n["OBSV/SNILS_V"];
    Console.WriteLine("Snils V: " + snils_v);
}
</code>```

Where is the problem?
How to get the information from SNILS_V?

答:
To select a single node from XML. You need to access that object using SelectSingleNode method.

```<code>xml.SelectSingleNode("xpath for node")
</code>```

To get collection of nodes you can write

```<code>xml.SelectNodes("xpath for node collection")
</code>```

Title: Pasting xml to console

Body:
I  need to get data SHILS_V from XML file. I read .xml

XML code for example:

<SVED_PR_GS>
          <ZGLV>
            <VERSION>99</VERSION>
            <DATA>9999</DATA>
            <FILENAME>1234</FILENAME>
            <FIRSTNAME>1234</FIRSTNAME>
          </ZGLV>
          <SVD>

            <YEAR></YEAR>
            <MONTH></MONTH>
          </SVD>
          <SV_PR_GS>
            <OBSV>
              <N_ZAP>1</N_ZAP>
              <MO_SV_V>12345</MO_SV_V>
              <SNILS_V>123456789</SNILS_V>
            </OBSV>
          </SV_PR_GS>
</SVED_PR_GS>

My code to read xml:

XmlDocument xml = new XmlDocument();
xml.Load(filename);
Console.WriteLine("this");
XmlNodeList nodes = xml.GetElementsByTagName("SVED_PR_GS/SV_PR_GS");

foreach (XmlNode n in nodes)
{
    Console.WriteLine("in loop");
    XmlNode snils_v = n["OBSV/SNILS_V"];
    Console.WriteLine("Snils V: " + snils_v);
}

Where is the problem?
How to get the information from SNILS_V?

Body:
To select a single node from XML. You need to access that object using SelectSingleNode method.

xml.SelectSingleNode("xpath for node")

To get collection of nodes you can write

xml.SelectNodes("xpath for node collection")


问:
Azure Functions - Blob Stream Dynamic Input bindings
I'm running a C# function on azure which needs to take in files from a container. The only problem is that the paths to the input files are going to be (potentially) different each time, and the number of input files will vary from 1 to about 4 or 5. Accordingly I can't just use the default input blob bindings as far as I'm aware. My options are give the container anonymous access and just grab the files through the link or figure out how to get dynamic input bindings.

Does anyone know how to declare the path for the input blob stream at runtime (in the C# code)?

If it helps I've managed to find this for dynamic output bindings

```<code>using (var writer = await binder.BindAsync<TextWriter>(
                  new BlobAttribute(containerPath + fileName)))
    {
        writer.Write(OutputVariable);
    }
</code>```

Thanks in advance, Cuan

答:
For dynamic output bindings, you could leverage the following code snippet:

```<code>var attributes = new Attribute[]
{
    new BlobAttribute("{container-name}/{blob-name}"),
    new StorageAccountAttribute("brucchStorage") //connection string name for storage connection
};
using (var writer = await binder.BindAsync<TextWriter>(attributes))
{
    writer.Write(userBlobText);
}
</code>```

Note: The above code would create the target blob if not exists and override the existing blob if it exists. Moreover, if you do not specify the StorageAccountAttribute, your target blob would be create into the storage account based on the app setting AzureWebJobsStorage.

Additionally, you could follow Azure Functions imperative bindings for more details.

UPDATE:

For dynamic input binding, you could just change the binding type as follows:

```<code>var blobString = await binder.BindAsync<string>(attributes);
</code>```

Or you could set the binding type to CloudBlockBlob and add the following namespace for azure storage blob:

```<code>#r "Microsoft.WindowsAzure.Storage"
using Microsoft.WindowsAzure.Storage.Blob;

CloudBlockBlob blob = await binder.BindAsync<CloudBlockBlob>(attributes);
</code>```

Moreover, more details about the operations for CloudBlockBlob, you could follow here.

Body:
I'm running a C# function on azure which needs to take in files from a container. The only problem is that the paths to the input files are going to be (potentially) different each time, and the number of input files will vary from 1 to about 4 or 5. Accordingly I can't just use the default input blob bindings as far as I'm aware. My options are give the container anonymous access and just grab the files through the link or figure out how to get dynamic input bindings.

Does anyone know how to declare the path for the input blob stream at runtime (in the C# code)?

If it helps I've managed to find this for dynamic output bindings

using (var writer = await binder.BindAsync<TextWriter>(
                  new BlobAttribute(containerPath + fileName)))
    {
        writer.Write(OutputVariable);
    }

Thanks in advance, Cuan

Body:
For dynamic output bindings, you could leverage the following code snippet:

var attributes = new Attribute[]
{
    new BlobAttribute("{container-name}/{blob-name}"),
    new StorageAccountAttribute("brucchStorage") //connection string name for storage connection
};
using (var writer = await binder.BindAsync<TextWriter>(attributes))
{
    writer.Write(userBlobText);
}

Note: The above code would create the target blob if not exists and override the existing blob if it exists. Moreover, if you do not specify the StorageAccountAttribute, your target blob would be create into the storage account based on the app setting AzureWebJobsStorage.

Additionally, you could follow Azure Functions imperative bindings for more details.

UPDATE:

For dynamic input binding, you could just change the binding type as follows:

var blobString = await binder.BindAsync<string>(attributes);

Or you could set the binding type to CloudBlockBlob and add the following namespace for azure storage blob:

#r "Microsoft.WindowsAzure.Storage"
using Microsoft.WindowsAzure.Storage.Blob;

CloudBlockBlob blob = await binder.BindAsync<CloudBlockBlob>(attributes);

Moreover, more details about the operations for CloudBlockBlob, you could follow here.


问:
Data gone after changing route
My data is gone after changing route.

Scenario:

CommentComponent (Data shown) -> ChangeRoute -> CommentComponent (No data shown)

The data only shown at the first load, but then it's gone whenever I change the route.

I found this question looks similar with my case/issue:
No data for FireStore after use of routerlink

But none of the comments/answer is helpful. So I decided to make this question.

COMPONENT.HTML: comment.component.html:

```<code><ng-template #noComments>
  <h1>No comment yet.</h1>
</ng-template>
<div *ngIf="comments?.length > 0; else noComments">
  <h1 style="margin-bottom: 3.5vh;">Comments</h1>
  <ul *ngFor="let comment of comments">
      <li>
        <mat-card>
          <h3>{{comment.name}}</h3>
          <p>{{comment.comment}}</p>
        </mat-card>
      </li>
    </ul>
</div>
</code>```

COMPONENT.TypeScript: comment.component.ts:

```<code>import { Component, OnInit } from '@angular/core';
import { AngularFirestore, AngularFirestoreCollection, AngularFirestoreDocument } from 'angularfire2/firestore';
import { Observable } from 'rxjs/Observable';

import { CommentService } from '../services/comment.service';
import { Comment } from '../models/comment';

@Component({
  selector: 'app-comment',
  templateUrl: './comment.component.html',
  styleUrls: ['./comment.component.css']
})
export class CommentComponent implements OnInit {

  comments: Comment[];

  constructor(private commentService: CommentService) {
  }

  ngOnInit() {
    this.commentService.getComments().subscribe(comments => {
      this.comments = comments;
    });
  }

}
</code>```

SERVICE: comments.service.ts:

```<code>import { Injectable } from '@angular/core';
import { Comment } from '../models/comment';

import { Observable } from 'rxjs/observable';
import { AngularFirestore, AngularFirestoreCollection, AngularFirestoreDocument } from 'angularfire2/firestore';

@Injectable()
export class CommentService {

  commentsCollection: AngularFirestoreCollection<Comment>;
  comments: Observable<Comment[]>;

  constructor(public afs: AngularFirestore) {
    this.commentsCollection = this.afs.collection('comments');
    this.comments = this.commentsCollection.valueChanges();
  }

  getComments() {
    return this.comments;
  }

}
</code>```

MODEL: comments.ts:

```<code>export interface Comment {
    name: string;
    comment: string;
}
</code>```

[SOLVED]

Here's how:

In comment.service.ts, do something from:

```<code>  constructor(public afs: AngularFirestore) {
    this.commentsCollection = this.afs.collection('comments');
    this.comments = this.commentsCollection.valueChanges();
  }

  getComments() {
    return this.comments;
  }
</code>```

To this:

```<code>  constructor(public afs: AngularFirestore) {
  }

  getComments() {
    this.commentsCollection = this.afs.collection('comments');
    return this.comments = this.commentsCollection.valueChanges();
  }
</code>```

答:
It seems to me the issue is you’re initially setting the comments on the service constructor, meaning it will only happen once. Since most likely this is an http call the observable will complete immediately after returning. In the component after changing route and navigating to it again is not restarting the observable só the subscription will never receive any values. The observable has completed already. </p>

<p>I believe that if you move the code you have inside the constructor to the getComments() method it should fix your problem. </p>

Title: Data gone after changing route

Body:
My data is gone after changing route.

Scenario:

CommentComponent (Data shown) -> ChangeRoute -> CommentComponent (No data shown)

The data only shown at the first load, but then it's gone whenever I change the route.

I found this question looks similar with my case/issue:
No data for FireStore after use of routerlink

But none of the comments/answer is helpful. So I decided to make this question.

COMPONENT.HTML: comment.component.html:

<ng-template #noComments>

No comment yet.

</ng-template>

 0; else noComments">

Comments

        <mat-card>

{{comment.name}}

{{comment.comment}}

        </mat-card>

COMPONENT.TypeScript: comment.component.ts:

import { Component, OnInit } from '@angular/core';
import { AngularFirestore, AngularFirestoreCollection, AngularFirestoreDocument } from 'angularfire2/firestore';
import { Observable } from 'rxjs/Observable';

import { CommentService } from '../services/comment.service';
import { Comment } from '../models/comment';

@Component({
  selector: 'app-comment',
  templateUrl: './comment.component.html',
  styleUrls: ['./comment.component.css']
})
export class CommentComponent implements OnInit {

  comments: Comment[];

  constructor(private commentService: CommentService) {
  }

  ngOnInit() {
    this.commentService.getComments().subscribe(comments => {
      this.comments = comments;
    });
  }

}

SERVICE: comments.service.ts:

import { Injectable } from '@angular/core';
import { Comment } from '../models/comment';

import { Observable } from 'rxjs/observable';
import { AngularFirestore, AngularFirestoreCollection, AngularFirestoreDocument } from 'angularfire2/firestore';

@Injectable()
export class CommentService {

  commentsCollection: AngularFirestoreCollection<Comment>;
  comments: Observable<Comment[]>;

  constructor(public afs: AngularFirestore) {
    this.commentsCollection = this.afs.collection('comments');
    this.comments = this.commentsCollection.valueChanges();
  }

  getComments() {
    return this.comments;
  }

}

MODEL: comments.ts:

export interface Comment {
    name: string;
    comment: string;
}

[SOLVED]

Here's how:

In comment.service.ts, do something from:

  constructor(public afs: AngularFirestore) {
    this.commentsCollection = this.afs.collection('comments');
    this.comments = this.commentsCollection.valueChanges();
  }

  getComments() {
    return this.comments;
  }

To this:

  constructor(public afs: AngularFirestore) {
  }

  getComments() {
    this.commentsCollection = this.afs.collection('comments');
    return this.comments = this.commentsCollection.valueChanges();
  }

Body:
It seems to me the issue is you’re initially setting the comments on the service constructor, meaning it will only happen once. Since most likely this is an http call the observable will complete immediately after returning. In the component after changing route and navigating to it again is not restarting the observable só the subscription will never receive any values. The observable has completed already.

I believe that if you move the code you have inside the constructor to the getComments() method it should fix your problem.


问:
Paste an Excel range in browser using Selenium + VBA
I have a scenario where I am trying to copy a range of cells (Single Column) from Excel and paste the range in a textarea tag in Chrome browser, which is identified using ID. I am using Excel VBA and Selenium.

There seems to be no error when copying of the range. However, when I try to paste the range in the textarea using Selenium Keys, I am currently unable to paste the values. As my Excel range can sometimes extend to more than 1000 rows, I am out of option to paste the cells one after the other, as the browser times out.

My html code is something like this.

=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

```<code><div>
    <div>
        <textarea> id = "textarea1"
        </textarea>
    </div>
</div>
</code>```

=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

I have tried using the below three codes, in vain.

=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

```<code>selenium.findElementByID("textarea1").sendkeys (keys.Control & "v")
selenium.findElementByID("textarea1").sendkeys keys.Control, "v"
selenium.findElementByID("textarea1").sendkeys (keys.Control +"v")
</code>```

=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

Can someone help me identify the issue here and the workaround.

答:
I'm not sure what keybindings you're using for Selenium (Python or Java?).

Anyway, you want to send a key chord. Please look at the examples in Key press in (Ctrl+A) Selenium WebDriver.

So maybe you want:

```<code>selenium.findElementByID("textarea1").sendKeys(Keys.chord(Keys.CONTROL,"v"))
</code>```

Body:
I have a scenario where I am trying to copy a range of cells (Single Column) from Excel and paste the range in a textarea tag in Chrome browser, which is identified using ID. I am using Excel VBA and Selenium.

There seems to be no error when copying of the range. However, when I try to paste the range in the textarea using Selenium Keys, I am currently unable to paste the values. As my Excel range can sometimes extend to more than 1000 rows, I am out of option to paste the cells one after the other, as the browser times out.

My html code is something like this.

=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

        <textarea> id = "textarea1"
        </textarea>

=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

I have tried using the below three codes, in vain.

=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

selenium.findElementByID("textarea1").sendkeys (keys.Control & "v")
selenium.findElementByID("textarea1").sendkeys keys.Control, "v"
selenium.findElementByID("textarea1").sendkeys (keys.Control +"v")

=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

Can someone help me identify the issue here and the workaround.

Body:
I'm not sure what keybindings you're using for Selenium (Python or Java?).

Anyway, you want to send a key chord. Please look at the examples in Key press in (Ctrl+A) Selenium WebDriver.

So maybe you want:

selenium.findElementByID("textarea1").sendKeys(Keys.chord(Keys.CONTROL,"v"))


问:
Retrieving servlet context, session and request in a POJO outside container
Is there any way to retrieve a session from a POJO? Or ultimately to retrieve a bean from a POJO.

To clarify:

Basically I am creating a bean from a servlet and I need to access the properties of that bean from outside of the web container (from a POJO). I cannot pass the request to the pojo; and the request is needed to retrieve the session.

More specifically I have a web application that uses the Cactus framework to run JUnit tests from a web interface. However the servlet that invokes the JUnit test runner is compiled in a jar; I added extra drop down menus to change settings from which the JUnit test will read from to switch between different environments (WLI clusters), so given that the runner servlet is already compiled I cannot modify it to handle the extra parameters from the multiple environments. I have tried the persistence approach of writing to a .dat file fro which the JUnit test will read from by way of a Reader class; also I have have tried the bean approach which ultimately was not accessible from the JUnit test.

答:
Only and only if your POJO is running in the same thread as the HttpServletRequest is running in, then you'll be able to achieve this with help of ThreadLocal<T>.

Create the following class:

```<code>public final class YourContext implements AutoCloseable {

    private static ThreadLocal<YourContext> instance = new ThreadLocal<>();

    private HttpServletRequest request;
    private HttpServletResponse response;

    private YourContext(HttpServletRequest request, HttpServletResponse response) {
        this.request = request;
        this.response = response;
    }

    public static YourContext create(HttpServletRequest request, HttpServletResponse response) {
        YourContext context = new YourContext(request, response);
        instance.set(context);
        return context;
    }

    public static YourContext getCurrentInstance() {
        return instance.get();
    }

    @Override
    public void close() {
        instance.remove();
    }

    public HttpServletRequest getRequest() {
        return request;
    }

    public HttpSession getSession() {
        return request.getSession();
    }

    public ServletContext getServletContext() {
        return request.getServletContext();
    }

    // ... (add if necessary more methods here which return/delegate the request/response).
}
</code>```

Implement javax.servlet.Filter which does the following in doFilter() method and is mapped on an url-pattern of interest, e.g. /* or on the servlet-name of your front controller servlet.

```<code>@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws ServletException, IOException {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;

    try (YourContext context = YourContext.create(request, response)) {
        chain.doFilter(request, response);
    }
}
</code>```

Note the importance of try-with-resources statement. It guarantees that the YourContext#close() will be called after the filter has done its job and the ThreadLocal resource will be cleared. Otherwise the thread will still contain it when recycled for another HTTP request.

And here's how you could use it in the POJO:

```<code>YourContext context = YourContext.getCurrentInstance();
HttpSession session = context.getSession();
</code>```

This all is basically also how the Context objects of the average MVC framework works, like JSF's FacesContext and the one in Wicket.

Said that, have you looked at CDI? Perhaps it's easier to make the artifacts CDI-managed so you can just @Inject them in each other.

Body:
Only and only if your POJO is running in the same thread as the HttpServletRequest is running in, then you'll be able to achieve this with help of ThreadLocal<T>.

Create the following class:

public final class YourContext implements AutoCloseable {

    private static ThreadLocal<YourContext> instance = new ThreadLocal<>();

    private HttpServletRequest request;
    private HttpServletResponse response;

    private YourContext(HttpServletRequest request, HttpServletResponse response) {
        this.request = request;
        this.response = response;
    }

    public static YourContext create(HttpServletRequest request, HttpServletResponse response) {
        YourContext context = new YourContext(request, response);
        instance.set(context);
        return context;
    }

    public static YourContext getCurrentInstance() {
        return instance.get();
    }

    @Override
    public void close() {
        instance.remove();
    }

    public HttpServletRequest getRequest() {
        return request;
    }

    public HttpSession getSession() {
        return request.getSession();
    }

    public ServletContext getServletContext() {
        return request.getServletContext();
    }

    // ... (add if necessary more methods here which return/delegate the request/response).
}

Implement javax.servlet.Filter which does the following in doFilter() method and is mapped on an url-pattern of interest, e.g. /* or on the servlet-name of your front controller servlet.

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws ServletException, IOException {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;

    try (YourContext context = YourContext.create(request, response)) {
        chain.doFilter(request, response);
    }
}

Note the importance of try-with-resources statement. It guarantees that the YourContext#close() will be called after the filter has done its job and the ThreadLocal resource will be cleared. Otherwise the thread will still contain it when recycled for another HTTP request.

And here's how you could use it in the POJO:

YourContext context = YourContext.getCurrentInstance();
HttpSession session = context.getSession();

This all is basically also how the Context objects of the average MVC framework works, like JSF's FacesContext and the one in Wicket.

Said that, have you looked at CDI? Perhaps it's easier to make the artifacts CDI-managed so you can just @Inject them in each other.


问:
Drag div content by grabbing its background
When the content goes outside the div, we use scrollbars to see it. How can I scroll the div content by grabbing and dragging its background? I've searched the solution but did not find what I need. Here is my fiddle:

https://jsfiddle.net/vaxobasilidze/xhn49e1j/

Drag any item to the right div and move it outside the container to the right or bottom. scrollbars appear to help you to scroll. Here is an example of what I want to achieve. See the first diagram on the link and drag it:

https://jsplumbtoolkit.com/

Any tips on how to do this?

答:
Check for mousemove between mousedown and mouseup on the body element is a good place to start.</p>

```<code>  element = $('body');
element.addEventListener("mousedown", function(){
 flag = 0;
  }, false);
 element.addEventListener("mousemove", function(){
    flag = 1;
   }, false);
    element.addEventListener("mouseup", function(){
      if(flag === 0){
       console.log("click");
      }
    else if(flag === 1){
        console.log("drag");
   }
  }, false);
</code>```

Body:
Check for mousemove between mousedown and mouseup on the body element is a good place to start.

  element = $('body');
element.addEventListener("mousedown", function(){
 flag = 0;
  }, false);
 element.addEventListener("mousemove", function(){
    flag = 1;
   }, false);
    element.addEventListener("mouseup", function(){
      if(flag === 0){
       console.log("click");
      }
    else if(flag === 1){
        console.log("drag");
   }
  }, false);


问:
Why my gitlab ci configuration exit with code 1?
I'm new to Gitlab CI.

I tried to ssh and execute a ls command to check whether my gitlab CI configuration is correct or not.

Here's my .gitlab-ci.yml file configuration :

```<code>before_script:
  - eval $(ssh-agent -s)
  - apt-get update
  - apt-get install sshpass

stage_deploy:
  only:
    - testing
  script:
    - sshpass -p $STAGING_PRIVATE_KEY ssh -p 20000 root@1.2.3.4 "ls"
</code>```

Whenever I trigger the repository push, it always ends up with an Error Message ERROR: Job failed: exit code 1, here's the job result :

```<code>Running with gitlab-runner 10.2.0 (0a75cdd1)
  on docker-auto-scale (e11ae361)
 Using Docker executor with image ruby:2.1 ...
 Using docker image sha256:9f27f70631c32ca0e5946c012e80704061ee559b30cb89e652c0936852e93e86 for predefined container...
 Pulling docker image ruby:2.1 ...
 Using docker image ruby:2.1 ID=sha256:223d1eaa9523fa64e78f5a92b701c9c11cbc507f0ff62246dbbacdae395ffea3 for build container...
 section_start:1512460812:prepare_script
Running on runner-e11ae361-project-4813010-concurrent-0 via runner-e11ae361-srm-1512460662-97b95eb4...
section_end:1512460814:prepare_script
section_start:1512460814:get_sources
 Cloning repository...
Cloning into '/builds/budiantoip/cicd-demo'...
 Checking out dde5cdc4 as testing...
 Skipping Git submodules setup
section_end:1512460816:get_sources
section_start:1512460816:restore_cache
section_end:1512460818:restore_cache
section_start:1512460818:download_artifacts
section_end:1512460819:download_artifacts
section_start:1512460819:build_script
 $ eval $(ssh-agent -s)
Agent pid 11
 $ apt-get update
Get:1 http://security.debian.org jessie/updates InRelease [63.1 kB]
Ign http://deb.debian.org jessie InRelease
Get:2 http://deb.debian.org jessie-updates InRelease [145 kB]
Get:3 http://deb.debian.org jessie Release.gpg [2373 B]
Get:4 http://deb.debian.org jessie Release [148 kB]
Get:5 http://security.debian.org jessie/updates/main amd64 Packages [588 kB]
Get:6 http://deb.debian.org jessie-updates/main amd64 Packages [23.2 kB]
Get:7 http://deb.debian.org jessie/main amd64 Packages [9063 kB]
Fetched 10.0 MB in 6s (1563 kB/s)
Reading package lists...
 $ apt-get install sshpass
Reading package lists...
Building dependency tree...
Reading state information...
The following NEW packages will be installed:
  sshpass
0 upgraded, 1 newly installed, 0 to remove and 62 not upgraded.
Need to get 11.2 kB of archives.
After this operation, 65.5 kB of additional disk space will be used.
Get:1 http://deb.debian.org/debian/ jessie/main sshpass amd64 1.05-1 [11.2 kB]
debconf: delaying package configuration, since apt-utils is not installed
Fetched 11.2 kB in 0s (12.0 kB/s)
Selecting previously unselected package sshpass.
(Reading database ...
(Reading database ... 5%
(Reading database ... 10%
(Reading database ... 15%
(Reading database ... 20%
(Reading database ... 25%
(Reading database ... 30%
(Reading database ... 35%
(Reading database ... 40%
(Reading database ... 45%
(Reading database ... 50%
(Reading database ... 55%
(Reading database ... 60%
(Reading database ... 65%
(Reading database ... 70%
(Reading database ... 75%
(Reading database ... 80%
(Reading database ... 85%
(Reading database ... 90%
(Reading database ... 95%
(Reading database ... 100%
(Reading database ... 21168 files and directories currently installed.)
Preparing to unpack .../sshpass_1.05-1_amd64.deb ...
Unpacking sshpass (1.05-1) ...
Setting up sshpass (1.05-1) ...
sshpass -p $STAGING_PRIVATE_KEY ssh  root@1.2.3.4 "ls"
ERROR: Job failed: exit code 1
</code>```

Any clue on what's going on?

答:
Did you intentionally replace your real server ip with 1.2.3.4 or was that the real configuration that you were using?

I think the problem is that the job failed is that it can not execute the last command

sshpass -p $STAGING_PRIVATE_KEY ssh -p 20000 root@1.2.3.4 "ls"

Body:
I'm new to Gitlab CI.

I tried to ssh and execute a ls command to check whether my gitlab CI configuration is correct or not.

Here's my .gitlab-ci.yml file configuration :

before_script:
  - eval $(ssh-agent -s)
  - apt-get update
  - apt-get install sshpass

stage_deploy:
  only:
    - testing
  script:
    - sshpass -p $STAGING_PRIVATE_KEY ssh -p 20000 root@1.2.3.4 "ls"

Whenever I trigger the repository push, it always ends up with an Error Message ERROR: Job failed: exit code 1, here's the job result :

Running with gitlab-runner 10.2.0 (0a75cdd1)
  on docker-auto-scale (e11ae361)
 Using Docker executor with image ruby:2.1 ...
 Using docker image sha256:9f27f70631c32ca0e5946c012e80704061ee559b30cb89e652c0936852e93e86 for predefined container...
 Pulling docker image ruby:2.1 ...
 Using docker image ruby:2.1 ID=sha256:223d1eaa9523fa64e78f5a92b701c9c11cbc507f0ff62246dbbacdae395ffea3 for build container...
 section_start:1512460812:prepare_script
Running on runner-e11ae361-project-4813010-concurrent-0 via runner-e11ae361-srm-1512460662-97b95eb4...
section_end:1512460814:prepare_script
section_start:1512460814:get_sources
 Cloning repository...
Cloning into '/builds/budiantoip/cicd-demo'...
 Checking out dde5cdc4 as testing...
 Skipping Git submodules setup
section_end:1512460816:get_sources
section_start:1512460816:restore_cache
section_end:1512460818:restore_cache
section_start:1512460818:download_artifacts
section_end:1512460819:download_artifacts
section_start:1512460819:build_script
 $ eval $(ssh-agent -s)
Agent pid 11
 $ apt-get update
Get:1 http://security.debian.org jessie/updates InRelease [63.1 kB]
Ign http://deb.debian.org jessie InRelease
Get:2 http://deb.debian.org jessie-updates InRelease [145 kB]
Get:3 http://deb.debian.org jessie Release.gpg [2373 B]
Get:4 http://deb.debian.org jessie Release [148 kB]
Get:5 http://security.debian.org jessie/updates/main amd64 Packages [588 kB]
Get:6 http://deb.debian.org jessie-updates/main amd64 Packages [23.2 kB]
Get:7 http://deb.debian.org jessie/main amd64 Packages [9063 kB]
Fetched 10.0 MB in 6s (1563 kB/s)
Reading package lists...
 $ apt-get install sshpass
Reading package lists...
Building dependency tree...
Reading state information...
The following NEW packages will be installed:
  sshpass
0 upgraded, 1 newly installed, 0 to remove and 62 not upgraded.
Need to get 11.2 kB of archives.
After this operation, 65.5 kB of additional disk space will be used.
Get:1 http://deb.debian.org/debian/ jessie/main sshpass amd64 1.05-1 [11.2 kB]
debconf: delaying package configuration, since apt-utils is not installed
Fetched 11.2 kB in 0s (12.0 kB/s)
Selecting previously unselected package sshpass.
(Reading database ...
(Reading database ... 5%
(Reading database ... 10%
(Reading database ... 15%
(Reading database ... 20%
(Reading database ... 25%
(Reading database ... 30%
(Reading database ... 35%
(Reading database ... 40%
(Reading database ... 45%
(Reading database ... 50%
(Reading database ... 55%
(Reading database ... 60%
(Reading database ... 65%
(Reading database ... 70%
(Reading database ... 75%
(Reading database ... 80%
(Reading database ... 85%
(Reading database ... 90%
(Reading database ... 95%
(Reading database ... 100%
(Reading database ... 21168 files and directories currently installed.)
Preparing to unpack .../sshpass_1.05-1_amd64.deb ...
Unpacking sshpass (1.05-1) ...
Setting up sshpass (1.05-1) ...
sshpass -p $STAGING_PRIVATE_KEY ssh  root@1.2.3.4 "ls"
ERROR: Job failed: exit code 1

Any clue on what's going on?


问:
Using django tag in a div ID
I am trying to generate dynamically an ID in my app using bootstrap dropdown menu but for some reason it does not appear ..

```<code><div class="dropdown">
  <button class="btn btn-secondary btn-sm btn-canvas dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
    Compare with
  </button>
  <div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
    {% for i in team_list_pop %}
      <a class="dropdown-item" id="{{i.first_name}}" href="#">{{i.first_name}} {{i.last_name}}</a>
    {% endfor %}
  </div>
</div>
</code>```

and the output when I do inspect in my browser

```<code><a class="dropdown-item" href="#">John Doe</a>
</code>```

with no traces of the ID. how can I get to hve an output

```<code><a id="john" class="dropdown-item" href="#">John Doe</a>
</code>```

thx you very much

答:
I think you should look if the value you are typing exit because i'm doing the same thing in my code and it worked:

```<code>... id="{{ values.0.vat }}" onclick="callAjax.call(this)" ...
</code>```

This is an example code that i've used in one of my project and it correctly show the id in inspect.

Title: Using django tag in a div ID

Body:
I am trying to generate dynamically an ID in my app using bootstrap dropdown menu but for some reason it does not appear ..

  <button class="btn btn-secondary btn-sm btn-canvas dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
    Compare with
  </button>

    {% for i in team_list_pop %}
      {{i.first_name}} {{i.last_name}}
    {% endfor %}

and the output when I do inspect in my browser

John Doe

with no traces of the ID. how can I get to hve an output

John Doe

thx you very much

Body:
I think you should look if the value you are typing exit because i'm doing the same thing in my code and it worked:

... id="{{ values.0.vat }}" onclick="callAjax.call(this)" ...

This is an example code that i've used in one of my project and it correctly show the id in inspect.


问:
Properly Solving a Big-O Proof
I am currently taking a class which is incorporating a topic I have not yet had much experience with - Big-O. Here is an example of the type of questions I will need to answer. Please note: these questions resemble that of those which I will need to do for homework, however, the numbers, etc. are changed.

I am not looking for solutions. I am looking for an explanation on how to effectively write the proof up.

The problems look like this (the first equation is f(n) the second is g(n)):

```<code>(a) 5^(log_5(n)) and 3n+2
(b) n^2 and sqrt(3)^(log(n))
</code>```

I understand that, to effectively write the proof, I must prove that

```<code>|f(x)| <= c|g(x)| for all x >= k
</code>```

(k == n_0 depending on how you were taught)
So for the first one I simplify the question to

```<code>n is O(3n+2)
</code>```

and I'm not entirely certain how to begin the second one.

From here, how do I pick values c and k? Are they simply arbitrary values which just make the equation true or is there something more which I am missing? I have seen many examples, but none of these explain how they are getting their values for c and k.

Thanks for your help!

答:
Remember what the purpose of big-O is anyway: you are trying to show that a function grows, with large enough inputs, at a rate no "faster" than a certain other function (its upper bound).  With that in mind, k can be fairly arbitrary, but you probably want to choose the smallest non-negative value of k for which the inequality holds.  If you can't find a definite smallest k, choose one that works.  Also, since we typically "throw out" constants on the most significant term of the upper bound, similarly, choose the smallest positive c for which the inequality holds.  Again, if you can't determine a "smallest," just choose one that works.  Once you recall what k and c represent, it isn't too hard to remember that this is what to do with them.

Your teacher/professor may have different ideas, so you'll probably wish to double-check, but this is pretty much what this particular music-major-who-took-some-graduate-comp-sci remembers from Algorithms class.

Hope that helps!

ContentLicense: CC BY-SA 2.5

Title: Properly Solving a Big-O Proof

Body:
I am currently taking a class which is incorporating a topic I have not yet had much experience with - Big-O. Here is an example of the type of questions I will need to answer. Please note: these questions resemble that of those which I will need to do for homework, however, the numbers, etc. are changed.

I am not looking for solutions. I am looking for an explanation on how to effectively write the proof up.

The problems look like this (the first equation is f(n) the second is g(n)):

(a) 5^(log_5(n)) and 3n+2
(b) n^2 and sqrt(3)^(log(n))

I understand that, to effectively write the proof, I must prove that

|f(x)| <= c|g(x)| for all x >= k

(k == n_0 depending on how you were taught)
So for the first one I simplify the question to

n is O(3n+2)

and I'm not entirely certain how to begin the second one.

From here, how do I pick values c and k? Are they simply arbitrary values which just make the equation true or is there something more which I am missing? I have seen many examples, but none of these explain how they are getting their values for c and k.

Thanks for your help!


问:
Docker entrypoint and cmd together
I try to setup a Docker with both entrypoint and cmd.

```<code>FROM debian:stretch
RUN apt-get update && \
apt install gnupg ca-certificates -y
RUN echo "deb http://repo.aptly.info/ squeeze main" > /etc/apt/sources.list.d/aptly.list
RUN apt-key adv --keyserver keys.gnupg.net --recv-keys 9E3E53F19C7DE460
RUN apt update && apt install aptly -y
ADD aptly.conf /etc/aptly.conf
ADD start.sh .
VOLUME ["/aptly"]
ENTRYPOINT ["/start.sh"]
CMD ["aptly", "api", "serve"]
</code>```

But entrypoint script is not stopping...
The cmd command is not launching

Here my script :

```<code>#!/bin/bash
 set -e
 init_aptly() {
 #import pgp key
#create nginx root folder in /aptly
su -c "mkdir -p /aptly/.aptly/public"
echo "12"
 #initialize repository
 #aptly create repo doze-server -   distribution="stable"
  }
  #check for first run
 if [ ! -e /aptly/.aptly/public ]; then
  init_aptly
  echo "13"
 fi
  echo "14"
</code>```

The script always echo 14, I would like only one and then, execute the cmd command from dockerfile

答:
Can't tell much without knowing what the entrypoint does, but essentially this is what you are doing with this combination of entrypoint and cmd:

```<code>/start.sh aptly api serve
</code>```

If you are after simply starting your server you can simply do something like this (valid path to the aptly executable may be neccessary):

```<code>ENTRYPOINT ["aptly"]
CMD ["api", "serve"]
</code>```

Unless you are doing much more than just running an executable there's no need for an entrypoint.

Title: Docker entrypoint and cmd together

Body:
I try to setup a Docker with both entrypoint and cmd.

FROM debian:stretch
RUN apt-get update && \
apt install gnupg ca-certificates -y
RUN echo "deb http://repo.aptly.info/ squeeze main" > /etc/apt/sources.list.d/aptly.list
RUN apt-key adv --keyserver keys.gnupg.net --recv-keys 9E3E53F19C7DE460
RUN apt update && apt install aptly -y
ADD aptly.conf /etc/aptly.conf
ADD start.sh .
VOLUME ["/aptly"]
ENTRYPOINT ["/start.sh"]
CMD ["aptly", "api", "serve"]

But entrypoint script is not stopping...
The cmd command is not launching

Here my script :

#!/bin/bash
 set -e
 init_aptly() {
 #import pgp key
#create nginx root folder in /aptly
su -c "mkdir -p /aptly/.aptly/public"
echo "12"
 #initialize repository
 #aptly create repo doze-server -   distribution="stable"
  }
  #check for first run
 if [ ! -e /aptly/.aptly/public ]; then
  init_aptly
  echo "13"
 fi
  echo "14"

The script always echo 14, I would like only one and then, execute the cmd command from dockerfile

Body:
Can't tell much without knowing what the entrypoint does, but essentially this is what you are doing with this combination of entrypoint and cmd:

/start.sh aptly api serve

If you are after simply starting your server you can simply do something like this (valid path to the aptly executable may be neccessary):

ENTRYPOINT ["aptly"]
CMD ["api", "serve"]

Unless you are doing much more than just running an executable there's no need for an entrypoint.


问:
How to do the same in JavaScript?
I have this jQuery that automaticali calculate when is focus out of the field. I need to the the same this in JavaScript and to call the function after each page refresh. Now after each validations my calculation from the fields get lost.

```<code><script language="javascript">
    $(function () {
        $(document).on("blur", "input[type=text]", function () {
            var imekontrolebase = $(this).attr('id');
            var ime = ($(this).attr('id')).substr(12, $(this).attr('id').length);
            var n = ime.indexOf("_");
            var red = ime.substr(n+1);

            var imekol1 = "txt_OBR_P_1_1_" + red;
            var imekol2 = "txt_OBR_P_1_2_" + red;
            var imekol3 = "txtKOL3_" + red;

            var txt_OBR_P_1_1 = parseFloat($('#' + imekol1).val().replace(/\,/g, '')) || 0
            var txt_OBR_P_1_2 = parseFloat($('#' + imekol2).val().replace(/\,/g, '')) || 0

            var txtKOL3 = txt_OBR_P_1_1 + txt_OBR_P_1_2;

            if (txtKOL3 === 0 || txtKOL3 === Infinity || isNaN(txtKOL3)) {
                txtKOL3 = $('#' + imekol3).val("");
            }
            else {
                var ukupnoID3 = ("" + txtKOL3).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, function ($1) { return $1 + "," });
                $('#' + imekol3).val(ukupnoID3);
            }
        })
    })
</script>
</code>```

I need to create some function like this:

```<code><script language="javascript">
    function startCalc() {
    }
</script>
</code>```

And call it from server side after each validation.

```<code>Page.ClientScript.RegisterStartupScript(Page.GetType(), "Script", "startCalc()", True)
</code>```

答:
If you want Vanilla JavaScript solution you can try this:

function startCalc() {
    var root = document.documentElement || document.body;
    root.addEventListener('blur', function(e) {
        var node = e.target;
        if (node.nodeName == 'input' &&
            node.getAttribute('type') == 'text') {
            var imekontrolebase = node.getAttribute('id');
            var ime = imekontrolebase.substr(12, imekontrolebase.length);
            var n = ime.indexOf("_");
            var red = ime.substr(n+1);

            var imekol1 = "txt_OBR_P_1_1_" + red;
            var imekol2 = "txt_OBR_P_1_2_" + red;
            var imekol3 = "txtKOL3_" + red;

            var txt_OBR_P_1_1 = parseFloat(document.getElementById(imekol1).value.replace(/\,/g, '')) || 0
            var txt_OBR_P_1_2 = parseFloat(document.getElementById(imekol2).value.replace(/\,/g, '')) || 0

            var txtKOL3 = txt_OBR_P_1_1 + txt_OBR_P_1_2;

            if (txtKOL3 === 0 || txtKOL3 === Infinity || isNaN(txtKOL3)) {
                txtKOL3 = document.getElementById(imekol3).value;
            }
            else {
                var ukupnoID3 = ("" + txtKOL3).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, function ($1) { return $1 + "," });
                document.getElementById(imekol3).value = ukupnoID3;
            }
        })

    });
}
```

basically

$('#name') -> document.getElementById('name'); or

document.querySelector('#name') that return single element or

document.querySelectorAll('#name') that return array like object

jqueryObject.val() -> htmlNode.value

$(document).on('blur' -> node.addEventListener('blur' and you need to check for the correct node using event.target

Title: How to do the same in JavaScript?

Body:
I have this jQuery that automaticali calculate when is focus out of the field. I need to the the same this in JavaScript and to call the function after each page refresh. Now after each validations my calculation from the fields get lost.

I need to create some function like this:

And call it from server side after each validation.

Page.ClientScript.RegisterStartupScript(Page.GetType(), "Script", "startCalc()", True)

Body:
If you want Vanilla JavaScript solution you can try this:

function startCalc() {
    var root = document.documentElement || document.body;
    root.addEventListener('blur', function(e) {
        var node = e.target;
        if (node.nodeName == 'input' &&
            node.getAttribute('type') == 'text') {
            var imekontrolebase = node.getAttribute('id');
            var ime = imekontrolebase.substr(12, imekontrolebase.length);
            var n = ime.indexOf("_");
            var red = ime.substr(n+1);

            var imekol1 = "txt_OBR_P_1_1_" + red;
            var imekol2 = "txt_OBR_P_1_2_" + red;
            var imekol3 = "txtKOL3_" + red;

            var txt_OBR_P_1_1 = parseFloat(document.getElementById(imekol1).value.replace(/\,/g, '')) || 0
            var txt_OBR_P_1_2 = parseFloat(document.getElementById(imekol2).value.replace(/\,/g, '')) || 0

            var txtKOL3 = txt_OBR_P_1_1 + txt_OBR_P_1_2;

            if (txtKOL3 === 0 || txtKOL3 === Infinity || isNaN(txtKOL3)) {
                txtKOL3 = document.getElementById(imekol3).value;
            }
            else {
                var ukupnoID3 = ("" + txtKOL3).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, function ($1) { return $1 + "," });
                document.getElementById(imekol3).value = ukupnoID3;
            }
        })

    });
}

basically

$('#name') -> document.getElementById('name'); or

document.querySelector('#name') that return single element or

document.querySelectorAll('#name') that return array like object

jqueryObject.val() -> htmlNode.value

$(document).on('blur' -> node.addEventListener('blur' and you need to check for the correct node using event.target