问:
python pandas: transform start and end datetime range (stored as 2 columns) to individual rows (eqpt utilisation)
Hi I have a data set like below df.. I am providing the image and sample dataframe separately.

I want to transform the original dataframe (df) to transformed dataframe (dft) so that I can see the utilisation of each equipment for a 24 hour period (or even longer periods upto 9 days)... at 5 minute intervals. The dft can then be used for plotting... tooltip of the description, etc.

surely, also if you have any alternative simpler solution as opposed to my outline below can also be great too.

Original Dataframe (df)

Here is the above dataframe (df) which you can copy paste to jupyter to create it:

```<code>from io import StringIO
import pandas as pd

dfstr = StringIO(u"""
eqpt;starttm;endtm;use_count;desc
AT1;2017-04-01 10:35;2017-04-01 11:05;2;test asdf1
AT2;2017-04-01 11:00;2017-04-01 11:30;5;test asdf2
AT1;2017-04-01 11:00;2017-04-01 11:30;4;test asdf3
AT3;2017-04-01 10:45;2017-04-01 11:45;3;test asdf4
CBL1;2017-04-01 11:10;2017-04-1 11:40;4;test asdf5
""")
df = pd.read_csv(dfstr, sep=";")
df
</code>```

I want to transform df to individual rows for each eqpt... with say starttime and endtime from 2017-04-01 00:00 to 23:55 so that I can know the equipment utilisation in each 5 minute grid as well as for plotting and resampling to say maximum in each 1 hour for summary, etc.

Transformed Dataframe (dft)

Here is the resulting transformed image.. and a sample result dataframe (dft) follows:

columns for this dataframe comes from 'eqpt' of the original dataframe.

just realized that the description column cannot be in the same dataframe dft if need to keep the use_counts aggregate a number only. Thus, please provide any alternate solution that can achieve the same purpose but keeping the columns as float for counts only and description text aggregate elsewhere.. and later can be merged or looked up.

Here is the above dataframe (dft):

```<code>dftstr = StringIO(u"""
datetime;Item;AT1;AT2;AT3;CBL1;AT_n
2017-04-01 10:30;use_count;;;;;
2017-04-01 10:35;use_count;2;;;;
2017-04-01 10:40;use_count;2;;;;
2017-04-01 10:45;use_count;2;;3;;
2017-04-01 10:50;use_count;2;;3;;
2017-04-01 10:55;use_count;2;;3;;
2017-04-01 11:00;use_count;6;5;3;;
2017-04-01 11:05;use_count;4;5;3;;
2017-04-01 11:10;use_count;4;5;3;4;
2017-04-01 11:15;use_count;4;5;3;4;
2017-04-01 11:20;use_count;4;5;3;4;
2017-04-01 11:25;use_count;4;5;3;4;
2017-04-01 11:30;use_count;;;3;4;
2017-04-01 11:35;use_count;;;3;4;
2017-04-01 11:40;use_count;;;3;;
2017-04-01 11:45;use_count;;;;;
2017-04-01 11:50;use_count;;;;;
2017-04-01 11:55;use_count;;;;;
2017-04-01 12:00;use_count;;;;;
2017-04-01 10:30;desc;;;;;
2017-04-01 10:35;desc;2: test_adf1;similar desc;;;
2017-04-01 10:40;desc;2: test_adf1;for;;;
2017-04-01 10:45;desc;2: test_adf1;the;;;
2017-04-01 10:50;desc;2: test_adf1;rest;;;
2017-04-01 10:55;desc;2: test_adf1;of;;;
2017-04-01 11:00;desc;"2: test_asdf1
4: test_asdf3";the;;;
2017-04-01 11:05;desc;4: test_asdf3;columns;;;
2017-04-01 11:10;desc;4: test_asdf3;;;;
2017-04-01 11:15;desc;4: test_asdf3;;;;
2017-04-01 11:20;desc;4: test_asdf3;;;;
2017-04-01 11:25;desc;4: test_asdf3;;;;
2017-04-01 11:30;desc;;;;;
2017-04-01 11:35;desc;;;;;
2017-04-01 11:40;desc;;;;;
2017-04-01 11:45;desc;;;;;
2017-04-01 11:50;desc;;;;;
2017-04-01 11:55;desc;;;;;
2017-04-01 12:00;desc;;;;;
;;and so on from 00:00 to  23:55;;;;
""")
dft = pd.read_csv(dftstr, sep=";")
dft
</code>```

答:
There are several steps required here. I used your setup but converted the timestamps to pandas date time objects right away via parse_dates:

```<code>from io import StringIO
import pandas as pd

dfstr = StringIO(u"""
eqpt;starttm;endtm;use_count;desc
AT1;2017-04-01 10:35;2017-04-01 11:05;2;test asdf1
AT2;2017-04-01 11:00;2017-04-01 11:30;5;test asdf2
AT1;2017-04-01 11:00;2017-04-01 11:30;4;test asdf3
AT3;2017-04-01 10:45;2017-04-01 11:45;3;test asdf4
CBL1;2017-04-01 11:10;2017-04-1 11:40;4;test asdf5
""")

df = pd.read_csv(dfstr, sep=";", parse_dates=["starttm", "endtm"])
print(df)

    eqpt    starttm                 endtm                   use_count       desc
0   AT1     2017-04-01 10:35:00     2017-04-01 11:05:00     2         test asdf1
1   AT2     2017-04-01 11:00:00     2017-04-01 11:30:00     5         test asdf2
2   AT1     2017-04-01 11:00:00     2017-04-01 11:30:00     4         test asdf3
3   AT3     2017-04-01 10:45:00     2017-04-01 11:45:00     3         test asdf4
4   CBL1    2017-04-01 11:10:00     2017-04-01 11:40:00     4         test asdf5
</code>```

Now, there are 3 functions here which do the job:

expand takes a single row of the input df and creates a data frame with a DatetimeIndex ranging from starttm to endtm with 5 minute intervals. In addition, the actual use_count and desc values are added.

summarize takes care of overlaps while combining desc strings and summing use_counts when an equipment is used multiple times simultaneously. It has to type check because the input may either be a pandas Series or DataFrame. If only a single row is given for a single equipment, a Series gets passed. Otherwise, a DataFrame is passed.

aggregate combines expand and summarize. First, all entries (rows) for a single equipment are expanded and concatenated. Then, expanded columns are summarized.

That's it. Finally, you use groupby to group the equipments and apply the aggregate function:

```<code>def expand(row):
    index = pd.date_range(row["starttm"], row["endtm"], freq="5min")
    use_count=row["use_count"]
    desc= "{}:{}".format(use_count, row["desc"])

    return pd.DataFrame(index=index).assign(use_count=use_count, desc=desc)

def summarize(index, use_count, desc):
    if isinstance(use_count, pd.DataFrame):
        use_count = use_count.sum(axis=1)

    if isinstance(desc, pd.DataFrame):
        desc = desc.apply(lambda x: ", ".join(x.dropna()), axis=1)

    return pd.DataFrame({"use_count": use_count, "desc": desc}, index=index)

def aggregate(sub_df):
    dfs = pd.concat([expand(series) for idx, series in sub_df.iterrows()], axis=1)
    return summarize(dfs.index, dfs["use_count"], dfs["desc"])

transformed = df.groupby("eqpt").apply(aggregate).unstack("eqpt")
</code>```

The resulting data frame has multiindex columns to distinguish desc and use_counts allowing for correct dtypes:

```<code>print(transformed["use_count"])

eqpt                 AT1  AT2  AT3  CBL1
2017-04-01 10:35:00  2.0  NaN  NaN   NaN
2017-04-01 10:40:00  2.0  NaN  NaN   NaN
2017-04-01 10:45:00  2.0  NaN  3.0   NaN
2017-04-01 10:50:00  2.0  NaN  3.0   NaN
2017-04-01 10:55:00  2.0  NaN  3.0   NaN
2017-04-01 11:00:00  6.0  5.0  3.0   NaN
2017-04-01 11:05:00  6.0  5.0  3.0   NaN
2017-04-01 11:10:00  4.0  5.0  3.0   4.0
2017-04-01 11:15:00  4.0  5.0  3.0   4.0
2017-04-01 11:20:00  4.0  5.0  3.0   4.0
2017-04-01 11:25:00  4.0  5.0  3.0   4.0
2017-04-01 11:30:00  4.0  5.0  3.0   4.0
2017-04-01 11:35:00  NaN  NaN  3.0   4.0
2017-04-01 11:40:00  NaN  NaN  3.0   4.0
2017-04-01 11:45:00  NaN  NaN  3.0   NaN

print(transformed)

                        desc                                                                        use_count
eqpt                    AT1                         AT2             AT3             CBL1            AT1     AT2     AT3     CBL1
2017-04-01 10:35:00     2:test asdf1                None            None            None            2.0     NaN     NaN     NaN
2017-04-01 10:40:00     2:test asdf1                None            None            None            2.0     NaN     NaN     NaN
2017-04-01 10:45:00     2:test asdf1                None            3:test asdf4    None            2.0     NaN     3.0     NaN
2017-04-01 10:50:00     2:test asdf1                None            3:test asdf4    None            2.0     NaN     3.0     NaN
2017-04-01 10:55:00     2:test asdf1                None            3:test asdf4    None            2.0     NaN     3.0     NaN
2017-04-01 11:00:00     2:test asdf1, 4:test asdf3  5:test asdf2    3:test asdf4    None            6.0     5.0     3.0     NaN
2017-04-01 11:05:00     2:test asdf1, 4:test asdf3  5:test asdf2    3:test asdf4    None            6.0     5.0     3.0     NaN
2017-04-01 11:10:00     4:test asdf3                5:test asdf2    3:test asdf4    4:test asdf5    4.0     5.0     3.0     4.0
2017-04-01 11:15:00     4:test asdf3                5:test asdf2    3:test asdf4    4:test asdf5    4.0     5.0     3.0     4.0
2017-04-01 11:20:00     4:test asdf3                5:test asdf2    3:test asdf4    4:test asdf5    4.0     5.0     3.0     4.0
2017-04-01 11:25:00     4:test asdf3                5:test asdf2    3:test asdf4    4:test asdf5    4.0     5.0     3.0     4.0
2017-04-01 11:30:00     4:test asdf3                5:test asdf2    3:test asdf4    4:test asdf5    4.0     5.0     3.0     4.0
2017-04-01 11:35:00     None                        None            3:test asdf4    4:test asdf5    NaN     NaN     3.0     4.0
2017-04-01 11:40:00     None                        None            3:test asdf4    4:test asdf5    NaN     NaN     3.0     4.0
2017-04-01 11:45:00     None                        None            3:test asdf4    None            NaN     NaN     3.0     NaN
</code>```

To span the date time index for the entire day, you can use reindex:

```<code>transformed.reindex(pd.date_range("2017-04-01 00:00", "2017-04-01 23:55", freq="5min"))
</code>```

Body:
Hi I have a data set like below df.. I am providing the image and sample dataframe separately.

I want to transform the original dataframe (df) to transformed dataframe (dft) so that I can see the utilisation of each equipment for a 24 hour period (or even longer periods upto 9 days)... at 5 minute intervals. The dft can then be used for plotting... tooltip of the description, etc.

surely, also if you have any alternative simpler solution as opposed to my outline below can also be great too.

Original Dataframe (df)

Here is the above dataframe (df) which you can copy paste to jupyter to create it:

from io import StringIO
import pandas as pd

