问:
How to understand that file was uploaded with Selenium and Ruby?
I am writing my first automatization script with Selenium + Ruby and I need to upload a file to the web application.
The thing is that uploading takes some time (from 30sec to 3min, it depends). After the file was uploaded, I need to click "Save" button.

How could my code recognize that the uploading process was completed and it can continue to execute?

Here is the standard code, just for your reference:

```<code>driver = Selenium::WebDriver.for :chrome
driver.navigate.to 'my-website.com/upload'

driver.find_element(id: 'upload-input').send_keys('my/path/to/the/document')
driver.find_element(id: 'upload-button').click

**Now my code needs to wait till upload will be completed and then to click "Save" button**

driver.find_element(id: 'save-button').click
</code>```

Thank you!

答:
From Selenium's perspective, there isn't anything from the file upload that you can use, but there is hopefully something else on the website you can use.

Does anything on the site change once a file has completed uploading? Maybe an icon that appears, or a box that says "upload complete"?

If so, you can use a conditional wait for that element to appear!

Something like:

Selenium::WebDriver::Wait.new(timeout: 30).until {
  driver.find_element(id: 'upload-complete').displayed?
}
```

You'll want to wrap that in a rescue block down the line to catch for edge-cases like the element not existing, but hopefully that gets you started!

Body:
I am writing my first automatization script with Selenium + Ruby and I need to upload a file to the web application.
The thing is that uploading takes some time (from 30sec to 3min, it depends). After the file was uploaded, I need to click "Save" button.

How could my code recognize that the uploading process was completed and it can continue to execute?

Here is the standard code, just for your reference:

driver = Selenium::WebDriver.for :chrome
driver.navigate.to 'my-website.com/upload'

driver.find_element(id: 'upload-input').send_keys('my/path/to/the/document')
driver.find_element(id: 'upload-button').click

**Now my code needs to wait till upload will be completed and then to click "Save" button**

driver.find_element(id: 'save-button').click

Thank you!

Body:
From Selenium's perspective, there isn't anything from the file upload that you can use, but there is hopefully something else on the website you can use.

Does anything on the site change once a file has completed uploading? Maybe an icon that appears, or a box that says "upload complete"?

If so, you can use a conditional wait for that element to appear!

Something like:

Selenium::WebDriver::Wait.new(timeout: 30).until {
  driver.find_element(id: 'upload-complete').displayed?
}

You'll want to wrap that in a rescue block down the line to catch for edge-cases like the element not existing, but hopefully that gets you started!


来源: stackexchange

问:
Python create dataframe from multiple dataframes with one having multiple columns
I have 3 NumPy dataframes, which I want to merge with Pandas to a DataFrame in order to some actions.

My dataframes are:

dataframe1, size (38 x 9)

```<code>at1 at2 at3 at4 at5 at6 at7 at8 at9
43  -0.333333   91.3333 -4  31.3333 -1.33333    48.6667 59.6667 11.3333
54.5    4   79  0   12  5.5 24  67  43
40.4    0.4 85.6    0.2 31.6    1.6 45  53.4    8.8
</code>```

dataframe2, size (38 x 1)

```<code>at10
43
25
2
</code>```

dataframe3, size (38 x 1)

```<code>at1
-3
5
20
</code>```

My code so far is the following:

```<code>df = DataFrame (
            {"reps": array1,
            "labels": array2,
            "weight": array3}
            )
</code>```

When I execute this, I receive the following error message:

```<code>Exception: Data must be 1-dimensional
</code>```

I've spent a lot of time trying things, with no luck.
Any idea?

答:
To solve the error, array 1 which is a multidimensional array is manipulated so as to get each array, this is done by converting it to a list.

Then a dictionary with all array values is created to make the solution elegant.

import pandas as pd

# get number of columns in multidimensional array
num_cols = len(array1)

# create column names
array1_col_names = ['reps_' + str(i) for i in range(num_cols)]

# get elements of array 1 and store them in a dictionary
values = dict(zip(col_names, list(array1)))
values.update({'labels': array2, 'weight': array3}) # add other arrays to dictionary

# create dataframe from the dictionary
df = pd.DataFrame(values)

df
```

ContentLicense: CC BY-SA 4.0

Body:
I have 3 NumPy dataframes, which I want to merge with Pandas to a DataFrame in order to some actions.

My dataframes are:

dataframe1, size (38 x 9)

at1 at2 at3 at4 at5 at6 at7 at8 at9
43  -0.333333   91.3333 -4  31.3333 -1.33333    48.6667 59.6667 11.3333
54.5    4   79  0   12  5.5 24  67  43
40.4    0.4 85.6    0.2 31.6    1.6 45  53.4    8.8

dataframe2, size (38 x 1)

at10
43
25
2

dataframe3, size (38 x 1)

at1
-3
5
20

My code so far is the following:

df = DataFrame (
            {"reps": array1,
            "labels": array2,
            "weight": array3}
            )

When I execute this, I receive the following error message:

Exception: Data must be 1-dimensional

I've spent a lot of time trying things, with no luck.
Any idea?


问:
Butterfly pattern appears in random walk using srand(), why?
About 3 years ago I coded a 2D random walk togheter with a coleague in C++, first it seemed to work properly as we obtained a diferent pattern each time. But whenever we decided to increase the number of steps above some threshold an apparent butterfly pattern appeared, we noticed that with each run of the code the pattern would repeat but starting on a different place of the butterfly. We concluded and reported then that it was due to the pseudorandom generator associated with srand() function, but today I found again this report and there are still some things that I would like to understand. I would like to understand better how the pseudorandom generator works in order to obtain this sort of symmetry and ciclic pattern. The pattern I'm talking about is this (The steps are color coded in a rainbow sequence to apreciate the progression of the walk):

EDIT:

I'm adding the code used to obtain this figure:

```<code>#include<iostream>
#include<cmath>
#include<stdlib.h>
#include<time.h>
#include <fstream>
#include <string.h>
#include <string>
#include <iomanip>

using namespace std;

int main ()
{
srand(time(NULL));
int num1,n=250000;

ofstream rnd_coordinates("Random2D.txt");
float x=0,y=0,sumx_f=0,sumy_f=0,sum_d=0,d_m,X,t,d;
float x_m,y_m;

x=0;
y=0;

for(int i=0;i<n;i++){

    t=i;
    num1= rand()%4;

    if(num1==0){
        x++;
    }
    if(num1==1){
        x--;
    }
    if(num1==2){
        y++;
    }
    if(num1==3){
        y--;
    }

    rnd_coordinates<<x<<','<<y<<','<<t<<endl;

}

rnd_coordinates.close();

return 0;
}
</code>```

答: You might want to look at my answer to another question here about older rand() implementations.  Sometimes with the old rand() and srand() functions the lower order bits are much less random than the higher order bits.  Some of these older implementations still persist, it's possible you used one.

Body:
About 3 years ago I coded a 2D random walk togheter with a coleague in C++, first it seemed to work properly as we obtained a diferent pattern each time. But whenever we decided to increase the number of steps above some threshold an apparent butterfly pattern appeared, we noticed that with each run of the code the pattern would repeat but starting on a different place of the butterfly. We concluded and reported then that it was due to the pseudorandom generator associated with srand() function, but today I found again this report and there are still some things that I would like to understand. I would like to understand better how the pseudorandom generator works in order to obtain this sort of symmetry and ciclic pattern. The pattern I'm talking about is this (The steps are color coded in a rainbow sequence to apreciate the progression of the walk):

EDIT:

I'm adding the code used to obtain this figure:

#include<iostream>
#include<cmath>
#include<stdlib.h>
#include<time.h>
#include <fstream>
#include <string.h>
#include <string>
#include <iomanip>

using namespace std;

int main ()
{
srand(time(NULL));
int num1,n=250000;

ofstream rnd_coordinates("Random2D.txt");
float x=0,y=0,sumx_f=0,sumy_f=0,sum_d=0,d_m,X,t,d;
float x_m,y_m;

x=0;
y=0;

for(int i=0;i<n;i++){

    t=i;
    num1= rand()%4;

    if(num1==0){
        x++;
    }
    if(num1==1){
        x--;
    }
    if(num1==2){
        y++;
    }
    if(num1==3){
        y--;
    }

    rnd_coordinates<<x<<','<<y<<','<<t<<endl;

}

rnd_coordinates.close();

return 0;
}


问:
Clean text images with OpenCV for OCR reading
I received some images that need to be treated in order to OCR some information out of them. Here are the originals:

original 1

original 2

original 3

original 4

After processing them with this code:

```<code>img = cv2.imread('original_1.jpg', 0)
ret,thresh = cv2.threshold(img,55,255,cv2.THRESH_BINARY)
opening = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, cv2.getStructuringElement(cv2.MORPH_RECT,(2,2)))
cv2.imwrite('result_1.jpg', opening)
</code>```

I get these results:

result 1

result 2

result 3

result 4

As you can see, some images get nice results for OCR reading, other still maintain some noise in the background.

Any suggestions as how to clean up the background?

答:
This is a fully coded Python solution based on the direction provided by @eldesgraciado.

This code assumes that you are already working with the properly binarized white-on-black image (e.g. after grayscale conversion, black hat morphing and Otsu's thesholding) - OpenCV documentation recommends working with the binarized images with the white foreground when applying morphological operations and stuff like that.

```<code>num_comps, labeled_pixels, comp_stats, comp_centroids = \
    cv2.connectedComponentsWithStats(thresh_image, connectivity=4)
min_comp_area = 10 # pixels
# get the indices/labels of the remaining components based on the area stat
# (skip the background component at index 0)
remaining_comp_labels = [i for i in range(1, num_comps) if comp_stats[i][4] >= min_comp_area]
# filter the labeled pixels based on the remaining labels,
# assign pixel intensity to 255 (uint8) for the remaining pixels
clean_img = np.where(np.isin(labeled_pixels,remaining_comp_labels)==True,255,0).astype('uint8')
</code>```

The advantage of this solution is that it allows you to filter out the noise without negatively affecting the characters that may already be compromised.

I work with dirty scans that have the undesirable effects like merged characters and character erosion, and I found out the hard way that there is no free lunch - even a seemingly harmless opening operation with the 3x3 kernel and one iteration results in some character degradation (despite being very effective for removing the noise around the characters).

So if the character quality allows, blunt cleanup operations on the entire image (e.g. blurring, opening, closing) are OK, but if not - this should be done first.

P.S. One more thing - you should not be using a lossy format like JPEG when working with text images, use a lossless format like PNG instead.

Body:
I received some images that need to be treated in order to OCR some information out of them. Here are the originals:

original 1

original 2

original 3

original 4

After processing them with this code:

img = cv2.imread('original_1.jpg', 0)
ret,thresh = cv2.threshold(img,55,255,cv2.THRESH_BINARY)
opening = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, cv2.getStructuringElement(cv2.MORPH_RECT,(2,2)))
cv2.imwrite('result_1.jpg', opening)

I get these results:

result 1

result 2

result 3

result 4

As you can see, some images get nice results for OCR reading, other still maintain some noise in the background.

Any suggestions as how to clean up the background?

Body:
This is a fully coded Python solution based on the direction provided by @eldesgraciado.

