答:
I think this ...
message_to_user("You managed to complete",levelcounter,"levels",green,0,40)

should become...

message_to_user("You managed to complete" +str(levelcounter)+" levels",green,0,40)

Title: Python- including a variable within the text part of parameters

Body:
So in Pygame have a function that displays messages to users:

def message_to_user(msg, color, X_displacement, Y_displacement):
    # creating function to display messages to the user
    message=font.render(msg,True,color)
    msgcenter=200+X_displacement,200+Y_displacement
    Game_display.blit(message,msgcenter)

now there is a message I need to display with another variable showing aswell:

        message_to_user("You managed to complete",levelcounter,"levels",green,0,40)

here is the error:

TypeError: message_to_user() takes exactly 4 arguments (6 given)

I understand why I am getting this error, just can't figure a way around it


来源: stackexchange

问:
Spring boot application Logging
We have a spring boot application and in the application.properties we set the log file location to be written to /var/log/onbase.log

But whenever the server is started there is one more log that is written to var/onbaseAPP.log (this log is filling up the memory on the box and the server is getting hung up)

We don't have any were in the code to create a onbaseApp.log not sure how it is getting created

please help. thanks in advance.

答:
if you use Log4j or Log4j2, you’ll need to change your dependencies to include the appropriate starter for the logging implementation you want to use and to exclude Logback.

For Maven builds, you can exclude Logback by excluding the default logging starter transitively resolved by the root starter dependency:

```<code><dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
    <exclusions>
        <exclusion>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-logging</artifactId>
        </exclusion>
    </exclusions>
</dependency>
</code>```

In Gradle, it’s easiest to place the exclusion under the configurations section:

```<code>configurations {
    all*.exclude group:'org.springframework.boot',
    module:'spring-boot-starter-logging'
}
</code>```

With the default logging starter excluded, you can now include the starter for the logging
implementation you’d rather use. With a Maven build you can add Log4j like this:

```<code><dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-log4j</artifactId>
</dependency>
</code>```

In a Gradle build you can add Log4j like this:

```<code>compile("org.springframework.boot:spring-boot-starter-log4j")
</code>```

your application.properties like this :

```<code>logging.path=/var/log/
logging.file=onbase.log
#logging.level.root=WARN
#logging.level.root.org.springframework.security=DEBUG
</code>```

Source: Spring Boot in action Craig Walls

ContentLicense: CC BY-SA 3.0

Title: Spring boot application Logging

Body:
if you use Log4j or Log4j2, you’ll need to change your dependencies to include the appropriate starter for the logging implementation you want to use and to exclude Logback.

For Maven builds, you can exclude Logback by excluding the default logging starter transitively resolved by the root starter dependency:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
    <exclusions>
        <exclusion>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-logging</artifactId>
        </exclusion>
    </exclusions>
</dependency>

In Gradle, it’s easiest to place the exclusion under the configurations section:

configurations {
    all*.exclude group:'org.springframework.boot',
    module:'spring-boot-starter-logging'
}

With the default logging starter excluded, you can now include the starter for the logging
implementation you’d rather use. With a Maven build you can add Log4j like this:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-log4j</artifactId>
</dependency>

In a Gradle build you can add Log4j like this:

compile("org.springframework.boot:spring-boot-starter-log4j")

your application.properties like this :

logging.path=/var/log/
logging.file=onbase.log
#logging.level.root=WARN
#logging.level.root.org.springframework.security=DEBUG

Source: Spring Boot in action Craig Walls


问:
Python- including a variable within the text part of parameters
So in Pygame have a function that displays messages to users:

```<code>def message_to_user(msg, color, X_displacement, Y_displacement):
    # creating function to display messages to the user
    message=font.render(msg,True,color)
    msgcenter=200+X_displacement,200+Y_displacement
    Game_display.blit(message,msgcenter)
</code>```

now there is a message I need to display with another variable showing aswell:

```<code>        message_to_user("You managed to complete",levelcounter,"levels",green,0,40)
</code>```

here is the error:

```<code>TypeError: message_to_user() takes exactly 4 arguments (6 given)
</code>```

I understand why I am getting this error, just can't figure a way around it

答:
You can concatenate the string with the variable to make your message 1 argument

```<code>message_to_user("You managed to complete " + levelcounter + " levels",green,0,40)
</code>```

This would fix the function call to make the arguments match the variables

Body:
You can concatenate the string with the variable to make your message 1 argument

message_to_user("You managed to complete " + levelcounter + " levels",green,0,40)

This would fix the function call to make the arguments match the variables


问:
How to break line in JavaScript?
Please let me know how to break line in JavaScript.

```<code><input type='submit' name='Submit' value='Submit'
onClick="parent.location='mailto:er.saurav123@gmail.com?subject=Thanks for writing to me &body=I will get back to you soon. Thanks and Regards Saurav Kumar'">
</code>```

I want a break line in Subject. The output I need is:

```<code>I will get back to you soon
Thanks and Regards
Saurav Kumar
</code>```

答:
```<code>alert("I will get back to you soon\nThanks and Regards\nSaurav Kumar");
</code>```

or use %0D%0A in a url

Title: How to break line in JavaScript?

Body:
Please let me know how to break line in JavaScript.

<input type='submit' name='Submit' value='Submit'
onClick="parent.location='mailto:er.saurav123@gmail.com?subject=Thanks for writing to me &body=I will get back to you soon. Thanks and Regards Saurav Kumar'">

I want a break line in Subject. The output I need is:

I will get back to you soon
Thanks and Regards
Saurav Kumar

Body:
alert("I will get back to you soon\nThanks and Regards\nSaurav Kumar");

or use %0D%0A in a url

ContentLicense: CC BY-SA 4.0


问:
Iterate over only the first n items of an array in a Go template
I have a vector with n elements. I'm using it to render items in a template. But I need to render only the 5 first elements. Please note that is possible to have less than 5 elements in vector, in this case will render all elements. Is there is a way to do it in template?

```<code>{{range .Categorias}}
    <li class="nav-item">
        {{.Nome}}
    </li>
{{end}}
</code>```

答:
Easiest would be to only pass 5 elements, so you don't need any logic in the template.

You can also do this in template, if you also store the index in the {{range}} action. Then you can use an {{if}} action to check the index, and only render the body of the {{if}} if the index is less than 5:

```<code>{{range $i, $e := .Categorias}}{{if lt $i 5}}
    <li class="nav-item">
        {{.Nome}}
    </li>
{{end}}{{end}}
</code>```

Here's a simple example demonstrating it:

```<code>func main() {
    t := template.Must(template.New("").Parse(src))
    numbers := []int{0, 1, 2, 3, 4, 5, 6, 7, 8}
    if err := t.Execute(os.Stdout, numbers); err != nil {
        panic(err)
    }
}

const src = `{{range $i, $e := .}}{{if lt $i 5}}{{.}} {{end}}{{end}}`
</code>```

Output (try it on the Go Playground):

```<code>0 1 2 3 4
</code>```

Go 1.10 template extension

Note that in Go 1.10 there will be new {{break}} and {{continue}} actions which will provide an alternative, better solution for this.

It will look something like this:

```<code>{{range $i, $e := .Categorias}}
    <li class="nav-item">
        {{.Nome}}
    </li>
{{if eq $i 4}}{{break}}{{end}}{{end}}
</code>```

This new {{break}} action will provide a superior solution as the above {{range}} action will only iterate over 5 elements at most (while the other solution without {{break}} has to iterate over all elements, just elements with index >=  5 are not rendered).

Go 1.13 template extension

Go 1.13 adds the slice builtin template function which provides an even nicer and more efficient solution. Slice the value you want to range over, so the {{range}} action only "gets" what you want to loop over:

```<code>func main() {
    t := template.Must(template.New("").Parse(src))
    numbers := []int{0, 1, 2, 3, 4, 5, 6, 7, 8}
    if err := t.Execute(os.Stdout, numbers); err != nil {
        panic(err)
    }
}

const src = `{{range $i, $e := (slice . 0 5)}}{{.}} {{end}}`
</code>```

This will output (try it on the Go Playground):

```<code>0 1 2 3 4
</code>```

Body:
I have a vector with n elements. I'm using it to render items in a template. But I need to render only the 5 first elements. Please note that is possible to have less than 5 elements in vector, in this case will render all elements. Is there is a way to do it in template?

{{range .Categorias}}

        {{.Nome}}

{{end}}

Body:
Easiest would be to only pass 5 elements, so you don't need any logic in the template.

You can also do this in template, if you also store the index in the {{range}} action. Then you can use an {{if}} action to check the index, and only render the body of the {{if}} if the index is less than 5:

{{range $i, $e := .Categorias}}{{if lt $i 5}}
    <li class="nav-item">
        {{.Nome}}
    </li>
{{end}}{{end}}

Here's a simple example demonstrating it:

func main() {
    t := template.Must(template.New("").Parse(src))
    numbers := []int{0, 1, 2, 3, 4, 5, 6, 7, 8}
    if err := t.Execute(os.Stdout, numbers); err != nil {
        panic(err)
    }
}

const src = `{{range $i, $e := .}}{{if lt $i 5}}{{.}} {{end}}{{end}}`

Output (try it on the Go Playground):

0 1 2 3 4

Go 1.10 template extension

Note that in Go 1.10 there will be new {{break}} and {{continue}} actions which will provide an alternative, better solution for this.

It will look something like this:

{{range $i, $e := .Categorias}}
    <li class="nav-item">
        {{.Nome}}
    </li>
{{if eq $i 4}}{{break}}{{end}}{{end}}

This new {{break}} action will provide a superior solution as the above {{range}} action will only iterate over 5 elements at most (while the other solution without {{break}} has to iterate over all elements, just elements with index >=  5 are not rendered).

Go 1.13 template extension

Go 1.13 adds the slice builtin template function which provides an even nicer and more efficient solution. Slice the value you want to range over, so the {{range}} action only "gets" what you want to loop over:

func main() {
    t := template.Must(template.New("").Parse(src))
    numbers := []int{0, 1, 2, 3, 4, 5, 6, 7, 8}
    if err := t.Execute(os.Stdout, numbers); err != nil {
        panic(err)
    }
}

const src = `{{range $i, $e := (slice . 0 5)}}{{.}} {{end}}`

This will output (try it on the Go Playground):

0 1 2 3 4


问:
Access object in Angular passed by Spring's ModelAndView
I am trying to set up an Atlassian Connect addon for Jira with atlassian-connect-spring-boot and Angular 4.

For rendering the view, I have to define a rest endpoint which returns a ModelAndView:

```<code>@RequestMapping(value = "/index", method = RequestMethod.GET)
public ModelAndView helloWorld(@AuthenticationPrincipal AtlassianHostUser hostUser) {
    ModelAndView model = new ModelAndView();
    model.setViewName("index");
    model.addObject("hostUser", hostUser);
    return model;
}
</code>```