dfstr = StringIO(u"""
eqpt;starttm;endtm;use_count;desc
AT1;2017-04-01 10:35;2017-04-01 11:05;2;test asdf1
AT2;2017-04-01 11:00;2017-04-01 11:30;5;test asdf2
AT1;2017-04-01 11:00;2017-04-01 11:30;4;test asdf3
AT3;2017-04-01 10:45;2017-04-01 11:45;3;test asdf4
CBL1;2017-04-01 11:10;2017-04-1 11:40;4;test asdf5
""")
df = pd.read_csv(dfstr, sep=";")
df

I want to transform df to individual rows for each eqpt... with say starttime and endtime from 2017-04-01 00:00 to 23:55 so that I can know the equipment utilisation in each 5 minute grid as well as for plotting and resampling to say maximum in each 1 hour for summary, etc.

Transformed Dataframe (dft)

Here is the resulting transformed image.. and a sample result dataframe (dft) follows:

columns for this dataframe comes from 'eqpt' of the original dataframe.

just realized that the description column cannot be in the same dataframe dft if need to keep the use_counts aggregate a number only. Thus, please provide any alternate solution that can achieve the same purpose but keeping the columns as float for counts only and description text aggregate elsewhere.. and later can be merged or looked up.

Here is the above dataframe (dft):

dftstr = StringIO(u"""
datetime;Item;AT1;AT2;AT3;CBL1;AT_n
2017-04-01 10:30;use_count;;;;;
2017-04-01 10:35;use_count;2;;;;
2017-04-01 10:40;use_count;2;;;;
2017-04-01 10:45;use_count;2;;3;;
2017-04-01 10:50;use_count;2;;3;;
2017-04-01 10:55;use_count;2;;3;;
2017-04-01 11:00;use_count;6;5;3;;
2017-04-01 11:05;use_count;4;5;3;;
2017-04-01 11:10;use_count;4;5;3;4;
2017-04-01 11:15;use_count;4;5;3;4;
2017-04-01 11:20;use_count;4;5;3;4;
2017-04-01 11:25;use_count;4;5;3;4;
2017-04-01 11:30;use_count;;;3;4;
2017-04-01 11:35;use_count;;;3;4;
2017-04-01 11:40;use_count;;;3;;
2017-04-01 11:45;use_count;;;;;
2017-04-01 11:50;use_count;;;;;
2017-04-01 11:55;use_count;;;;;
2017-04-01 12:00;use_count;;;;;
2017-04-01 10:30;desc;;;;;
2017-04-01 10:35;desc;2: test_adf1;similar desc;;;
2017-04-01 10:40;desc;2: test_adf1;for;;;
2017-04-01 10:45;desc;2: test_adf1;the;;;
2017-04-01 10:50;desc;2: test_adf1;rest;;;
2017-04-01 10:55;desc;2: test_adf1;of;;;
2017-04-01 11:00;desc;"2: test_asdf1
4: test_asdf3";the;;;
2017-04-01 11:05;desc;4: test_asdf3;columns;;;
2017-04-01 11:10;desc;4: test_asdf3;;;;
2017-04-01 11:15;desc;4: test_asdf3;;;;
2017-04-01 11:20;desc;4: test_asdf3;;;;
2017-04-01 11:25;desc;4: test_asdf3;;;;
2017-04-01 11:30;desc;;;;;
2017-04-01 11:35;desc;;;;;
2017-04-01 11:40;desc;;;;;
2017-04-01 11:45;desc;;;;;
2017-04-01 11:50;desc;;;;;
2017-04-01 11:55;desc;;;;;
2017-04-01 12:00;desc;;;;;
;;and so on from 00:00 to  23:55;;;;
""")
dft = pd.read_csv(dftstr, sep=";")
dft

Body:
There are several steps required here. I used your setup but converted the timestamps to pandas date time objects right away via parse_dates:

from io import StringIO
import pandas as pd

dfstr = StringIO(u"""
eqpt;starttm;endtm;use_count;desc
AT1;2017-04-01 10:35;2017-04-01 11:05;2;test asdf1
AT2;2017-04-01 11:00;2017-04-01 11:30;5;test asdf2
AT1;2017-04-01 11:00;2017-04-01 11:30;4;test asdf3
AT3;2017-04-01 10:45;2017-04-01 11:45;3;test asdf4
CBL1;2017-04-01 11:10;2017-04-1 11:40;4;test asdf5
""")

df = pd.read_csv(dfstr, sep=";", parse_dates=["starttm", "endtm"])
print(df)

    eqpt    starttm                 endtm                   use_count       desc
0   AT1     2017-04-01 10:35:00     2017-04-01 11:05:00     2         test asdf1
1   AT2     2017-04-01 11:00:00     2017-04-01 11:30:00     5         test asdf2
2   AT1     2017-04-01 11:00:00     2017-04-01 11:30:00     4         test asdf3
3   AT3     2017-04-01 10:45:00     2017-04-01 11:45:00     3         test asdf4
4   CBL1    2017-04-01 11:10:00     2017-04-01 11:40:00     4         test asdf5

Now, there are 3 functions here which do the job:

expand takes a single row of the input df and creates a data frame with a DatetimeIndex ranging from starttm to endtm with 5 minute intervals. In addition, the actual use_count and desc values are added.

summarize takes care of overlaps while combining desc strings and summing use_counts when an equipment is used multiple times simultaneously. It has to type check because the input may either be a pandas Series or DataFrame. If only a single row is given for a single equipment, a Series gets passed. Otherwise, a DataFrame is passed.

aggregate combines expand and summarize. First, all entries (rows) for a single equipment are expanded and concatenated. Then, expanded columns are summarized.

That's it. Finally, you use groupby to group the equipments and apply the aggregate function:

def expand(row):
    index = pd.date_range(row["starttm"], row["endtm"], freq="5min")
    use_count=row["use_count"]
    desc= "{}:{}".format(use_count, row["desc"])

    return pd.DataFrame(index=index).assign(use_count=use_count, desc=desc)

def summarize(index, use_count, desc):
    if isinstance(use_count, pd.DataFrame):
        use_count = use_count.sum(axis=1)

    if isinstance(desc, pd.DataFrame):
        desc = desc.apply(lambda x: ", ".join(x.dropna()), axis=1)

    return pd.DataFrame({"use_count": use_count, "desc": desc}, index=index)

def aggregate(sub_df):
    dfs = pd.concat([expand(series) for idx, series in sub_df.iterrows()], axis=1)
    return summarize(dfs.index, dfs["use_count"], dfs["desc"])

transformed = df.groupby("eqpt").apply(aggregate).unstack("eqpt")

The resulting data frame has multiindex columns to distinguish desc and use_counts allowing for correct dtypes:

print(transformed["use_count"])

eqpt                 AT1  AT2  AT3  CBL1
2017-04-01 10:35:00  2.0  NaN  NaN   NaN
2017-04-01 10:40:00  2.0  NaN  NaN   NaN
2017-04-01 10:45:00  2.0  NaN  3.0   NaN
2017-04-01 10:50:00  2.0  NaN  3.0   NaN
2017-04-01 10:55:00  2.0  NaN  3.0   NaN
2017-04-01 11:00:00  6.0  5.0  3.0   NaN
2017-04-01 11:05:00  6.0  5.0  3.0   NaN
2017-04-01 11:10:00  4.0  5.0  3.0   4.0
2017-04-01 11:15:00  4.0  5.0  3.0   4.0
2017-04-01 11:20:00  4.0  5.0  3.0   4.0
2017-04-01 11:25:00  4.0  5.0  3.0   4.0
2017-04-01 11:30:00  4.0  5.0  3.0   4.0
2017-04-01 11:35:00  NaN  NaN  3.0   4.0
2017-04-01 11:40:00  NaN  NaN  3.0   4.0
2017-04-01 11:45:00  NaN  NaN  3.0   NaN

print(transformed)

                        desc                                                                        use_count
eqpt                    AT1                         AT2             AT3             CBL1            AT1     AT2     AT3     CBL1
2017-04-01 10:35:00     2:test asdf1                None            None            None            2.0     NaN     NaN     NaN
2017-04-01 10:40:00     2:test asdf1                None            None            None            2.0     NaN     NaN     NaN
2017-04-01 10:45:00     2:test asdf1                None            3:test asdf4    None            2.0     NaN     3.0     NaN
2017-04-01 10:50:00     2:test asdf1                None            3:test asdf4    None            2.0     NaN     3.0     NaN
2017-04-01 10:55:00     2:test asdf1                None            3:test asdf4    None            2.0     NaN     3.0     NaN
2017-04-01 11:00:00     2:test asdf1, 4:test asdf3  5:test asdf2    3:test asdf4    None            6.0     5.0     3.0     NaN
2017-04-01 11:05:00     2:test asdf1, 4:test asdf3  5:test asdf2    3:test asdf4    None            6.0     5.0     3.0     NaN
2017-04-01 11:10:00     4:test asdf3                5:test asdf2    3:test asdf4    4:test asdf5    4.0     5.0     3.0     4.0
2017-04-01 11:15:00     4:test asdf3                5:test asdf2    3:test asdf4    4:test asdf5    4.0     5.0     3.0     4.0
2017-04-01 11:20:00     4:test asdf3                5:test asdf2    3:test asdf4    4:test asdf5    4.0     5.0     3.0     4.0
2017-04-01 11:25:00     4:test asdf3                5:test asdf2    3:test asdf4    4:test asdf5    4.0     5.0     3.0     4.0
2017-04-01 11:30:00     4:test asdf3                5:test asdf2    3:test asdf4    4:test asdf5    4.0     5.0     3.0     4.0
2017-04-01 11:35:00     None                        None            3:test asdf4    4:test asdf5    NaN     NaN     3.0     4.0
2017-04-01 11:40:00     None                        None            3:test asdf4    4:test asdf5    NaN     NaN     3.0     4.0
2017-04-01 11:45:00     None                        None            3:test asdf4    None            NaN     NaN     3.0     NaN

To span the date time index for the entire day, you can use reindex:

transformed.reindex(pd.date_range("2017-04-01 00:00", "2017-04-01 23:55", freq="5min"))


来源: stackexchange

问:
Authenticating new users through mail?
so I have a table of users in my database in phpmyadmin for a website. This users table has an auto-incremented id, mail, firstname, lastname, hash(for password) and authentication_state. I want to be able to send a mail to new users that includes a link and that link makes authentication_state go from 0(the default value) to 1 wherein he is authenticated. How would I go about doing this?

Thanks in advance.

答:
In the mail you send just include the user id in the link which they will use to go back to your site for authentication. Or you can create some random string instead of using the user id for security and send this string to them in the link. You can create a separate table for these authentication strings and once the user authenticates their account, delete it as you won't need it anymore

Then when they use that link to reach your authentication page, update their authentication_state to 1 and delete the entry of the authentication string from your database in order to keep the database well-maintained and leave only those entries that you will need time and time again.

But provide some code inorder for me to help you further.

ContentLicense: CC BY-SA 3.0

Title: Authenticating new users through mail?


问:
canvas and stage losing global scope in easel.js
Here's the code. At the top, you can see that canvas and stage are declared as global variables. Then the initializeCanvas() function runs on page load and assigns those variables and loads a background image.

Strangely, though, stage and canvas end up undefined.

Why? And what can I do about it?

Roger

```<code>var canvas, stage

function initializeCanvas() {
    canvas = document.getElementById("starCanvas")
    canvas.width = window.innerWidth
    canvas.height = 720

    stage = new createjs.Stage("starCanvas")

    background = new createjs.Bitmap("background1.jpg");
    background.image.onload = handleBackgroundImage_Loaded
}

function handleBackgroundImage_Loaded(evt) {
    background.x = 0
    background.y = 0
    stage.addChildAt(background,0);
    stage.update()
}

alert(canvas)
alert(stage)
</code>```