This code assumes that you are already working with the properly binarized white-on-black image (e.g. after grayscale conversion, black hat morphing and Otsu's thesholding) - OpenCV documentation recommends working with the binarized images with the white foreground when applying morphological operations and stuff like that.

num_comps, labeled_pixels, comp_stats, comp_centroids = \
    cv2.connectedComponentsWithStats(thresh_image, connectivity=4)
min_comp_area = 10 # pixels
# get the indices/labels of the remaining components based on the area stat
# (skip the background component at index 0)
remaining_comp_labels = [i for i in range(1, num_comps) if comp_stats[i][4] >= min_comp_area]
# filter the labeled pixels based on the remaining labels,
# assign pixel intensity to 255 (uint8) for the remaining pixels
clean_img = np.where(np.isin(labeled_pixels,remaining_comp_labels)==True,255,0).astype('uint8')

The advantage of this solution is that it allows you to filter out the noise without negatively affecting the characters that may already be compromised.

I work with dirty scans that have the undesirable effects like merged characters and character erosion, and I found out the hard way that there is no free lunch - even a seemingly harmless opening operation with the 3x3 kernel and one iteration results in some character degradation (despite being very effective for removing the noise around the characters).

So if the character quality allows, blunt cleanup operations on the entire image (e.g. blurring, opening, closing) are OK, but if not - this should be done first.

P.S. One more thing - you should not be using a lossy format like JPEG when working with text images, use a lossless format like PNG instead.


问:
Inject variable as Array parameter
I have var:

```<code>// Russia, US, and other country, its dynamical changing
var mytest = someTextLabel.text
</code>```

and I need to inject 'mytest' as a Dictionary parameter after JSON parsing:

```<code>// compile error, dailyStat don't have member 'mytest'
self.myArray = dailyStat.mytest.map{ Double($0.recovered) }
</code>```

dailyStat have the following structure:

```<code>struct dailyStat: Codable {
    let france: [CovidNums]
    let russia: [CovidNums]
    let us: [CovidNums]
    let brazil : [CovidNums]
    let uk: [CovidNums]
    let spain: [CovidNums]

    enum CodingKeys: String, CodingKey {
        case us = "US"
        case russia = "Russia"
        case france = "France"
        case brazil = "Brazil"
        case uk = "United Kingdom"
        case spain = "Spain"
    }
}

struct CovidNums: Codable {
    let date: String
    let confirmed, deaths, recovered: Int
}
</code>```

I don't want to use case switch:

```<code>switch mytest {
    case "Russia"
        self.myArray = dailyStat.russia.map{ Double($0.recovered) }
    case "US"
        self.myArray = dailyStat.us.map{ Double($0.recovered) }
    ...
</code>```

since I have 100 countries

答:
You should better write all your countries to one variable:</p>

```<code>var countries: Dictionary<String: CovidNums>
</code>```

Title: Inject variable as Array parameter

Body:
I have var:

// Russia, US, and other country, its dynamical changing
var mytest = someTextLabel.text

and I need to inject 'mytest' as a Dictionary parameter after JSON parsing:

// compile error, dailyStat don't have member 'mytest'
self.myArray = dailyStat.mytest.map{ Double($0.recovered) }

dailyStat have the following structure:

struct dailyStat: Codable {
    let france: [CovidNums]
    let russia: [CovidNums]
    let us: [CovidNums]
    let brazil : [CovidNums]
    let uk: [CovidNums]
    let spain: [CovidNums]

    enum CodingKeys: String, CodingKey {
        case us = "US"
        case russia = "Russia"
        case france = "France"
        case brazil = "Brazil"
        case uk = "United Kingdom"
        case spain = "Spain"
    }
}

struct CovidNums: Codable {
    let date: String
    let confirmed, deaths, recovered: Int
}

I don't want to use case switch:

switch mytest {
    case "Russia"
        self.myArray = dailyStat.russia.map{ Double($0.recovered) }
    case "US"
        self.myArray = dailyStat.us.map{ Double($0.recovered) }
    ...

since I have 100 countries

Body:
You should better write all your countries to one variable:

var countries: Dictionary<String: CovidNums>


问:
how to auto restart node app after aws codeDeploy
I have setup travis to aws codeDeploy for a node app. Now that the latest code can be deployed to EC2 correctly, but I need to manually restart the node app again to make the changes take effect.

How to auto restart the node app after codeDeploy? I guess I can do it by setting afterInstall in appspec.yml, but I find that many tutorial/walkthrough didn't mention about this, so I wonder is this the only/best way to restart the node app.

答:
You can use pm2 or forever and you can restart your node after code deploy. Your appspec.yml should be as below

```<code>version: 0.0
os: linux
files:
  - source: /deployment.zip
    destination: /home/ubuntu/PorjDir/
hooks:
  BeforeInstall:
    - location: stop_server.sh
      timeout: 300
      runas: ubuntu
  AfterInstall:
    - location: start_server.sh
      timeout: 300
      runas: ubuntu
</code>```

Note: You need to create stop_server.sh and start_server.sh into your project and need to export it as artifact so code deploy agent can use it.

start_server.sh should contains below:

```<code>sudo /usr/bin/pm2 restart appname
</code>```

Hope this will help you!!

Body:
You can use pm2 or forever and you can restart your node after code deploy. Your appspec.yml should be as below

version: 0.0
os: linux
files:
  - source: /deployment.zip
    destination: /home/ubuntu/PorjDir/
hooks:
  BeforeInstall:
    - location: stop_server.sh
      timeout: 300
      runas: ubuntu
  AfterInstall:
    - location: start_server.sh
      timeout: 300
      runas: ubuntu

Note: You need to create stop_server.sh and start_server.sh into your project and need to export it as artifact so code deploy agent can use it.

start_server.sh should contains below:

sudo /usr/bin/pm2 restart appname

Hope this will help you!!


问:
Fetch all values irrespective of keys from a column of JSON type in a Spark dataframe using Spark with scala
I was trying to load a TSV file containing some metadata on movies using Spark, this TSV file contains genre info on movies in JSON format [ The last column in every row ]

Sample File

```<code>975900  /m/03vyhn   Ghosts of Mars  2001-08-24  14010832    98.0    {"/m/02h40lc": "English Language"}  {"/m/09c7w0": "United States of America"}   {"/m/01jfsb": "Thriller", "/m/06n90": "Science Fiction", "/m/03npn": "Horror", "/m/03k9fj": "Adventure", "/m/0fdjb": "Supernatural", "/m/02kdv5l": "Action", "/m/09zvmj": "Space western"}
3196793 /m/08yl5d   Getting Away with Murder: The JonBenét Ramsey Mystery   2000-02-16      95.0    {"/m/02h40lc": "English Language"}  {"/m/09c7w0": "United States of America"}   {"/m/02n4kr": "Mystery", "/m/03bxz7": "Biographical film", "/m/07s9rl0": "Drama", "/m/0hj3n01": "Crime Drama"}
</code>```

I had tried the below code which enables me to access a particular value from the genre JSON

```<code>val ss = SessionCreator.createSession("DataCleaning", "local[*]")//helper function creates a spark session and returns it
val headerInfoRb = ResourceBundle.getBundle("conf.headerInfo")
val movieDF = DataReader.readFromTsv(ss, "D:/Utility/Datasets/MovieSummaries/movie.metadata.tsv")
                .toDF(headerInfoRb.getString("metadataReader").split(',').toSeq:_*)//Datareader.readFromTsv is a helper function to read TSV file ,takes sparkSession and file path as input to resurn a dataframe, which uses sparkSession's read function

movieDF.select("wiki_mv_id","mv_nm","mv_genre")
                .withColumn("genre_frmttd", get_json_object(col("mv_genre"), "$./m/02kdv5l"))
                .show(1,false)
</code>```

Output

```<code>+----------+--------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+------------+
|wiki_mv_id|mv_nm         |mv_genre                                                                                |genre_frmttd|
+----------+--------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+------------+
|975900    |Ghosts of Mars|{"/m/01jfsb": "Thriller", "/m/06n90": "Science Fiction", "/m/03npn": "Horror", "/m/03k9fj": "Adventure", "/m/0fdjb": "Supernatural", "/m/02kdv5l": "Action", "/m/09zvmj": "Space western"}|Action      |
+----------+--------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+------------+
only showing top 1 row
</code>```

I want genre_frmttd column in the way shown below for every row in the data Frame [ below snippet is for the first sample row ]

```<code>[Thriller,Fiction,Horror,Adventure,Supernatural,Action,Space Western]
</code>```

I am bit of a rookie in scala and spark, do suggest some way to list out the values

答:
parse the JSON using from_json

cast it to MapType(StringType, StringType)

extract only values using map_values

```<code>import org.apache.spark.sql.functions._
import org.apache.spark.sql.types.{MapType, StringType}

movieDF.select("wiki_mv_id","mv_nm","mv_genre")
      .withColumn("genre_frmttd",map_values(from_json(col("mv_genre"),MapType(StringType, StringType))))
      .show(1,false)
</code>```

Body:
I was trying to load a TSV file containing some metadata on movies using Spark, this TSV file contains genre info on movies in JSON format [ The last column in every row ]

Sample File

975900  /m/03vyhn   Ghosts of Mars  2001-08-24  14010832    98.0    {"/m/02h40lc": "English Language"}  {"/m/09c7w0": "United States of America"}   {"/m/01jfsb": "Thriller", "/m/06n90": "Science Fiction", "/m/03npn": "Horror", "/m/03k9fj": "Adventure", "/m/0fdjb": "Supernatural", "/m/02kdv5l": "Action", "/m/09zvmj": "Space western"}
3196793 /m/08yl5d   Getting Away with Murder: The JonBenét Ramsey Mystery   2000-02-16      95.0    {"/m/02h40lc": "English Language"}  {"/m/09c7w0": "United States of America"}   {"/m/02n4kr": "Mystery", "/m/03bxz7": "Biographical film", "/m/07s9rl0": "Drama", "/m/0hj3n01": "Crime Drama"}

I had tried the below code which enables me to access a particular value from the genre JSON

val ss = SessionCreator.createSession("DataCleaning", "local[*]")//helper function creates a spark session and returns it
val headerInfoRb = ResourceBundle.getBundle("conf.headerInfo")
val movieDF = DataReader.readFromTsv(ss, "D:/Utility/Datasets/MovieSummaries/movie.metadata.tsv")
                .toDF(headerInfoRb.getString("metadataReader").split(',').toSeq:_*)//Datareader.readFromTsv is a helper function to read TSV file ,takes sparkSession and file path as input to resurn a dataframe, which uses sparkSession's read function

movieDF.select("wiki_mv_id","mv_nm","mv_genre")
                .withColumn("genre_frmttd", get_json_object(col("mv_genre"), "$./m/02kdv5l"))
                .show(1,false)

Output

+----------+--------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+------------+
|wiki_mv_id|mv_nm         |mv_genre                                                                                |genre_frmttd|
+----------+--------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+------------+
|975900    |Ghosts of Mars|{"/m/01jfsb": "Thriller", "/m/06n90": "Science Fiction", "/m/03npn": "Horror", "/m/03k9fj": "Adventure", "/m/0fdjb": "Supernatural", "/m/02kdv5l": "Action", "/m/09zvmj": "Space western"}|Action      |
+----------+--------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+------------+
only showing top 1 row

I want genre_frmttd column in the way shown below for every row in the data Frame [ below snippet is for the first sample row ]

[Thriller,Fiction,Horror,Adventure,Supernatural,Action,Space Western]

I am bit of a rookie in scala and spark, do suggest some way to list out the values

Body:
parse the JSON using from_json

cast it to MapType(StringType, StringType)

extract only values using map_values

import org.apache.spark.sql.functions._
import org.apache.spark.sql.types.{MapType, StringType}

movieDF.select("wiki_mv_id","mv_nm","mv_genre")
      .withColumn("genre_frmttd",map_values(from_json(col("mv_genre"),MapType(StringType, StringType))))
      .show(1,false)


问:
How can I have access into *argv[ ] in C?
Say that I have this part of code. If user does not enter the file names as command line arguments I want to ask him again so as to enter them now but as it seems I cannot have access in argv[1] and argv[2]. For example when the first scanf is executed segmentation fault occurs. But in this case how can I read the arguments and place them into argv[1] and argv[2]?
Thanks in advance for your help!</p>

```<code>int main (int argc, char **argv)
{
    if (argc != 3)
    {
        printf("You did not enter two files.\n");
        printf("You can now enter those two files.\n");
        printf("file 1: ");
        scanf("%s", argv[1]);
        printf("file 2: ");
        scanf("%s ", argv[2]);
    }

    printf("%s\n", argv[1]);
    printf("%s\n", argv[2]);

    FILE *file1 = fopen(argv[1], "r");
    FILE *file2 = fopen(argv[2], "r");
}
</code>```

答:
A segmentation fault occurs because length of the argv array is determined when the user runs the program. If you run a program like this:

```<code>./programName
</code>```

argv is only 1 element long. It's impossible to access argv[1] or argv[2] after that. Still, You can get the necessary data and save them in regular variables.

Body:
Say that I have this part of code. If user does not enter the file names as command line arguments I want to ask him again so as to enter them now but as it seems I cannot have access in argv[1] and argv[2]. For example when the first scanf is executed segmentation fault occurs. But in this case how can I read the arguments and place them into argv[1] and argv[2]?
Thanks in advance for your help!

int main (int argc, char **argv)
{
    if (argc != 3)
    {
        printf("You did not enter two files.\n");
        printf("You can now enter those two files.\n");
        printf("file 1: ");
        scanf("%s", argv[1]);
        printf("file 2: ");
        scanf("%s ", argv[2]);
    }

    printf("%s\n", argv[1]);
    printf("%s\n", argv[2]);

    FILE *file1 = fopen(argv[1], "r");
    FILE *file2 = fopen(argv[2], "r");
}

Body:
A segmentation fault occurs because length of the argv array is determined when the user runs the program. If you run a program like this:

./programName

argv is only 1 element long. It's impossible to access argv[1] or argv[2] after that. Still, You can get the necessary data and save them in regular variables.


问:
Flutter: Unimplemented handling of missing static target

I am running my first Flutter project

I created a sample project and I was able to run the app in
simulator

I have edited the file main.dart

main.dart

```<code>import 'package:flutter/material.dart';

void main() => runApp(MaterialApp(home: Text('Hello World')));
</code>```

Now I am getting the error :

pubspec.yaml

```<code>name: flutter_app
description: A new Flutter application.

# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
version: 1.0.0+1

environment:
  sdk: ">=2.1.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^0.1.2

dev_dependencies:
  flutter_test:
    sdk: flutter

# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec

# The following section is specific to Flutter.
flutter:

  # The following line ensures that the Material Icons font is
  # included with your application, so that you can use the icons in
  # the material Icons class.
  uses-material-design: true

  # To add assets to your application, add an assets section, like this:
  # assets:
  #  - images/a_dot_burr.jpeg
  #  - images/a_dot_ham.jpeg

  # An image asset can refer to one or more resolution-specific "variants", see
  # https://flutter.dev/assets-and-images/#resolution-aware.

  # For details regarding adding assets from package dependencies, see
  # https://flutter.dev/assets-and-images/#from-packages

  # To add custom fonts to your application, add a fonts section here,
  # in this "flutter" section. Each entry in this list should have a
  # "family" key with the font family name, and a "fonts" key with a
  # list giving the asset and other descriptors for the font. For
  # example:
  # fonts:
  #   - family: Schyler
  #     fonts:
  #       - asset: fonts/Schyler-Regular.ttf
  #       - asset: fonts/Schyler-Italic.ttf
  #         style: italic
  #   - family: Trajan Pro
  #     fonts:
  #       - asset: fonts/TrajanPro.ttf
  #       - asset: fonts/TrajanPro_Bold.ttf
  #         weight: 700
  #
  # For details regarding fonts from package dependencies,
  # see https://flutter.dev/custom-fonts/#from-packages
</code>```

答: Just press the red stop button and click the play button again. It will work :)</p>

Body:
I am running my first Flutter project

I created a sample project and I was able to run the app in
simulator

I have edited the file main.dart

main.dart

import 'package:flutter/material.dart';

void main() => runApp(MaterialApp(home: Text('Hello World')));

Now I am getting the error :

pubspec.yaml

name: flutter_app
description: A new Flutter application.

# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
version: 1.0.0+1

environment:
  sdk: ">=2.1.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^0.1.2

dev_dependencies:
  flutter_test:
    sdk: flutter

# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec

# The following section is specific to Flutter.
flutter:

  # The following line ensures that the Material Icons font is
  # included with your application, so that you can use the icons in
  # the material Icons class.
  uses-material-design: true

  # To add assets to your application, add an assets section, like this:
  # assets:
  #  - images/a_dot_burr.jpeg
  #  - images/a_dot_ham.jpeg

  # An image asset can refer to one or more resolution-specific "variants", see
  # https://flutter.dev/assets-and-images/#resolution-aware.

  # For details regarding adding assets from package dependencies, see
  # https://flutter.dev/assets-and-images/#from-packages

  # To add custom fonts to your application, add a fonts section here,
  # in this "flutter" section. Each entry in this list should have a
  # "family" key with the font family name, and a "fonts" key with a
  # list giving the asset and other descriptors for the font. For
  # example:
  # fonts:
  #   - family: Schyler
  #     fonts:
  #       - asset: fonts/Schyler-Regular.ttf
  #       - asset: fonts/Schyler-Italic.ttf
  #         style: italic
  #   - family: Trajan Pro
  #     fonts:
  #       - asset: fonts/TrajanPro.ttf
  #       - asset: fonts/TrajanPro_Bold.ttf
  #         weight: 700
  #
  # For details regarding fonts from package dependencies,
  # see https://flutter.dev/custom-fonts/#from-packages


问:
dispatchEvent doesn't work in javascript with Internet explorer 11
In my website I have a javascript in which I wish to open a file save dialog. The purpose is to save in a text file some data that are coming from the web server.

I am trying to use the code snippet shown in this post:

[Using HTML5/JavaScript to generate and save a file

And to be precise:

```<code>function download(filename, text) {
    var pom = document.createElement('a');
    pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
    pom.setAttribute('download', filename);

    if (document.createEvent) {
        var event = document.createEvent('MouseEvents');
        event.initEvent('click', true, true);
        pom.dispatchEvent(event);
    }
    else {
        pom.click();
    }
}
</code>```

This works great for Firefox and Chrome. However with Internet Explorer 11 it doesn't work. When this instruction is executed...

```<code>pom.dispatchEvent(event);
</code>```

...nothing happens. The save dialog is not opened, and no error is shown in the java console of the browser. The event seems to get lost in the void.
Any help would be greatly appreciated.

答:
Your code works fine for me in Internet Explorer 11.836.18362.0,
however with that said, MDN advises not to use the technique you are using. createEvent and initEvent are depricated, can have unpredictable results and may be dropped at any time. Use Event() instead. See initEvent and createEvent MDN doc pages.

Body:
In my website I have a javascript in which I wish to open a file save dialog. The purpose is to save in a text file some data that are coming from the web server.

I am trying to use the code snippet shown in this post:

[Using HTML5/JavaScript to generate and save a file

And to be precise:

function download(filename, text) {
    var pom = document.createElement('a');
    pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
    pom.setAttribute('download', filename);

    if (document.createEvent) {
        var event = document.createEvent('MouseEvents');
        event.initEvent('click', true, true);
        pom.dispatchEvent(event);
    }
    else {
        pom.click();
    }
}

This works great for Firefox and Chrome. However with Internet Explorer 11 it doesn't work. When this instruction is executed...

pom.dispatchEvent(event);

...nothing happens. The save dialog is not opened, and no error is shown in the java console of the browser. The event seems to get lost in the void.
Any help would be greatly appreciated.


问:
Record from firebase query does not exist as expected
I am writing an async function async_unlike_post, used for my firebase HTTP function unlike_post of the form in index.js. The implementation of async_unlike_post is stored in another file posts.js

index.js

```<code>exports.unlike_post = functions
  .https
  .onCall(async_unlike_post);
</code>```

posts.js

```<code>const { admin, db } = require("../util/admin");
//admin.initializeApp(config);
//const db = admin.firestore();

const { uuid } = require("uuidv4");

const {
  success_response,
  error_response
} = require("../util/validators");

exports.async_unlike_post = async function(req, res) {
  try {
    const like_snapshot = await db
      .collection('likes')
      .where("liker_id", '==', req.liker_id)
      .where('entity_id', '==', req.entity_id)
      .limit(1).get();

    if (!like_snapshot.exists) {

      console.log("Case 1");

      return error_response("Post has not been liked by user");
    }

    const post_document = db.doc(`/posts/${req.entity_id}`);
    const post_snapshot = await post_document.get();

    if (!post_snapshot.exists) {

      console.log("Case 2");
      return error_response("Post not found");
    }

    console.log("Should delete");

    return db.collection("likes").doc(like_snapshot.id).delete();

  } catch (error) {
    return error_response(error);
  }
}

mockLike = {
  liker_id: "string1",
  entity_id: "string2"
}

exports.async_unlike_post(mockLike);
</code>```

After running node posts.js, I am expecting to see the document in my Firestore database being deleted. However, on my console, it says it goes to Case 1. There is certainly a document in my firestore database in the likes collection with  the following attributes.

```<code>created_at: Some_timestamp,
entity_id: "string2",
liker_id: "string1",
type: "post"
</code>```

Can someone enlighten me why does the execution of my code goes into Case 1?

答:
Your function takes parameters for res and req:

```<code>function asyncUnlikePost(req, res)
</code>```

However, you are exporting an onCall function, which does not provide the same arguments:

```<code>exports.unlike_post = functions
  .https
  .onCall(async_unlike_post);
</code>```

As you can see from the documentation for callable functions, it provides a data and context parameters, not req and res.  onCall functions are different than onRequest functions.  They are not "compatible".

Also, this invocation here:

```<code>mockLike = {
  liker_id: "string1",
  entity_id: "string2"
}

exports.async_unlike_post(mockLike);
</code>```

Isn't passing the required res and req parameters.  You're just passing some object instead.  That's not going to work.

Body:
I am writing an async function async_unlike_post, used for my firebase HTTP function unlike_post of the form in index.js. The implementation of async_unlike_post is stored in another file posts.js

index.js

exports.unlike_post = functions
  .https
  .onCall(async_unlike_post);

posts.js

const { admin, db } = require("../util/admin");
//admin.initializeApp(config);
//const db = admin.firestore();

const { uuid } = require("uuidv4");

const {
  success_response,
  error_response
} = require("../util/validators");

exports.async_unlike_post = async function(req, res) {
  try {
    const like_snapshot = await db
      .collection('likes')
      .where("liker_id", '==', req.liker_id)
      .where('entity_id', '==', req.entity_id)
      .limit(1).get();

    if (!like_snapshot.exists) {

      console.log("Case 1");

      return error_response("Post has not been liked by user");
    }

    const post_document = db.doc(`/posts/${req.entity_id}`);
    const post_snapshot = await post_document.get();

    if (!post_snapshot.exists) {

      console.log("Case 2");
      return error_response("Post not found");
    }

    console.log("Should delete");

    return db.collection("likes").doc(like_snapshot.id).delete();

  } catch (error) {
    return error_response(error);
  }
}

mockLike = {
  liker_id: "string1",
  entity_id: "string2"
}

exports.async_unlike_post(mockLike);

After running node posts.js, I am expecting to see the document in my Firestore database being deleted. However, on my console, it says it goes to Case 1. There is certainly a document in my firestore database in the likes collection with  the following attributes.

created_at: Some_timestamp,
entity_id: "string2",
liker_id: "string1",
type: "post"

Can someone enlighten me why does the execution of my code goes into Case 1?

Body:
Your function takes parameters for res and req:

function asyncUnlikePost(req, res)

However, you are exporting an onCall function, which does not provide the same arguments:

exports.unlike_post = functions
  .https
  .onCall(async_unlike_post);

As you can see from the documentation for callable functions, it provides a data and context parameters, not req and res.  onCall functions are different than onRequest functions.  They are not "compatible".

Also, this invocation here:

mockLike = {
  liker_id: "string1",
  entity_id: "string2"
}

exports.async_unlike_post(mockLike);

Isn't passing the required res and req parameters.  You're just passing some object instead.  That's not going to work.


问:
How to register this in xml configuration
How do I register something like this in the xml configuration (i know, i know, convention over config, but I'm supporting legacy code, so i need to do it in the xml config).

Specifically, I'm unclear on how to register AssignTechniciansFactory with the abstract base class AND the interface type. Normally, i get how to do it for either a base class OR just the interface. But how about registering both to the component?

```<code>public class AssignTechniciansFactory:
         BaseAssignTechniciansFactory<Service>, IAssignTechniciansFactory
</code>```

Where:

```<code>public class Service : BaseAssignTechnician
</code>```

And:

```<code>public abstract class BaseAssignTechniciansFactory<T>
                         where T: BaseAssignTechnician
</code>```

This is what I have, and I know it's not correct:

```<code><component id="assignTechniciansFactory"
           service="MyNamespace.IAssignTechniciansFactory, MyAssembly"
           type="MyNamespace.AssignTechniciansFactory, MyAssembly">
   <parameters>
     <dmq>${dmq}</dmq>
     <builder>${builder}</builder>
   </parameters>
</component>
</code>```

答:
Castle is very forgiving now and you shouldn't have to specify the assembly or namespace if the service and type are unique in all the types loaded. This should work if you had namespace issues or assembly name issues:</p>

```<code><component id="assignTechniciansFactory"
           service="IAssignTechniciansFactory"
           type="AssignTechniciansFactory">
   <parameters>
     <dmq>${dmq}</dmq>
     <builder>${builder}</builder>
   </parameters>
</component>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
How do I register something like this in the xml configuration (i know, i know, convention over config, but I'm supporting legacy code, so i need to do it in the xml config).

Specifically, I'm unclear on how to register AssignTechniciansFactory with the abstract base class AND the interface type. Normally, i get how to do it for either a base class OR just the interface. But how about registering both to the component?

public class AssignTechniciansFactory:
         BaseAssignTechniciansFactory<Service>, IAssignTechniciansFactory

Where:

public class Service : BaseAssignTechnician

And:

public abstract class BaseAssignTechniciansFactory<T>
                         where T: BaseAssignTechnician

This is what I have, and I know it's not correct:

<component id="assignTechniciansFactory"
           service="MyNamespace.IAssignTechniciansFactory, MyAssembly"
           type="MyNamespace.AssignTechniciansFactory, MyAssembly">
   <parameters>
     <dmq>${dmq}</dmq>
     <builder>${builder}</builder>
   </parameters>
</component>

Body:
Castle is very forgiving now and you shouldn't have to specify the assembly or namespace if the service and type are unique in all the types loaded. This should work if you had namespace issues or assembly name issues:

<component id="assignTechniciansFactory"
           service="IAssignTechniciansFactory"
           type="AssignTechniciansFactory">
   <parameters>
     <dmq>${dmq}</dmq>
     <builder>${builder}</builder>
   </parameters>
</component>


问:
Print the detected classes and scores when using TF Object Detection API
Hello i'm looking for a way to print out the detected classes and scores while doing an Object Detection with the object_detection_tutorial.
Most solutions here are for Tensorflow 1 and do not work anymore.

I found one Solution here on StackOverflow but sadly it only prints out one of the detected Objects. I can't find out how i have to modify the code to get the scores for all detected Objects in the image.

This is the code given in the Solution i found here

```<code>def get_classes_name_and_scores(
    boxes,
    classes,
    scores,
    category_index,
    max_boxes_to_draw=20,
    min_score_thresh=.9): # returns bigger than 90% precision
display_str = {}
if not max_boxes_to_draw:
    max_boxes_to_draw = boxes.shape[0]
for i in range(min(max_boxes_to_draw, boxes.shape[0])):
    if scores is None or scores[i] > min_score_thresh:
        if classes[i] in six.viewkeys(category_index):
            display_str['name'] = category_index[classes[i]]['name']
            display_str['score'] = '{}%'.format(int(100 * scores[i]))

return display_str
</code>```

I print this out using this code

```<code>def show_inference(model, image_path):
  # the array based representation of the image will be used later in order to prepare the
  # result image with boxes and labels on it.
  image_np = np.array(Image.open(image_path))
  # Actual detection.
  output_dict = run_inference_for_single_image(model, image_np)
  # Visualization of the results of a detection.
  vis_util.visualize_boxes_and_labels_on_image_array(
    image_np,
    output_dict['detection_boxes'],
    output_dict['detection_classes'],
    output_dict['detection_scores'],
    category_index,
    instance_masks=output_dict.get('detection_masks_reframed', None),
    use_normalized_coordinates=True,
    line_thickness=8)

  # Print the Name and Score of each detected Object
  print(get_classes_name_and_scores(
    output_dict['detection_boxes'],
    output_dict['detection_classes'],
    output_dict['detection_scores'],
    category_index))

  display(Image.fromarray(image_np))
</code>```

答:
every time through the loop these 2 lines are overwritten so the previous contents are gone:

```<code>display_str['name'] = category_index[classes[i]]['name']
display_str['score'] = '{}%'.format(int(100 * scores[i]))
</code>```

I assume you want to record each instance that the loop triggers those lines. Personally, for this I would add the result to a list and return that:

```<code>display_str_list = []
    ### your loop code
    display_str_dict = {
        'name': category_index[classes[i]]['name'],
        'score': '{}%'.format(int(100 * scores[i])),
    }
    display_str_list.append(display_str_dict)
return display_str_list
</code>```

Body:
Hello i'm looking for a way to print out the detected classes and scores while doing an Object Detection with the object_detection_tutorial.
Most solutions here are for Tensorflow 1 and do not work anymore.

I found one Solution here on StackOverflow but sadly it only prints out one of the detected Objects. I can't find out how i have to modify the code to get the scores for all detected Objects in the image.

This is the code given in the Solution i found here

def get_classes_name_and_scores(
    boxes,
    classes,
    scores,
    category_index,
    max_boxes_to_draw=20,
    min_score_thresh=.9): # returns bigger than 90% precision
display_str = {}
if not max_boxes_to_draw:
    max_boxes_to_draw = boxes.shape[0]
for i in range(min(max_boxes_to_draw, boxes.shape[0])):
    if scores is None or scores[i] > min_score_thresh:
        if classes[i] in six.viewkeys(category_index):
            display_str['name'] = category_index[classes[i]]['name']
            display_str['score'] = '{}%'.format(int(100 * scores[i]))

return display_str

I print this out using this code

def show_inference(model, image_path):
  # the array based representation of the image will be used later in order to prepare the
  # result image with boxes and labels on it.
  image_np = np.array(Image.open(image_path))
  # Actual detection.
  output_dict = run_inference_for_single_image(model, image_np)
  # Visualization of the results of a detection.
  vis_util.visualize_boxes_and_labels_on_image_array(
    image_np,
    output_dict['detection_boxes'],
    output_dict['detection_classes'],
    output_dict['detection_scores'],
    category_index,
    instance_masks=output_dict.get('detection_masks_reframed', None),
    use_normalized_coordinates=True,
    line_thickness=8)

  # Print the Name and Score of each detected Object
  print(get_classes_name_and_scores(
    output_dict['detection_boxes'],
    output_dict['detection_classes'],
    output_dict['detection_scores'],
    category_index))

  display(Image.fromarray(image_np))

Body:
every time through the loop these 2 lines are overwritten so the previous contents are gone:

display_str['name'] = category_index[classes[i]]['name']
display_str['score'] = '{}%'.format(int(100 * scores[i]))

I assume you want to record each instance that the loop triggers those lines. Personally, for this I would add the result to a list and return that:

display_str_list = []
    ### your loop code
    display_str_dict = {
        'name': category_index[classes[i]]['name'],
        'score': '{}%'.format(int(100 * scores[i])),
    }
    display_str_list.append(display_str_dict)
return display_str_list


问:
Columns children cannot return null, but returning would stop the loop
I am trying to iterate through a list and produce a widget (Text) for now for each 'step' in the list.

When printing I get exactly as expected, however, I get the error Column's children must not contain any null values, but a null value was found at index 0.

Which I understand as I am not returning anything. But if I do return something the loop stops, so I just get the first step.

```<code>recipeMethodList(recipeMethod) {
for (var step in recipeMethod) {
  stepNumber = stepNumber + 1;
  Row(
    children: <Widget>[
      Text('$stepNumber. $step'),
    ],
  );
  print('$stepNumber. $step');
}
</code>```

I call this with:

```<code>Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[recipeMethodList(recipeMethod)],
            ),
</code>```

答:
you can try changing the function like</p>

```<code>List<Widget> recipeMethodList(List recipeMethod) {
  int stepNumber=0;
  return recipeMethod.map((step) {
    stepNumber = stepNumber + 1;
    return Text('$stepNumber. $step');
  }).toList();
}
</code>```

Body:
I am trying to iterate through a list and produce a widget (Text) for now for each 'step' in the list.

When printing I get exactly as expected, however, I get the error Column's children must not contain any null values, but a null value was found at index 0.

Which I understand as I am not returning anything. But if I do return something the loop stops, so I just get the first step.

recipeMethodList(recipeMethod) {
for (var step in recipeMethod) {
  stepNumber = stepNumber + 1;
  Row(
    children: <Widget>[
      Text('$stepNumber. $step'),
    ],
  );
  print('$stepNumber. $step');
}

I call this with:

Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[recipeMethodList(recipeMethod)],
            ),

Body:
you can try changing the function like

List<Widget> recipeMethodList(List recipeMethod) {
  int stepNumber=0;
  return recipeMethod.map((step) {
    stepNumber = stepNumber + 1;
    return Text('$stepNumber. $step');
  }).toList();
}


问:
Is it possible to avoid this loop using numpy?
Suppose you have two numpy matrices:

```<code>import numpy as np

n = 800
m = 16
A = np.zeros((n, 4)) #np.random.rand(n,4) if you wish
B = np.zeros(m)      #np.random.rand(m) if you wish
</code>```

In my code, I need to substract each value found in B to all values of A, then calculate that square and get the index that give me the minimum of that new matrix. Therefore, I will have m minimums. From those, I need the minimum. To do this now I use a loop such:

```<code>min_C = np.zeros(m)

for j in range(m):
    C = A[:,2]-B[j]
    C = C*C
    min_C[j] = np.where(C == np.amin(C))[0][0]
</code>```

So I have a minimum for each j. Then, I do the minimum of min_C. Can I avoid this loop to obtain the absolute minimum? I cannot imagine now how to code it, if possible. It's just to improve efficency in my code, which I need it, since this calculation is done lots of times with differents A and B, of course.

答:
Leveraging broadcasting, you can reduce this to the following taking the min of the resulting (m,n) array:

```<code>((A[:,2]-B[:,None])**2).min()
</code>```

Body:
Suppose you have two numpy matrices:

import numpy as np

n = 800
m = 16
A = np.zeros((n, 4)) #np.random.rand(n,4) if you wish
B = np.zeros(m)      #np.random.rand(m) if you wish

In my code, I need to substract each value found in B to all values of A, then calculate that square and get the index that give me the minimum of that new matrix. Therefore, I will have m minimums. From those, I need the minimum. To do this now I use a loop such:

min_C = np.zeros(m)

for j in range(m):
    C = A[:,2]-B[j]
    C = C*C
    min_C[j] = np.where(C == np.amin(C))[0][0]

So I have a minimum for each j. Then, I do the minimum of min_C. Can I avoid this loop to obtain the absolute minimum? I cannot imagine now how to code it, if possible. It's just to improve efficency in my code, which I need it, since this calculation is done lots of times with differents A and B, of course.

Body:
Leveraging broadcasting, you can reduce this to the following taking the min of the resulting (m,n) array:

((A[:,2]-B[:,None])**2).min()


问:
Plotting credible intervals in Julia from Turing model
Ok so I figured out how to plot the credible intervals for a univariate linear model in Turing.jl using the following code (I'm replicating Statistical rethinking by McElreath) This particular exercise is in chapter 4. If anyone has already plotted these types of models with Turing and can give me a guide, it would be great!!!

Univariate model code:

```<code>    using Turing
    using StatsPlots
    using Plots

    height = df2.height

    weight = df2.weight

    @model heightmodel(y, x) = begin
        #priors
        α ~ Normal(178, 100)
        σ ~ Uniform(0, 50)
        β ~ LogNormal(0, 10)

        x_bar = mean(x)
        #model

            μ = α .+ (x.-x_bar).*β
        y ~ MvNormal(μ, σ)
    end

    chns = sample(heightmodel(height, weight), NUTS(), 100000)

    ## code 4.43
    describe(chns) |> display

    # covariance and correlation

    alph = get(chns, :α)[1].data

    bet = get(chns, :β)[1].data

    sigm = get(chns, :σ)[1].data

    vecs = (alph[1:352], bet[1:352])
    arr = vcat(transpose.(vecs)...)'

    ss = [vec(alph + bet.*(x)) for x in 25:1:70]

    arrr = vcat(transpose.(ss)...)'

    plot([mean(arrr[:,x]) for x in 1:46],25:1:70, ribbon = ([-1*(quantile(arrr[:,x],[0.1,0.9])[1] - mean(arrr[:,x])) for x in 1:46], [quantile(arrr[:,x],[0.1,0.9])[2] - mean(arrr[:,x]) for x in 1:46]))
</code>```

Credible interval Univariate:

However, when I try to replicate it with a multivatiate function, very strange things are drawn:

Multivariate model code:

```<code>    weight_s = (df.weight .-mean(df.weight))./std(df.weight)

    weight_s² = weight_s.^2

    @model heightmodel(height, weight, weight²) = begin
        #priors
        α ~ Normal(178, 20)
        σ ~ Uniform(0, 50)
        β1 ~ LogNormal(0, 1)
        β2 ~ Normal(0, 1)
        #model
        μ = α .+ weight.*β1 + weight².*β2
        height ~ MvNormal(μ, σ)
    end

    chns = sample(heightmodel(height, weight_s, weight_s²), NUTS(), 100000)

    describe(chns) |> display

    ### painting the fit

    alph = get(chns, :α)[1].data

    bet1 = get(chns, :β1)[1].data

    bet2 = get(chns, :β2)[1].data

    vecs = (alph[1:99000], bet1[1:99000], bet2[1:99000])
    arr = vcat(transpose.(vecs)...)'

    polinomial = [vec(alph + bet1.*(x) + bet2.*(x.^2)) for x in -2:0.01:2]

    arrr = vcat(transpose.(polinomial)...)'

    plot([mean(arrr[:,x]) for x in 1:401],-2:0.01:2, ribbon = ([-1*(quantile(arrr[:,x],[0.1,0.9])[1] - mean(arrr[:,x])) for x in 1:46], [quantile(arrr[:,x],[0.1,0.9])[2] - mean(arrr[:,x]) for x in 1:46]))
</code>```

Credible interval Univariate:

答:
In the Julia Slack channel (https://slackinvite.julialang.org/) Jens was kind enough to give me the answer. The credit goes to him --He doesn't have a SO account.

The main problem was that I was lacking simplicity and was trying to plot the mean the wrong way --in a very inefficient and strange way might I add. Each parameter has a vector which corresponds to 99000 draws from the posterior distribution, I was trying to draw the mean through the matrix but it's much easier to define the median first and then plot it, then you don't make mistakes as I did calculating the mean.

old code

```<code>vecs = (alph[1:99000], bet1[1:99000], bet2[1:99000])
arr = vcat(transpose.(vecs)...)'
[mean(arrr[:,x]) for x in 1:401]
</code>```

can be written as:

```<code>testweights = -2:0.01:2
arr = [fheight.(w, res.α, res.β1, res.β2) for w in testweights]
m = [mean(v) for v in arr]
</code>```

Moreover, the way Jens defined the Credible intervals is much more elegant and Julianic:

Jens' code:

```<code>quantiles = [quantile(v, [0.1, 0.9]) for v in arr]
lower = [q[1] - m for (q, m) in zip(quantiles, m)]
upper = [q[2] - m for (q, m) in zip(quantiles, m)]
</code>```

My code:

```<code>ribbon = ([-1*(quantile(arrr[:,x],[0.1,0.9])[1] - mean(arrr[:,x])) for x in 1:46], [quantile(arrr[:,x],[0.1,0.9])[2] - mean(arrr[:,x]) for x in 1:46]))
</code>```

Complete Solution:

```<code>weight_s = (d.weight .-mean(d.weight))./std(d.weight)
height = d.height
@model heightmodel(height, weight) = begin
    #priors
    α ~ Normal(178, 20)´
    σ ~ Uniform(0, 50)
    β1 ~ LogNormal(0, 1)
    β2 ~ Normal(0, 1)
    #model
    μ = α .+ weight .* β1 + weight.^2 .* β2
    # or μ = fheight.(weight, α, β1, β2) if we are defining fheigth anyways
    height ~ MvNormal(μ, σ)
end
chns = sample(heightmodel(height, weight_s), NUTS(), 10000)
describe(chns) |> display
res = DataFrame(chns)
fheight(weight, α, β1, β2) = α + weight * β1 + weight^2 * β2
testweights = -2:0.01:2
arr = [fheight.(w, res.α, res.β1, res.β2) for w in testweights]
m = [mean(v) for v in arr]
quantiles = [quantile(v, [0.1, 0.9]) for v in arr]
lower = [q[1] - m for (q, m) in zip(quantiles, m)]
upper = [q[2] - m for (q, m) in zip(quantiles, m)]
plot(testweights, m, ribbon = [lower, upper])
</code>```

Body:
Ok so I figured out how to plot the credible intervals for a univariate linear model in Turing.jl using the following code (I'm replicating Statistical rethinking by McElreath) This particular exercise is in chapter 4. If anyone has already plotted these types of models with Turing and can give me a guide, it would be great!!!

Univariate model code:

    using Turing
    using StatsPlots
    using Plots

    height = df2.height

    weight = df2.weight

    @model heightmodel(y, x) = begin
        #priors
        α ~ Normal(178, 100)
        σ ~ Uniform(0, 50)
        β ~ LogNormal(0, 10)

        x_bar = mean(x)
        #model

            μ = α .+ (x.-x_bar).*β
        y ~ MvNormal(μ, σ)
    end

    chns = sample(heightmodel(height, weight), NUTS(), 100000)

    ## code 4.43
    describe(chns) |> display

    # covariance and correlation

    alph = get(chns, :α)[1].data

    bet = get(chns, :β)[1].data

    sigm = get(chns, :σ)[1].data

    vecs = (alph[1:352], bet[1:352])
    arr = vcat(transpose.(vecs)...)'

    ss = [vec(alph + bet.*(x)) for x in 25:1:70]

    arrr = vcat(transpose.(ss)...)'

    plot([mean(arrr[:,x]) for x in 1:46],25:1:70, ribbon = ([-1*(quantile(arrr[:,x],[0.1,0.9])[1] - mean(arrr[:,x])) for x in 1:46], [quantile(arrr[:,x],[0.1,0.9])[2] - mean(arrr[:,x]) for x in 1:46]))

Credible interval Univariate:

However, when I try to replicate it with a multivatiate function, very strange things are drawn:

Multivariate model code:

    weight_s = (df.weight .-mean(df.weight))./std(df.weight)

    weight_s² = weight_s.^2

    @model heightmodel(height, weight, weight²) = begin
        #priors
        α ~ Normal(178, 20)
        σ ~ Uniform(0, 50)
        β1 ~ LogNormal(0, 1)
        β2 ~ Normal(0, 1)
        #model
        μ = α .+ weight.*β1 + weight².*β2
        height ~ MvNormal(μ, σ)
    end

    chns = sample(heightmodel(height, weight_s, weight_s²), NUTS(), 100000)

    describe(chns) |> display

    ### painting the fit

    alph = get(chns, :α)[1].data

    bet1 = get(chns, :β1)[1].data

    bet2 = get(chns, :β2)[1].data

    vecs = (alph[1:99000], bet1[1:99000], bet2[1:99000])
    arr = vcat(transpose.(vecs)...)'

    polinomial = [vec(alph + bet1.*(x) + bet2.*(x.^2)) for x in -2:0.01:2]

    arrr = vcat(transpose.(polinomial)...)'

    plot([mean(arrr[:,x]) for x in 1:401],-2:0.01:2, ribbon = ([-1*(quantile(arrr[:,x],[0.1,0.9])[1] - mean(arrr[:,x])) for x in 1:46], [quantile(arrr[:,x],[0.1,0.9])[2] - mean(arrr[:,x]) for x in 1:46]))

Credible interval Univariate:

Body:
In the Julia Slack channel (https://slackinvite.julialang.org/) Jens was kind enough to give me the answer. The credit goes to him --He doesn't have a SO account.

The main problem was that I was lacking simplicity and was trying to plot the mean the wrong way --in a very inefficient and strange way might I add. Each parameter has a vector which corresponds to 99000 draws from the posterior distribution, I was trying to draw the mean through the matrix but it's much easier to define the median first and then plot it, then you don't make mistakes as I did calculating the mean.

old code

vecs = (alph[1:99000], bet1[1:99000], bet2[1:99000])
arr = vcat(transpose.(vecs)...)'
[mean(arrr[:,x]) for x in 1:401]

can be written as:

testweights = -2:0.01:2
arr = [fheight.(w, res.α, res.β1, res.β2) for w in testweights]
m = [mean(v) for v in arr]

Moreover, the way Jens defined the Credible intervals is much more elegant and Julianic:

Jens' code:

quantiles = [quantile(v, [0.1, 0.9]) for v in arr]
lower = [q[1] - m for (q, m) in zip(quantiles, m)]
upper = [q[2] - m for (q, m) in zip(quantiles, m)]

My code:

ribbon = ([-1*(quantile(arrr[:,x],[0.1,0.9])[1] - mean(arrr[:,x])) for x in 1:46], [quantile(arrr[:,x],[0.1,0.9])[2] - mean(arrr[:,x]) for x in 1:46]))

Complete Solution:

weight_s = (d.weight .-mean(d.weight))./std(d.weight)
height = d.height
@model heightmodel(height, weight) = begin
    #priors
    α ~ Normal(178, 20)´
    σ ~ Uniform(0, 50)
    β1 ~ LogNormal(0, 1)
    β2 ~ Normal(0, 1)
    #model
    μ = α .+ weight .* β1 + weight.^2 .* β2
    # or μ = fheight.(weight, α, β1, β2) if we are defining fheigth anyways
    height ~ MvNormal(μ, σ)
end
chns = sample(heightmodel(height, weight_s), NUTS(), 10000)
describe(chns) |> display
res = DataFrame(chns)
fheight(weight, α, β1, β2) = α + weight * β1 + weight^2 * β2
testweights = -2:0.01:2
arr = [fheight.(w, res.α, res.β1, res.β2) for w in testweights]
m = [mean(v) for v in arr]
quantiles = [quantile(v, [0.1, 0.9]) for v in arr]
lower = [q[1] - m for (q, m) in zip(quantiles, m)]
upper = [q[2] - m for (q, m) in zip(quantiles, m)]
plot(testweights, m, ribbon = [lower, upper])


问:
How do I handle a ManyToMany relationship in JSON?
This is a follow-up question to my previous question on "Managing employee contracts in a many-to-many relationship?" and this question

I have a relationship that can be explained thusly:

company --< contracts >-- employees

I am importing the data through JSON.  For simplicity sake it is shown below.

```<code>{
  "companies" : [
    {
      "name" : "Company A",
      "employees" : [
        {
          "name" : "Tom",
          "contract" : {
            "length" : "10",
            "salary" : "10000"
          }
        }
      ]
    }
  ]
}
</code>```

The problem is, I am not sure if this is correct.

In my Model relationship the contract sits between company and employees whereas in my above code I've put it as an object and it sits as a child under the employees.

Therefore, my question is, where should a junction table sit within the JSON feed?

Should it sit as a parent to employees, or is it okay where it is?

I'm not sure if I am doing it right and would welcome any help/thoughts on the best way to structure/layout a JSON feed that is reliant upon a junction table.

I know it may seem silly, but I'm trying to ascertain best standards when dealing with junction tables.

Thanks.

Edit.

Purpose/Context

I am attempting to read in JSON into Core data using TouchJSON.  Apologies for not clarifying the context earlier.  Updated tags.

I read the JSON into a NSDictionary.  If I start to separate the objects out I am not sure how to make TouchJSON/iOS understand the context of each relationship when it comes to parse/read the data into memory.

答:
The primary reason your entity-relationship (E-R) model expresses many:many relationships via an associative entity is because the relational data model (a relational database being the most likely locus of your E-R model's implementation) can't directly express a many:many relationship — it requires an intersect table for a many:many relationship. Note that there are other reasons you might need such an intersect table (a contract, for instance, being an entity unto itself).

However, there's no reason that your object model has to suffer the constraints imposed by the relational database.

Body:
This is a follow-up question to my previous question on "Managing employee contracts in a many-to-many relationship?" and this question

I have a relationship that can be explained thusly:

company --< contracts >-- employees

I am importing the data through JSON.  For simplicity sake it is shown below.

{
  "companies" : [
    {
      "name" : "Company A",
      "employees" : [
        {
          "name" : "Tom",
          "contract" : {
            "length" : "10",
            "salary" : "10000"
          }
        }
      ]
    }
  ]
}

The problem is, I am not sure if this is correct.

In my Model relationship the contract sits between company and employees whereas in my above code I've put it as an object and it sits as a child under the employees.

Therefore, my question is, where should a junction table sit within the JSON feed?

Should it sit as a parent to employees, or is it okay where it is?

I'm not sure if I am doing it right and would welcome any help/thoughts on the best way to structure/layout a JSON feed that is reliant upon a junction table.

I know it may seem silly, but I'm trying to ascertain best standards when dealing with junction tables.

Thanks.

Edit.

Purpose/Context

I am attempting to read in JSON into Core data using TouchJSON.  Apologies for not clarifying the context earlier.  Updated tags.

I read the JSON into a NSDictionary.  If I start to separate the objects out I am not sure how to make TouchJSON/iOS understand the context of each relationship when it comes to parse/read the data into memory.


问:
Why is my python app continues to get a 500 Internal Server Error?
I'm trying to get my app.py to link with MySQL database but I keep getting the following errors shown below.  The link to my repository is here: https://github.com/trhubwork/python-mysql-proj.git

I'm running python 3.5.1

Console Errors:

jquery-1.11.2.js:9659 POST [runningonlocalhost]/signUp 500 (INTERNAL
  SERVER ERROR)send @ jquery-1.11.2.js:9659ajax @
  jquery-1.11.2.js:9210(anonymous function) @ signUp.js:4dispatch @
  jquery-1.11.2.js:4665elemData.handle @ jquery-1.11.2.js:4333
  signUp.js:12 Object {readyState: 4, responseText: "↵", status: 500, statusText: "INTERNAL SERVER ERROR"}

Gitbash terminal Errors:

Running on [localhost]:5002/ (Press CTRL+C to quit)
  127.0.0.1 - - [29/Sep/2016 22:06:17] "GET / HTTP/1.1" 200 -
  127.0.0.1 - - [29/Sep/2016 22:06:20] "GET /showSignUp HTTP/1.1" 200 - [2016-09-29 22:06:22,142] ERROR in app: Exception on /signUp [POST]
  Traceback (most recent call last):   File
  "C:\Users\TR\AppData\Local\Programs\Python\Python35-32\lib\site-packages\flask\app.py",
  line 1988, in wsgi_app
  response = self.full_dispatch_request()   File "C:\Users\TR\AppData\Local\Programs\Python\Python35-32\lib\site-packages\flask\app.py",
  line 1641, in full_dispatch_request
  rv = self.handle_user_exception(e)   File "C:\Users\TR\AppData\Local\Programs\Python\Python35-32\lib\site-packages\flask\app.py",
  line 1544, in handle_user_exception
  reraise(exc_type, exc_value, tb)   File "C:\Users\TR\AppData\Local\Programs\Python\Python35-32\lib\site-packages\flask_compat.py",
  line 33, in reraise
  raise value   File "C:\Users\TR\AppData\Local\Programs\Python\Python35-32\lib\site-packages\flask\app.py",
  line 1639, in full_dispatch_request
  rv = self.dispatch_request()   File "C:\Users\TR\AppData\Local\Programs\Python\Python35-32\lib\site-packages\flask\app.py",
  line 1625, in dispatch_request
  return self.view_functionsrule.endpoint   File "app.py", line 54, in signUp
  cursor.close() UnboundLocalError: local variable 'cursor' referenced before assignment
  127.0.0.1 - - [29/Sep/2016 22:06:22] "POST /signUp HTTP/1.1" 500 - [2016-09-29 22:09:03,808] ERROR in app: Exception on /signUp [POST]
  Traceback (most recent call last):   File
  "C:\Users\TR\AppData\Local\Programs\Python\Python35-32\lib\site-packages\flask\app.py",
  line 1988, in wsgi_app
  response = self.full_dispatch_request()   File "C:\Users\TR\AppData\Local\Programs\Python\Python35-32\lib\site-packages\flask\app.py",
  line 1641, in full_dispatch_request
  rv = self.handle_user_exception(e)   File "C:\Users\TR\AppData\Local\Programs\Python\Python35-32\lib\site-packages\flask\app.py",
  line 1544, in handle_user_exception
  reraise(exc_type, exc_value, tb)   File "C:\Users\TR\AppData\Local\Programs\Python\Python35-32\lib\site-packages\flask_compat.py",
  line 33, in reraise
  raise value   File "C:\Users\TR\AppData\Local\Programs\Python\Python35-32\lib\site-packages\flask\app.py",
  line 1639, in full_dispatch_request
  rv = self.dispatch_request()   File "C:\Users\TR\AppData\Local\Programs\Python\Python35-32\lib\site-packages\flask\app.py",
  line 1625, in dispatch_request
  return self.view_functionsrule.endpoint   File "app.py", line 54, in signUp
  cursor.close() UnboundLocalError: local variable 'cursor' referenced before assignment
  127.0.0.1 - - [29/Sep/2016 22:09:03] "POST /signUp HTTP/1.1" 500 -

This is my app.py

```<code>from flask import Flask, render_template, json, request
from flaskext.mysql import MySQL
from werkzeug import generate_password_hash, check_password_hash

mysql = MySQL()
app = Flask(__name__)

# MySQL configurations
app.config['MYSQL_DATABASE_USER'] = 'jay'
app.config['MYSQL_DATABASE_PASSWORD'] = 'jay'
app.config['MYSQL_DATABASE_DB'] = 'BucketList'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
mysql.init_app(app)

@app.route('/')
def main():
    return render_template('index.html')

@app.route('/showSignUp')
def showSignUp():
    return render_template('signup.html')

@app.route('/signUp',methods=['POST','GET'])
def signUp():
    try:
        _name = request.form['inputName']
        _email = request.form['inputEmail']
        _password = request.form['inputPassword']

        # validate the received values
        if _name and _email and _password:

            # All Good, let's call MySQL

            conn = mysql.connect()
            cursor = conn.cursor()
            _hashed_password = generate_password_hash(_password)
            cursor.callproc('sp_createUser',(_name,_email,_hashed_password))
            data = cursor.fetchall()

            if len(data) is 0:
                conn.commit()
                return json.dumps({'message':'User created successfully !'})
            else:
                return json.dumps({'error':str(data[0])})
        else:
            return json.dumps({'html':'<span>Enter the required fields</span>'})

    except Exception as e:
        return json.dumps({'error':str(e)})
    finally:
        cursor.close()
        conn.close()

if __name__ == "__main__":
    app.run(port=5002)

    enter code here
</code>```

Signup.html

```<code><!DOCTYPE html>
<html lang="en">
  <head>
    <title>Python Flask Bucket List App</title>

    <link href="http://getbootstrap.com/dist/css/bootstrap.min.css" rel="stylesheet">

    <link href="http://getbootstrap.com/examples/jumbotron-narrow/jumbotron-narrow.css" rel="stylesheet">
    <link href="../static/css/signup.css" rel="stylesheet">
    <script src="../static/js/jquery-1.11.2.js"></script>
    <script src="../static/js/signUp.js"></script>

  </head>

  <body>

    <div class="container">
      <div class="header">
        <nav>
          <ul class="nav nav-pills pull-right">
            <li role="presentation" ><a href="showHome">Home</a></li>
            <li role="presentation"><a href="#">Sign In</a></li>
            <li role="presentation" class="active"><a href="#">Sign Up</a></li>
          </ul>
        </nav>
        <h3 class="text-muted">Python Flask App</h3>
      </div>

      <div class="jumbotron">
        <h1>Bucket List App</h1>
        <form class="form-signin">
        <label for="inputName" class="sr-only">Name</label>
        <input type="name" name="inputName" id="inputName" class="form-control" placeholder="Name" required autofocus>
        <label for="inputEmail" class="sr-only">Email address</label>
        <input type="email" name="inputEmail" id="inputEmail" class="form-control" placeholder="Email address" required autofocus>
        <label for="inputPassword" class="sr-only">Password</label>
        <input type="password" name="inputPassword" id="inputPassword" class="form-control" placeholder="Password" required>

        <button id="btnSignUp" class="btn btn-lg btn-primary btn-block" type="button">Sign up</button>
      </form>
      </div>

      <footer class="footer">
        <p>© Company 2015</p>
      </footer>

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

signUp.js

```<code>$(function(){
    $('#btnSignUp').click(function(){

        $.ajax({
            url: '/signUp',
            data: $('form').serialize(),
            type: 'POST',
            success: function(response){
                console.log(response);
            },
            error: function(error){
                console.log(error);
            }
        });
    });
});
</code>```

答:
You can try it like that.</p>

```<code>def signUp():
    try:
        _name = request.form['inputName']
        _email = request.form['inputEmail']
        _password = request.form['inputPassword']

        # validate the received values
        if _name and _email and _password:

            # All Good, let's call the MySQL

            with closing(mysql.connect()) as conn:
                with closing(conn.cursor()) as cursor:
                    _hashed_password = generate_password_hash(_password)
                    cursor.callproc('sp_createUser',(_name,_email,_hashed_password))
                    data = cursor.fetchall()

                    if len(data) is 0:
                        conn.commit()
                        return json.dumps({'message':'User created successfully !'})
                    else:
                        return json.dumps({'error':str(data[0])})
        else:
            return json.dumps({'html':'<span>Enter the required fields</span>'})
</code>```

Body:
I'm trying to get my app.py to link with MySQL database but I keep getting the following errors shown below.  The link to my repository is here: https://github.com/trhubwork/python-mysql-proj.git

I'm running python 3.5.1

Console Errors:

jquery-1.11.2.js:9659 POST [runningonlocalhost]/signUp 500 (INTERNAL
  SERVER ERROR)send @ jquery-1.11.2.js:9659ajax @
  jquery-1.11.2.js:9210(anonymous function) @ signUp.js:4dispatch @
  jquery-1.11.2.js:4665elemData.handle @ jquery-1.11.2.js:4333
  signUp.js:12 Object {readyState: 4, responseText: "↵", status: 500, statusText: "INTERNAL SERVER ERROR"}

Gitbash terminal Errors:

Running on [localhost]:5002/ (Press CTRL+C to quit)
  127.0.0.1 - - [29/Sep/2016 22:06:17] "GET / HTTP/1.1" 200 -
  127.0.0.1 - - [29/Sep/2016 22:06:20] "GET /showSignUp HTTP/1.1" 200 - [2016-09-29 22:06:22,142] ERROR in app: Exception on /signUp [POST]
  Traceback (most recent call last):   File
  "C:\Users\TR\AppData\Local\Programs\Python\Python35-32\lib\site-packages\flask\app.py",
  line 1988, in wsgi_app
  response = self.full_dispatch_request()   File "C:\Users\TR\AppData\Local\Programs\Python\Python35-32\lib\site-packages\flask\app.py",
  line 1641, in full_dispatch_request
  rv = self.handle_user_exception(e)   File "C:\Users\TR\AppData\Local\Programs\Python\Python35-32\lib\site-packages\flask\app.py",
  line 1544, in handle_user_exception
  reraise(exc_type, exc_value, tb)   File "C:\Users\TR\AppData\Local\Programs\Python\Python35-32\lib\site-packages\flask_compat.py",
  line 33, in reraise
  raise value   File "C:\Users\TR\AppData\Local\Programs\Python\Python35-32\lib\site-packages\flask\app.py",
  line 1639, in full_dispatch_request
  rv = self.dispatch_request()   File "C:\Users\TR\AppData\Local\Programs\Python\Python35-32\lib\site-packages\flask\app.py",
  line 1625, in dispatch_request
  return self.view_functionsrule.endpoint   File "app.py", line 54, in signUp
  cursor.close() UnboundLocalError: local variable 'cursor' referenced before assignment
  127.0.0.1 - - [29/Sep/2016 22:06:22] "POST /signUp HTTP/1.1" 500 - [2016-09-29 22:09:03,808] ERROR in app: Exception on /signUp [POST]
  Traceback (most recent call last):   File
  "C:\Users\TR\AppData\Local\Programs\Python\Python35-32\lib\site-packages\flask\app.py",
  line 1988, in wsgi_app
  response = self.full_dispatch_request()   File "C:\Users\TR\AppData\Local\Programs\Python\Python35-32\lib\site-packages\flask\app.py",
  line 1641, in full_dispatch_request
  rv = self.handle_user_exception(e)   File "C:\Users\TR\AppData\Local\Programs\Python\Python35-32\lib\site-packages\flask\app.py",
  line 1544, in handle_user_exception
  reraise(exc_type, exc_value, tb)   File "C:\Users\TR\AppData\Local\Programs\Python\Python35-32\lib\site-packages\flask_compat.py",
  line 33, in reraise
  raise value   File "C:\Users\TR\AppData\Local\Programs\Python\Python35-32\lib\site-packages\flask\app.py",
  line 1639, in full_dispatch_request
  rv = self.dispatch_request()   File "C:\Users\TR\AppData\Local\Programs\Python\Python35-32\lib\site-packages\flask\app.py",
  line 1625, in dispatch_request
  return self.view_functionsrule.endpoint   File "app.py", line 54, in signUp
  cursor.close() UnboundLocalError: local variable 'cursor' referenced before assignment
  127.0.0.1 - - [29/Sep/2016 22:09:03] "POST /signUp HTTP/1.1" 500 -

This is my app.py

from flask import Flask, render_template, json, request
from flaskext.mysql import MySQL
from werkzeug import generate_password_hash, check_password_hash

mysql = MySQL()
app = Flask(__name__)

# MySQL configurations
app.config['MYSQL_DATABASE_USER'] = 'jay'
app.config['MYSQL_DATABASE_PASSWORD'] = 'jay'
app.config['MYSQL_DATABASE_DB'] = 'BucketList'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
mysql.init_app(app)

@app.route('/')
def main():
    return render_template('index.html')

@app.route('/showSignUp')
def showSignUp():
    return render_template('signup.html')

@app.route('/signUp',methods=['POST','GET'])
def signUp():
    try:
        _name = request.form['inputName']
        _email = request.form['inputEmail']
        _password = request.form['inputPassword']

        # validate the received values
        if _name and _email and _password:

            # All Good, let's call MySQL

            conn = mysql.connect()
            cursor = conn.cursor()
            _hashed_password = generate_password_hash(_password)
            cursor.callproc('sp_createUser',(_name,_email,_hashed_password))
            data = cursor.fetchall()

            if len(data) is 0:
                conn.commit()
                return json.dumps({'message':'User created successfully !'})
            else:
                return json.dumps({'error':str(data[0])})
        else:
            return json.dumps({'html':'Enter the required fields'})

    except Exception as e:
        return json.dumps({'error':str(e)})
    finally:
        cursor.close()
        conn.close()

if __name__ == "__main__":
    app.run(port=5002)

    enter code here

Signup.html

<!DOCTYPE html>

    <title>Python Flask Bucket List App</title>

    <link href="http://getbootstrap.com/dist/css/bootstrap.min.css" rel="stylesheet">

    <link href="http://getbootstrap.com/examples/jumbotron-narrow/jumbotron-narrow.css" rel="stylesheet">
    <link href="../static/css/signup.css" rel="stylesheet">

Home

Sign In

Sign Up

Python Flask App

Bucket List App

        <form class="form-signin">
        Name
        <input type="name" name="inputName" id="inputName" class="form-control" placeholder="Name" required autofocus>
        Email address
        <input type="email" name="inputEmail" id="inputEmail" class="form-control" placeholder="Email address" required autofocus>
        Password
        <input type="password" name="inputPassword" id="inputPassword" class="form-control" placeholder="Password" required>

        <button id="btnSignUp" class="btn btn-lg btn-primary btn-block" type="button">Sign up</button>
      </form>

© Company 2015

signUp.js

$(function(){
    $('#btnSignUp').click(function(){

        $.ajax({
            url: '/signUp',
            data: $('form').serialize(),
            type: 'POST',
            success: function(response){
                console.log(response);
            },
            error: function(error){
                console.log(error);
            }
        });
    });
});

Body:
You can try it like that.

def signUp():
    try:
        _name = request.form['inputName']
        _email = request.form['inputEmail']
        _password = request.form['inputPassword']

        # validate the received values
        if _name and _email and _password:

            # All Good, let's call the MySQL

            with closing(mysql.connect()) as conn:
                with closing(conn.cursor()) as cursor:
                    _hashed_password = generate_password_hash(_password)
                    cursor.callproc('sp_createUser',(_name,_email,_hashed_password))
                    data = cursor.fetchall()

                    if len(data) is 0:
                        conn.commit()
                        return json.dumps({'message':'User created successfully !'})
                    else:
                        return json.dumps({'error':str(data[0])})
        else:
            return json.dumps({'html':'<span>Enter the required fields</span>'})


问:
How do I determine the category with the highest count within a group?
```<code>select substr(shopabb, 1, 4) as shopgroup, count(*)
from table
where shopabb like'h%'
group by substr(shoppabb, 1, 4)
order by count(*) DESC;
</code>```

I'm counting all the shop abbreviations from my table in substring groups. I have another column called city that shows where the shop abbreviations are located. Now I also want to select/show the city where the substring group most often occurs and if possible also the count of the shopabb in this city. The result should look like that:

```<code>    shopabb   Count(*)   City      Count_City
    -----------------------------------------
   hel         50         London    40
   heal        20         Berlin    15
   hot         10         Rome       8
</code>```

Thanks!

答:
Use row_number() with two levels of aggregation:

```<code>select shopgroup, sum(cnt) as total_count,
       max(case when seqnum = 1 then city end) as city_with_max,
       max(case when seqnum = 1 then cnt end) as cnt_at_max
from (select substr(shopabb, 1, 4) as shopgroup, city, count(*) as cnt,
             row_number() over (partition by substr(shopabb, 1, 4) order by count(*) desc) as seqnum
      from table
      where shopabb like'h%'
      group by substr(shopabb, 1, 4), city
     ) t
group by shopgroup
order by sum(cnt) DESC;
</code>```

Here is a db<>fiddle illustrating that the syntax works.

EDIT:

You can do this without window functions, but it is much more cumbersome:

```<code>select substr(shopabb, 1, 4) as shopgroup, city, count(*) as cnt
from table t
where shopabb like'h%'
group by substr(shoppabb, 1, 4), city
having count(*) = (select count(*)
                   from table t2
                   where substr(t2.shopabb, 1, 4) = substr(t.shopabb, 1, 4)
                   group by city
                   order by count(*) desc
                   limit 1
                  );
</code>```

Note that this will return duplicates if two cities ties for the max.  It requires a bit more work to get the overall total as well.

Body:
select substr(shopabb, 1, 4) as shopgroup, count(*)
from table
where shopabb like'h%'
group by substr(shoppabb, 1, 4)
order by count(*) DESC;

I'm counting all the shop abbreviations from my table in substring groups. I have another column called city that shows where the shop abbreviations are located. Now I also want to select/show the city where the substring group most often occurs and if possible also the count of the shopabb in this city. The result should look like that:

    shopabb   Count(*)   City      Count_City
    -----------------------------------------
   hel         50         London    40
   heal        20         Berlin    15
   hot         10         Rome       8

Thanks!

Body:
Use row_number() with two levels of aggregation:

select shopgroup, sum(cnt) as total_count,
       max(case when seqnum = 1 then city end) as city_with_max,
       max(case when seqnum = 1 then cnt end) as cnt_at_max
from (select substr(shopabb, 1, 4) as shopgroup, city, count(*) as cnt,
             row_number() over (partition by substr(shopabb, 1, 4) order by count(*) desc) as seqnum
      from table
      where shopabb like'h%'
      group by substr(shopabb, 1, 4), city
     ) t
group by shopgroup
order by sum(cnt) DESC;

Here is a db<>fiddle illustrating that the syntax works.

EDIT:

You can do this without window functions, but it is much more cumbersome:

select substr(shopabb, 1, 4) as shopgroup, city, count(*) as cnt
from table t
where shopabb like'h%'
group by substr(shoppabb, 1, 4), city
having count(*) = (select count(*)
                   from table t2
                   where substr(t2.shopabb, 1, 4) = substr(t.shopabb, 1, 4)
                   group by city
                   order by count(*) desc
                   limit 1
                  );

Note that this will return duplicates if two cities ties for the max.  It requires a bit more work to get the overall total as well.


问:
Melting in pandas loses index
I have the following dataframe:

```<code>        Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
Year
2010    9.8 9.8 9.9 9.9 9.6 9.4 9.4 9.5 9.5 9.4 9.8 9.3
2011    9.1 9.0 9.0 9.1 9.0 9.1 9.0 9.0 9.0 8.8 8.6 8.5
2012    8.3 8.3 8.2 8.2 8.2 8.2 8.2 8.1 7.8 7.8 7.7 7.9
</code>```

I want to achieve the following result:

```<code>      Month Values
Year
2010  Jan    9.8
2010  Feb    9.8
2010  Mar    9.9
etc......
</code>```

I tried the method proposed here:
pandas, melt, unmelt preserve index:

```<code>df = pd.melt(df.reset_index(), id_vars='index',value_vars=months)
</code>```

"Months" is a list I created from by getting a list of column names for the months:

```<code>months = df.columns.values.tolist()[1:]
</code>```

However, the result was:

```<code>       index variable  value
   0    NaN   Jan      9.8
   1    NaN   Jan      9.1
   2    NaN   Jan      8.3
   3    NaN   Jan      8.0
   4    NaN   Jan      6.6
</code>```

So, I want to retain the year value as the index. How can I do this?
Thanks.

答:
With melt:

```<code>df.reset_index().melt('Year',var_name='Month',value_name='Values').set_index('Year')

    Month  Values
Year
2010   Jan     9.8
2011   Jan     9.1
2012   Jan     8.3
2010   Feb     9.8
2011   Feb     9.0
.........
.......
</code>```

With stack():

```<code>df.rename_axis('Month',axis=1).stack().reset_index(1,name='Values')

      Month  Values
Year
2010   Jan     9.8
2010   Feb     9.8
2010   Mar     9.9
2010   Apr     9.9
2010   May     9.6
2010   Jun     9.4
.......
......
</code>```

Title: Melting in pandas loses index

Body:
I have the following dataframe:

        Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
Year
2010    9.8 9.8 9.9 9.9 9.6 9.4 9.4 9.5 9.5 9.4 9.8 9.3
2011    9.1 9.0 9.0 9.1 9.0 9.1 9.0 9.0 9.0 8.8 8.6 8.5
2012    8.3 8.3 8.2 8.2 8.2 8.2 8.2 8.1 7.8 7.8 7.7 7.9

I want to achieve the following result:

      Month Values
Year
2010  Jan    9.8
2010  Feb    9.8
2010  Mar    9.9
etc......

I tried the method proposed here:
pandas, melt, unmelt preserve index:

df = pd.melt(df.reset_index(), id_vars='index',value_vars=months)

"Months" is a list I created from by getting a list of column names for the months:

months = df.columns.values.tolist()[1:]

However, the result was:

       index variable  value
   0    NaN   Jan      9.8
   1    NaN   Jan      9.1
   2    NaN   Jan      8.3
   3    NaN   Jan      8.0
   4    NaN   Jan      6.6

So, I want to retain the year value as the index. How can I do this?
Thanks.

Body:
With melt:

df.reset_index().melt('Year',var_name='Month',value_name='Values').set_index('Year')

    Month  Values
Year
2010   Jan     9.8
2011   Jan     9.1
2012   Jan     8.3
2010   Feb     9.8
2011   Feb     9.0
.........
.......

With stack():

df.rename_axis('Month',axis=1).stack().reset_index(1,name='Values')

      Month  Values
Year
2010   Jan     9.8
2010   Feb     9.8
2010   Mar     9.9
2010   Apr     9.9
2010   May     9.6
2010   Jun     9.4
.......
......


问:
returning the 2nd letter in a string in a list and sorted the words by it. keep getting indexing range out of bound. Python
I am working on an assignment with the below requirements:

You will be sorting the following list by each element’s second letter, a to z. Create a function to use when sorting, called second_let. It will take a string as input and return the second letter of that string. Then sort the list, create a variable called sorted_by_second_let and assign the sorted list to it.

This is my code:

```<code>ex_lst = ['hi', 'how are you', 'bye', 'apple', 'zebra', 'dance']

def second_let(x):

    lst= []
    for wrd in x:
        lst.append(wrd[1])
    return lst

print(second_let(ex_lst))
print(sorted(second_let(ex_lst)))

sorted_by_second_let= sorted(ex_lst, key= second_let)

</code>```

I keep getting this error:

IndexError: string index out of range on line 7, which is the lst.append(wrd[1]). what am I doing wrong? how can I do it better?

Thank you.

答:
It depends on how sorted works when it has a key parameter that takes a function as value:

ex_lst = ['hi', 'how are you', 'bye', 'apple', 'zebra', 'dance']

def second_let(x):
    return x[1]

sorted_by_second_let = sorted(ex_lst, key=second_let)
```

The sorted function loops through each item of the list when it is used like this. That is why there is no need for a for loop.

Body:
I am working on an assignment with the below requirements:

You will be sorting the following list by each element’s second letter, a to z. Create a function to use when sorting, called second_let. It will take a string as input and return the second letter of that string. Then sort the list, create a variable called sorted_by_second_let and assign the sorted list to it.

This is my code:

ex_lst = ['hi', 'how are you', 'bye', 'apple', 'zebra', 'dance']

def second_let(x):

    lst= []
    for wrd in x:
        lst.append(wrd[1])
    return lst

print(second_let(ex_lst))
print(sorted(second_let(ex_lst)))

sorted_by_second_let= sorted(ex_lst, key= second_let)

I keep getting this error:

IndexError: string index out of range on line 7, which is the lst.append(wrd[1]). what am I doing wrong? how can I do it better?

Thank you.

Body:
It depends on how sorted works when it has a key parameter that takes a function as value:

ex_lst = ['hi', 'how are you', 'bye', 'apple', 'zebra', 'dance']

def second_let(x):
    return x[1]

sorted_by_second_let = sorted(ex_lst, key=second_let)

The sorted function loops through each item of the list when it is used like this. That is why there is no need for a for loop.


问:
convert one string type to another string type
I have two string types. I'm string to convert one string to another string type. This doesn't work and fails on the nextT = nextS assignment. Why? They both have an underlying string type. Thanks.

```<code>package main

import (
    "fmt"
    "reflect"
)

type TFirstType string
type TSecondType string

func main() {
    var firstT TFirstType
    firstT = "asdf"

    var secondT = fmt.Sprintf("%s", firstT )

    nextS := secondT
    fmt.Println(reflect.TypeOf(nextS))

    var nextT TSecondType
    nextT = nextS
}

func (c TFirstType ) String() string {
    return string(c)
}
</code>```

Example: https://play.golang.org/p/DwEY6hWacVA

答:
This wasn't obvious to, and I'm going to have to read a lot more to figure it out.JimB, Adrian, and Abu each helped. This worked...</p>

```<code>package main

import (
    "fmt"
    "reflect"
)

type TFirstType string
type TSecondType string

func main() {
    var firstT TFirstType
    firstT = "asdf"

    var secondT = fmt.Sprintf("%s", firstT )

    nextS := secondT
    fmt.Println(reflect.TypeOf(nextS))

    var nextT TSecondType
    nextT = TSecondType(nextS)
    fmt.Println(nextT)
}

func (c TFirstType ) String() string {
    return string(c)
}
</code>```

Body:
I have two string types. I'm string to convert one string to another string type. This doesn't work and fails on the nextT = nextS assignment. Why? They both have an underlying string type. Thanks.

package main

import (
    "fmt"
    "reflect"
)

type TFirstType string
type TSecondType string

func main() {
    var firstT TFirstType
    firstT = "asdf"

    var secondT = fmt.Sprintf("%s", firstT )

    nextS := secondT
    fmt.Println(reflect.TypeOf(nextS))

    var nextT TSecondType
    nextT = nextS
}

func (c TFirstType ) String() string {
    return string(c)
}

Example: https://play.golang.org/p/DwEY6hWacVA

Body:
This wasn't obvious to, and I'm going to have to read a lot more to figure it out.JimB, Adrian, and Abu each helped. This worked...

package main

import (
    "fmt"
    "reflect"
)

type TFirstType string
type TSecondType string

func main() {
    var firstT TFirstType
    firstT = "asdf"

    var secondT = fmt.Sprintf("%s", firstT )

    nextS := secondT
    fmt.Println(reflect.TypeOf(nextS))

    var nextT TSecondType
    nextT = TSecondType(nextS)
    fmt.Println(nextT)
}

func (c TFirstType ) String() string {
    return string(c)
}


问:
How to pass default for named parameters in javascript
I have a method in typescript as below using named parameters

```<code>public foo({x, y, z , m , n} : {x:string, y: number, z: number, m?:string, n?:number}) {
}
</code>```

parameters m and n will be provided from another object like

```<code>const default = { m : 'M', n :10, o:6 }
</code>```

Now I want to call foo like below and I want default parameters will be added without explicitly passing them in the call

```<code>  foo({x:'x', y: 5, z: 0})
</code>```

So my question is how to apply default in the body of foo or somehow intercepting foo before call and apply default

```<code>public foo({x, y, z , m , n} = {x:string, y: number, z: number, m?:string, n?:number}) {
   // for example how to apply default here

}
</code>```

Please note for simplicity I reduced number of parameters

Also I know these below solutions already I am looking for something with less boilerplate code

```<code>public foo({x, y, z , m , n} = {x:string, y: number, z: number, m?:string, n?:number}) {
   if (!m) {
     m = default.m;
   }
   if (!n) {
     n = default.n;
   }

}
</code>```

or

```<code>foo({...default, x:'x', y: 5, z: 0 });
</code>```

答:
How about combining and destructing object inside function?

type someType = {x:string, y: number, z: number, m?:string, n?:number};
const initialValues = { m : 'M', n :10, o:6 }

function foo(obj: someType) {
  const {x, y, z , m , n} = {
    ...initialValues,
    ...obj
  }

}
```

Body:
I have a method in typescript as below using named parameters

public foo({x, y, z , m , n} : {x:string, y: number, z: number, m?:string, n?:number}) {
}

parameters m and n will be provided from another object like

const default = { m : 'M', n :10, o:6 }

Now I want to call foo like below and I want default parameters will be added without explicitly passing them in the call

  foo({x:'x', y: 5, z: 0})

So my question is how to apply default in the body of foo or somehow intercepting foo before call and apply default

public foo({x, y, z , m , n} = {x:string, y: number, z: number, m?:string, n?:number}) {
   // for example how to apply default here

}

Please note for simplicity I reduced number of parameters

Also I know these below solutions already I am looking for something with less boilerplate code

public foo({x, y, z , m , n} = {x:string, y: number, z: number, m?:string, n?:number}) {
   if (!m) {
     m = default.m;
   }
   if (!n) {
     n = default.n;
   }

}

or

foo({...default, x:'x', y: 5, z: 0 });


问:
SQLite query that calculates if Unix epoch time occurs on today's date
I have an integer column that holds a Unix epoch time value. I want to calculate if it falls within today.

For example, let today be the 24th day in the month. The query should return rows that fall on the 24th, but not ones that fall on the 23rd or some time before that.

Thanks for looking.

答:
With MySQL Try:</p>

```<code>SELECT *
FROM yourTable
WHERE DATE(FROM_UNIXTIME(yourUnixEpochField)) = DATE(NOW());
</code>```

ContentLicense: CC BY-SA 2.5

Body:
With MySQL Try:

SELECT *
FROM yourTable
WHERE DATE(FROM_UNIXTIME(yourUnixEpochField)) = DATE(NOW());