This will render my frontend, so the index.html. This works perfectly fine, except I do not know how I can access the object hostUser in Angular now.

Is this even possible, if yes how? If not, how can I pass an object from the spring backend to the angular frontend without having to make a custom rest call (due to the fact that Atlassian Connect handles the authentication by calling the rest endpoints itself)

I contacted Atlassian already, but I have not received an answer yet.

答:
You seem to have been confused with server and client side technologies.

Assuming you have configured InternalResourceViewResolver which is JSP+JSTL ViewResolver your controller will return a JSP file. If you are using Thymeleaf template then your view resolver will change accordingly.

Angular is client side part and nothing to do with server side presentation. If you are using angular you should create spring boot webservices to get the data and render it in accordingly in the UI.

Look at below blog for example -
https://spring.io/blog/2015/08/19/migrating-a-spring-web-mvc-application-from-jsp-to-angularjs . Specially the "Considerations when moving from JSP to AngularJS" part.

Don't try to mix both :)

Body:
I am trying to set up an Atlassian Connect addon for Jira with atlassian-connect-spring-boot and Angular 4.

For rendering the view, I have to define a rest endpoint which returns a ModelAndView:

@RequestMapping(value = "/index", method = RequestMethod.GET)
public ModelAndView helloWorld(@AuthenticationPrincipal AtlassianHostUser hostUser) {
    ModelAndView model = new ModelAndView();
    model.setViewName("index");
    model.addObject("hostUser", hostUser);
    return model;
}

This will render my frontend, so the index.html. This works perfectly fine, except I do not know how I can access the object hostUser in Angular now.

Is this even possible, if yes how? If not, how can I pass an object from the spring backend to the angular frontend without having to make a custom rest call (due to the fact that Atlassian Connect handles the authentication by calling the rest endpoints itself)

I contacted Atlassian already, but I have not received an answer yet.


问:
How to implement a password text input widget (input obscured) for google-apps-script gmail add-on?
Couldn't see any option available for the TextInput widget to obscure a user's input for fields like password, etc.

https://developers.google.com/apps-script/reference/card-service/text-input

答:
In the overview section of the CardService,
It quotes:

“Currently you can only use this service to construct Gmail add-ons.“

So HtmlService is not available in constructing
Gmail addon’s currently.  And there is no option
In the CardService object to obscure the textInput
widget.  The reference says when constructing
your addon to keep it simple, nothing complex.
You may want to rethink your use-case for your addon.


问:
Array implementation of Binary Search Tree
I am creating a binary search tree using a 1D array. My problem is with the insertion function.

Inserting 5, 8, 3, 1, 4, and 9 results in the correct index when I output the tree. However, when I try to add numbers after 9 into the tree, the index is incorrect. For example, with the previous numbers mentioned, 9 has an index of 7. If I insert 17, which should be 9's right child, instead of its index at 15, it's index is 11.

I know that the issue is with how I increment i but I'm not sure how to fix it. Any help is appreciated. Thanks!

```<code>    void insert(int x)
    {
    int i = 1;  //Counter

    if (ptr->arr[1] == -1)   //If bst is empty.
    {
        ptr->arr[1] = x;
    }
    else
    {
        int *temp = &ptr->arr[1];  //Temp starts at root
        int *parent = NULL;
        while (*temp != -1 && *temp != x)
        {
            if (x < *temp)
            {
                parent = temp;
                temp = &ptr->arr[i*2];
                i++;
            }

            else
            {
                parent = temp;
                temp = &ptr->arr[i*2+1];
                i+=2;
            }

        }

        *temp = x;

    }
</code>```

答:
You are maintaining the current node in two different variables: a pointer to the node is kept in temp and the index of the node is kept in i. This by itself - although probably not optimal - is not a problem. However, you don't keep the two variables consistent (you update the pointer differently than the index). A simple fix would be to make this consistent:

```<code>temp = &ptr->arr[i*2]; //the pointer update is correct
i = i * 2; //same update as above
//...
temp = &ptr->arr[i*2+1];
i = i * 2 + 1; //same update as above
</code>```

In my opinion, it is also a good idea to drop the pointer temp completely and always access the array by its index. This would not require any synchronization between two variables.

Body:
I am creating a binary search tree using a 1D array. My problem is with the insertion function.

Inserting 5, 8, 3, 1, 4, and 9 results in the correct index when I output the tree. However, when I try to add numbers after 9 into the tree, the index is incorrect. For example, with the previous numbers mentioned, 9 has an index of 7. If I insert 17, which should be 9's right child, instead of its index at 15, it's index is 11.