答:
You forgot to call the function I guess.
Somewhere paste:</p>

```<code>initializeCanvas();
</code>```

Body:
Here's the code. At the top, you can see that canvas and stage are declared as global variables. Then the initializeCanvas() function runs on page load and assigns those variables and loads a background image.

Strangely, though, stage and canvas end up undefined.

Why? And what can I do about it?

Roger

var canvas, stage

function initializeCanvas() {
    canvas = document.getElementById("starCanvas")
    canvas.width = window.innerWidth
    canvas.height = 720

    stage = new createjs.Stage("starCanvas")

    background = new createjs.Bitmap("background1.jpg");
    background.image.onload = handleBackgroundImage_Loaded
}

function handleBackgroundImage_Loaded(evt) {
    background.x = 0
    background.y = 0
    stage.addChildAt(background,0);
    stage.update()
}

alert(canvas)
alert(stage)

Body:
You forgot to call the function I guess.
Somewhere paste:

initializeCanvas();


问:
Trying to read and write on PhantomJS
I'm trying to read and write on a JSON file but I'm a bit stuck in implementing it. I'm trying to append new datas in a JSON file as I iterate on more records.

// scripts.js

```<code>var jsonFile    = '../data/data.json';
var data        = { "id": 0, "animal": "Dog" }, { "id": 1, "animal": "Cat" };

var readData    = fs.read( jsonFile );

readData = readData.push( data );

fs.write( jsonFile, readData, 'a' );
</code>```

--

What i'm trying to achieve

data.json

```<code>[]
</code>```

data.json - 1st iteration

```<code>[
    { "id": 0, "animal": "Dog" },
    { "id": 1, "animal": "Cat" }
]
</code>```

data.json - 2nd iteration

```<code>[
    { "id": 0, "animal": "Dog" },
    { "id": 1, "animal": "Cat" },
    { "id": 2, "animal": "Owl" },
    { "id": 3, "animal": "Bat" }
]
</code>```

答:
Put [] in the file 'data.json' before running this.

```<code>const fs = require('fs-promise');

async function addRecord(jsonFile, row) {
  const json = await fs.readFile(jsonFile,'utf8');
  const rows = JSON.parse(json);
  rows.push(row);
  await fs.writeFile(jsonFile, JSON.stringify(rows));
}

async function test1() {
  const jsonFile = 'data.json';
  await addRecord(jsonFile, { "id": 0, "animal": "Dog" });
  await addRecord(jsonFile, { "id": 1, "animal": "Cat" });
}

test1().catch(console.error);
</code>```

Title: Trying to read and write on PhantomJS

Body:
I'm trying to read and write on a JSON file but I'm a bit stuck in implementing it. I'm trying to append new datas in a JSON file as I iterate on more records.

// scripts.js

var jsonFile    = '../data/data.json';
var data        = { "id": 0, "animal": "Dog" }, { "id": 1, "animal": "Cat" };

var readData    = fs.read( jsonFile );

readData = readData.push( data );

fs.write( jsonFile, readData, 'a' );

--

What i'm trying to achieve

data.json

[]

data.json - 1st iteration

[
    { "id": 0, "animal": "Dog" },
    { "id": 1, "animal": "Cat" }
]

data.json - 2nd iteration

[
    { "id": 0, "animal": "Dog" },
    { "id": 1, "animal": "Cat" },
    { "id": 2, "animal": "Owl" },
    { "id": 3, "animal": "Bat" }
]

Body:
Put [] in the file 'data.json' before running this.

const fs = require('fs-promise');

async function addRecord(jsonFile, row) {
  const json = await fs.readFile(jsonFile,'utf8');
  const rows = JSON.parse(json);
  rows.push(row);
  await fs.writeFile(jsonFile, JSON.stringify(rows));
}

async function test1() {
  const jsonFile = 'data.json';
  await addRecord(jsonFile, { "id": 0, "animal": "Dog" });
  await addRecord(jsonFile, { "id": 1, "animal": "Cat" });
}

test1().catch(console.error);


问:
R: Creating an alphanumeric sequence with fixed length numbers
I need to create an alphanumeric sequence as follows. The following code creates the sequence as M_1, M_2, ... etc

```<code>paste0("M_",seq(1:100))
</code>```

I need all the numbers to appear as 3 digit numbers. i.e. M_001, M_002 etc

答:
We can use sprintf

```<code>sprintf("M_%03d", 1:100)
</code>```

Body:
I need to create an alphanumeric sequence as follows. The following code creates the sequence as M_1, M_2, ... etc

paste0("M_",seq(1:100))

I need all the numbers to appear as 3 digit numbers. i.e. M_001, M_002 etc

Body:
We can use sprintf

sprintf("M_%03d", 1:100)


问:
how to fetch data automatically from database for drag and drop
I want a drag and drop question and its options in to be fetched from a MySQL table and make all options in a correct sequence.

I got this working. but how to apply this for multiple questions fetching automatically from the database.

$(function() {
    $( "#sortable" ).sortable();
    $( "#sortable" ).disableSelection();
    $( "#savebutton" ).click(function() { LISTOBJ.saveList(); });
    });

    var LISTOBJ = {
        saveList: function() {
            var listCSV = "";
            $( "#sortable li" ).each(function() {
                if (listCSV === "") {
                    listCSV = $(this).val();
                } else {
                    listCSV += "," + $(this).val();
                }
                $("#output").text(listCSV);
                $("#hiddenListInput").val(listCSV);
                //$("#listsaveform").submit();
            });
        }
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>        <ul id="sortable">
      <li value="1" class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>Item 1</li>
      <li value="2" class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>Item 2</li>
      <li value="3" class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>Item 3</li>

    </ul>
    <input type="button" id="savebutton" value="save"/>
    <div id="output"></div>
    <form id="listsaveform" method="POST" action="script.php">
        <input type="hidden" name="list" id="hiddenListInput" />
    </form></code>```

答:
If you want to save the options, I suggest that you use <input>
tags for the options and save the same in PHP rather than jQuery. use <input name="options[q1]" />  and you can post all the answers related to the questions. The sortorder of the options / questions will also be the same as the order in the form.

If you use jQuery, you can always serialize the data and then pass the same to PHP.

Body:
I want a drag and drop question and its options in to be fetched from a MySQL table and make all options in a correct sequence.

I got this working. but how to apply this for multiple questions fetching automatically from the database.

$(function() {
    $( "#sortable" ).sortable();
    $( "#sortable" ).disableSelection();
    $( "#savebutton" ).click(function() { LISTOBJ.saveList(); });
    });

    var LISTOBJ = {
        saveList: function() {
            var listCSV = "";
            $( "#sortable li" ).each(function() {
                if (listCSV === "") {
                    listCSV = $(this).val();
                } else {
                    listCSV += "," + $(this).val();
                }
                $("#output").text(listCSV);
                $("#hiddenListInput").val(listCSV);
                //$("#listsaveform").submit();
            });
        }
    }

Item 1

Item 2

Item 3

    <input type="button" id="savebutton" value="save"/>

    <form id="listsaveform" method="POST" action="script.php">
        <input type="hidden" name="list" id="hiddenListInput" />
    </form>


问:
Printing Values In Excel
Sample Template

Please Refer the above Screenshot attached here.As i have find max Value of two numbers ,I also want to print Value whose number is max ie Hello,how do i achieve this?

答:
You can try with the following formula</p>

```<code>=INDEX(A:A,MATCH(MAX(B:B),B:B,0))
</code>```

Title: Printing Values In Excel

Body:
You can try with the following formula

=INDEX(A:A,MATCH(MAX(B:B),B:B,0))


问:
Session works in one page but not another
I am working in a php charting package. I start with a form.html that sends to an answer.php page. The answer.php creates the SESSION. Then a required test.php page picks up the session but the required graph.php page does not. I cannot transfer my data from the form to the graph. The required phplot.php is the graph engine and is not needed in the SESSION thread.

I have spent five days researching and testing with no luck. I have switched the coding around many times. I'm hoping that someone with great php experience will recognize something easily.

The coding for the three pages is below.

answer.php page:

```<code><?php
session_unset();
session_start();
require_once 'phplot/test.php';
?>
<?php
$_POST['bs_now2'];$bs_now2 = $_POST['bs_now2'];$_SESSION['bs_now2'] = $bs_now2;
echo "<div id='graph'>";
echo "<p class='martop10 f18 b'>Graph:</p>";
echo "<img src='phplot/graph.php'>";
echo "</div>";
?>
<?php
session_destroy();
?>
</code>```

graph.php page:

```<code><?php
$Sbs_now2 == 0;
session_start();# Is this redundant? I've tried it in and out.
?>
<?php
require_once 'phplot.php';#Graph engine
$delta = 0.1;$sigma = 15;$sqrt2pi = sqrt(2*M_PI);$u = 75;
$data = array();
for ($x = 0; $x <= 150; $x++)
  $data[] = array('', $x, $Sbs_now2 + $x);
unset($Sbs_now2);
?>
</code>```

test.php page:

```<code><?php
#I don't need the session_start() for this page
$_POST['bs_now2'];$bs_now2 = $_POST['bs_now2'];$_SESSION['bs_now2'] = $bs_now2;$Sbs_now2 = $_SESSION['bs_now2'];
echo '<b>Session BS Now: '.$Sbs_now2.'</b><br>';
?>
</code>```

Thank you,

Gary

答:
Hi Luiz Fernando Sousa Camargo and All,

With help from Luiz Fernando Sousa Camargo I have got it!

answer.php page has one change:

```<code><?php
session_unset();
session_start();
require_once 'phplot/test1.php';
?>
<?php
$_POST['bs_now2'];$bs_now2 = $_POST['bs_now2'];$_SESSION['bs_now2'] = $bs_now2;$Sbs_now2 = $_SESSION['bs_now2'];
echo "<div id='graph'>";
echo "<p class='martop10 f18 b'>Graph:</p>";
echo "<img src='phplot/bs4c.php?bs_now2=$Sbs_now2'>";#CHANGE:
#I set bs_now2= to the session variable(as it would come from the form input). No other changes.
echo "</div>";
?>
<?php
session_destroy();
?>
</code>```

graph.php page has a one important change:

```<code><?php
$Sbs_now2 == 0;
session_start();
$_GET['bs_now2'];$bs_now2 = $_GET['bs_now2'];$_SESSION['bs_now2'] = $bs_now2;$Sbs_now2 = $_SESSION['bs_now2'];#CHANGE
#Use GET to acquire the session variable
#Remove End php and Start php Marks(not important)
require_once 'phplot.php';
$data = array();
for ($x = 0; $x <= 150; $x++)
  $data[] = array('', $x, $Sbs_now2 + $x);
unset($Sbs_now2);
?>
</code>```

Thank you Luiz Fernando Sousa Camargo and All,

Gary

Body:
I am working in a php charting package. I start with a form.html that sends to an answer.php page. The answer.php creates the SESSION. Then a required test.php page picks up the session but the required graph.php page does not. I cannot transfer my data from the form to the graph. The required phplot.php is the graph engine and is not needed in the SESSION thread.

I have spent five days researching and testing with no luck. I have switched the coding around many times. I'm hoping that someone with great php experience will recognize something easily.

The coding for the three pages is below.

answer.php page:

<?php
session_unset();
session_start();
require_once 'phplot/test.php';
?>
<?php
$_POST['bs_now2'];$bs_now2 = $_POST['bs_now2'];$_SESSION['bs_now2'] = $bs_now2;
echo "
";
echo "
Graph:
";
echo "";
echo "
";
?>
<?php
session_destroy();
?>

graph.php page:

<?php
$Sbs_now2 == 0;
session_start();# Is this redundant? I've tried it in and out.
?>
<?php
require_once 'phplot.php';#Graph engine
$delta = 0.1;$sigma = 15;$sqrt2pi = sqrt(2*M_PI);$u = 75;
$data = array();
for ($x = 0; $x <= 150; $x++)
  $data[] = array('', $x, $Sbs_now2 + $x);
unset($Sbs_now2);
?>

test.php page:

<?php
#I don't need the session_start() for this page
$_POST['bs_now2'];$bs_now2 = $_POST['bs_now2'];$_SESSION['bs_now2'] = $bs_now2;$Sbs_now2 = $_SESSION['bs_now2'];
echo 'Session BS Now: '.$Sbs_now2.'
';
?>

Thank you,

Gary

Body:
Hi Luiz Fernando Sousa Camargo and All,

With help from Luiz Fernando Sousa Camargo I have got it!

answer.php page has one change:

<?php
session_unset();
session_start();
require_once 'phplot/test1.php';
?>
<?php
$_POST['bs_now2'];$bs_now2 = $_POST['bs_now2'];$_SESSION['bs_now2'] = $bs_now2;$Sbs_now2 = $_SESSION['bs_now2'];
echo "<div id='graph'>";
echo "<p class='martop10 f18 b'>Graph:</p>";
echo "<img src='phplot/bs4c.php?bs_now2=$Sbs_now2'>";#CHANGE:
#I set bs_now2= to the session variable(as it would come from the form input). No other changes.
echo "</div>";
?>
<?php
session_destroy();
?>

graph.php page has a one important change:

<?php
$Sbs_now2 == 0;
session_start();
$_GET['bs_now2'];$bs_now2 = $_GET['bs_now2'];$_SESSION['bs_now2'] = $bs_now2;$Sbs_now2 = $_SESSION['bs_now2'];#CHANGE
#Use GET to acquire the session variable
#Remove End php and Start php Marks(not important)
require_once 'phplot.php';
$data = array();
for ($x = 0; $x <= 150; $x++)
  $data[] = array('', $x, $Sbs_now2 + $x);
unset($Sbs_now2);
?>

Thank you Luiz Fernando Sousa Camargo and All,

Gary


问:
How to read this php code: $input = JFactory::getApplication()->input;
I get confuse reading this php line of code:

```<code>$input = JFactory::getApplication()->input;
</code>```

As I understand this is a declaration for $input variable.
Can anyone help to explain the right part of the declaration?

答:
$input = JFactory::getApplication()->input;

JFACTORY is a class

getApplication() is static function and returns JFactory object

input is a parameter

for example

```<code>    class JFactory
    {
        public $input='sugumar';
        public static function getApplication()
        {
           return new JFactory;
        }

    }

    $input = JFactory::getApplication()->input;
    echo $input;
</code>```

JFactory is a class

```<code>JFactory::getApplication() when we use this class is not initialized
</code>```

but only executes the getApplication().
   if you have __construct(){} function it will not be executed. only the getApplication function is executed.

this may assign some value to $input are initialize the class with some default parameter which set $input value... it's bit complicated.

Body:
I get confuse reading this php line of code:

$input = JFactory::getApplication()->input;

As I understand this is a declaration for $input variable.
Can anyone help to explain the right part of the declaration?

Body:
$input = JFactory::getApplication()->input;

JFACTORY is a class

getApplication() is static function and returns JFactory object

input is a parameter

for example

    class JFactory
    {
        public $input='sugumar';
        public static function getApplication()
        {
           return new JFactory;
        }

    }

    $input = JFactory::getApplication()->input;
    echo $input;

JFactory is a class

JFactory::getApplication() when we use this class is not initialized

but only executes the getApplication().
   if you have __construct(){} function it will not be executed. only the getApplication function is executed.

this may assign some value to $input are initialize the class with some default parameter which set $input value... it's bit complicated.


问:
Memory leakage when trying to remove an object in C++
I have a dynamically allocated array and I am trying to remove a chosen object from it. But I end up with memory leakage.
Array:

```<code>Competitor* *person;
</code>```

Which is allocated:

```<code>person = new Competitor*[capacity];
for (int i = 0; i < this->capacity; i++) {
    person[i] = nullptr;
}
</code>```

This is my removal function:

```<code>bool Handler::removeCompetitor(string name) {
    bool removed = false;
    if (find(name) != -1) {
        Competitor* *temp = new Competitor*[capacity];
        int j = 0;

        for (int i = 0; i < nrOfCompetitors; i++) {
            if (person[i] != person[find(name)]) {
                temp[j] = person[i];
                j++;
            }
        }
        delete[] person;

        nrOfCompetitors -= 1;
        person = temp;
        removed = true;
    }
    return removed;
}
</code>```

And this is my find function:

```<code>int Handler::find(string name) const {
    int found = -1;
    for (int i = 0; i < nrOfCompetitors; i++) {
        if (person[i]->getName() == name) {
            found = i;
        }
    }
    return found;
}
</code>```

The class "Competitor" is an abstract base class.
Why do I end up with memory leakage?

答:
After removing the Competitor* from the array by creating a new array that does not include the Competitor*, you very likely need to delete the Competitor *.

Right before delete[] person; add delete person[find(name)];

If you really want to be sneaky, up at the top found = find(name); and use found instead of re-finding name over and over.

Body:
I have a dynamically allocated array and I am trying to remove a chosen object from it. But I end up with memory leakage.
Array:

Competitor* *person;

Which is allocated:

person = new Competitor*[capacity];
for (int i = 0; i < this->capacity; i++) {
    person[i] = nullptr;
}

This is my removal function:

bool Handler::removeCompetitor(string name) {
    bool removed = false;
    if (find(name) != -1) {
        Competitor* *temp = new Competitor*[capacity];
        int j = 0;

        for (int i = 0; i < nrOfCompetitors; i++) {
            if (person[i] != person[find(name)]) {
                temp[j] = person[i];
                j++;
            }
        }
        delete[] person;

        nrOfCompetitors -= 1;
        person = temp;
        removed = true;
    }
    return removed;
}

And this is my find function:

int Handler::find(string name) const {
    int found = -1;
    for (int i = 0; i < nrOfCompetitors; i++) {
        if (person[i]->getName() == name) {
            found = i;
        }
    }
    return found;
}

The class "Competitor" is an abstract base class.
Why do I end up with memory leakage?


问:
how to select a specific character on a specific place
My question goes about the following list of data.

```<code>data = ['TNNI3', 'TSHZ3/THEG5', 'ACTR3BP2-', 'BIN1/CYP27C1',
'-', 'NBPF1/NBPF20', 'ERBB4', '-NBPF20', '-']
</code>```

I need to select the character "-" only if is combined with something else. In case it stand by it self, it needs to stay unselected.

For example the "-" in 'ACTR3BP2-' and '-NBPF20' needs to be selected and the two '-' in the list needs to stay unselected.

Does anyone know how to do this by using regex in python3??

Once the correct "-" are selected I want to remove them from the list.
How I think to do this is to use the re.sub function and replace it with an empty space. If someone has a better idea to do this. I'm glad to hear them!

答:
There is a better way to do this if you don't require regex.  Doing a string compare and replace would be faster than using Regex.</p>

```<code>import re

data = ['TNNI3', 'TSHZ3/THEG5', 'ACTR3BP2-', 'BIN1/CYP27C1',
       '-', 'NBPF1/NBPF20', 'ERBB4', '-NBPF20', '-']

for e in data:
    if "-" in e and e != "-":
        old = e
        new = e.replace("-", "")
        print(old + " >> " + new)
</code>```

Body:
My question goes about the following list of data.

data = ['TNNI3', 'TSHZ3/THEG5', 'ACTR3BP2-', 'BIN1/CYP27C1',
'-', 'NBPF1/NBPF20', 'ERBB4', '-NBPF20', '-']

I need to select the character "-" only if is combined with something else. In case it stand by it self, it needs to stay unselected.

For example the "-" in 'ACTR3BP2-' and '-NBPF20' needs to be selected and the two '-' in the list needs to stay unselected.

Does anyone know how to do this by using regex in python3??

Once the correct "-" are selected I want to remove them from the list.
How I think to do this is to use the re.sub function and replace it with an empty space. If someone has a better idea to do this. I'm glad to hear them!

Body:
There is a better way to do this if you don't require regex.  Doing a string compare and replace would be faster than using Regex.

import re

data = ['TNNI3', 'TSHZ3/THEG5', 'ACTR3BP2-', 'BIN1/CYP27C1',
       '-', 'NBPF1/NBPF20', 'ERBB4', '-NBPF20', '-']

for e in data:
    if "-" in e and e != "-":
        old = e
        new = e.replace("-", "")
        print(old + " >> " + new)


问:
Group items in multidimensional array by same value at index
I have a multi-dimensional array like this:

```<code>var arr = [ [x,x,1] , [x,x,2] , [x,x,2] , [x,x,3] , [x,x,3] , [x,x,3] ];
</code>```

and I want to make it like this (grouping each sub-array according to matching  arr[i][2] values):

```<code>var arr = [ [[x,x,1]] , [[x,x,2],[x,x,2]] , [[x,x,3],[x,x,3],[x,x,3]] ];
</code>```

My attempts are getting increasingly long-winded, and I'm ashamed of posting them here. Any efficient suggestions greatly appreciated!

答:
You could use a Map and generate the new array with Array#reduce in a single loop.

var array = [['x', 'x', 1], ['x', 'x', 2], ['x', 'x', 2], ['x', 'x', 3], ['x', 'x', 3], ['x', 'x', 3]],
    grouped = array.reduce((map =>
        (r, a) =>
            (!map.has(a[2]) && map.set(a[2], r[r.push([]) - 1]), map.get(a[2]).push(a), r)
        )(new Map), []);

console.log(grouped);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
I have a multi-dimensional array like this:

var arr = [ [x,x,1] , [x,x,2] , [x,x,2] , [x,x,3] , [x,x,3] , [x,x,3] ];

and I want to make it like this (grouping each sub-array according to matching  arr[i][2] values):

var arr = [ [[x,x,1]] , [[x,x,2],[x,x,2]] , [[x,x,3],[x,x,3],[x,x,3]] ];

My attempts are getting increasingly long-winded, and I'm ashamed of posting them here. Any efficient suggestions greatly appreciated!

Body:
You could use a Map and generate the new array with Array#reduce in a single loop.

var array = [['x', 'x', 1], ['x', 'x', 2], ['x', 'x', 2], ['x', 'x', 3], ['x', 'x', 3], ['x', 'x', 3]],
    grouped = array.reduce((map =>
        (r, a) =>
            (!map.has(a[2]) && map.set(a[2], r[r.push([]) - 1]), map.get(a[2]).push(a), r)
        )(new Map), []);

console.log(grouped);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
How to extract images from pdf using Java (not using pdfbox)
I've being researching on how to extract images from a big (> 300MB) PDF file. I'm using pdfbox but for some particular reason that I can't figure out, some pages are not correctly extracted.

I'm using the PDFToImage class of pdfbox as base for my code.

So, do you know another library that may help me to do this? I know that iText may be used, but I read that it can't be used for commercial products.

I've installed the packages xpdf and xpdf-utils, and the utility called pdfimages is working perfect. But I need to solve this problem from Java and it should be portable.

答: The most likely reason why it is hard working with 300 Mb PDF's is that you run out of memory.  If it works well for smaller PDF's I would have a closer look at why it fails.</p>

ContentLicense: CC BY-SA 2.5


问:
Recompiling node dependencies using another node version
I want to install some dependencies and in this case installing node-pty. But when I run it they give me this error:

Error: The module '/home/dev/Documents/project/node_web_kit/node_modules/node-pty/build/Release/pty.node'
  was compiled against a different Node.js version using
  NODE_MODULE_VERSION 46. This version of Node.js requires
  NODE_MODULE_VERSION 51. Please try re-compiling or re-installing

any solutions?

答: The simplest way to be sure is just to delete node_modules and re-run npm i from scratch, that way all modules will definitely be set up for the new Node version.


问:
Styling a wordpress widget title
I've been struggling with this problem for a while now. How do I style my widget title to have this horizontal line besides my widget title and not under it. Like so:enter image description here</p>

答:
Use your developer inspect tool (firebug, chrome dev tools), locate
the widget and it's selector.

Then simply apply your custom styles to this relevant selector you found ( ie. it's title).

If it does not have a unique selector, or a selector for the
particular area you want to style. Navigate through your theme's
files and locate the widgets php code or it's include mark-up area, add a
unique selector directly in there, that you could then style to your
preference.

Or, if you really must; you could add the selector with jQuery or
javaScript and then style it. ie, $('widget').addClass('customWidget');

Hope this helps!

Title: Styling a wordpress widget title


问:
MySQL - Entity : The value for column 'IsPrimaryKey' in table 'TableDetails' is DBNull
I am using Visual Studio 2013 with Entity Framework 5 and MySQL Server 5.7.9.

When trying to create a Model from the database (or 'Update Model From Database') the following message appears:

'System.Data.StrongTypingException: The value for column
  'IsPrimaryKey' in table 'TableDetails' is DBNull . ---> System.InvalidCastException: Specified cast is not valid.

I know that this question has been asked before, but i haven't find any solution.
Also i don't have the option of downgrading to MySQL 5.6.

The problem occurs even for a simple table.

The sample table

```<code>CREATE TABLE new_table
(
  id int(11) NOT NULL AUTO_INCREMENT,
  name varchar(45) NOT NULL,
  PRIMARY KEY (id)
)
ENGINE = InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
</code>```

If the table consists only from the Primary Key then the model is being created as it should.

EDIT:
If i make both the fields PRIMARY Keys the model is being created without any errors.

Does anyone have any idea about this?

Kind Regards.

The full error stack:

Unable to generate the model because of the following exception:
  'System.Data.StrongTypingException: The value for column
  'IsPrimaryKey' in table 'TableDetails' is DBNull. --->
  System.InvalidCastException: Specified cast is not valid.    at
  Microsoft.Data.Entity.Design.VersioningFacade.ReverseEngineerDb.SchemaDiscovery.TableDetailsRow.get_IsPrimaryKey()
  --- End of inner exception stack trace ---    at Microsoft.Data.Entity.Design.VersioningFacade.ReverseEngineerDb.SchemaDiscovery.TableDetailsRow.get_IsPrimaryKey()
  at
  Microsoft.Data.Entity.Design.VersioningFacade.ReverseEngineerDb.StoreModelBuilder.CreateProperties(IList1
  columns, IList1 errors, List1& keyColumns, List1& excludedColumns,
  List1& invalidKeyTypeColumns)    at
  Microsoft.Data.Entity.Design.VersioningFacade.ReverseEngineerDb.StoreModelBuilder.CreateEntityType(IList1
  columns, Boolean& needsDefiningQuery)    at
  Microsoft.Data.Entity.Design.VersioningFacade.ReverseEngineerDb.StoreModelBuilder.CreateEntitySets(IEnumerable1
  tableDetailsRows, EntityRegister entityRegister, IList1
  entitySetsForReadOnlyEntityTypes, DbObjectType objectType)    at
  Microsoft.Data.Entity.Design.VersioningFacade.ReverseEngineerDb.StoreModelBuilder.CreateEntitySets(IEnumerable1
  tableDetailsRowsForTables, IEnumerable1 tableDetailsRowsForViews,
  EntityRegister entityRegister)    at
  Microsoft.Data.Entity.Design.VersioningFacade.ReverseEngineerDb.StoreModelBuilder.Build(StoreSchemaDetails
  storeSchemaDetails)    at
  Microsoft.Data.Entity.Design.VisualStudio.ModelWizard.Engine.ModelGenerator.CreateStoreModel()
  at
  Microsoft.Data.Entity.Design.VisualStudio.ModelWizard.Engine.ModelGenerator.GenerateModel(List1
  errors)    at
  Microsoft.Data.Entity.Design.VisualStudio.ModelWizard.Engine.ModelBuilderEngine.GenerateModels(String
  storeModelNamespace, List1 errors)    at
  Microsoft.Data.Entity.Design.VisualStudio.ModelWizard.Engine.ModelBuilderEngine.GenerateModel(EdmxHelper
  edmxHelper)'. Loading metadata from the database took
  00:00:00.5856317.

答:
Every answer above works fine, but when the server or dev-machine is restarted, we need to make all steps again and again.
To solve completely, we can put this attibute 'derived_merge=OFF' in the mysql configuration.
Ok, to do that, you need to access your MySQL server with de MySQL Workbench, and open "Option File" > Select Performance tab. In Optimizer group, look for optimizer_switch, click the checkbox to enable a field, and put 'derived_merge=OFF'.
Restart your server in services.msc and voilá!</p>

Body:
I am using Visual Studio 2013 with Entity Framework 5 and MySQL Server 5.7.9.

When trying to create a Model from the database (or 'Update Model From Database') the following message appears:

'System.Data.StrongTypingException: The value for column
  'IsPrimaryKey' in table 'TableDetails' is DBNull . ---> System.InvalidCastException: Specified cast is not valid.

I know that this question has been asked before, but i haven't find any solution.
Also i don't have the option of downgrading to MySQL 5.6.

The problem occurs even for a simple table.

The sample table

CREATE TABLE new_table
(
  id int(11) NOT NULL AUTO_INCREMENT,
  name varchar(45) NOT NULL,
  PRIMARY KEY (id)
)
ENGINE = InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

If the table consists only from the Primary Key then the model is being created as it should.

EDIT:
If i make both the fields PRIMARY Keys the model is being created without any errors.

Does anyone have any idea about this?

Kind Regards.

The full error stack:

Unable to generate the model because of the following exception:
  'System.Data.StrongTypingException: The value for column
  'IsPrimaryKey' in table 'TableDetails' is DBNull. --->
  System.InvalidCastException: Specified cast is not valid.    at
  Microsoft.Data.Entity.Design.VersioningFacade.ReverseEngineerDb.SchemaDiscovery.TableDetailsRow.get_IsPrimaryKey()
  --- End of inner exception stack trace ---    at Microsoft.Data.Entity.Design.VersioningFacade.ReverseEngineerDb.SchemaDiscovery.TableDetailsRow.get_IsPrimaryKey()
  at
  Microsoft.Data.Entity.Design.VersioningFacade.ReverseEngineerDb.StoreModelBuilder.CreateProperties(IList1
  columns, IList1 errors, List1& keyColumns, List1& excludedColumns,
  List1& invalidKeyTypeColumns)    at
  Microsoft.Data.Entity.Design.VersioningFacade.ReverseEngineerDb.StoreModelBuilder.CreateEntityType(IList1
  columns, Boolean& needsDefiningQuery)    at
  Microsoft.Data.Entity.Design.VersioningFacade.ReverseEngineerDb.StoreModelBuilder.CreateEntitySets(IEnumerable1
  tableDetailsRows, EntityRegister entityRegister, IList1
  entitySetsForReadOnlyEntityTypes, DbObjectType objectType)    at
  Microsoft.Data.Entity.Design.VersioningFacade.ReverseEngineerDb.StoreModelBuilder.CreateEntitySets(IEnumerable1
  tableDetailsRowsForTables, IEnumerable1 tableDetailsRowsForViews,
  EntityRegister entityRegister)    at
  Microsoft.Data.Entity.Design.VersioningFacade.ReverseEngineerDb.StoreModelBuilder.Build(StoreSchemaDetails
  storeSchemaDetails)    at
  Microsoft.Data.Entity.Design.VisualStudio.ModelWizard.Engine.ModelGenerator.CreateStoreModel()
  at
  Microsoft.Data.Entity.Design.VisualStudio.ModelWizard.Engine.ModelGenerator.GenerateModel(List1
  errors)    at
  Microsoft.Data.Entity.Design.VisualStudio.ModelWizard.Engine.ModelBuilderEngine.GenerateModels(String
  storeModelNamespace, List1 errors)    at
  Microsoft.Data.Entity.Design.VisualStudio.ModelWizard.Engine.ModelBuilderEngine.GenerateModel(EdmxHelper
  edmxHelper)'. Loading metadata from the database took
  00:00:00.5856317.


问:
SQL query regarding Sequence
I made a sequence in Net Beans. But when I tried to insert data in the table I get an error.

My code is:

```<code>CREATE SEQUENCE seq_person
MINVALUE 1
START WITH 1
INCREMENT BY 1

INSERT INTO Persons (ID,FirstName,LastName)
VALUES (seq_person.nextval,'Lars','Monsen');
</code>```

The error is:

[Exception, Error code 30,000, SQLState 42X04] Column
  'SEQ_PERSON.NEXTVAL' is either not in any table in the FROM list or
  appears within a join specification and is outside the scope of the
  join specification or appears in a HAVING clause and is not in the
  GROUP BY list. If this is a CREATE or ALTER TABLE  statement then
  'SEQ_PERSON.NEXTVAL' is not a column in the target table.

答:
The error message Error code 30,000, SQLState 42X04 indicates you are using Derby DB not Oracle. That being the case you need to use Derby syntax for getting the next value. So your insert should look like this:

```<code>INSERT INTO Persons (ID,FirstName,LastName)
VALUES (NEXT VALUE FOR seq_person,'Lars','Monsen')
</code>```

Title: SQL query regarding Sequence

Body:
I made a sequence in Net Beans. But when I tried to insert data in the table I get an error.

My code is:

CREATE SEQUENCE seq_person
MINVALUE 1
START WITH 1
INCREMENT BY 1

INSERT INTO Persons (ID,FirstName,LastName)
VALUES (seq_person.nextval,'Lars','Monsen');

The error is:

[Exception, Error code 30,000, SQLState 42X04] Column
  'SEQ_PERSON.NEXTVAL' is either not in any table in the FROM list or
  appears within a join specification and is outside the scope of the
  join specification or appears in a HAVING clause and is not in the
  GROUP BY list. If this is a CREATE or ALTER TABLE  statement then
  'SEQ_PERSON.NEXTVAL' is not a column in the target table.

Body:
The error message Error code 30,000, SQLState 42X04 indicates you are using Derby DB not Oracle. That being the case you need to use Derby syntax for getting the next value. So your insert should look like this:

INSERT INTO Persons (ID,FirstName,LastName)
VALUES (NEXT VALUE FOR seq_person,'Lars','Monsen')


问:
SQL Server 2012 GROUP BY must have at least one column that is not an outer reference- I only have inner joins
Hi I have been trying to solve this problem for two days. The above error message:

Msg 164, Level 15, State 1, Line 21 Each GROUP BY expression must
  contain at least one column that is not an outer reference.

WHAT I AM TRYING TO DO: total prescriptions for each patient by hospital stay (patients_records record), listing first, last, patient record begin and end dates (for each stay), and total of prescriptions

I have searched the web, stackoverflow similar questions (which most or all seem to involve variables or constants).  I am stumped and could really use some help. My query doesn't use any outer joins, and I have tried removing all but the 'TotalOfPresc' column from the group by.  I am a beginner- please be gentle. Here is my code:

```<code>USE [BestHospitalDB];

SELECT PATIENTS.Last, PATIENTS.First,
    Presc.PrescQuantity * Meds.PrescPrice As 'TotalOfPresc',
    pr.SubmissionDate, pr.DischargeDate

FROM
    PATIENTS AS p,
    [PRESCRIPTIONS] AS Presc,
    [PRESC_MEDS] AS Meds,
    PATIENTS_RECORDS AS pr

INNER JOIN
    PATIENTS ON pr.PatientID = PATIENTS.[PatientID]

INNER JOIN
    PRESCRIPTIONS ON PRESCRIPTIONS.PatientsRecordsID = pr.PatientsRecordsID
INNER JOIN
    PRESC_MEDS ON PRESCRIPTIONS.PrescPresc_MedsID = PRESC_MEDS.Presc_MedsID

GROUP BY PATIENTS.First, PATIENTS.Last, pr.SubmissionDate, pr.DischargeDate, 'TotalOfPresc'
</code>```

答:
You cannot group by a constant value.  Your query doesn't make sense in several ways.  I assume you intend something like this:

```<code>SELECT p.Last, p.First,
       SUM(px.PrescQuantity * m.PrescPrice) As TotalOfPresc
FROM PATIENTS_RECORDS pr INNER JOIN
     PATIENTS p
     ON pr.PatientID = PATIENTS.[PatientID] INNER JOIN
     PRESCRIPTIONS px
     ON px.PatientsRecordsID = pr.PatientsRecordsID INNER JOIN
     PRESC_MEDS pm
    ON px.PrescPresc_MedsID = pm.Presc_MedsID
GROUP BY p.First, p.Last;
</code>```

Some words of advice:

Never use commas in the FROM clause.  You have the proper join syntax, why do you also want unnecessary Cartesian products?

Don't use single quotes to name columns.  You'll just confuse yourself -- that is the specific problem you are encountering.

Only aggregate by the keys that define a single row in the output.  If you use GROUP BY, you usually also want aggregation functions.

Body:
Hi I have been trying to solve this problem for two days. The above error message:

Msg 164, Level 15, State 1, Line 21 Each GROUP BY expression must
  contain at least one column that is not an outer reference.

WHAT I AM TRYING TO DO: total prescriptions for each patient by hospital stay (patients_records record), listing first, last, patient record begin and end dates (for each stay), and total of prescriptions

I have searched the web, stackoverflow similar questions (which most or all seem to involve variables or constants).  I am stumped and could really use some help. My query doesn't use any outer joins, and I have tried removing all but the 'TotalOfPresc' column from the group by.  I am a beginner- please be gentle. Here is my code:

USE [BestHospitalDB];

SELECT PATIENTS.Last, PATIENTS.First,
    Presc.PrescQuantity * Meds.PrescPrice As 'TotalOfPresc',
    pr.SubmissionDate, pr.DischargeDate

FROM
    PATIENTS AS p,
    [PRESCRIPTIONS] AS Presc,
    [PRESC_MEDS] AS Meds,
    PATIENTS_RECORDS AS pr

INNER JOIN
    PATIENTS ON pr.PatientID = PATIENTS.[PatientID]

INNER JOIN
    PRESCRIPTIONS ON PRESCRIPTIONS.PatientsRecordsID = pr.PatientsRecordsID
INNER JOIN
    PRESC_MEDS ON PRESCRIPTIONS.PrescPresc_MedsID = PRESC_MEDS.Presc_MedsID

GROUP BY PATIENTS.First, PATIENTS.Last, pr.SubmissionDate, pr.DischargeDate, 'TotalOfPresc'

Body:
You cannot group by a constant value.  Your query doesn't make sense in several ways.  I assume you intend something like this:

SELECT p.Last, p.First,
       SUM(px.PrescQuantity * m.PrescPrice) As TotalOfPresc
FROM PATIENTS_RECORDS pr INNER JOIN
     PATIENTS p
     ON pr.PatientID = PATIENTS.[PatientID] INNER JOIN
     PRESCRIPTIONS px
     ON px.PatientsRecordsID = pr.PatientsRecordsID INNER JOIN
     PRESC_MEDS pm
    ON px.PrescPresc_MedsID = pm.Presc_MedsID
GROUP BY p.First, p.Last;

Some words of advice:

Never use commas in the FROM clause.  You have the proper join syntax, why do you also want unnecessary Cartesian products?

Don't use single quotes to name columns.  You'll just confuse yourself -- that is the specific problem you are encountering.

Only aggregate by the keys that define a single row in the output.  If you use GROUP BY, you usually also want aggregation functions.


问:
Anchor mouse pointer doesn´t work with CSS and bootstrap
I need to change the cursor pointer in an anchor to "not-allowed" when it has  a "disabled" class.
I have tried the following, with no luck.

What am I doing wrong?

Link to test: https://plnkr.co/edit/isoqoP2EbKjWb9fkfQpN?p=preview

Markup:

```<code><div class="container">
    <ul class="nav nav-pills nav-stacked lefttabs well">
      <li><a>Home</a>
      </li>
      <li><a class="disabled">Perfil</a>
      </li>
    </ul>
 </div>
</code>```

CSS:

```<code>/* Styles go here */
.nav, .pagination, .carousel, .panel-title a { cursor: pointer; }

.disabled {
    color: #900;
    cursor: not-allowed;
    pointer-events: none;
    text-decoration: none;
}
</code>```

答:
Change you're CSS code to:

```<code>.nav, .pagination, .carousel, .panel-title a { cursor: pointer; }

.disabled {
    color: #900;
    cursor: not-allowed;
    text-decoration: none;
}
</code>```

You have to remove the pointer-events: none; this stops the cursor from changing (Or removes it all together) and therefore remains the same, despite you setting the cursor.

ContentLicense: CC BY-SA 4.0

Body:
I need to change the cursor pointer in an anchor to "not-allowed" when it has  a "disabled" class.
I have tried the following, with no luck.

What am I doing wrong?

Link to test: https://plnkr.co/edit/isoqoP2EbKjWb9fkfQpN?p=preview

Markup:

Home

Perfil

CSS:

/* Styles go here */
.nav, .pagination, .carousel, .panel-title a { cursor: pointer; }

.disabled {
    color: #900;
    cursor: not-allowed;
    pointer-events: none;
    text-decoration: none;
}

Body:
Change you're CSS code to:

.nav, .pagination, .carousel, .panel-title a { cursor: pointer; }

.disabled {
    color: #900;
    cursor: not-allowed;
    text-decoration: none;
}

You have to remove the pointer-events: none; this stops the cursor from changing (Or removes it all together) and therefore remains the same, despite you setting the cursor.


问:
create two vars in datatable R (divide operation)
I have a datatable with this columns. (Note : total is not  sum of A+B).

```<code>Date       Total     A      B
12-2015     10       2      3
01-2016     7        1      3
02-2016     15       8      3
</code>```

I want add two variables one with percentage of A from total and b percentaje of B from total.

Anyone could help?

Body:
I have a datatable with this columns. (Note : total is not  sum of A+B).

Date       Total     A      B
12-2015     10       2      3
01-2016     7        1      3
02-2016     15       8      3

I want add two variables one with percentage of A from total and b percentaje of B from total.

Anyone could help?

Body:
We can specify the columns in .SDcols and divide by 'Total' to assign it to new columns

dt[, paste0("Perc_", c("A", "B")) :=  .SD/Total, .SDcols = A:B]
dt
#     Date Total A B    Perc_A    Perc_B
#1: 12-2015    10 2 3 0.2000000 0.3000000
#2: 01-2016     7 1 3 0.1428571 0.4285714
#3: 02-2016    15 8 3 0.5333333 0.2000000


问:
Modeling user account referring to different entities
I'm starting a new project which will act as an authorization/authentication server and a simple user management for certain type of users. A user can be a HelpDeskResponsible, GroupManager, Employee, Customer and more. All these groups members will be able to login with the same form on the web interface. Each model will contain different set of data describing them.

My problem is model design. I am pretty sure I need some User entity with all data necessary to login and read roles but I don't know how to associate rest of models with user account to easily fetch info about logged-in user. Another problem is users management - given user account is created I'd need to somehow link it to model of one of types I mentioned above.

Is my concept an over-engineering? Are there any solutions for such problem? Maybe I don't need multiple entities for different account types?

Thanks for any advice.

EDIT: Different permission levels are not the bigest problem here - I want to store different info about user depending on a role he belongs to. Customer will have different dataset than Employee. I'm pretty sure they are different models but I want to save an ability to login with the same login form.

答:
I think the main issue is that your coupling goes backward: in your case the User Management context will have to know about specifics of other Bounded Contexts (BC) while it should be the other way around. Otherwise you will find yourself having to constantly modify your User Management context as more systems are using it.

For instance, the HelpDeskResponsible role is much likely played in a Helpdesk system which lives in it's own BC (or set of BCs). It is that context that should be responsible for modeling and persisting the specifics of a HelpDeskResponsible. The only thing the User Management context should hold is whether or not a user is in a specific role and perhaps some information that is generic to all users (e.g. first name, last name).

Obviously, the above diagram misses the Anti-Corruption layer (service(s) e.g. HelpDeskUserService) which lives in the Help Desk BC and is responsible for abstracting away the coupling with the User Management BC and translating User into HelpDeskResponsible.


问:
Matlab Engine Java Exeption Unable to launch matlab
I am trying to use matlab from java using the java engine (Working on Ubuntu 16.04 and the trial of Matlab 2017a. Also, I'm following the code posted in the official page of Matlab ( https://www.mathworks.com/help/matlab/matlab_external/execute-matlab-functions-from-java.html) with the example of obtain the roots of some numbers. I added in the Java build path the external Jars and the native library location. After all of this, the code does not present any error. But running the code, it shows the next exception at the moment i enter my Matlab account and the password:

```<code>Exception in thread "main" com.mathworks.engine.EngineException: Unable to launch MATLAB.
at com.mathworks.engine.MatlabEngine.open(MatlabEngine.java:334)
at com.mathworks.engine.MatlabEngine.startMatlab(MatlabEngine.java:143)
at LoadImageFromFile.ReadImage.main(ReadImage.java:26)
</code>```

What I need to do? There's something that I am forgetting?

答: I had the same problem when I upgrated from Matlab 2016b to 2017b , you have to keep matlab closed when calling it from Java</p>

Body:
I am trying to use matlab from java using the java engine (Working on Ubuntu 16.04 and the trial of Matlab 2017a. Also, I'm following the code posted in the official page of Matlab ( https://www.mathworks.com/help/matlab/matlab_external/execute-matlab-functions-from-java.html) with the example of obtain the roots of some numbers. I added in the Java build path the external Jars and the native library location. After all of this, the code does not present any error. But running the code, it shows the next exception at the moment i enter my Matlab account and the password:

Exception in thread "main" com.mathworks.engine.EngineException: Unable to launch MATLAB.
at com.mathworks.engine.MatlabEngine.open(MatlabEngine.java:334)
at com.mathworks.engine.MatlabEngine.startMatlab(MatlabEngine.java:143)
at LoadImageFromFile.ReadImage.main(ReadImage.java:26)

What I need to do? There's something that I am forgetting?


问:
How to properly insert an object into a List in Java?
In this code, are there any differences between these two ways to insert an element into a list in Java?  If so, what are they? And what way should I use when inserting an element into a list?

```<code>List<MyClass>myList=new ArrayList<MyClass>();

myList.add(new MyClass());

MyClass foo=new MyClass();
myList.add(foo);
</code>```

I'm a beginner in Java. I'm really sorry if you find this question obvious or non-sense.

答:
The difference I find is related to garbage collection. If you are considering that you are not going to assign the object to any other variable,
Using the first one, if you remove the object from the list it becomes eligible for gc. In the second one the object will not be eligible for gc as long as either foo keeps the reference to the object or its available in the list.</p>

Body:
In this code, are there any differences between these two ways to insert an element into a list in Java?  If so, what are they? And what way should I use when inserting an element into a list?

List<MyClass>myList=new ArrayList<MyClass>();

myList.add(new MyClass());

MyClass foo=new MyClass();
myList.add(foo);

I'm a beginner in Java. I'm really sorry if you find this question obvious or non-sense.


问:
Google Apps Script to Generate and Populate Sheet Based on Other Sheet's Data
I maintain a spreadsheet workbook that tracks cake orders. Column headers (A–H) on the tracking sheet (named CakeOrders) are as follows:

(A1) Pickup Date, (B1) Client Name, (C1) Phone#, (D1) Text on Cake, (E1) Cake Flavor, (F1) Frosting Flavor, (G1) Fruit Filling, (H1) Link to PO

Each row of data below these headers corresponds to a new purchase order (PO) with a unique date, client name, etc. View CakeOrders sheet here.

On a second sheet (named Admin) within the same workbook, I have a table that runs match functions to find the Column# for each column header on CakeOrders. This was set up so that my script, which calls upon these Columns#s, will stay accurate even if I end up rearranging or adding Columns and new headers to the CakeOrders sheet—the script will always reference the appropriate column because of the match functions on the Admin sheet. View the Admin sheet here.

I currently have a script set up that allows me to generate new formatted spreadsheets (designed to be blank POs) directly from this spreadsheet. The script names the new sheet (or PO) based on data from within the selected row, and it adds a link to the new PO in Column H.

I would like to extend this script so that it also fills in select cells on the new PO based on information within its originating row.

Does anyone know a script that would allow me to populate specific cells of a new spreadsheet with data from a specific row of another?

Thanks!

Below is my current script, which creates a new spreadsheet with a name based on row content, stores the new sheet in a specific folder, and includes a link to the spreadsheet in the originating row.

```<code>function onOpen() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var customMenu = [{name: "Create PO", functionName: "Create"}];
   ss.addMenu("Create PO", customMenu);
};