I know that the issue is with how I increment i but I'm not sure how to fix it. Any help is appreciated. Thanks!

    void insert(int x)
    {
    int i = 1;  //Counter

    if (ptr->arr[1] == -1)   //If bst is empty.
    {
        ptr->arr[1] = x;
    }
    else
    {
        int *temp = &ptr->arr[1];  //Temp starts at root
        int *parent = NULL;
        while (*temp != -1 && *temp != x)
        {
            if (x < *temp)
            {
                parent = temp;
                temp = &ptr->arr[i*2];
                i++;
            }

            else
            {
                parent = temp;
                temp = &ptr->arr[i*2+1];
                i+=2;
            }

        }

        *temp = x;

    }

Body:
You are maintaining the current node in two different variables: a pointer to the node is kept in temp and the index of the node is kept in i. This by itself - although probably not optimal - is not a problem. However, you don't keep the two variables consistent (you update the pointer differently than the index). A simple fix would be to make this consistent:

temp = &ptr->arr[i*2]; //the pointer update is correct
i = i * 2; //same update as above
//...
temp = &ptr->arr[i*2+1];
i = i * 2 + 1; //same update as above

In my opinion, it is also a good idea to drop the pointer temp completely and always access the array by its index. This would not require any synchronization between two variables.


问:
Regex to select everything a replace with a word
I have lots of diffrent lines with numbers, symbols and words, i need them all replaced with a word of my choosing, i tried ^.(.) but it didnt work

```<code>james!@
fire11
exampleexample
</code>```

I need them to become any word i put in replace with, so for example

```<code>Football
Football
football
</code>```

The regex would need to target everything inside the file, not just words, but symbols and numbers, any help is appreciated

答:
Try it

```<code>(.*)$
</code>```

Replace with it

```<code>Football
</code>```

Body:
I have lots of diffrent lines with numbers, symbols and words, i need them all replaced with a word of my choosing, i tried ^.(.) but it didnt work

james!@
fire11
exampleexample

I need them to become any word i put in replace with, so for example

Football
Football
football

The regex would need to target everything inside the file, not just words, but symbols and numbers, any help is appreciated

Body:
Try it

(.*)$

Replace with it

Football


问:
How can I make Docker trigger higher CPU frequencies
OK, so my title may not actually be linked to a possible solution, however this is my problem.
I am running a Python 3 Jupyter notebook inside a docker container in from my windows 10 kaby-lake (2 physical cores, 4 virtual cores) laptop.
I noticed while doing heavy computing from there, my CPU usage seen in the task monitor is very low (~15%).
When going on the details for each process, the VBoxHeadless.exe actually uses 24% of the processor, which matches docker stats command which yields 97-100% CPU usage, and therefore makes sense from a single-core operation point of view.

My actual issue is that even though on thread is filled in terms of CPU time, windows (I guess) does not decide that it may actually be useful to speed up the CPU, and therefore it runs at 1.7GHz (with other apps in high performance mode, I usually hit the max 3.5GHz that the computer is capable of).

Therefore, how can I induce the higher clock speeds (nominal 2.7GHz or max 3.5GHZ) (considering that they would probably double my single threaded speed) from docker itself or inside windows 10?

答:
Defining CPU Shares can help you but not exactly.

CPU limits are based on shares as these shares are a weight between how much processing time one process should get compared to another. If a CPU is idle, then the process will use all the available resources. If a second process requires the CPU then the available CPU time will be shared based on the weighting.
e.g. The --cpu-shares parameter defines a share between 0-768. If a container defines a share of 768, while another defines a share of 256, the first container will have 50% share while the other one having 25% of the available share total.

Below the first container will be allowed to have 75% of the share. The second container will be limited to 25%.

```<code>docker run -d --name p1 --cpuset-cpus 0 --cpu-shares 768 image_name
docker run -d --name p2 --cpuset-cpus 0 --cpu-shares 256 image_name
sleep 5
docker stats --no-stream
docker rm -f p1 p2
</code>```

It's important to note that a process can have 100% of the share, no matter defined weight, if no other processes are running.

Body:
Defining CPU Shares can help you but not exactly.

CPU limits are based on shares as these shares are a weight between how much processing time one process should get compared to another. If a CPU is idle, then the process will use all the available resources. If a second process requires the CPU then the available CPU time will be shared based on the weighting.
e.g. The --cpu-shares parameter defines a share between 0-768. If a container defines a share of 768, while another defines a share of 256, the first container will have 50% share while the other one having 25% of the available share total.

Below the first container will be allowed to have 75% of the share. The second container will be limited to 25%.

docker run -d --name p1 --cpuset-cpus 0 --cpu-shares 768 image_name
docker run -d --name p2 --cpuset-cpus 0 --cpu-shares 256 image_name
sleep 5
docker stats --no-stream
docker rm -f p1 p2

It's important to note that a process can have 100% of the share, no matter defined weight, if no other processes are running.


问:
SQL Add to Existing Table from Temp Table
I'm making a basketball stats database, and have a table in SQL with the player's totals from all of their games combined. I'm having trouble adding to it, however. I use a temporary table for each game, and then I need to add all of the temporary values to the player's total table. How would I do this? I have tried many methods, each of which throw an error. Here are a few:

(live_players is the temporary table, and here I'm only trying to join the points column.)

```<code>db.execute("UPDATE players JOIN live_players AS t1 ON players.player_id
= t1.player_id SET points = points + t1.points")

db.execute("MERGE INTO players USING live_players ON players.player_id
= live_players.player_id WHEN MATCHED THEN UPDATE
SET points = points + live_players.points")
</code>```

答:
This should will give you the player_id and points for records in live_players that are new (not sure if that's possible) or have matching records in the players table, along with the addition of that points when player currently exist:

```<code>SELECT ST1.player_id, case when ST2.points > 0 THEN ST1.points+ST2.points Else ST1.points END as test FROM live_players ST1 LEFT JOIN players ST2 USING(player_id)
</code>```

Integrating that with an UPDATE operation, depending on the unique indexing of our players table should get you where you need to be.

Body:
I'm making a basketball stats database, and have a table in SQL with the player's totals from all of their games combined. I'm having trouble adding to it, however. I use a temporary table for each game, and then I need to add all of the temporary values to the player's total table. How would I do this? I have tried many methods, each of which throw an error. Here are a few:

(live_players is the temporary table, and here I'm only trying to join the points column.)

db.execute("UPDATE players JOIN live_players AS t1 ON players.player_id
= t1.player_id SET points = points + t1.points")

db.execute("MERGE INTO players USING live_players ON players.player_id
= live_players.player_id WHEN MATCHED THEN UPDATE
SET points = points + live_players.points")

Body:
This should will give you the player_id and points for records in live_players that are new (not sure if that's possible) or have matching records in the players table, along with the addition of that points when player currently exist:

SELECT ST1.player_id, case when ST2.points > 0 THEN ST1.points+ST2.points Else ST1.points END as test FROM live_players ST1 LEFT JOIN players ST2 USING(player_id)

Integrating that with an UPDATE operation, depending on the unique indexing of our players table should get you where you need to be.


问:
How to count the frequency of the elements in an unordered list?
Given an unordered list of values like

```<code>a = [5, 1, 2, 2, 4, 3, 1, 2, 3, 1, 1, 5, 2]
</code>```

How can I get the frequency of each value that appears in the list, like so?

```<code># `a` has 4 instances of `1`, 4 of `2`, 2 of `3`, 1 of `4,` 2 of `5`
b = [4, 4, 2, 1, 2] # expected output
</code>```

答:
This approach can be tried if you don't want to use any library and keep it simple and short!

```<code>a = [1,1,1,1,2,2,2,2,3,3,4,5,5]
marked = []
b = [(a.count(i), marked.append(i))[0] for i in a if i not in marked]
print(b)
</code>```

o/p

```<code>[4, 4, 2, 1, 2]
</code>```

Body:
Given an unordered list of values like

a = [5, 1, 2, 2, 4, 3, 1, 2, 3, 1, 1, 5, 2]

How can I get the frequency of each value that appears in the list, like so?

# `a` has 4 instances of `1`, 4 of `2`, 2 of `3`, 1 of `4,` 2 of `5`
b = [4, 4, 2, 1, 2] # expected output

Body:
This approach can be tried if you don't want to use any library and keep it simple and short!

a = [1,1,1,1,2,2,2,2,3,3,4,5,5]
marked = []
b = [(a.count(i), marked.append(i))[0] for i in a if i not in marked]
print(b)

o/p

[4, 4, 2, 1, 2]


问:
need help with an odd json parsing issue
I have odd problems with parsing what I believe to be well-formed json returned from an ajax call (using jQuery 1.4.4). Oddly, on my dev server it works fine but fails online.

The data is returned from the ajax call as follows:

```<code>returnData = { "status": true, "data": { "error_return": false, "error_index": -1, "message_display": { "main_message": "hello", "name": "tommy tune the man", "mailed_to": "t@t.com", "subject": "I tried this", "subject_message": "you have a technical question or comment.", "test_me": "you have a technical question or comment." } } };
</code>```

jsLint and jsonLint both validate this structure.

The error occurs when I try to access returnData.data

In the "fail" cases, I have removed the dataType from the jQuery.ajax options, thereby allowing the "best-guess" feature.  If I specify json, jQuery throws a parse error, claiming invalid json. I have tried all kinds of things (including the dreaded eval() and the jquery-2json plugin but no luck.  Even the jQ utility jQuery.parseJSON fails.

The problem occurs in both FF 3.6.13 and latest Safari / Chrome.

Question 1: does anyone why know the latest jQuery throws a parse error on this?

Question 2: when I try the following, I have success:

var success = returnData.status;

BUT the following is undefined:

var errorReturn = returnData.data.error_return.

Oddly, Firebug sees this as an object if I "paste" the object into the console, but within the script
1) returns "no child objects" in console.dir
2) BUT will display the object in console.log.

Ideas greatly appreciated

UPDATE:
I discovered that the server was setting the Content type incorrectly.  In the server-side PHP that formats the JSON for return (created in this case in Drupal 6 (I had to hack the core-optional include "commons.inc"), I replaced the content type with 'application/json'. This now works. This problem has been corrected in Drupal 7.

答:
See my update as I have solved the problem. I apologize for not being more specific in my original post.  The variable returnedData is actually in the success callback (sorry about not specifying.)

For clarity, I am using the following with the jQ submit() function (in the click handler for this form submission):

```<code>var ajaxOptions = {
  type: 'POST',
  url: url,
  dataType: "json",
  beforeSubmit: checkInput,
  success:
  evaluateResponse
  }

  e.preventDefault();

  $(this).ajaxSubmit(contactOptions);
</code>```

Where the success callback is:

```<code>  function
  evaluateContactResponse(returnData) {
  //and so on }
</code>```

(Side-note: I was using the jQ form plugin until these failures occurred but moved to a different implementation since the form plugin failed silently.  I may now move this back since the form plugin is so elegant.)

The callback "evaluateResponse" is where the parsing takes place, and as I said, now works.

Thanks again... you are a smart guy
N

ContentLicense: CC BY-SA 2.5

Body:
I have odd problems with parsing what I believe to be well-formed json returned from an ajax call (using jQuery 1.4.4). Oddly, on my dev server it works fine but fails online.

The data is returned from the ajax call as follows:

returnData = { "status": true, "data": { "error_return": false, "error_index": -1, "message_display": { "main_message": "hello", "name": "tommy tune the man", "mailed_to": "t@t.com", "subject": "I tried this", "subject_message": "you have a technical question or comment.", "test_me": "you have a technical question or comment." } } };

jsLint and jsonLint both validate this structure.

The error occurs when I try to access returnData.data

In the "fail" cases, I have removed the dataType from the jQuery.ajax options, thereby allowing the "best-guess" feature.  If I specify json, jQuery throws a parse error, claiming invalid json. I have tried all kinds of things (including the dreaded eval() and the jquery-2json plugin but no luck.  Even the jQ utility jQuery.parseJSON fails.

The problem occurs in both FF 3.6.13 and latest Safari / Chrome.

Question 1: does anyone why know the latest jQuery throws a parse error on this?

Question 2: when I try the following, I have success:

var success = returnData.status;

BUT the following is undefined:

var errorReturn = returnData.data.error_return.

Oddly, Firebug sees this as an object if I "paste" the object into the console, but within the script
1) returns "no child objects" in console.dir
2) BUT will display the object in console.log.

Ideas greatly appreciated

UPDATE:
I discovered that the server was setting the Content type incorrectly.  In the server-side PHP that formats the JSON for return (created in this case in Drupal 6 (I had to hack the core-optional include "commons.inc"), I replaced the content type with 'application/json'. This now works. This problem has been corrected in Drupal 7.

Body:
See my update as I have solved the problem. I apologize for not being more specific in my original post.  The variable returnedData is actually in the success callback (sorry about not specifying.)

For clarity, I am using the following with the jQ submit() function (in the click handler for this form submission):

var ajaxOptions = {
  type: 'POST',
  url: url,
  dataType: "json",
  beforeSubmit: checkInput,
  success:
  evaluateResponse
  }

  e.preventDefault();

  $(this).ajaxSubmit(contactOptions);

Where the success callback is:

  function
  evaluateContactResponse(returnData) {
  //and so on }

(Side-note: I was using the jQ form plugin until these failures occurred but moved to a different implementation since the form plugin failed silently.  I may now move this back since the form plugin is so elegant.)

The callback "evaluateResponse" is where the parsing takes place, and as I said, now works.

Thanks again... you are a smart guy
N


问:
Why return type of AKKA actor postStop not void?
In overriding the postStop method I got this very strange:
error message from illelliJ

the class is very simple:

```<code>public class TempClass extends AbstractActor {
      @Override
      public void postStop(){}
}
</code>```

the api indicates the return type is void, do I miss something in my code?

答: Don't mix the scala and java API or you will be in for a lot of headaches. Look at the imports and so on. Also make sure you are up to date with the version of Akka. </p>

Body:
In overriding the postStop method I got this very strange:
error message from illelliJ

the class is very simple:

public class TempClass extends AbstractActor {
      @Override
      public void postStop(){}
}

the api indicates the return type is void, do I miss something in my code?


问:
Parse.com relations with ParseObject
I'm trying to fix relation between two ParseObjects: Place & Visit.
I tried the method of extending the objects to ParseObjects which is a clean approach. The problem is the related Place object does not get saved.

Place:

```<code>@ParseClassName("Place")
public class Place extends ParseObject {

    public Place() {
    }

    private String title;
    private ParseGeoPoint geoPoint;

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public ParseGeoPoint getGeoPoint() {
        return geoPoint;
    }

    public void setGeoPoint(ParseGeoPoint geoPoint) {
        this.geoPoint = geoPoint;
    }

    //Get distance to current location
    public double getDistance(ParseGeoPoint currentLocation) {
        return this.geoPoint.distanceInKilometersTo(currentLocation);
    }
}
</code>```

Visit

```<code>@ParseClassName("Visit")
public class Visit extends ParseObject {

    public Visit() {
    }

    private long timestamp;
    private long duration;

    private Place place;

    public long getTimestamp() {
        return timestamp;
    }

    public void setTimestamp(long timestamp) {
        this.timestamp = timestamp;
    }

    public long getDuration() {
        return duration;
    }

    public void setDuration(long duration) {
        this.duration = duration;
    }

    public Place getPlace() {
        return place;
    }

    public void setPlace(Place place) {
        this.place = place;
    }
}
</code>```

This is the way I save to the backend:

```<code>final Place place = new Place();
        place.setTitle("Home");

        final Visit visit = new Visit();
        visit.setTimestamp(Utils.getUnixNow());
        visit.setPlace(place);

        visit.saveEventually(new SaveCallback() {
            @Override
            public void done(ParseException e) {
                if (e == null) {
                    Logger.d("visit " + place.getTitle() + " was saved");
                } else {
                    Logger.d("Place was not saved, error " + e.getCode());
                }
            }
        });
</code>```

Both classes are registered in the MyApplication class.

答:
First of all: Your implementation of Parse classes is wrong.

1- remove all field variables

2- create the getters and setters as following

```<code>public String getTitle() {
    return get("Title"); // 'Title' is the column name in your Parse server table
}

public void setTitle(String title) {
    put("Title", title);
}
</code>```

if you want to return a parse object,

```<code>public ParseObject  getPlace () { // it's ParseObject  not Place
    return get("Place "); // 'Place ' is the column name in your Parse server table
}

public void setPlace (ParseObject title) { // it's ParseObject  not Place
    put("Place ", title);
}
</code>```

Creating objects

```<code>Place place= ParseObject.create(Place .class);
place.setTitle("some title");

Visit visit= ParseObject.create(Visit.class);
visit.setPlace(place);
visit.save(); // or use saveInBackground();
</code>```

In Your Application Class

```<code>    ParseObject.registerSubclass(Visit.class);
    ParseObject.registerSubclass(Place.class);
    Parse.initialize(this);
</code>```

Title: Parse.com relations with ParseObject

Body:
I'm trying to fix relation between two ParseObjects: Place & Visit.
I tried the method of extending the objects to ParseObjects which is a clean approach. The problem is the related Place object does not get saved.

Place:

@ParseClassName("Place")
public class Place extends ParseObject {

    public Place() {
    }

    private String title;
    private ParseGeoPoint geoPoint;

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public ParseGeoPoint getGeoPoint() {
        return geoPoint;
    }

    public void setGeoPoint(ParseGeoPoint geoPoint) {
        this.geoPoint = geoPoint;
    }

    //Get distance to current location
    public double getDistance(ParseGeoPoint currentLocation) {
        return this.geoPoint.distanceInKilometersTo(currentLocation);
    }
}

Visit

@ParseClassName("Visit")
public class Visit extends ParseObject {

    public Visit() {
    }

    private long timestamp;
    private long duration;

    private Place place;

    public long getTimestamp() {
        return timestamp;
    }

    public void setTimestamp(long timestamp) {
        this.timestamp = timestamp;
    }

    public long getDuration() {
        return duration;
    }

    public void setDuration(long duration) {
        this.duration = duration;
    }

    public Place getPlace() {
        return place;
    }

    public void setPlace(Place place) {
        this.place = place;
    }
}

This is the way I save to the backend:

final Place place = new Place();
        place.setTitle("Home");

        final Visit visit = new Visit();
        visit.setTimestamp(Utils.getUnixNow());
        visit.setPlace(place);

        visit.saveEventually(new SaveCallback() {
            @Override
            public void done(ParseException e) {
                if (e == null) {
                    Logger.d("visit " + place.getTitle() + " was saved");
                } else {
                    Logger.d("Place was not saved, error " + e.getCode());
                }
            }
        });

Both classes are registered in the MyApplication class.

Body:
First of all: Your implementation of Parse classes is wrong.

1- remove all field variables

2- create the getters and setters as following

public String getTitle() {
    return get("Title"); // 'Title' is the column name in your Parse server table
}

public void setTitle(String title) {
    put("Title", title);
}

if you want to return a parse object,

public ParseObject  getPlace () { // it's ParseObject  not Place
    return get("Place "); // 'Place ' is the column name in your Parse server table
}

public void setPlace (ParseObject title) { // it's ParseObject  not Place
    put("Place ", title);
}

Creating objects

Place place= ParseObject.create(Place .class);
place.setTitle("some title");

Visit visit= ParseObject.create(Visit.class);
visit.setPlace(place);
visit.save(); // or use saveInBackground();

In Your Application Class

    ParseObject.registerSubclass(Visit.class);
    ParseObject.registerSubclass(Place.class);
    Parse.initialize(this);


问:
Get Google Blockly Block by Id?
I would like to query the DOM to get a block by ID. Currently I have to find all elements by class name, and manually extract the correct index, which is not sustainable.

How can give a block a unique ID?

Thanks

答: All blocks already have an id (api docs). However, a Block object isn't a DOM object so you won't find it by using document.getElementById(..). Instead you'll use Workspace.getBlockById(..). Your workspace is usually Blockly.mainWorkspace

Title: Get Google Blockly Block by Id?


问:
PHP JSON Twitter Trends
Can anyone spot the problem with this PHP, nothing appears on the screen:</p>

```<code><?php
function get_data($url)
{
$ch = curl_init();
$timeout = 5;
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}

$url='http://search.twitter.com/trends.json';
$obj = json_decode(get_data($url));
foreach ($obj as $item) {
$trend = $item->name;
$link = $item->url;
echo "<a href='.$link.'>".$trend."</a>";
}
?>
</code>```

答:
You're not looping over the collection properly. Use:

```<code>foreach ($obj->trends as $item) {
</code>```

Your $obj is an object (just a stdClass) with a trends property which is an array of objects with name and url properties.  This reflects the structure of the JSON which looks like:

```<code>{
    "trends": [
        {
            "name": "#yepthatsme",
            "url": "http://search.twitter.com/search?q=%23yepthatsme"
        },
        {
            "name": "Miley Citrus",
            "url": "http://search.twitter.com/search?q=Miley+Citrus"
        },
        /* lots more */
        {
            "name": "Keith Olbermann",
            "url": "http://search.twitter.com/search?q=Keith+Olbermann"
        }
    ],
    "as_of": "Sat, 22 Jan 2011 13:37:25 +0000"
}
</code>```

Title: PHP JSON Twitter Trends

Body:
Can anyone spot the problem with this PHP, nothing appears on the screen:

<?php
function get_data($url)
{
$ch = curl_init();
$timeout = 5;
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}

$url='http://search.twitter.com/trends.json';
$obj = json_decode(get_data($url));
foreach ($obj as $item) {
$trend = $item->name;
$link = $item->url;
echo "".$trend."";
}
?>

Body:
You're not looping over the collection properly. Use:

foreach ($obj->trends as $item) {

Your $obj is an object (just a stdClass) with a trends property which is an array of objects with name and url properties.  This reflects the structure of the JSON which looks like:

{
    "trends": [
        {
            "name": "#yepthatsme",
            "url": "http://search.twitter.com/search?q=%23yepthatsme"
        },
        {
            "name": "Miley Citrus",
            "url": "http://search.twitter.com/search?q=Miley+Citrus"
        },
        /* lots more */
        {
            "name": "Keith Olbermann",
            "url": "http://search.twitter.com/search?q=Keith+Olbermann"
        }
    ],
    "as_of": "Sat, 22 Jan 2011 13:37:25 +0000"
}


问:
How to display a flash message in login page
I'm using Grails 3.2.7 along with spring-security-core:3.1.1, I want to set a message to the flash object from a controller upon logout, then I need to display this message in my login screen (auth.gsp)

see the below code I wrote.

In controller

if(condition 1){
flash.message = "logged out successfully and your claim id is 12345"; redirect(uri:"/logout");
}else if(condition b){
flash.message = "logged out"; redirect(uri:"/logout");
}else if(condition c){
flash.message = "multiple login is not allowed"; redirect(uri:"/logout");
}```
</div>
</div>
</p>

<p>In the auth.gsp</p>

```<g:if test='${flash.message}'>

${flash.message}

</g:if>
```

I could not see this message. Does anyone know how to display this message?

答:
If you are not redirected to the auth page when you logout, you will not see the flash message.

Find out which page you are redirected to and this code.

```<code><g:if test='${flash.message}'>
<div class="login_message">${flash.message}</div>
</g:if>
</code>```

If you really want to see this message on the auth page, then make sure logout redirects you directly to the auth page.

Have you thought about using sessions?

http://docs.grails.org/3.1.1/ref/Servlet%20API/session.html

Unlike flash message, they exist until you reset them. Flash messages are reset after the first time you request them.

Body:
I'm using Grails 3.2.7 along with spring-security-core:3.1.1, I want to set a message to the flash object from a controller upon logout, then I need to display this message in my login screen (auth.gsp)

see the below code I wrote.

In controller

if(condition 1){
flash.message = "logged out successfully and your claim id is 12345"; redirect(uri:"/logout");
}else if(condition b){
flash.message = "logged out"; redirect(uri:"/logout");
}else if(condition c){
flash.message = "multiple login is not allowed"; redirect(uri:"/logout");
}

In the auth.gsp

<g:if test='${flash.message}'>

${flash.message}

</g:if>

I could not see this message. Does anyone know how to display this message?

Body:
If you are not redirected to the auth page when you logout, you will not see the flash message.

Find out which page you are redirected to and this code.

<g:if test='${flash.message}'>
<div class="login_message">${flash.message}</div>
</g:if>

If you really want to see this message on the auth page, then make sure logout redirects you directly to the auth page.

Have you thought about using sessions?

http://docs.grails.org/3.1.1/ref/Servlet%20API/session.html

Unlike flash message, they exist until you reset them. Flash messages are reset after the first time you request them.


问:
Javascript Why isn't "this" defined in subclass until after super() is called
I have found that keyword "this" is "undefined" until super() is called, and I'm wondering where this behavior documented.  I'm asking only to learn where I can lookup these answers myself (in the future).

Code that shows this behavior is given below:

class BaseClass {
    constructor(){
        this.baseVar = 1;
    }
}

class SubClass extends BaseClass {
    constructor(...args){
        try {
            console.log('this BEFORE calling super.  this:', this);
        } catch(ex) {
            console.log('this BEFORE calling super. this: caused exception!');
        }
        super(...args);
        this.subVar = 2;
        console.log('this AFTER calling super.  this:', this);
    }
}

var base = new BaseClass();
var subclass = new SubClass();```
</div>
</div>
</p>

<p>The output from this is shown below:</p>

```this BEFORE calling super. this: caused exception!
this AFTER calling super.  this: SubClass { baseVar: 1, subVar: 2 }
```

答: JavaScript's biggest problem currently is that debugging is harder compared to other languages as many things are dynamic and you can basically change the core concepts of how the language works. The main aim of ES6 was to get rid of common dynamic problems and missconceptions of the language. While prototypal Inheritance is really useful in some cases, the language architects saw a need for a better readable and more stable way of creating inheritance ( and more familar for java folks ). Thats why they introduced class, and that you can't work with thisbefore calling super() is one of the things to make it more stable.

Body:
I have found that keyword "this" is "undefined" until super() is called, and I'm wondering where this behavior documented.  I'm asking only to learn where I can lookup these answers myself (in the future).

Code that shows this behavior is given below:

class BaseClass {
    constructor(){
        this.baseVar = 1;
    }
}

class SubClass extends BaseClass {
    constructor(...args){
        try {
            console.log('this BEFORE calling super.  this:', this);
        } catch(ex) {
            console.log('this BEFORE calling super. this: caused exception!');
        }
        super(...args);
        this.subVar = 2;
        console.log('this AFTER calling super.  this:', this);
    }
}

var base = new BaseClass();
var subclass = new SubClass();

The output from this is shown below:

this BEFORE calling super. this: caused exception!
this AFTER calling super.  this: SubClass { baseVar: 1, subVar: 2 }


问:
Retrieve elements removed by List splice
Is there a way to receive the elements that were excluded from a List during a splice() operation?  splice() seems to return a new List with the elements spliced excluded, which is what I expected according to the API, but I am not sure how to get the elements that I excluded.

```<code>const a: List<number> = List<number>([1, 2, 3, 4]),
    b: List<number> = List<number>(a.splice(1, 1));
console.log(a.toArray()); // [1, 2, 3, 4]
console.log(b.toArray()); // [1, 3, 4]

// How would I get the hypothetical [2] that was excluded?
</code>```

I assumed that splice() would mirror the native Array.splice() or at least provide some way to get both the new List and the removed elements.

Do I have to break this into 2 steps using a slice() and then a splice()?

```<code>const a: List<number> = List<number>([1, 2, 3, 4]),
    excluded: List<number> = List<number>(a.slice(1, 2)),
    b: List<number> = List<number>(a.splice(1, 1));
console.log(a.toArray()); // [1, 2, 3, 4]
console.log(b.toArray()); // [1, 3, 4]
console.log(excluded.toArray()); // [2]
</code>```

答:
I think you should use slice method instead of splice.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice

Body:
Is there a way to receive the elements that were excluded from a List during a splice() operation?  splice() seems to return a new List with the elements spliced excluded, which is what I expected according to the API, but I am not sure how to get the elements that I excluded.

const a: List<number> = List<number>([1, 2, 3, 4]),
    b: List<number> = List<number>(a.splice(1, 1));
console.log(a.toArray()); // [1, 2, 3, 4]
console.log(b.toArray()); // [1, 3, 4]

// How would I get the hypothetical [2] that was excluded?

I assumed that splice() would mirror the native Array.splice() or at least provide some way to get both the new List and the removed elements.

Do I have to break this into 2 steps using a slice() and then a splice()?

const a: List<number> = List<number>([1, 2, 3, 4]),
    excluded: List<number> = List<number>(a.slice(1, 2)),
    b: List<number> = List<number>(a.splice(1, 1));
console.log(a.toArray()); // [1, 2, 3, 4]
console.log(b.toArray()); // [1, 3, 4]
console.log(excluded.toArray()); // [2]


问:
Does DocumentDB support MongoDB 3.4.2?
I set up MongoDB (DocumentDB) in Azure and could not find an option to change the MongoDB version.

```<code>db.version() // return 3.2.0
</code>```

Is it possible to update it to 3.4.2?

答:
Seems like CosmosDB supports 3.4.

https://azure.microsoft.com/en-us/blog/azure-cosmosdb-extends-support-for-mongodb-aggregation-pipeline-unique-indexes-and-more/

The list of supported MongoDB API for CosmosDB is listed here

Title: Does DocumentDB support MongoDB 3.4.2?

Body:
I set up MongoDB (DocumentDB) in Azure and could not find an option to change the MongoDB version.

db.version() // return 3.2.0

Is it possible to update it to 3.4.2?


问:
How to do weighted softmax output custom op in mxnet?
I want to replace mx.symbol.SoftmaxOutput with the weighted version (assign different weight respect to label's frequency in the whole dataset)

The original function works well like below:

```<code>cls_prob = mx.symbol.SoftmaxOutput(data=data,
                                   label=label,
                                   multi_output=True,
                                   normalization='valid',
                                   use_ignore=True,
                                   ignore_label=-1,
                                   name='cls_prob')
</code>```

The current code I wrote as below. The code can run without errors, but the loss quickly explode to nan. I am dealing with detection problem, RCNNL1 loss with quickly become nan when I use my code as CustomOp.
Another thing is that I have to ignore label -1 and I am not sure how to do it properly. Any help will be greatly appreciated.

```<code>import mxnet as mx
import numpy as np

class WeightedSoftmaxCrossEntropyLoss(mx.operator.CustomOp):
    def __init__(self, num_class):
        self.num_class = int(num_class)

    def forward(self, is_train, req, in_data, out_data, aux):

        data = in_data[0]
        label = in_data[1]
        pred = mx.nd.SoftmaxOutput(data, label, multi_output=True,
                               normalization='valid', use_ignore=True, ignore_label=-1,
                               name='rcnn_cls_prob')

        self.assign(out_data[0], req[0], pred)

    def backward(self, req, out_grad, in_data, out_data, in_grad, aux):
        cls_weight = np.array([
            0.002852781814876101,
            0.30715984513157385,
            1.0932468996115976,
            1.1598757152765971,
            0.20739109264009636,
            1.1984256112776808,
            0.18746186040248036,
            2.9009928470737023,
            0.92140970338602113,
            1.200317380251021
        ])
        label = in_data[1]
        pred = out_data[0]
        label = label.asnumpy().astype('int32').reshape((-1))
        pred = pred.asnumpy().reshape((pred.shape[0], pred.shape[1], -1)).transpose((0, 2, 1))
        pred = pred.reshape((label.shape[0], -1))

        # Need to ignore label (how)
        out_inds = np.where(label == -1)[0]
        #label = label[keep_inds]
        one_hot = np.zeros((label.shape[0], self.num_class))
        one_hot[np.arange(label.shape[0]), label] = 1
        # gradient
        dx = pred - one_hot
        #dx[out_inds] = 0.0
        weighted_dx = cls_weight * dx / 4
        self.assign(in_grad[0], req[0], weighted_dx)

@mx.operator.register("weighted_softmax_ce_loss")
class WeightedSoftmaxCrossEntropyLossProp(mx.operator.CustomOpProp):
    def __init__(self, num_class):
        super(WeightedSoftmaxCrossEntropyLossProp, self).__init__(need_top_grad=False)
        self.num_class = num_class

    def list_arguments(self):
        return ['data', 'label']

    def list_outputs(self):
        return ['output']

    def infer_shape(self, in_shapes):
        data_shape = in_shapes[0]
        label_shape = (in_shapes[0][0],)
        output_shape = in_shapes[0]
        return [data_shape, label_shape], [output_shape], []

    def create_operator(self, ctx, in_shapes, in_dtypes):
        #  create and return the CustomOp class.
        `enter code here`return WeightedSoftmaxCrossEntropyLoss(self.num_class)
</code>```

答:
I am not sure if using a customop here would be the best as it may be slow.
Because SoftmaxOuput computes the gradient in the backward pass, it is not convenient to multiply losses as you want to do.
However, it is not too complicated to do with the symbolic API. I have attached a toy example, hope it helps.

import mxnet as mx
import numpy as np
import logging

# learn floor function from random numbers in [-1, -1 + num_classes]
n = 10000
batch_size = 128
num_classes = 10
x = (np.random.random((n,)) * num_classes) - 1
y = np.floor(x)
print(x[:2])
print(y[:2])

# define graph
data = mx.symbol.Variable('data')
label = mx.symbol.Variable('label')
class_weights = mx.symbol.Variable('class_weights')
fc = mx.sym.FullyConnected(data=data, num_hidden=num_classes)
fc = mx.sym.Activation(data=fc, act_type='relu')
proba = mx.sym.FullyConnected(data=fc, num_hidden=num_classes)
proba = mx.sym.softmax(proba)

# multipy cross entropy loss by weight
cross_entropy = -mx.sym.pick(proba, label) * mx.sym.pick(class_weights, label)

# mask the loss to zero when label is -1
mask = mx.sym.broadcast_not_equal(label, mx.sym.ones_like(label) * -1)
cross_entropy = cross_entropy * mask

# fit module
class_weights = np.array([np.arange(1, 1 + num_classes)]*n)
data_iter = mx.io.NDArrayIter(data={'data': x, 'class_weights': class_weights}, label={'label': y}, batch_size=batch_size)
mod = mx.mod.Module(
    mx.sym.Group([mx.sym.MakeLoss(cross_entropy, name='ce_loss'), mx.sym.BlockGrad(proba)]),
    data_names=[v.name for v in data_iter.provide_data],
    label_names=[v.name for v in data_iter.provide_label]
)
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
mod.bind(data_shapes=data_iter.provide_data, label_shapes=data_iter.provide_label)
mod.init_params()
mod.fit(
    data_iter,
    num_epoch=200,
    optimizer=mx.optimizer.Adam(learning_rate=0.01, rescale_grad=1.0/batch_size),
    batch_end_callback=mx.callback.Speedometer(batch_size, 200),
    eval_metric=mx.metric.Loss(name="loss", output_names=["ce_loss_output"]))

# show result, -1 are not predicted correctly as we did not compute their loss
probas = mod.predict(data_iter)[1].asnumpy()
print(zip(x, np.argmax(probas, axis=1)))
```

Body:
I want to replace mx.symbol.SoftmaxOutput with the weighted version (assign different weight respect to label's frequency in the whole dataset)

The original function works well like below:

cls_prob = mx.symbol.SoftmaxOutput(data=data,
                                   label=label,
                                   multi_output=True,
                                   normalization='valid',
                                   use_ignore=True,
                                   ignore_label=-1,
                                   name='cls_prob')

The current code I wrote as below. The code can run without errors, but the loss quickly explode to nan. I am dealing with detection problem, RCNNL1 loss with quickly become nan when I use my code as CustomOp.
Another thing is that I have to ignore label -1 and I am not sure how to do it properly. Any help will be greatly appreciated.

import mxnet as mx
import numpy as np

class WeightedSoftmaxCrossEntropyLoss(mx.operator.CustomOp):
    def __init__(self, num_class):
        self.num_class = int(num_class)

    def forward(self, is_train, req, in_data, out_data, aux):

        data = in_data[0]
        label = in_data[1]
        pred = mx.nd.SoftmaxOutput(data, label, multi_output=True,
                               normalization='valid', use_ignore=True, ignore_label=-1,
                               name='rcnn_cls_prob')

        self.assign(out_data[0], req[0], pred)

    def backward(self, req, out_grad, in_data, out_data, in_grad, aux):
        cls_weight = np.array([
            0.002852781814876101,
            0.30715984513157385,
            1.0932468996115976,
            1.1598757152765971,
            0.20739109264009636,
            1.1984256112776808,
            0.18746186040248036,
            2.9009928470737023,
            0.92140970338602113,
            1.200317380251021
        ])
        label = in_data[1]
        pred = out_data[0]
        label = label.asnumpy().astype('int32').reshape((-1))
        pred = pred.asnumpy().reshape((pred.shape[0], pred.shape[1], -1)).transpose((0, 2, 1))
        pred = pred.reshape((label.shape[0], -1))

        # Need to ignore label (how)
        out_inds = np.where(label == -1)[0]
        #label = label[keep_inds]
        one_hot = np.zeros((label.shape[0], self.num_class))
        one_hot[np.arange(label.shape[0]), label] = 1
        # gradient
        dx = pred - one_hot
        #dx[out_inds] = 0.0
        weighted_dx = cls_weight * dx / 4
        self.assign(in_grad[0], req[0], weighted_dx)

@mx.operator.register("weighted_softmax_ce_loss")
class WeightedSoftmaxCrossEntropyLossProp(mx.operator.CustomOpProp):
    def __init__(self, num_class):
        super(WeightedSoftmaxCrossEntropyLossProp, self).__init__(need_top_grad=False)
        self.num_class = num_class

    def list_arguments(self):
        return ['data', 'label']

    def list_outputs(self):
        return ['output']

    def infer_shape(self, in_shapes):
        data_shape = in_shapes[0]
        label_shape = (in_shapes[0][0],)
        output_shape = in_shapes[0]
        return [data_shape, label_shape], [output_shape], []

    def create_operator(self, ctx, in_shapes, in_dtypes):
        #  create and return the CustomOp class.
        `enter code here`return WeightedSoftmaxCrossEntropyLoss(self.num_class)


问:
mySQL DB Desgin
In my application I have different categories that users can post their transactions as.
Example: Food, Shopping, Movies, etc..
I want the user to be able to edit these categories and add/remove categories.
What is the best way to store this information in a database.

A categories table with the category and corresponding user? Then I can query the uid and get all of their categories.

User table w/ a category field and seperate the categories by comma. Then I can query user and seperate their categories into an array w/ explode or something along those lines.

OR an idea I have not even thought of.

答:
Option 3

A Category Table
CategoryID, Category_Name, etc...

A User Table
UserID, User_Name, etc.

An intersection table USER_Category

UserID, CategoryID

Why?

If you have

UserName, CategoryName

and say

"Jim", "Food"

"Joe", "Food"

"Judy", "Beauty Products"

If you delete "Judy" because you are no longer interested in her transactions, you also lose the category "Beauty Products".  This way categories and users are separate.

It is also easier to ask questions like "Who is spending most of their money on Food".  If the user enters categories in, you may get "Food", "Groceries", "Dining Out", and a ton of different categories, maybe even misspellings like "fod", "fooooooooooooooooood", etc...  So by having unified categories you can just select based on foodID in your queries.

Basically now the user can browse a list of categories and if they spot the category they are interest in from the list, they will create the entry UserID, CategoryID in the intersection table.  This reduces the likelihood of misspellings.  If the category isn't there, the user can add it.  Then when the next user views the categories they will see the new entry so if they are interested they can just click it and reduce the chance of misspelling it.

Title: mySQL DB Desgin

OwnerDisplayName: Cervo


问:
Where do you add 'commons-codec-1.4.jar' to if you want access to encodeHexString etc?
Hey, this question links into another post  I made today: Reading the first 10 bytes of a file in Java

Having been told that my solution could involve the apache commons codec library, I've tried to figure out where the file needs to be placed and am seriously not getting it. Can't find anything online that simply says 'It goes here...' so maybe someone on here can help?

I've got Windows 7, I'm using JCreator and have the 'jre6' and 'jdk1.6.0_23' folders in my Program Files/Java folder

Any help at all would be appreciated so please let me know :)

Thanks :D

答:
You may also specified globally CLASSPATH environment variable i.e:

unix:
export CLASSPATH=/path/to/jar1.jar:/path/to/jar2.jar: ...

windows:
set CLASSPATH=c:/path/to/jar1.jar;c:/path/to/jar2.jar

Remember on windows classpath separator is ";" and on unix/linux it is ":".

It is also correct for -cp option mentioned in previous answer by Brian


问:
Using Css to prevent wrapping of text with previous text?
Is there a CSS way to prevent a text element from wrapping from a previous text element?

i.e.
My Table Header  shows as

My

Table

Header

MySearchIcon

But I want it to display like this:

My

Table

Header MySearchIcon

The actual code is a combination of Razor and Html

```<code>  <th>
   @Html.DisplayNameFor(m => m.Projects.FirstOrDefault().Name) <i class="fa fa-search smaller fa-fade"></i>
  </th>
</code>```

This is in a header of a table and depending on the header length I do want wrapping but I want a space and the icon to be stuck to the last word in the header and not wrap.

Because of the Razor piece of the code I can't place the non-breaking space up against the output directly,

Body:
Is there a CSS way to prevent a text element from wrapping from a previous text element?

i.e.
My Table Header  shows as

My

Table

Header

MySearchIcon

But I want it to display like this:

My

Table

Header MySearchIcon

The actual code is a combination of Razor and Html

   @Html.DisplayNameFor(m => m.Projects.FirstOrDefault().Name)

This is in a header of a table and depending on the header length I do want wrapping but I want a space and the icon to be stuck to the last word in the header and not wrap.

Because of the Razor piece of the code I can't place the non-breaking space up against the output directly,

Body:
Sure.  You can use an HTML entity for a nonbreaking space.  It would make your text node and icon be as follows

My Table Header&nbsp;<i class="fa fa-search"></i>


问:
How can I check if a package is installed and install it if not?
I'm working on a Ubuntu system and currently this is what I'm doing:

if ! which command > /dev/null; then
   echo -e "Command not found! Install? (y/n) \c"
   read
   if "$REPLY" = "y"; then
      sudo apt-get install command
   fi
fi
```

Is this what most people would do? Or is there a more elegant solution?

答:
For Ubuntu, apt provides a fairly decent way to do this. Below is an example for Google Chrome:

apt -qq list google-chrome-stable 2>/dev/null | grep -qE "(installed|upgradeable)" || apt-get install google-chrome-stable

I'm redirecting error output to null, because apt warns against using its "unstable cli". I suspect list package is stable, so I think it's ok to throw this warning away. The -qq makes apt super quiet.

Body:
I'm working on a Ubuntu system and currently this is what I'm doing:

if ! which command > /dev/null; then
   echo -e "Command not found! Install? (y/n) \c"
   read
   if "$REPLY" = "y"; then
      sudo apt-get install command
   fi
fi

Is this what most people would do? Or is there a more elegant solution?


问:
warning: espcomm_sync failed error: espcomm_open failed error: espcomm_upload_mem failed
```<code> /*
 * 115200. Connect GPIO 0 of your ESP8266 to VCC and reset the board
 */

#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>

MDNSResponder mdns;

// Network id and pw
const char* ssid = "MY_ID";
const char* password = "MY_PASSWORD";

ESP8266WebServer server(80);

String webPage = "";

int gpio0_pin = 0;
int gpio2_pin = 2;

void setup(void)
{
  webPage += "<h1>ESP8266 Web Server</h1><p>Socket #1 <a href=\"socket1On\"><button>ON</button></a> <a href=\"socket1Off\"><button>OFF</button></a>    </p>";
  webPage += "<p>Socket #2 <a href=\"socket2On\"><button>ON</button></a> <a     href=\"socket2Off\"><button>OFF</button></a></p>";

  // preparing GPIOs
  pinMode(gpio0_pin, OUTPUT);
  digitalWrite(gpio0_pin, LOW);
  pinMode(gpio2_pin, OUTPUT);
  digitalWrite(gpio2_pin, LOW);

  delay(1000);
  Serial.begin(115200);
  WiFi.begin(ssid, password);
  Serial.println("");

  // Wait for connection
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());

  if (mdns.begin("esp8266", WiFi.localIP()))
    Serial.println("MDNS responder started");

  server.on("/", []()
  {
    server.send(200, "text/html", webPage);
  });

  server.on("/socket1On", []()
  {
    server.send(200, "text/html", webPage);
    digitalWrite(gpio0_pin, HIGH);
    delay(1000);
   });

  server.on("/socket1Off", []()
  {
    server.send(200, "text/html", webPage);
    digitalWrite(gpio0_pin, LOW);
    delay(1000);
  });

  server.on("/socket2On", []()
  {
    server.send(200, "text/html", webPage);
    digitalWrite(gpio2_pin, HIGH);
    delay(1000);
  });

  server.on("/socket2Off", []()
  {
    server.send(200, "text/html", webPage);
    digitalWrite(gpio2_pin, LOW);
    delay(1000);
  });
  server.begin();
  Serial.println("HTTP server started");
}

void loop(void)
{
  server.handleClient();
}
</code>```

Hi I'm trying to make a wifi webserver with the ESP8266 using an Arduino. The code is in this link: code. I'm following the
   steps of this site. I've connected my yp-01 (USB to serial)
   with my ESP8266.

USB --> ESP

TX  --> RX

RX  --> TX

I use the 3.3V supply of my arduino mega.

ARDUINO --> ESP

3.3V    --> VCC

GND     --> GND.

When I try to upload the code it gives the error:

warning: espcomm_sync failed error: espcomm_open
     failed error: espcomm_upload_mem failed

I've read a lot of posts but none of them fixed my problem. Is there anyone who knows the solution or someone who had the same problem? I'm using ARduino IDE 1.6.9

答:
for the error "espcomm_open_failed"

ESP01 Flash config:
Flash real size: 1048576 1MB 512SPIFFS
Flash ide speed: 40000000 - 4MHz
Flash ide mode: DOUT

ESP07 Flash config:
Flash real size: 1048576 1MB 512SPIFFS
Flash ide speed: 40000000 - 4MHz
Flash ide mode: QIO

When programming the ESP8266, connect VCC, ground, TX and RX properly. (FTDI <->ESP)

```<code>VCC --> 3.3V
GND --> GND
TX -->RX
RX --> TX
</code>```

(Power from USB 2.0 was enough to program ESP01 and ESP07; I used arduino software to program; Nodemcu flasher can also be used to flash)

In order to turn into program the ESP, first both the RESET and the GPIO0 should be connected to the ground.
Then keep it for around 5 seconds
Then remove the RESET BUT do not remove GPIO0.

Body:
 /*
 * 115200. Connect GPIO 0 of your ESP8266 to VCC and reset the board
 */

#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>

MDNSResponder mdns;

// Network id and pw
const char* ssid = "MY_ID";
const char* password = "MY_PASSWORD";

ESP8266WebServer server(80);

String webPage = "";

int gpio0_pin = 0;
int gpio2_pin = 2;

void setup(void)
{
  webPage += "
ESP8266 Web Server

Socket #1 <button>ON</button> <button>OFF</button>
";
  webPage += "
Socket #2 <button>ON</button> <button>OFF</button>
";

  // preparing GPIOs
  pinMode(gpio0_pin, OUTPUT);
  digitalWrite(gpio0_pin, LOW);
  pinMode(gpio2_pin, OUTPUT);
  digitalWrite(gpio2_pin, LOW);

  delay(1000);
  Serial.begin(115200);
  WiFi.begin(ssid, password);
  Serial.println("");

  // Wait for connection
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());

  if (mdns.begin("esp8266", WiFi.localIP()))
    Serial.println("MDNS responder started");

  server.on("/", []()
  {
    server.send(200, "text/html", webPage);
  });

  server.on("/socket1On", []()
  {
    server.send(200, "text/html", webPage);
    digitalWrite(gpio0_pin, HIGH);
    delay(1000);
   });

  server.on("/socket1Off", []()
  {
    server.send(200, "text/html", webPage);
    digitalWrite(gpio0_pin, LOW);
    delay(1000);
  });

  server.on("/socket2On", []()
  {
    server.send(200, "text/html", webPage);
    digitalWrite(gpio2_pin, HIGH);
    delay(1000);
  });

  server.on("/socket2Off", []()
  {
    server.send(200, "text/html", webPage);
    digitalWrite(gpio2_pin, LOW);
    delay(1000);
  });
  server.begin();
  Serial.println("HTTP server started");
}

void loop(void)
{
  server.handleClient();
}

Hi I'm trying to make a wifi webserver with the ESP8266 using an Arduino. The code is in this link: code. I'm following the
   steps of this site. I've connected my yp-01 (USB to serial)
   with my ESP8266.

USB --> ESP

TX  --> RX

RX  --> TX

I use the 3.3V supply of my arduino mega.

ARDUINO --> ESP

3.3V    --> VCC

GND     --> GND.

When I try to upload the code it gives the error:

warning: espcomm_sync failed error: espcomm_open
     failed error: espcomm_upload_mem failed

I've read a lot of posts but none of them fixed my problem. Is there anyone who knows the solution or someone who had the same problem? I'm using ARduino IDE 1.6.9

Body:
for the error "espcomm_open_failed"

ESP01 Flash config:
Flash real size: 1048576 1MB 512SPIFFS
Flash ide speed: 40000000 - 4MHz
Flash ide mode: DOUT

ESP07 Flash config:
Flash real size: 1048576 1MB 512SPIFFS
Flash ide speed: 40000000 - 4MHz
Flash ide mode: QIO

When programming the ESP8266, connect VCC, ground, TX and RX properly. (FTDI <->ESP)

VCC --> 3.3V
GND --> GND
TX -->RX
RX --> TX

(Power from USB 2.0 was enough to program ESP01 and ESP07; I used arduino software to program; Nodemcu flasher can also be used to flash)

In order to turn into program the ESP, first both the RESET and the GPIO0 should be connected to the ground.
Then keep it for around 5 seconds
Then remove the RESET BUT do not remove GPIO0.


问:
Abstracting Core Data Fetch Request
```<code>func fetchRequestFromViewContext(nameOfEntity: NSManagedObject) {
    let fetchRequest = NSFetchRequest<nameOfEntity>(entityName: "\(nameOfEntity)")
    do {
        let result = try? CoreDataStack.instance.viewContext.fetch(fetchRequest)

    }
}
</code>```

Trying to abstract the core data fetch request therefore making an argument of type managed object and passing it into the fetch request generic but is not letting me, am I on the right track on abstracting this core data fetch request?

答:
NSFetchRequest(entityName:) takes a String but nameofEntity was given as an NSManagedObject. Change that to a String and then also pass in the type of the entity. You can use generics (the <T> below) to allow for any class conforming to NSManagedObject.

```<code>func fetchRequestFromViewContext<T: NSManagedObject>(nameOfEntity: String, type: T.Type) {
    let fetchRequest = NSFetchRequest<T>(entityName: nameOfEntity)
    do {
        let result = try? CoreDataStack.instance.viewContext.fetch(fetchRequest)

    }
}
</code>```

To call this you would simply do:

```<code>fetchRequestFromViewContext(nameOfEntity: "YourEntity", type: YourEntity.self)
</code>```

Title: Abstracting Core Data Fetch Request

Body:
func fetchRequestFromViewContext(nameOfEntity: NSManagedObject) {
    let fetchRequest = NSFetchRequest<nameOfEntity>(entityName: "\(nameOfEntity)")
    do {
        let result = try? CoreDataStack.instance.viewContext.fetch(fetchRequest)

    }
}

Trying to abstract the core data fetch request therefore making an argument of type managed object and passing it into the fetch request generic but is not letting me, am I on the right track on abstracting this core data fetch request?

Body:
NSFetchRequest(entityName:) takes a String but nameofEntity was given as an NSManagedObject. Change that to a String and then also pass in the type of the entity. You can use generics (the <T> below) to allow for any class conforming to NSManagedObject.

func fetchRequestFromViewContext<T: NSManagedObject>(nameOfEntity: String, type: T.Type) {
    let fetchRequest = NSFetchRequest<T>(entityName: nameOfEntity)
    do {
        let result = try? CoreDataStack.instance.viewContext.fetch(fetchRequest)

    }
}

To call this you would simply do:

fetchRequestFromViewContext(nameOfEntity: "YourEntity", type: YourEntity.self)


问:
Difference between &mut and ref mut for trait objects
First of all, I'm not asking what's the difference between &mut and ref mut per se.

I'm asking because I thought:

```<code>let ref mut a = MyStruct
</code>```

is the same as

```<code>let a = &mut MyStruct
</code>```

Consider returning a trait object from a function. You can return a Box<Trait> or a &Trait. If you want to have mutable access to its methods, is it possible to return &mut Trait?

Given this example:

```<code>trait Hello {
    fn hello(&mut self);
}

struct English;
struct Spanish;

impl Hello for English {
    fn hello(&mut self) {
        println!("Hello!");
    }
}

impl Hello for Spanish {
    fn hello(&mut self) {
        println!("Hola!");
    }
}
</code>```

The method receives a mutable reference for demonstration purposes.

This won't compile:

```<code>fn make_hello<'a>() -> &'a mut Hello {
    &mut English
}
</code>```

nor this:

```<code>fn make_hello<'a>() -> &'a mut Hello {
    let b = &mut English;
    b
}
</code>```

But this will compile and work:

```<code>fn make_hello<'a>() -> &'a mut Hello {
    let ref mut b = English;
    b
}
</code>```

My theory

This example will work out of the box with immutable references (not necessary to assign it to a variable, just return &English) but not with mutable references. I think this is due to the rule that there can be only one mutable reference or as many immutable as you want.

In the case of immutable references, you are creating an object and borrowing it as a return expression; its reference won't die because it's being borrowed.

In the case of mutable references, if you try to create an object and borrow it mutably as a return expression you have two mutable references (the created object and its mutable reference). Since you cannot have two mutable references to the same object it won't perform the second, hence the variable won't live long enough. I think that when you write let mut ref b = English and return b you are moving the mutable reference because it was captured by a pattern.

All of the above is a poor attempt to explain to myself why it works, but I don't have the fundamentals to prove it.

Why does this happen?

I've also cross-posted this question to Reddit.

答:
This is a bug. My original analysis below completely ignored the fact that it was returning a mutable reference. The bits about promotion only make sense in the context of immutable values.

This is allowable due to a nuance of the rules governing temporaries (emphasis mine):

When using an rvalue in most lvalue contexts, a temporary unnamed lvalue is created and used instead, if not promoted to 'static.

The reference continues:

Promotion of an rvalue expression to a 'static slot occurs when the expression could be written in a constant, borrowed, and dereferencing that borrow where the expression was the originally written, without changing the runtime behavior. That is, the promoted expression can be evaluated at compile-time and the resulting value does not contain interior mutability or destructors (these properties are determined based on the value where possible, e.g. &None always has the type &'static Option<_>, as it contains nothing disallowed).

Your third case can be rewritten as this to "prove" that the 'static promotion is occurring:

```<code>fn make_hello_3<'a>() -> &'a mut Hello {
    let ref mut b = English;
    let c: &'static mut Hello = b;
    c
}
</code>```

As for why ref mut allows this and &mut doesn't, my best guess is that the 'static promotion is on a best-effort basis and &mut just isn't caught by whatever checks are present. You could probably look for or file an issue describing the situation.

Body:
First of all, I'm not asking what's the difference between &mut and ref mut per se.

I'm asking because I thought:

let ref mut a = MyStruct

is the same as

let a = &mut MyStruct

Consider returning a trait object from a function. You can return a Box<Trait> or a &Trait. If you want to have mutable access to its methods, is it possible to return &mut Trait?

Given this example:

trait Hello {
    fn hello(&mut self);
}

struct English;
struct Spanish;

impl Hello for English {
    fn hello(&mut self) {
        println!("Hello!");
    }
}

impl Hello for Spanish {
    fn hello(&mut self) {
        println!("Hola!");
    }
}

The method receives a mutable reference for demonstration purposes.

This won't compile:

fn make_hello<'a>() -> &'a mut Hello {
    &mut English
}

nor this:

fn make_hello<'a>() -> &'a mut Hello {
    let b = &mut English;
    b
}

But this will compile and work:

fn make_hello<'a>() -> &'a mut Hello {
    let ref mut b = English;
    b
}

My theory

This example will work out of the box with immutable references (not necessary to assign it to a variable, just return &English) but not with mutable references. I think this is due to the rule that there can be only one mutable reference or as many immutable as you want.

In the case of immutable references, you are creating an object and borrowing it as a return expression; its reference won't die because it's being borrowed.

In the case of mutable references, if you try to create an object and borrow it mutably as a return expression you have two mutable references (the created object and its mutable reference). Since you cannot have two mutable references to the same object it won't perform the second, hence the variable won't live long enough. I think that when you write let mut ref b = English and return b you are moving the mutable reference because it was captured by a pattern.

All of the above is a poor attempt to explain to myself why it works, but I don't have the fundamentals to prove it.

Why does this happen?

I've also cross-posted this question to Reddit.

Body:
This is a bug. My original analysis below completely ignored the fact that it was returning a mutable reference. The bits about promotion only make sense in the context of immutable values.

This is allowable due to a nuance of the rules governing temporaries (emphasis mine):

When using an rvalue in most lvalue contexts, a temporary unnamed lvalue is created and used instead, if not promoted to 'static.

The reference continues:

Promotion of an rvalue expression to a 'static slot occurs when the expression could be written in a constant, borrowed, and dereferencing that borrow where the expression was the originally written, without changing the runtime behavior. That is, the promoted expression can be evaluated at compile-time and the resulting value does not contain interior mutability or destructors (these properties are determined based on the value where possible, e.g. &None always has the type &'static Option<_>, as it contains nothing disallowed).

Your third case can be rewritten as this to "prove" that the 'static promotion is occurring:

fn make_hello_3<'a>() -> &'a mut Hello {
    let ref mut b = English;
    let c: &'static mut Hello = b;
    c
}

As for why ref mut allows this and &mut doesn't, my best guess is that the 'static promotion is on a best-effort basis and &mut just isn't caught by whatever checks are present. You could probably look for or file an issue describing the situation.


问:
Python- including a variable within the text part of parameters
So in Pygame have a function that displays messages to users:

```<code>def message_to_user(msg, color, X_displacement, Y_displacement):
    # creating function to display messages to the user
    message=font.render(msg,True,color)
    msgcenter=200+X_displacement,200+Y_displacement
    Game_display.blit(message,msgcenter)
</code>```

now there is a message I need to display with another variable showing aswell:

```<code>        message_to_user("You managed to complete",levelcounter,"levels",green,0,40)
</code>```

here is the error:

```<code>TypeError: message_to_user() takes exactly 4 arguments (6 given)
</code>```

I understand why I am getting this error, just can't figure a way around it

答:
I would just take the levelcounter as an argument, and then create the msg within the definition.

```<code>def message_to_user(levelcounter, color, X_displacement, Y_displacement):
    msg = "You managed to complete " + str(levelcounter) + " levels!"
    message = font.render(msg, True, color)
    msgcenter = 200 + X_displacement, 200 + Y_displacement
    Game_display.blit(message, msgcenter)
</code>```

Body:
So in Pygame have a function that displays messages to users:

def message_to_user(msg, color, X_displacement, Y_displacement):
    # creating function to display messages to the user
    message=font.render(msg,True,color)
    msgcenter=200+X_displacement,200+Y_displacement
    Game_display.blit(message,msgcenter)

now there is a message I need to display with another variable showing aswell:

        message_to_user("You managed to complete",levelcounter,"levels",green,0,40)

here is the error:

TypeError: message_to_user() takes exactly 4 arguments (6 given)

I understand why I am getting this error, just can't figure a way around it

Body:
I would just take the levelcounter as an argument, and then create the msg within the definition.

def message_to_user(levelcounter, color, X_displacement, Y_displacement):
    msg = "You managed to complete " + str(levelcounter) + " levels!"
    message = font.render(msg, True, color)
    msgcenter = 200 + X_displacement, 200 + Y_displacement
    Game_display.blit(message, msgcenter)


问:
What is the difference between these two ways to start an activity?
First off, I'm totally new at all of this and am mostly learning be searching the internet for directions on how to do what I want and then figuring out how to use it.

So I've found these two versions of how to start an activity, but I don't really understand the difference.  Is one better than the other?  Or should they be used in different circumstances?  Or are they just two different ways of doing the same thing?

```<code>Button home = (Button) findViewById(R.id.to_home);
    home.setOnClickListener (new View.OnClickListener() {
        public void onClick(View view) {
            Intent i = new Intent(view.getContext(), Home.class);
                startActivityForResult (i, 0);

        }
    });
</code>```

or this one

```<code>Button button = (Button)findViewById(R.id.b_cup);
    button.setOnClickListener (new View.OnClickListener() {
        public void onClick (View view) {
            Intent i = new Intent (Home.this, Cup.class);
            startActivity (i);

        }
    });
</code>```

答:
Using the startIntentForResult(Intent,RequestCode) is extremely useful though. when the Intent that has been called closes then this is called

@Override
protected void onActivityResult
( int request_code, int result_code, Intent i )
{

```<code>super.onActivityResult( request_code, result_code, i );
</code>```

}

The Result code can then be used to see if the intent was cancelled or completed successfully. Also if you are calling several Intents from the main activity specifying a unique request code will let you handle intent results unique to the intents purpose eg

startIntentForResult(Intent1,1)

...

startIntentForResult(Intent2,2)

...

startIntentForResult(Intent3,3)

...

Then in the onActivityReslut:

@Override
protected void onActivityResult
( int request_code, int result_code, Intent i )
{

```<code>if (result_code == RESULT_OK){

    switch (request_code)
    {
    case 1:
        //Do Something
        break;
    case 2:
        //Do Something
        break;
    case 3:
        //Do Something
        break;
    default:
        //Unrecognised request_code
    }
}

super.onActivityResult( request_code, result_code, i );
</code>```

}

startIntenetForResult is very very useful.

Body:
First off, I'm totally new at all of this and am mostly learning be searching the internet for directions on how to do what I want and then figuring out how to use it.

So I've found these two versions of how to start an activity, but I don't really understand the difference.  Is one better than the other?  Or should they be used in different circumstances?  Or are they just two different ways of doing the same thing?

Button home = (Button) findViewById(R.id.to_home);
    home.setOnClickListener (new View.OnClickListener() {
        public void onClick(View view) {
            Intent i = new Intent(view.getContext(), Home.class);
                startActivityForResult (i, 0);

        }
    });

or this one

Button button = (Button)findViewById(R.id.b_cup);
    button.setOnClickListener (new View.OnClickListener() {
        public void onClick (View view) {
            Intent i = new Intent (Home.this, Cup.class);
            startActivity (i);

        }
    });

Body:
Using the startIntentForResult(Intent,RequestCode) is extremely useful though. when the Intent that has been called closes then this is called

@Override
protected void onActivityResult
( int request_code, int result_code, Intent i )
{

super.onActivityResult( request_code, result_code, i );

}

The Result code can then be used to see if the intent was cancelled or completed successfully. Also if you are calling several Intents from the main activity specifying a unique request code will let you handle intent results unique to the intents purpose eg

startIntentForResult(Intent1,1)

...

startIntentForResult(Intent2,2)

...

startIntentForResult(Intent3,3)

...

Then in the onActivityReslut:

@Override
protected void onActivityResult
( int request_code, int result_code, Intent i )
{

if (result_code == RESULT_OK){

    switch (request_code)
    {
    case 1:
        //Do Something
        break;
    case 2:
        //Do Something
        break;
    case 3:
        //Do Something
        break;
    default:
        //Unrecognised request_code
    }
}

super.onActivityResult( request_code, result_code, i );

}

startIntenetForResult is very very useful.


问:
React radio buttons not setting initial value; only subsequent values

I have a form with 4 radio inputs. I want the component state to be updated with the value of the checked input.

Currently the input is one value behind the checked value (i.e. doesn't start correctly updating the state until the second click).

How can I get it to set the state on the first click?

component.js

import React, { Component } from 'react';

class Graph extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      option: null
    };
  }

  setOption(value) {
    this.setState({option: value});
  }

  render() {
    return (
      <form>
        <input
        type="radio"
        name="option"
        onChange={(e) => this.setOption('tmax_C')}
        checked={ this.state.option === 'tmax_C' }
        value="tmax_C" />
        Max Temp.

        <input type="radio"
        name="option"
        onChange={(e) => this.setOption('tmin_C')}
        checked={ this.state.option === 'tmin_C' }
        value="tmin_C" />
        Min Temp

        <input type="radio"
        name="option"
        onChange={(e) => this.setOption('rain_mm')}
        checked={ this.state.option === 'rain_mm' }
        value="rain_mm" />
        Rain mm

        <input type="radio"
        name="option"
        onChange={(e) => this.setOption('sunshine_hours')}
        checked={ this.state.option === 'sunshine_hours' }
        value="sunshine_hours" />
        Sunshine Hours
      </form>
    );
  }
}

export default Graph;```

答:
setting component state is async. Using a function will update the component right away: this.setState(() => ({option: value}));

more info: react setState docs

Per the second part of your question: Another way to make the handlers more functional is to return a handler that sets the passed value:

import React, { Component } from 'react';

class Graph extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      option: null
    };
  }

  setOption = (value) =>
    this.setState(() => {
      return { option: value };
    });

  render() {
    return (
      <form>
        <input
        type="radio"
        name="option"
        onChange={this.setOption('tmax_C')}
        checked={ this.state.option === 'tmax_C' }
        value="tmax_C" />
        Max Temp.

        <input type="radio"
        name="option"
        onChange={this.setOption('tmin_C')}
        checked={ this.state.option === 'tmin_C' }
        value="tmin_C" />
        Min Temp

        <input type="radio"
        name="option"
        onChange={this.setOption('rain_mm')}
        checked={ this.state.option === 'rain_mm' }
        value="rain_mm" />
        Rain mm

        <input type="radio"
        name="option"
        onChange={this.setOption('sunshine_hours')}
        checked={ this.state.option === 'sunshine_hours' }
        value="sunshine_hours" />
        Sunshine Hours
      </form>
    );
  }
}

export default Graph;```

Body:
setting component state is async. Using a function will update the component right away: this.setState(() => ({option: value}));

more info: react setState docs

Per the second part of your question: Another way to make the handlers more functional is to return a handler that sets the passed value:

import React, { Component } from 'react';

class Graph extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      option: null
    };
  }

  setOption = (value) =>
    this.setState(() => {
      return { option: value };
    });

  render() {
    return (
      <form>
        <input
        type="radio"
        name="option"
        onChange={this.setOption('tmax_C')}
        checked={ this.state.option === 'tmax_C' }
        value="tmax_C" />
        <label htmlFor="option">Max Temp.</label>

        <input type="radio"
        name="option"
        onChange={this.setOption('tmin_C')}
        checked={ this.state.option === 'tmin_C' }
        value="tmin_C" />
        <label htmlFor="option">Min Temp</label>

        <input type="radio"
        name="option"
        onChange={this.setOption('rain_mm')}
        checked={ this.state.option === 'rain_mm' }
        value="rain_mm" />
        <label htmlFor="option">Rain mm</label>

        <input type="radio"
        name="option"
        onChange={this.setOption('sunshine_hours')}
        checked={ this.state.option === 'sunshine_hours' }
        value="sunshine_hours" />
        <label htmlFor="option">Sunshine Hours</label>
      </form>
    );
  }
}

export default Graph;


问:
get the client from pyspark
I want to retrieve a list of file. I saw a post sayong that these commands would do the job:

```<code>from hdfs import Config
client = Config().get_client('dev')
client.list('/*')
</code>```

But actually, execution fails:

```<code>---------------------------------------------------------------------------
HdfsError                                 Traceback (most recent call last)
<ipython-input-308-ab40dc16879a> in <module>()
----> 1 client = Config().get_client('dev')

/opt/cloudera/extras/anaconda3/lib/python3.5/site-packages/hdfs/config.py in get_client(self, alias)
    117           break
    118       else:
--> 119         raise HdfsError('Alias %r not found in %r.', alias, self.path)
    120     return self._clients[alias]
    121

HdfsError: Alias 'dev' not found in '/home/sbenet/.hdfscli.cfg'.
</code>```

As you can see, it is trying to access the file /home/sbenet/.hdfscli.cfg which does not exists.

If I want to use this method to retrieve the list of files, I need to fix this .hdfscli.cfg file issue, or to use another method with sc maybe.

答:
You have to create a configuration file first. Check this out 1</p>

```<code>[global]
default.alias = dev

[dev.alias]
url = http://dev.namenode:port
user = ann

[prod.alias]
url = http://prod.namenode:port
root = /jobs/
</code>```

Title: get the client from pyspark

Body:
I want to retrieve a list of file. I saw a post sayong that these commands would do the job:

from hdfs import Config
client = Config().get_client('dev')
client.list('/*')

But actually, execution fails:

---------------------------------------------------------------------------
HdfsError                                 Traceback (most recent call last)
<ipython-input-308-ab40dc16879a> in <module>()
----> 1 client = Config().get_client('dev')

/opt/cloudera/extras/anaconda3/lib/python3.5/site-packages/hdfs/config.py in get_client(self, alias)
    117           break
    118       else:
--> 119         raise HdfsError('Alias %r not found in %r.', alias, self.path)
    120     return self._clients[alias]
    121

HdfsError: Alias 'dev' not found in '/home/sbenet/.hdfscli.cfg'.

As you can see, it is trying to access the file /home/sbenet/.hdfscli.cfg which does not exists.

If I want to use this method to retrieve the list of files, I need to fix this .hdfscli.cfg file issue, or to use another method with sc maybe.

Body:
You have to create a configuration file first. Check this out 1

[global]
default.alias = dev

[dev.alias]
url = http://dev.namenode:port
user = ann

[prod.alias]
url = http://prod.namenode:port
root = /jobs/