function Create() {
  var sheet = SpreadsheetApp.getActive().getSheetByName("Admin");
  var folderID = sheet.getRange("B2").getValue(); //These are column numbers
  var templateID = sheet.getRange("B3").getValue();
  var pickupDate = sheet.getRange("B4").getValue();
  var clientName = sheet.getRange("B5").getValue();
  var textOnCake = sheet.getRange("B6").getValue();
  var cakeFlavor = sheet.getRange("B7").getValue();
  var frostingFlavor = sheet.getRange("B8").getValue();
  var fruitFilling = sheet.getRange("B9").getValue();
  var POColumn = sheet.getRange("B10").getValue();

  var ss = SpreadsheetApp.getActiveSheet(); // Back to CakeOrders sheet
  var cell = ss.getActiveCell();
  var row = cell.getRow(); //User has to pick the correct row

  if (row <= 1){
   Browser.msgBox("Cannot create new document within the header. Please select the row to which you'd like to add a new PO doc and run the script again.");
    return;
  }

  try{

  var pickupDateValue = Utilities.formatDate(ss.getRange(row,pickupDate).getValue(), "America/Chicago", "MMddYY");
  }
  catch(e) {
  var pickupDateValue = ss.getRange(row,pickupDate).getValue();
  }

  var clientNameValue = ss.getRange(row,clientName).getValue();//getting the actual values now using column numbers from admin sheet
  var textOnCakeValue = ss.getRange(row,textOnCake).getValue();
  var cakeFlavorValue = ss.getRange(row,cakeFlavor).getValue();
  var frostingFlavorValue = ss.getRange(row,frostingFlavor).getValue();
  var fruitFillingValue = ss.getRange(row,fruitFilling).getValue();
  var POColumnValue = ss.getRange(row,POColumn).getValue();

    if (POColumnValue != ""){
   Browser.msgBox("There is already content in the PO column. Please clear the contents and try again.");
    return;
  }

  if (clientNameValue == "" || textOnCakeValue == "" || cakeFlavor == "" || frostingFlavor == ""|| fruitFilling == ""){
   Browser.msgBox("Client Name, Text On Cake, Cake Flavor, Frosting Flavor, and Fruit Filling are required. Please enter a value in each of these columns and then try again.");
    return;
  }

  var docName = "PO." + pickupDateValue + "." + clientNameValue;

  var template = DriveApp.getFileById(templateID);
  var destFolder = DriveApp.getFolderById(folderID);

  var newDocID = template.makeCopy(docName, destFolder).getId();
  var docLink = "https://docs.google.com/spreadsheets/d/" + newDocID;
  ss.getRange(row,POColumn).setValue(docLink);
}
</code>```

答:
I would probably modify the column headings by making them single word Camel Code and use them as the keys for an associative array. So that when I get data from a row I build an array from a table that look like this:

```<code>PickupDate  ClientName    Phone         CakeText             CakeFlavor     FrostingFlavor  FruitFilling    LinktoPO
4/15/2017   Bart Simpson  123-456-7899  Your Wierd Bart      Dessert Cactus Frozen Spinach  Tomato
4/16/2017   Bugs Bunny    987-654-3210  Happy Birthdays Bugs Carrot         Carrot          Carrots
</code>```

To an array that looks like this:

```<code>var rowA = {PickupData:'4/16/2017',ClientName:'Bugs Bunny',Phone:'987-654-3210',CakeText:'Happy Birthday Bugs',CakeFlavor:'Carrot',FrostingFlavor:'Carrot', FruitFilling:'Carrots',LinkToPO:''}
</code>```

Now when you go in to your PO form to fill in data you will be able to enter the data like this:

```<code>rowA[PickupData]
rowA[ClientName] etc...
</code>```

The keys come from the column headers and the values come from which ever row your own.  So it doesn't really matter what the order of the columns is.  And later you can change the names of the variable by changing the names of the columns.

You can store the other information in a file as a string with file.setContent('string') and then take it out with file.getBlob().getDataAsString().split(delimiter) and split it with any delimiter that you choose.  I often choose really wierd ones that you'll never expect to see anywhere like '|@@@|'.

Your final question was "Does anyone know a script that would allow me to populate specific cells of a new spreadsheet with data from a specific row of another?" and here's an answer to that:

```<code>function copyToNewSS()
{
  var dstlocdict = {PickupDate:'A1',ClientName:'B2',Phone:'C3',CakeText:'D4',CakeFlavor:'E5',FrostingFlavor:'F6',FruitFilling:'G7',LinktoPO:'H8'}
  var srcss = SpreadsheetApp.getActiveSpreadsheet();
  var srcsht = srcss.getActiveSheet();
  var dstss = SpreadsheetApp.openById('Insert ID of Destination Spreadsheet');
  var dstsht = dstss.getSheetByName('PO');
  var srcrow = srcsht.getActiveCell().getRow();
  if((srcrow - 1)==0 || srcrow > srcsht.getLastRow()){SpreadsheetApp.getUi().alert('Error: Invalid Data Row');return;}
  var srcdatR = srcsht.getDataRange();
  var srcdatA = srcdatR.getValues();
  var srcdatdict = {};
  var srcnumcols = srcsht.getLastColumn();
  var s = '{';
  for(var i = 0;i < srcdatA[srcrow - 1].length; i++)
  {
    srcdatdict[srcdatA[0][i]]= srcdatA[srcrow-1][i];
    if(i>0)s += ', ';
    s += srcdatA[0][i] + ':' + srcdatA[srcrow-1][i];
  }
  myUtilities.dispStatus('Source Data Dictionary for Row ' + srcrow , s, 800, 400)
  for(var key in srcdatdict)
  {
    dstsht.getRange(dstlocdict[key]).setValue(srcdatdict[key]);
  }
}
</code>```

Body:
I maintain a spreadsheet workbook that tracks cake orders. Column headers (A–H) on the tracking sheet (named CakeOrders) are as follows:

(A1) Pickup Date, (B1) Client Name, (C1) Phone#, (D1) Text on Cake, (E1) Cake Flavor, (F1) Frosting Flavor, (G1) Fruit Filling, (H1) Link to PO

Each row of data below these headers corresponds to a new purchase order (PO) with a unique date, client name, etc. View CakeOrders sheet here.

On a second sheet (named Admin) within the same workbook, I have a table that runs match functions to find the Column# for each column header on CakeOrders. This was set up so that my script, which calls upon these Columns#s, will stay accurate even if I end up rearranging or adding Columns and new headers to the CakeOrders sheet—the script will always reference the appropriate column because of the match functions on the Admin sheet. View the Admin sheet here.

I currently have a script set up that allows me to generate new formatted spreadsheets (designed to be blank POs) directly from this spreadsheet. The script names the new sheet (or PO) based on data from within the selected row, and it adds a link to the new PO in Column H.

I would like to extend this script so that it also fills in select cells on the new PO based on information within its originating row.

Does anyone know a script that would allow me to populate specific cells of a new spreadsheet with data from a specific row of another?

Thanks!

Below is my current script, which creates a new spreadsheet with a name based on row content, stores the new sheet in a specific folder, and includes a link to the spreadsheet in the originating row.

function onOpen() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var customMenu = [{name: "Create PO", functionName: "Create"}];
   ss.addMenu("Create PO", customMenu);
};

function Create() {
  var sheet = SpreadsheetApp.getActive().getSheetByName("Admin");
  var folderID = sheet.getRange("B2").getValue(); //These are column numbers
  var templateID = sheet.getRange("B3").getValue();
  var pickupDate = sheet.getRange("B4").getValue();
  var clientName = sheet.getRange("B5").getValue();
  var textOnCake = sheet.getRange("B6").getValue();
  var cakeFlavor = sheet.getRange("B7").getValue();
  var frostingFlavor = sheet.getRange("B8").getValue();
  var fruitFilling = sheet.getRange("B9").getValue();
  var POColumn = sheet.getRange("B10").getValue();

  var ss = SpreadsheetApp.getActiveSheet(); // Back to CakeOrders sheet
  var cell = ss.getActiveCell();
  var row = cell.getRow(); //User has to pick the correct row

  if (row <= 1){
   Browser.msgBox("Cannot create new document within the header. Please select the row to which you'd like to add a new PO doc and run the script again.");
    return;
  }

  try{

  var pickupDateValue = Utilities.formatDate(ss.getRange(row,pickupDate).getValue(), "America/Chicago", "MMddYY");
  }
  catch(e) {
  var pickupDateValue = ss.getRange(row,pickupDate).getValue();
  }

  var clientNameValue = ss.getRange(row,clientName).getValue();//getting the actual values now using column numbers from admin sheet
  var textOnCakeValue = ss.getRange(row,textOnCake).getValue();
  var cakeFlavorValue = ss.getRange(row,cakeFlavor).getValue();
  var frostingFlavorValue = ss.getRange(row,frostingFlavor).getValue();
  var fruitFillingValue = ss.getRange(row,fruitFilling).getValue();
  var POColumnValue = ss.getRange(row,POColumn).getValue();

    if (POColumnValue != ""){
   Browser.msgBox("There is already content in the PO column. Please clear the contents and try again.");
    return;
  }

  if (clientNameValue == "" || textOnCakeValue == "" || cakeFlavor == "" || frostingFlavor == ""|| fruitFilling == ""){
   Browser.msgBox("Client Name, Text On Cake, Cake Flavor, Frosting Flavor, and Fruit Filling are required. Please enter a value in each of these columns and then try again.");
    return;
  }

  var docName = "PO." + pickupDateValue + "." + clientNameValue;

  var template = DriveApp.getFileById(templateID);
  var destFolder = DriveApp.getFolderById(folderID);

  var newDocID = template.makeCopy(docName, destFolder).getId();
  var docLink = "https://docs.google.com/spreadsheets/d/" + newDocID;
  ss.getRange(row,POColumn).setValue(docLink);
}

Body:
I would probably modify the column headings by making them single word Camel Code and use them as the keys for an associative array. So that when I get data from a row I build an array from a table that look like this:

PickupDate  ClientName    Phone         CakeText             CakeFlavor     FrostingFlavor  FruitFilling    LinktoPO
4/15/2017   Bart Simpson  123-456-7899  Your Wierd Bart      Dessert Cactus Frozen Spinach  Tomato
4/16/2017   Bugs Bunny    987-654-3210  Happy Birthdays Bugs Carrot         Carrot          Carrots

To an array that looks like this:

var rowA = {PickupData:'4/16/2017',ClientName:'Bugs Bunny',Phone:'987-654-3210',CakeText:'Happy Birthday Bugs',CakeFlavor:'Carrot',FrostingFlavor:'Carrot', FruitFilling:'Carrots',LinkToPO:''}

Now when you go in to your PO form to fill in data you will be able to enter the data like this:

rowA[PickupData]
rowA[ClientName] etc...

The keys come from the column headers and the values come from which ever row your own.  So it doesn't really matter what the order of the columns is.  And later you can change the names of the variable by changing the names of the columns.

You can store the other information in a file as a string with file.setContent('string') and then take it out with file.getBlob().getDataAsString().split(delimiter) and split it with any delimiter that you choose.  I often choose really wierd ones that you'll never expect to see anywhere like '|@@@|'.

Your final question was "Does anyone know a script that would allow me to populate specific cells of a new spreadsheet with data from a specific row of another?" and here's an answer to that:

function copyToNewSS()
{
  var dstlocdict = {PickupDate:'A1',ClientName:'B2',Phone:'C3',CakeText:'D4',CakeFlavor:'E5',FrostingFlavor:'F6',FruitFilling:'G7',LinktoPO:'H8'}
  var srcss = SpreadsheetApp.getActiveSpreadsheet();
  var srcsht = srcss.getActiveSheet();
  var dstss = SpreadsheetApp.openById('Insert ID of Destination Spreadsheet');
  var dstsht = dstss.getSheetByName('PO');
  var srcrow = srcsht.getActiveCell().getRow();
  if((srcrow - 1)==0 || srcrow > srcsht.getLastRow()){SpreadsheetApp.getUi().alert('Error: Invalid Data Row');return;}
  var srcdatR = srcsht.getDataRange();
  var srcdatA = srcdatR.getValues();
  var srcdatdict = {};
  var srcnumcols = srcsht.getLastColumn();
  var s = '{';
  for(var i = 0;i < srcdatA[srcrow - 1].length; i++)
  {
    srcdatdict[srcdatA[0][i]]= srcdatA[srcrow-1][i];
    if(i>0)s += ', ';
    s += srcdatA[0][i] + ':' + srcdatA[srcrow-1][i];
  }
  myUtilities.dispStatus('Source Data Dictionary for Row ' + srcrow , s, 800, 400)
  for(var key in srcdatdict)
  {
    dstsht.getRange(dstlocdict[key]).setValue(srcdatdict[key]);
  }
}


问:
How to close the DatagramSocket and reuse it
I have this code on which I am receiving data through the android phone

```<code> public void run() {
                try {
                    while(true) {
                        final String hey;
                        int server_port = 9875;
                        byte[] message = new byte[255];
                        DatagramPacket p = new DatagramPacket(message, message.length);
                        DatagramSocket s = new DatagramSocket(server_port);
                        s.receive(p);
                        hey = new String( message, 0 , p.getLength());
                        Log.d("MESSAGE: ", "Message is:" + hey);
                        s.close();

                        //codes for setting the Ultrasonic Sensor
                        if (hey.equals("Strainer is Empty")){
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Empty.setAlpha((float) 0.8);
                                    Full.setAlpha((float) 0.2);
                                    SFull.setAlpha((float) 0.2);
                                    AFull.setAlpha((float) 0.2);

                                }
                            });
                        }

                        if(hey.equals("Strainer is Full")){
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Full.setAlpha((float) 0.8);
                                    Empty.setAlpha((float)0.2);
                                    SFull.setAlpha((float) 0.2);
                                    AFull.setAlpha((float) 0.2);
                                }
                            });
                        }
</code>```

The problem is whenever i go back to my main activity and call this one, error seems to point out on the Datagram Socket. I have read about binding the address but i do not know on how to implement it

答:
I solve the issue when i try to implement it this way</p>

```<code>DatagramSocket s = new DatagramSocket(null);
                        s.setReuseAddress(true);
                        s.setBroadcast(true);
                        s.bind(new InetSocketAddress(server_port));
</code>```

Body:
I have this code on which I am receiving data through the android phone

 public void run() {
                try {
                    while(true) {
                        final String hey;
                        int server_port = 9875;
                        byte[] message = new byte[255];
                        DatagramPacket p = new DatagramPacket(message, message.length);
                        DatagramSocket s = new DatagramSocket(server_port);
                        s.receive(p);
                        hey = new String( message, 0 , p.getLength());
                        Log.d("MESSAGE: ", "Message is:" + hey);
                        s.close();

                        //codes for setting the Ultrasonic Sensor
                        if (hey.equals("Strainer is Empty")){
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Empty.setAlpha((float) 0.8);
                                    Full.setAlpha((float) 0.2);
                                    SFull.setAlpha((float) 0.2);
                                    AFull.setAlpha((float) 0.2);

                                }
                            });
                        }

                        if(hey.equals("Strainer is Full")){
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Full.setAlpha((float) 0.8);
                                    Empty.setAlpha((float)0.2);
                                    SFull.setAlpha((float) 0.2);
                                    AFull.setAlpha((float) 0.2);
                                }
                            });
                        }

The problem is whenever i go back to my main activity and call this one, error seems to point out on the Datagram Socket. I have read about binding the address but i do not know on how to implement it

Body:
I solve the issue when i try to implement it this way

DatagramSocket s = new DatagramSocket(null);
                        s.setReuseAddress(true);
                        s.setBroadcast(true);
                        s.bind(new InetSocketAddress(server_port));


问:
java how can i check a file name and open with FileResource auxFr = new FileResource("/testing/yob" + auxYear + "short.csv");
Using FileResource from edu.duke, how can I check if the file exists before opening it like this?</p>

```<code>FileResource auxFr = new FileResource("/testing/yob" + auxYear + "short.csv");
</code>```

答:
There is an api File.exists() which you can use to check if the file exist. Something like: </p>

```<code>File file = new File("/testing/yob" + auxYear + "short.csv");
if(file.exists()) {
  System.out.println("Exists");
}
</code>```

Body:
Using FileResource from edu.duke, how can I check if the file exists before opening it like this?

FileResource auxFr = new FileResource("/testing/yob" + auxYear + "short.csv");

Body:
There is an api File.exists() which you can use to check if the file exist. Something like:

File file = new File("/testing/yob" + auxYear + "short.csv");
if(file.exists()) {
  System.out.println("Exists");
}


问:
Why does kotlin have componentN functions in data class, if they already have getters and setters?
There is a data class in kotlin, e.g.

```<code>@Entity
data class Record(
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    val id: Long? = null,
    @Column(nullable = false, name = "name")
    var name: String? = null
)
</code>```

And I can call component1 and component2 functions to access the properties. However, as I declare the property var, I have getter and setter, and if I declare property val I have the getter. Are componentN functions are redundant in this case, and why do we need them, because getters seem to be much more self-explanatory?

答:
Kotlin supports the following syntax via componentN functions:

```<code>val (name, age) = person
</code>```

This syntax is called a destructuring declaration. A destructuring declaration creates multiple variables at once. We have declared two new variables: name and age.

A destructuring declaration is compiled down to the following code:

```<code>val name = person.component1()
val age = person.component2()
</code>```

the component1() and component2() functions are another example of the
  principle of conventions widely used in Kotlin (see operators like +
  and *, for-loops etc.). Anything can be on the right-hand side of a
  destructuring declaration, as long as the required number of component
  functions can be called on it. And, of course, there can be
  component3() and component4() and so on.

Note that the componentN() functions need to be marked with the
  operator keyword to allow using them in a destructuring declaration.

Body:
There is a data class in kotlin, e.g.

@Entity
data class Record(
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    val id: Long? = null,
    @Column(nullable = false, name = "name")
    var name: String? = null
)

And I can call component1 and component2 functions to access the properties. However, as I declare the property var, I have getter and setter, and if I declare property val I have the getter. Are componentN functions are redundant in this case, and why do we need them, because getters seem to be much more self-explanatory?

Body:
Kotlin supports the following syntax via componentN functions:

val (name, age) = person

This syntax is called a destructuring declaration. A destructuring declaration creates multiple variables at once. We have declared two new variables: name and age.

A destructuring declaration is compiled down to the following code:

val name = person.component1()
val age = person.component2()

the component1() and component2() functions are another example of the
  principle of conventions widely used in Kotlin (see operators like +
  and *, for-loops etc.). Anything can be on the right-hand side of a
  destructuring declaration, as long as the required number of component
  functions can be called on it. And, of course, there can be
  component3() and component4() and so on.

Note that the componentN() functions need to be marked with the
  operator keyword to allow using them in a destructuring declaration.


问:
numpy array of zeros or empty
I am writing code and efficiency is very important.
Actually I need 2d array, that I am filling with 0 and 1 in for loop. What is better and why?

Make empty array and fill it with "0" and "1". It's pseudocode, my array will be much bigger.

Make array filled by zeros and make if() and if not zero - put one.

So I need information what is more efficiency:
1. Put every element "0" and "1" to empty array
or
2. Make if() (efficiency of 'if') and then put only "1" element.

答: It is better to create array of zeros and fill it using if-else. Even conditions makes slow your code, reshaping empty array or concatenating it with new vectors each iteration of loop is more slower operation, because each time new array of new size is created and old array is copied there together with new vector value by value.</p>

Title: numpy array of zeros or empty


问:
How do I stitch multiple photos together to create necklace structure with imagemagick?
I want create necklace like structure by stitching images together with image magick, how can I achieve this?

We are using PHP to call imagemagick.

Attaching image here...
These small nuts will be separate images

答:
1/ Resize, crop and mask your images - round image on transparent background.

2/ Assuming you always have the same amount of images; work out the positions and composite your images into the position on the blank canvas.

There is a lot more you can do like adding drop shadows or adding a glossy button finish etc.

Stackoverflow is not here to provide code for you but to help you with any code you have. You can find a lot of examples here: https://www.imagemagick.org/Usage/ and they will all work with php and exec()