问:
Android: Failed to build project with Android Studio 3.6
Can anyone help me fix this error? I got the error "Entry name 'AndroidManifest.xml' collided" on Android Studio 3.6. However, I could not find anything wrong with the file. All activities are defined correctly. Below are the details of 'AndroidManifest.xml':</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.cmd.getcoin">

    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <meta-data
            android:name="com.google.android.gms.ads.APPLICATION_ID"
            android:value="ca-app-pub-xxxxxxxxxxxx~xxxxxxxxxxx" />

        <activity android:name=".ui.activity.RewardAdsActivity" />
        <activity
            android:name=".ui.activity.InstallAppActivity"
            android:theme="@style/AppTheme.NoActionBar" />
        <activity
            android:name=".ui.activity.LuckyActivity"
            android:theme="@style/AppTheme.NoActionBar" />
        <activity
            android:name=".ui.activity.MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar" />
        <activity
            android:name=".ui.activity.LoginActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity> <!-- Facebook Configuration -->
        <meta-data
            android:name="com.facebook.sdk.ApplicationId"
            android:value="@string/facebook_application_id"
            tools:replace="android:value" />

        <activity
            android:name="com.facebook.FacebookActivity"
            android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
            android:label="@string/app_name"
            android:theme="@android:style/Theme.Translucent.NoTitleBar"
            tools:replace="android:theme" />

    </application>

</manifest>
</code>```

答:
Double check your dependencies.
Some of them may use support instead of androidx.

I've fixed same problem in that way

Body:
Can anyone help me fix this error? I got the error "Entry name 'AndroidManifest.xml' collided" on Android Studio 3.6. However, I could not find anything wrong with the file. All activities are defined correctly. Below are the details of 'AndroidManifest.xml':

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.cmd.getcoin">

    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <meta-data
            android:name="com.google.android.gms.ads.APPLICATION_ID"
            android:value="ca-app-pub-xxxxxxxxxxxx~xxxxxxxxxxx" />

        <activity android:name=".ui.activity.RewardAdsActivity" />
        <activity
            android:name=".ui.activity.InstallAppActivity"
            android:theme="@style/AppTheme.NoActionBar" />
        <activity
            android:name=".ui.activity.LuckyActivity"
            android:theme="@style/AppTheme.NoActionBar" />
        <activity
            android:name=".ui.activity.MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar" />
        <activity
            android:name=".ui.activity.LoginActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <meta-data
            android:name="com.facebook.sdk.ApplicationId"
            android:value="@string/facebook_application_id"
            tools:replace="android:value" />

        <activity
            android:name="com.facebook.FacebookActivity"
            android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
            android:label="@string/app_name"
            android:theme="@android:style/Theme.Translucent.NoTitleBar"
            tools:replace="android:theme" />

    </application>

</manifest>


来源: stackexchange

问:
How to display values of an array as colored lattice points?
I am creating a python program that simulates the folding of proteins. My protein is 19 elements (amino acids) long, with each element specified by a number between 1 and 20. I used randint() to create the protein and created an array of zeros.

The protein is initially unfolded and centered horizontally in a 21 by 21 array. So the nonzero values of the array are on the 10th row. I imported matplotlib and used matshow() to display this arrangement:

.

What I like about this figure is that it is apparent that the protein is made up of different amino acids/elements, as shown by color of each square. I would like to keep this feature. However, instead of squares I would like each element to show up as a colored dot connected to its neighbor by a link, or on a grid:

 .

I have provided my code below. To summarize my questions:

1) How do I display the elements in an array as circles or as lattice points with links connecting the dots?

2) How do I do the above while keeping the colors the same for each element?

3) How do I specify that the zero-values (currently purple) should be white? I don't have a preference for the other colors, I would like a white background.

```<code>import numpy as np
import matplotlib.pyplot as plt
import random
from matplotlib.colors import ListedColormap

###create grid
rows = 21
columns = 21
x = np.zeros(rows) #create arrays for the x- and y-positions
y = np.zeros(columns)
middle = (rows-1)/2

grid = np.zeros((rows,columns)) #grid = [row][columns] = value = grid[j][i]

###create protein:
n = 20
protein = []
while len(protein) < n:
     a = random.randint(1, 20)
     protein = np.append(protein, a)

###specify initial condition with protein unfolded along y=0
j = int(middle)
i = 1
while i < rows-1:
    grid[j][i] = protein[i]
    i = i+1
print(grid)
plt.matshow(grid)
</code>```

答:
Q1 & 2-
I think you're looking to add a scatter plot with different colour markers on top of your current graph. Might be tricky to add both a line and different colour markers so your best bet might be to simply add a line plot that relies on the same x/y values so that the two are updated at the same time (assuming you are updating them to display folding). Given code is just the scatter but it maintains your current colour system.

Edit: See the other answer for a great example of this (scatter and plot).

```<code>import matplotlib.colors as mcolors
from matplotlib import cm
normalize = mcolors.Normalize(vmin=0, vmax=20)
mapping = cm.viridis(normalize(protein))  # maintain current colours
plt.scatter(range(20), np.broadcast_to(10, 20), c=mapping, marker='o')
</code>```

Q3-
You can set values for a specific colourmap to display particular colours with .set_under, see for example this answer- https://stackoverflow.com/a/22552651/9754355 This should make your mapping background white.

```<code>cm.viridis.set_under(c='w')
plt.matshow(grid, vim=1e-9)  # Arbitrary low value.
</code>```

If this negatively affects your protein colours consider using numpy NaN or infinty or something similar and set_bad instead.

ContentLicense: CC BY-SA 4.0

Body:
I am creating a python program that simulates the folding of proteins. My protein is 19 elements (amino acids) long, with each element specified by a number between 1 and 20. I used randint() to create the protein and created an array of zeros.

The protein is initially unfolded and centered horizontally in a 21 by 21 array. So the nonzero values of the array are on the 10th row. I imported matplotlib and used matshow() to display this arrangement:

.

What I like about this figure is that it is apparent that the protein is made up of different amino acids/elements, as shown by color of each square. I would like to keep this feature. However, instead of squares I would like each element to show up as a colored dot connected to its neighbor by a link, or on a grid:

 .

I have provided my code below. To summarize my questions:

1) How do I display the elements in an array as circles or as lattice points with links connecting the dots?

2) How do I do the above while keeping the colors the same for each element?

3) How do I specify that the zero-values (currently purple) should be white? I don't have a preference for the other colors, I would like a white background.

import numpy as np
import matplotlib.pyplot as plt
import random
from matplotlib.colors import ListedColormap

###create grid
rows = 21
columns = 21
x = np.zeros(rows) #create arrays for the x- and y-positions
y = np.zeros(columns)
middle = (rows-1)/2

grid = np.zeros((rows,columns)) #grid = [row][columns] = value = grid[j][i]

###create protein:
n = 20
protein = []
while len(protein) < n:
     a = random.randint(1, 20)
     protein = np.append(protein, a)

###specify initial condition with protein unfolded along y=0
j = int(middle)
i = 1
while i < rows-1:
    grid[j][i] = protein[i]
    i = i+1
print(grid)
plt.matshow(grid)

Body:
Q1 & 2-
I think you're looking to add a scatter plot with different colour markers on top of your current graph. Might be tricky to add both a line and different colour markers so your best bet might be to simply add a line plot that relies on the same x/y values so that the two are updated at the same time (assuming you are updating them to display folding). Given code is just the scatter but it maintains your current colour system.

Edit: See the other answer for a great example of this (scatter and plot).

import matplotlib.colors as mcolors
from matplotlib import cm
normalize = mcolors.Normalize(vmin=0, vmax=20)
mapping = cm.viridis(normalize(protein))  # maintain current colours
plt.scatter(range(20), np.broadcast_to(10, 20), c=mapping, marker='o')

Q3-
You can set values for a specific colourmap to display particular colours with .set_under, see for example this answer- https://stackoverflow.com/a/22552651/9754355 This should make your mapping background white.

cm.viridis.set_under(c='w')
plt.matshow(grid, vim=1e-9)  # Arbitrary low value.

If this negatively affects your protein colours consider using numpy NaN or infinty or something similar and set_bad instead.


问:
Not getting the expected output (compound interest calculator)
The expected output if I enter £100, 0.10, 10 (10 years) should be £259.37, but I'm getting 100.00000001000001</p>
```<code>using System;
using System.Security.Cryptography;

namespace compound_interest
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Please enter the amount of money that is being compounded! ");
            double P = Convert.ToDouble(Console.ReadLine());
            Console.Write("Please enter the amount of interest (write it is 0.10 for 10% etc!! ");
            double MP2 = Convert.ToDouble(Console.ReadLine());
            Console.Write("Please enter the number of years");
            double Y = Convert.ToDouble(Console.ReadLine());
            double MP1 = Convert.ToDouble(Math.Pow(MP2, Y));
            double MP = (MP1) + 1;
            double A = (P) * (MP);
            Console.WriteLine(A);
        }
    }
}
</code>```

答:
Before you do this

```<code> double MP1 = Convert.ToDouble(Math.Pow(MP2, Y));
</code>```

Do this

```<code> MP2 = 1 + MP2
</code>```

Body:
The expected output if I enter £100, 0.10, 10 (10 years) should be £259.37, but I'm getting 100.00000001000001

using System;
using System.Security.Cryptography;

namespace compound_interest
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Please enter the amount of money that is being compounded! ");
            double P = Convert.ToDouble(Console.ReadLine());
            Console.Write("Please enter the amount of interest (write it is 0.10 for 10% etc!! ");
            double MP2 = Convert.ToDouble(Console.ReadLine());
            Console.Write("Please enter the number of years");
            double Y = Convert.ToDouble(Console.ReadLine());
            double MP1 = Convert.ToDouble(Math.Pow(MP2, Y));
            double MP = (MP1) + 1;
            double A = (P) * (MP);
            Console.WriteLine(A);
        }
    }
}

Body:
Before you do this

 double MP1 = Convert.ToDouble(Math.Pow(MP2, Y));

Do this

 MP2 = 1 + MP2


问:
Plotting percentage in seaborn bar plot
For a dataframe

```<code>import pandas as pd
df=pd.DataFrame({'group':list("AADABCBCCCD"),'Values':[1,0,1,0,1,0,0,1,0,1,0]})
</code>```

I am trying to plot a barplot showing percentage of times A, B, C, D takes zero (or one).

I have a round about way which works but I am thinking there has to be more straight forward way

```<code>tempdf=df.groupby(['group','Values']).Values.count().unstack().fillna(0)
tempdf['total']=df['group'].value_counts()
tempdf['percent']=tempdf[0]/tempdf['total']*100

tempdf.reset_index(inplace=True)
print tempdf

sns.barplot(x='group',y='percent',data=tempdf)
</code>```

If it were plotting just the mean value, I could simply do sns.barplot on df dataframe than tempdf. I am not sure how to do it elegantly if I am interested in plotting percentages.

Thanks,

答:
You can follow these steps so that you can see the count and percentages on top of the bars in your plot. Check the example outputs down below

with_hue function will plot percentages on the bar graphs if you have the 'hue' parameter in your plots. It takes the actual graph, feature, Number_of_categories in feature, and hue_categories(number of categories in hue feature) as a parameter.

without_hue function will plot percentages on the bar graphs if you have a normal plot. It takes the actual graph and feature as a parameter.

```<code>def with_hue(plot, feature, Number_of_categories, hue_categories):
    a = [p.get_height() for p in plot.patches]
    patch = [p for p in plot.patches]
    for i in range(Number_of_categories):
        total = feature.value_counts().values[i]
        for j in range(hue_categories):
            percentage = '{:.1f}%'.format(100 * a[(j*Number_of_categories + i)]/total)
            x = patch[(j*Number_of_categories + i)].get_x() + patch[(j*Number_of_categories + i)].get_width() / 2 - 0.15
            y = patch[(j*Number_of_categories + i)].get_y() + patch[(j*Number_of_categories + i)].get_height()
            ax.annotate(percentage, (x, y), size = 12)
    plt.show()

def without_hue(plot, feature):
    total = len(feature)
    for p in ax.patches:
        percentage = '{:.1f}%'.format(100 * p.get_height()/total)
        x = p.get_x() + p.get_width() / 2 - 0.05
        y = p.get_y() + p.get_height()
        ax.annotate(percentage, (x, y), size = 12)
    plt.show()
</code>```

Title: Plotting percentage in seaborn bar plot

Body:
For a dataframe

import pandas as pd
df=pd.DataFrame({'group':list("AADABCBCCCD"),'Values':[1,0,1,0,1,0,0,1,0,1,0]})

I am trying to plot a barplot showing percentage of times A, B, C, D takes zero (or one).

I have a round about way which works but I am thinking there has to be more straight forward way

tempdf=df.groupby(['group','Values']).Values.count().unstack().fillna(0)
tempdf['total']=df['group'].value_counts()
tempdf['percent']=tempdf[0]/tempdf['total']*100

tempdf.reset_index(inplace=True)
print tempdf

sns.barplot(x='group',y='percent',data=tempdf)

If it were plotting just the mean value, I could simply do sns.barplot on df dataframe than tempdf. I am not sure how to do it elegantly if I am interested in plotting percentages.

Thanks,

Body:
You can follow these steps so that you can see the count and percentages on top of the bars in your plot. Check the example outputs down below

with_hue function will plot percentages on the bar graphs if you have the 'hue' parameter in your plots. It takes the actual graph, feature, Number_of_categories in feature, and hue_categories(number of categories in hue feature) as a parameter.

without_hue function will plot percentages on the bar graphs if you have a normal plot. It takes the actual graph and feature as a parameter.

def with_hue(plot, feature, Number_of_categories, hue_categories):
    a = [p.get_height() for p in plot.patches]
    patch = [p for p in plot.patches]
    for i in range(Number_of_categories):
        total = feature.value_counts().values[i]
        for j in range(hue_categories):
            percentage = '{:.1f}%'.format(100 * a[(j*Number_of_categories + i)]/total)
            x = patch[(j*Number_of_categories + i)].get_x() + patch[(j*Number_of_categories + i)].get_width() / 2 - 0.15
            y = patch[(j*Number_of_categories + i)].get_y() + patch[(j*Number_of_categories + i)].get_height()
            ax.annotate(percentage, (x, y), size = 12)
    plt.show()

def without_hue(plot, feature):
    total = len(feature)
    for p in ax.patches:
        percentage = '{:.1f}%'.format(100 * p.get_height()/total)
        x = p.get_x() + p.get_width() / 2 - 0.05
        y = p.get_y() + p.get_height()
        ax.annotate(percentage, (x, y), size = 12)
    plt.show()


问:
Python JSON Formatting for Redis Cache
I'm relatively new to working with JSON and am trying to output a dictionary to JSON using the json library in python. The issue I have is the format is very specific and I'm not sure how to approach. Specifically the desired format has extra braces and brackets. Below is an example of the dictionary I'm converting to JSON and the desired output:</p>

```<code>    #Sample Data
sample_dict = {"office":{"50":"pencil;paper",
                      "100":"stapler;eraser"},
             "warehouse":{"50":"forklift;wrench",
                         "100":"truck,screw"}}

with open('test.json', 'w') as f:
    json.dump(sample_dict, f,indent = 4)

##Output I'm able to acheive
{
    "office": {
        "50": "pencil;paper",
        "100": "stapler;eraser"
    },
    "warehouse": {
        "50": "forklift;wrench",
        "100": "truck,screw"
    }
}

##Desired Output
[{
    {"office": {
        "50": "pencil;paper",
        "100": "stapler;eraser"
    }},
    {"warehouse": {
        "50": "forklift;wrench",
        "100": "truck,screw"
    }}
}]
</code>```

答:
I think you need to make the "sample_dict" a string with square brackets.

```<code>import json

sample_dict = '[{"office":{"50":"pencil;paper", "100":"stapler;eraser"}, "warehouse":{"50":"forklift;wrench", "100":"truck,screw"}}]'

load=json.loads(sample_dict)
print(json.dumps(load, indent=4))
</code>```

Title: Python JSON Formatting for Redis Cache

Body:
I'm relatively new to working with JSON and am trying to output a dictionary to JSON using the json library in python. The issue I have is the format is very specific and I'm not sure how to approach. Specifically the desired format has extra braces and brackets. Below is an example of the dictionary I'm converting to JSON and the desired output:

    #Sample Data
sample_dict = {"office":{"50":"pencil;paper",
                      "100":"stapler;eraser"},
             "warehouse":{"50":"forklift;wrench",
                         "100":"truck,screw"}}

with open('test.json', 'w') as f:
    json.dump(sample_dict, f,indent = 4)

##Output I'm able to acheive
{
    "office": {
        "50": "pencil;paper",
        "100": "stapler;eraser"
    },
    "warehouse": {
        "50": "forklift;wrench",
        "100": "truck,screw"
    }
}

##Desired Output
[{
    {"office": {
        "50": "pencil;paper",
        "100": "stapler;eraser"
    }},
    {"warehouse": {
        "50": "forklift;wrench",
        "100": "truck,screw"
    }}
}]

Body:
I think you need to make the "sample_dict" a string with square brackets.

import json

sample_dict = '[{"office":{"50":"pencil;paper", "100":"stapler;eraser"}, "warehouse":{"50":"forklift;wrench", "100":"truck,screw"}}]'

load=json.loads(sample_dict)
print(json.dumps(load, indent=4))


答:
The extra [] would be easy — the whole dictionary is in a list. However, the extra {} are not; the sample you posted is not, in fact, valid JSON.

At this point, you'll need to clarify whether the output should be JSON or whether it should match the given sample.

If the output should be JSON, you'll need to get a correct sample output, then work from there. At a minimum, the top level is a list of dictionaries.

If the output should match the given sample, it's not JSON and you won't be using the json library. Depending on the situation, you can:

format it up with Python string formatting (% or .format() or f"..." strings); or

use a templating library like Jinja or Mako or similar; or

if the data structure is extensive and the format is consistent, write your own library for outputting that format.

Title: Python JSON Formatting for Redis Cache


问:
Pandas: Transform column to join unique elements
I am doing a groupby in Pandas to combine data however I want to only include the unique elements in the column.

I am currently running:

```<code>df.groupby(['Col1','Col2'])['Grade'].transform(lambda x: ','.join(x))
</code>```

which will produce:

```<code>Col1   Col2   Grade
1      1      A-,A-,B+
1      2      A,B,B-,B-
2      1      B,C,C,D
...
</code>```

How do I perform a join only on the unique elements of the grade column so my output looks like:

```<code>Col1   Col2   Grade
1      1      A-,B+
1      2      A,B,B-
2      1      B,C,D
...
</code>```

答:
Use set to drop duplicates in your aggregation:

```<code>df.groupby(['Col1','Col2'])['Grade'].transform(lambda x: ','.join(set(x)))
</code>```

Or to keep the correct order, use np.unique:

```<code>df.groupby(['Col1','Col2'])['Grade'].transform(lambda x: ','.join(np.unique(x)))
</code>```

Body:
I am doing a groupby in Pandas to combine data however I want to only include the unique elements in the column.

I am currently running:

df.groupby(['Col1','Col2'])['Grade'].transform(lambda x: ','.join(x))

which will produce:

Col1   Col2   Grade
1      1      A-,A-,B+
1      2      A,B,B-,B-
2      1      B,C,C,D
...

How do I perform a join only on the unique elements of the grade column so my output looks like:

Col1   Col2   Grade
1      1      A-,B+
1      2      A,B,B-
2      1      B,C,D
...

Body:
Use set to drop duplicates in your aggregation:

df.groupby(['Col1','Col2'])['Grade'].transform(lambda x: ','.join(set(x)))

Or to keep the correct order, use np.unique:

df.groupby(['Col1','Col2'])['Grade'].transform(lambda x: ','.join(np.unique(x)))


问:
How do I transform a data table column from cumulative to difference when reading CSV into spring boot application?
I have data in a table like

```<code>   date  | city | Cumulative total
---------------------------------
1/1/2020 | NYC  |    10
1/2/2020 | NYC  |    15
1/3/2020 | NYC  |    31
1/4/2020 | NYC  |    36
1/5/2020 | NYC  |    55
 .
 .  // more data for NYC continued
 .
1/1/2020 | BER  |    1
1/2/2020 | BER  |    5
1/3/2020 | BER  |    13
1/4/2020 | BER  |    42
1/5/2020 | BER  |    45
 .
 .  // more data for BER continued
 .
</code>```

I want this data to not hold the cumulative, but rather hold the difference. Basically I want to subtract the next day from the day before it, making sure that the cities match up.

```<code>   date  | city | Cumulative total
---------------------------------
1/1/2020 | NYC  |    10
1/2/2020 | NYC  |    5
1/3/2020 | NYC  |    16
1/4/2020 | NYC  |    5
1/5/2020 | NYC  |    19
 .
 .  // more data for NYC continued
 .
1/1/2020 | BER  |    1
1/2/2020 | BER  |    4
1/3/2020 | BER  |    8
1/4/2020 | BER  |    29
1/5/2020 | BER  |    3
 .
 .  // more data for BER continued
 .
</code>```

I have the data within a CSV and am to load it into a database for a spring boot application. However, the spring boot application needs the difference, not the cumulative. How can I properly transform this data either

Within the database upon reading the data from the CSV?

By writing a special query within the JpaRepository so that my POJO's come back as the transformed data?

I have no idea how to implement either of the previous, but they are my ideas for what to do. I ask that someone help me see what the most "industry standard" way to handle this situation is. Maybe there is a better way than what I proposed.

Thanks!

答:
If your database supports window functions, this is an easy task for lag(), which lets you access any column on the previous row, given a partition and order by specification:

```<code>select
    t.*,
    cumulative
        - lag(cumulative, 1, 0) over(partition by city order by date) as difference
from mytable t
</code>```

Not all databases support the 3-argument form of lag(), in which case you can do:

```<code>select
    t.*,
    coalesce(
        cumulative - lag(cumulative) over(partition by city order by date),
        cumulative
    ) difference
from mytable t
</code>```

Body:
I have data in a table like

   date  | city | Cumulative total
---------------------------------
1/1/2020 | NYC  |    10
1/2/2020 | NYC  |    15
1/3/2020 | NYC  |    31
1/4/2020 | NYC  |    36
1/5/2020 | NYC  |    55
 .
 .  // more data for NYC continued
 .
1/1/2020 | BER  |    1
1/2/2020 | BER  |    5
1/3/2020 | BER  |    13
1/4/2020 | BER  |    42
1/5/2020 | BER  |    45
 .
 .  // more data for BER continued
 .

I want this data to not hold the cumulative, but rather hold the difference. Basically I want to subtract the next day from the day before it, making sure that the cities match up.

   date  | city | Cumulative total
---------------------------------
1/1/2020 | NYC  |    10
1/2/2020 | NYC  |    5
1/3/2020 | NYC  |    16
1/4/2020 | NYC  |    5
1/5/2020 | NYC  |    19
 .
 .  // more data for NYC continued
 .
1/1/2020 | BER  |    1
1/2/2020 | BER  |    4
1/3/2020 | BER  |    8
1/4/2020 | BER  |    29
1/5/2020 | BER  |    3
 .
 .  // more data for BER continued
 .

I have the data within a CSV and am to load it into a database for a spring boot application. However, the spring boot application needs the difference, not the cumulative. How can I properly transform this data either

Within the database upon reading the data from the CSV?

By writing a special query within the JpaRepository so that my POJO's come back as the transformed data?

I have no idea how to implement either of the previous, but they are my ideas for what to do. I ask that someone help me see what the most "industry standard" way to handle this situation is. Maybe there is a better way than what I proposed.

Thanks!

Body:
If your database supports window functions, this is an easy task for lag(), which lets you access any column on the previous row, given a partition and order by specification:

select
    t.*,
    cumulative
        - lag(cumulative, 1, 0) over(partition by city order by date) as difference
from mytable t

Not all databases support the 3-argument form of lag(), in which case you can do:

select
    t.*,
    coalesce(
        cumulative - lag(cumulative) over(partition by city order by date),
        cumulative
    ) difference
from mytable t


问:
Python Web Framework for Small Team
I have 4 days off and I will use this time to rewrite our RoR (Ruby on Rails) Application in a python web framework just for fun ;-] (and why not make the switch, RoR is great but keep changing all the time, can be exhausting.)

I don't know the python web framework very well, I've glad web.py, django, cherry.py, pylons/pyramid and few others. Our requirements are (put everything can be irrelevant) :

MVC (Strict or not)

Small Team (2-3 people included one designer)

Fun to use

REST support

Multilevel caching (DB query, page cache)

Nginx Support (X-Accel-Redirect File Download)

Heavy traffic (1,200,000 ~ views)

Urls rewrting (Multi-domains support not only subdomain)

Not a problem if it's not hype

Not a problem if there is no plugins

Either SQL or NOSQL (can be fun to try NOSQL)

So what you would advise ?

答:
Of the frameworks you've mentioned, Django has the most momentum and is most likely to fit your ideals of a framework, coming from a Rails background. By this I mean it has helpers that allow you to generate your forms quickly, though no scaffolding. (In fact, Django's way is a little better than scaffolding in Rails because you can use all or just pieces of it)

It has a good ORM with lots of helper methods and, one of the best features, it has a fully functional admin interface once you define your models. You can start porting data even while the site is being developed.

It also provides excellent user support, including permissions, access control, groups, user profiles.

It's easy (and fun) to create your own middleware and context processors that let you abstract out often reused pieces as plugins to the framework.

The only feature Django doesn't have that you specified above is the NoSQL support. And this is only half true. If you want to use a non relational database for some parts of your app, such as session storage, you can. If you want to use it as your exclusive backend you'll lose some of Django's awesome features unless you patch Django with django-nonrel.

I've used turbo gears which is a combination of several of the other options you mentioned. That community has some great people in it but they're currently experiencing a major architecture revamp and honestly, they're just not getting as much developer attention as Django.

ContentLicense: CC BY-SA 3.0

Title: Python Web Framework for Small Team


问:
Input/If statement - correct way of writing
I am currently taking part of a beginner Python code challenge and whilst my code runs how it should, the solution is written differently to my program.

As I am just starting out, I was wondering which way is more preferable to write the program,

The solution is:

```<code># Prompt user if they want to proceed. Y/N?
should_proceed = input("Do you want to proceed? Y/N ")

# If they want to proceed
if should_proceed.lower() == "y":
    # print out to the screen "SOLD!" to confirm purchase
    # TODO: Gatjer credit card information and process it.
    print("SOLD!")
    # and then decrement the tickets remaining by the number of tickets purchased
    tickets_remaining -= num_tickets
# Otherwise...
else:
    # Thank them by name
    print("Thank you anyways, {}!".format(name))
</code>```

Whereas, I have put:

```<code># Prompt user if they want to proceed. Y/N?
proceed = input("Would you like to proceed? Y/N ").upper()

# If they want to proceed
if proceed == "Y":
    # print out to the screen "SOLD!" to confirm purchase
    # TODO: Gatjer credit card information and process it.
    print("SOLD!")
    # and then decrement the tickets remaining by the number of tickets purchased
    tickets_remaining = tickets_remaining - ticket_request
    print(tickets_remaining)
# Otherwise...
elif proceed == "N":
    # Thank them by name
    print("Thank you for your time, {}".format(customer_name))
</code>```

Was it incorrect to call upper() on the input?

Is there any other errors I have done?

Many thanks,

答:
Was it incorrect to call upper() on the input?

No, this is a perfectly fine way to allow case-insensitive input. Their solution shows an alternative that works just as well.

Body:
I am currently taking part of a beginner Python code challenge and whilst my code runs how it should, the solution is written differently to my program.

As I am just starting out, I was wondering which way is more preferable to write the program,

The solution is:

# Prompt user if they want to proceed. Y/N?
should_proceed = input("Do you want to proceed? Y/N ")

# If they want to proceed
if should_proceed.lower() == "y":
    # print out to the screen "SOLD!" to confirm purchase
    # TODO: Gatjer credit card information and process it.
    print("SOLD!")
    # and then decrement the tickets remaining by the number of tickets purchased
    tickets_remaining -= num_tickets
# Otherwise...
else:
    # Thank them by name
    print("Thank you anyways, {}!".format(name))

Whereas, I have put:

# Prompt user if they want to proceed. Y/N?
proceed = input("Would you like to proceed? Y/N ").upper()

# If they want to proceed
if proceed == "Y":
    # print out to the screen "SOLD!" to confirm purchase
    # TODO: Gatjer credit card information and process it.
    print("SOLD!")
    # and then decrement the tickets remaining by the number of tickets purchased
    tickets_remaining = tickets_remaining - ticket_request
    print(tickets_remaining)
# Otherwise...
elif proceed == "N":
    # Thank them by name
    print("Thank you for your time, {}".format(customer_name))

Was it incorrect to call upper() on the input?

Is there any other errors I have done?

Many thanks,


问:
Stop waiting time out for resources in chrome automation
I have automated chrome with Python Selenium Webdriver. Is there any chrome option or method to stop waiting for third party resources ?

When i launched google-chrome in debug mode, it's waiting on below google fonts for 2 minutes.

https://fonts.googleapis.com/css?family=Open+Sans:400,300,500,600,700,800

https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900

Environment Limitations
 1. No internet
 2. No sudo permission

This is not a rendering issue, browser is waiting on those resources and selenium is giving timeout exception. Need to stop this waiting time and continue automation without errors.

答: Selenium Wire has a way of waiting for requests to finish before proceeding with test execution. See https://pypi.org/project/selenium-wire/#waiting-for-a-request</p>


问:
How to fail aws_instance creation if user_data fails to run to completion
Is it possible to fail an aws_instance creation if script passed into user_data fails to run? e.g., with exit 1?

I have a null_resource that uses depends_on [aws_instance.myVM] to post a JSON to the instance, and I need that depends_on to fail when the user_data script fails.

Thanks!

答:
user_data is handled by software running inside the instance itself, such as cloud-init, and so its processing is asynchronous from the ec2:RunInstances call that Terraform's AWS provider makes to start the instance running. There is therefore no way to feed back status information from the user_data handling because it could potentially be running some time after the EC2 API starts reporting that the instance is "running", depending on where in the boot process it's dealt with.

Also, depends_on is for ordering rather than for handling errors, so a depends_on clause will never change anything about Terraform's error handling.

If you want to run software on your instance synchronously as part of Terraform's create operation then unfortunately the only practical option is to use the remote-exec provisioners. This comes at the expense of some considerable extra complexity, because Terraform must now be able to open an SSH session with the instance and authenticate with it to create a two-way communications channel.

In return for that complexity, Terraform can be the one to run the code in question and so Terraform can detect whether it succeeded or not (using its exit status). If the remote command fails, Terraform will halt further processing, return an error, and mark the instance as tainted so that the next plan will attempt to create it again.

With that said, it may be better to find a different way to achieve your goal that doesn't require coupling the Terraform run directly to the state of the software running in the virtual machine. It's not usually expected that a Terraform configuration should need to both start up a virtual machine and interact with software running in that virtual machine in the same operation. This could be a good point for some system decomposition, where you'd have one Terraform configuration that declares that the virtual machine should exist and then a second configuration that assumes that the virtual machine exists and takes actions against it. You can then run whatever other software you need to run in between those two, in order to check whether the instance started up successfully.


问:
HTTPoison request failes on specific machine but works in another machine
Am doing a post with HTTPoison, on one machine everything works well, but in the other the same code, with similar environment parameters.

```<code>HTTPoison.post!("https://remote_api", "", [{"X-TOKEN", System.get_env("API_TOKEN"}, {"Content-Type", "application/json"}])
</code>```

fails with

```<code>** (HTTPoison.Error) {:options, {:sslv3, {:versions, [:"tlsv1.2", :"tlsv1.1", :tlsv1, :sslv3]}}}
    (httpoison) lib/httpoison.ex:128: HTTPoison.request!/5
</code>```

both machines are setup the same running centos7, but i get expected results in one but not in the other. am not sure what i got wrong

Downgrading to OTP 22 fixed it, thanks Aleksei Matiushkin.

答:
Bumping hackney to version 1.16 worked for me.

```<code> defp deps do
    [
      ...
      {:httpoison, "~> 1.6"},
      {:hackney, "~> 1.16"}
    ]
  end
</code>```

Body:
Am doing a post with HTTPoison, on one machine everything works well, but in the other the same code, with similar environment parameters.

HTTPoison.post!("https://remote_api", "", [{"X-TOKEN", System.get_env("API_TOKEN"}, {"Content-Type", "application/json"}])

fails with

** (HTTPoison.Error) {:options, {:sslv3, {:versions, [:"tlsv1.2", :"tlsv1.1", :tlsv1, :sslv3]}}}
    (httpoison) lib/httpoison.ex:128: HTTPoison.request!/5

both machines are setup the same running centos7, but i get expected results in one but not in the other. am not sure what i got wrong

Downgrading to OTP 22 fixed it, thanks Aleksei Matiushkin.

Body:
Bumping hackney to version 1.16 worked for me.

 defp deps do
    [
      ...
      {:httpoison, "~> 1.6"},
      {:hackney, "~> 1.16"}
    ]
  end


问:
Is there a way to mock Facter::Core::Execution.execute output in ruby?
I have a custom fact in ruby that uses Facter::Core::Execution.execute to execute a system command and sets the fact to true or false based on the output of the execute command. Is there a way I could mock the output of the execute command to test it?

答:
Using rspec:</p>

```<code>expect(Facter::Core::Execution).to receive(:execute).and_return(true)
</code>```

Body:
Using rspec:

expect(Facter::Core::Execution).to receive(:execute).and_return(true)


问:
How to get intellisense of mapGetters, mapActions Vuex and typescript without class-style or decorators syntax
I use Vue.js and Vuex for some time, but always with javascript.

I'm trying to use Vue with Typescript, nuxt.js to be more specifically, but without using decorators or style-class-component, only continue with the normal Vue syntax

This is the code I have in my Vuex store

/store/todos/types.ts

```<code>export interface Todo {
  id: number
  text: string
  done: boolean
}

export interface TodoState {
  list: Todo[]
}

</code>```

/store/todos/state.ts

```<code>import { TodoState } from './types'

export default (): TodoState => ({
  list: [
    {
      id: 1,
      text: 'first todo',
      done: true
    },
    {
      id: 2,
      text: 'second todo',
      done: false
    }
  ]
})

</code>```

/store/todos/mutations.ts

```<code>import { MutationTree } from 'vuex'
import { TodoState, Todo } from './types'

export default {
  remove(state, { id }: Todo) {
    const index = state.list.findIndex((x) => x.id === id)
    state.list.splice(index, 1)
  }
} as MutationTree<TodoState>

</code>```

/store/todos/actions.ts

```<code>import { ActionTree } from 'vuex'
import { RootState } from '../types'
import { TodoState, Todo } from './types'

export default {
  delete({ commit }, { id }: Todo): void {
    commit('remove', id)
  }
} as ActionTree<TodoState, RootState>

</code>```

/store/todos/getters.ts

```<code>import { GetterTree } from 'vuex'
import { RootState } from '../types'
import { TodoState, Todo } from './types'

export default {
  list(state): Todo[] {
    return state.list
  }
} as GetterTree<TodoState, RootState>

</code>```

This is code that I have my component,

```<code><template>
  <div>
    <ul>
      <li v-for="todo in todos" :key="todo.id">
        {{ todo.text }}
        <button @click="destroy(todo)">delete</button>
      </li>
    </ul>
  </div>
</template>

<script lang="ts">
import Vue from 'vue'
import { mapGetters, mapActions } from 'vuex'

export default Vue.extend({
  computed: {
    ...mapGetters({
      todos: 'todos/list'
    })
  },
  methods: {
    ...mapActions({
      destroy: 'todos/delete'
    })
  }
})
</script>

</code>```

Everything works perfectly, except the auto complete / intellisense of the getters or actions that came from Vuex

Someone can help me?

Thanks for this o/

答:
Vuex, in current form, doesn't work well with Typescript. That's probably going to change in Vue 3.

Just as you, I also don't want to use @Component decorators, especially because they have been deprecated. However, when it comes to using the default Vue typescript component style:

```<code><script lang="ts">
  import Vue from 'vue';
  export default Vue.extend({...})
</script>
</code>```

... after testing multiple solutions I found the easiest to use is actually a plugin which does use decorators: vuex-module-decorators

Vuex module:

I typically leave the parent state clean (empty) and use namespaced modules. I do it mostly because more than once I decided at the end of the project it would be cleaner to have more than one module, and it's more of a hassle to move it from parent to module than to simply create an additional module.

The store looks like this:

import Vue from 'vue';
import Vuex from 'vuex';
import { getModule } from 'vuex-module-decorators';
import Whatever from '@/store/whatever';

Vue.use(Vuex);

const store = new Vuex.Store({
  modules: {
    whatever: Whatever
  }
});

getModule(Whatever, store); // this is important for typescript to work properly

export type State = typeof store.state;
export default store;
```

<p>Here are a few examples of <code>mapState</code>, <code>mapGetters</code> or get/set computed that work directly with the store:</p>

```computed: {
  ...mapGetters({
    foo: 'whatever/foo',
    bar: 'whatever/bar'
  }),
  ...mapState({
    prop1: (state: State): prop1Type[] => state.whatever.prop1,
    prop2: (state: State): number | null => state.whatever.prop2
  }),
  // if i want get/set, for a v-model in template
  baz: {
    get: function(): number {
      return this.$store.state.whatever.baz;
    },
    set: function(value: number) {
      if (value !== this.baz) { // read * Note 1
        this.$store.dispatch('whatever/setBaz', value);
        // setBaz can be an `@Action` or a `@MutationAction`
      }
    }
  }
}
```

<p><code>baz</code> can now be used in a <code>v-model</code>. Note <code>mapGetters</code> need to be actual module store getters: </p>

```import { $http, $store } from '@/main'; // read * Note 2
import { Action, Module, Mutation, MutationAction, VuexModule } from 'vuex-module-decorators';

@Module({ namespaced: true, store: $store, name: 'whatever' })
export default class Whatever extends VuexModule {

  get foo() {
    return // something. `this` refers to class Whatever and it's typed
  }
  baz = 0;
  prop1 = [] as prop1Type[];       // here you cast the type you'll get throughout the app
  prop2 = null as null | number;   // I tend not to mix types, but there are valid cases
                                   // where `0` is to be treated differently than `null`, so...
  @MutationAction({ mutate: ['baz'] })
  async setBaz(baz: number) {
    return { baz }
  }
}
```

<p>Now, you won't have any trouble using <code>@Action</code> or <code>@Mutation</code> decorators and you can stop there, you won't have any typescript problems. But, because I like them, I find myself using <code>@MutationAction</code>s a lot, even though, to be fair, they're a hybrid. A hack, if you want.<br>
Inside a <code>@MutationAction</code>, <code>this</code> is not the module class. It's an ActionContext (basically what the first param in a normal js vuex action would be): </p>

<pre class="lang-js prettyprint-override"><code>interface ActionContext<S, R> {
  dispatch: Dispatch;
  commit: Commit;
  state: S;
  getters: any;
  rootState: R;
  rootGetters: any;
}
</code>```

And that's not even the problem. The problem is Typescript thinks this is the module class inside a @MutationAction. And here's when you need to start casting or use typeguards. As a general rule, I try to keep casting to a minimum and I never use any. Typeguards can go a long way.

The golden rule is: If I need to cast as any or as unknown as SomeType, it's a clear sign I should split the @MutationAction into an @Action and a @Mutation. But in vast majority of cases, a typeguard is enough. Example:

```<code>import { get } from 'lodash';
...
@Module({ namespaced: true, store: $store, name: 'whatever' })
export default class Whatever extends VuexModule {
  @MutationAction({ mutate: ['someStateProp'] })
  async someMutationAction() {
    const boo = get(this, 'getters.boo'); // or `get(this, 'state.boo')`, etc...
    if (boo instaceof Boo) {
      // boo is properly typed inside a typeguard
      // depending on what boo is, you could use other typeguards:
      // `is`, `in`, `typeof`
    }
}
</code>```

If you only need the values of state or getters:  this.state?.prop1 || [] or this.getters?.foo also work.

In all fairness, @MutationAction requires some form of type hacking, since you need to declare the types: they are not inferred properly. So, if you want to be 100% correct, limit their usage to cases where you're simply setting the value of a state property and you want to save having to write both the action and the mutation:

```<code>@MutationAction({ mutate: ['items'] })
async setItems(items: Item[]) {
  return { items }
}
</code>```

Which replaces:

```<code>@Action
setItems(items: Item[]) {
  this.context.commit('setItems', items);
  // btw, if you want to call other @Action from here or any @MutationAction
  // they work as `this.someAction();` or `this.someMutationAction()`;
}

@Mutation
setItems(items: Item[]) {
  this.items = items;
}
</code>```

@MutationActions are registered as @Actions, they take a { mutate: [/* full list of props to be mutated*/]} and return an object having all the declared state props which are declared in the array of props to be mutated.

That's about it.

* Note 1: I had to use that check when I used two different inputs (a normal one and a slider input) on the same get/set v-model. Without that check, each of them would trigger a set when updated, resulting in a stack-overflow error. You normally don't need that check when you only have 1 input.

* Note 2: here's how my main.ts typically looks like

import ...
Vue.use(...);
Vue.config...

const Instance = new Vue({
  ...
}).$mount(App);

// anything I might want to import in components, store modules or tests:
export { $store, $t, $http, $bus } = Instance;
/* I'd say I use these imports more for correct typing than for anything else
 (since they're already available on `this` in any component). But they're
 quite useful outside of components (in services, helpers, store, translation
 files, tests, etc...)
 */
```

Body:
I use Vue.js and Vuex for some time, but always with javascript.

I'm trying to use Vue with Typescript, nuxt.js to be more specifically, but without using decorators or style-class-component, only continue with the normal Vue syntax

This is the code I have in my Vuex store

/store/todos/types.ts

export interface Todo {
  id: number
  text: string
  done: boolean
}

export interface TodoState {
  list: Todo[]
}

/store/todos/state.ts

import { TodoState } from './types'

export default (): TodoState => ({
  list: [
    {
      id: 1,
      text: 'first todo',
      done: true
    },
    {
      id: 2,
      text: 'second todo',
      done: false
    }
  ]
})

/store/todos/mutations.ts

import { MutationTree } from 'vuex'
import { TodoState, Todo } from './types'

export default {
  remove(state, { id }: Todo) {
    const index = state.list.findIndex((x) => x.id === id)
    state.list.splice(index, 1)
  }
} as MutationTree<TodoState>

/store/todos/actions.ts

import { ActionTree } from 'vuex'
import { RootState } from '../types'
import { TodoState, Todo } from './types'

export default {
  delete({ commit }, { id }: Todo): void {
    commit('remove', id)
  }
} as ActionTree<TodoState, RootState>

/store/todos/getters.ts

import { GetterTree } from 'vuex'
import { RootState } from '../types'
import { TodoState, Todo } from './types'

export default {
  list(state): Todo[] {
    return state.list
  }
} as GetterTree<TodoState, RootState>

This is code that I have my component,

<template>

        {{ todo.text }}
        <button @click="destroy(todo)">delete</button>

</template>

Everything works perfectly, except the auto complete / intellisense of the getters or actions that came from Vuex

Someone can help me?

Thanks for this o/

Body:
Vuex, in current form, doesn't work well with Typescript. That's probably going to change in Vue 3.

Just as you, I also don't want to use @Component decorators, especially because they have been deprecated. However, when it comes to using the default Vue typescript component style:

<script lang="ts">
  import Vue from 'vue';
  export default Vue.extend({...})
</script>

... after testing multiple solutions I found the easiest to use is actually a plugin which does use decorators: vuex-module-decorators

Vuex module:

I typically leave the parent state clean (empty) and use namespaced modules. I do it mostly because more than once I decided at the end of the project it would be cleaner to have more than one module, and it's more of a hassle to move it from parent to module than to simply create an additional module.

The store looks like this:

import Vue from 'vue';
import Vuex from 'vuex';
import { getModule } from 'vuex-module-decorators';
import Whatever from '@/store/whatever';

Vue.use(Vuex);

const store = new Vuex.Store({
  modules: {
    whatever: Whatever
  }
});

getModule(Whatever, store); // this is important for typescript to work properly

export type State = typeof store.state;
export default store;

Here are a few examples of mapState, mapGetters or get/set computed that work directly with the store:

computed: {
  ...mapGetters({
    foo: 'whatever/foo',
    bar: 'whatever/bar'
  }),
  ...mapState({
    prop1: (state: State): prop1Type[] => state.whatever.prop1,
    prop2: (state: State): number | null => state.whatever.prop2
  }),
  // if i want get/set, for a v-model in template
  baz: {
    get: function(): number {
      return this.$store.state.whatever.baz;
    },
    set: function(value: number) {
      if (value !== this.baz) { // read * Note 1
        this.$store.dispatch('whatever/setBaz', value);
        // setBaz can be an `@Action` or a `@MutationAction`
      }
    }
  }
}

baz can now be used in a v-model. Note mapGetters need to be actual module store getters:

import { $http, $store } from '@/main'; // read * Note 2
import { Action, Module, Mutation, MutationAction, VuexModule } from 'vuex-module-decorators';

@Module({ namespaced: true, store: $store, name: 'whatever' })
export default class Whatever extends VuexModule {

  get foo() {
    return // something. `this` refers to class Whatever and it's typed
  }
  baz = 0;
  prop1 = [] as prop1Type[];       // here you cast the type you'll get throughout the app
  prop2 = null as null | number;   // I tend not to mix types, but there are valid cases
                                   // where `0` is to be treated differently than `null`, so...
  @MutationAction({ mutate: ['baz'] })
  async setBaz(baz: number) {
    return { baz }
  }
}

Now, you won't have any trouble using @Action or @Mutation decorators and you can stop there, you won't have any typescript problems. But, because I like them, I find myself using @MutationActions a lot, even though, to be fair, they're a hybrid. A hack, if you want.

Inside a @MutationAction, this is not the module class. It's an ActionContext (basically what the first param in a normal js vuex action would be):

interface ActionContext<S, R> {
  dispatch: Dispatch;
  commit: Commit;
  state: S;
  getters: any;
  rootState: R;
  rootGetters: any;
}

And that's not even the problem. The problem is Typescript thinks this is the module class inside a @MutationAction. And here's when you need to start casting or use typeguards. As a general rule, I try to keep casting to a minimum and I never use any. Typeguards can go a long way.

The golden rule is: If I need to cast as any or as unknown as SomeType, it's a clear sign I should split the @MutationAction into an @Action and a @Mutation. But in vast majority of cases, a typeguard is enough. Example:

import { get } from 'lodash';
...
@Module({ namespaced: true, store: $store, name: 'whatever' })
export default class Whatever extends VuexModule {
  @MutationAction({ mutate: ['someStateProp'] })
  async someMutationAction() {
    const boo = get(this, 'getters.boo'); // or `get(this, 'state.boo')`, etc...
    if (boo instaceof Boo) {
      // boo is properly typed inside a typeguard
      // depending on what boo is, you could use other typeguards:
      // `is`, `in`, `typeof`
    }
}

If you only need the values of state or getters:  this.state?.prop1 || [] or this.getters?.foo also work.

In all fairness, @MutationAction requires some form of type hacking, since you need to declare the types: they are not inferred properly. So, if you want to be 100% correct, limit their usage to cases where you're simply setting the value of a state property and you want to save having to write both the action and the mutation:

@MutationAction({ mutate: ['items'] })
async setItems(items: Item[]) {
  return { items }
}

Which replaces:

@Action
setItems(items: Item[]) {
  this.context.commit('setItems', items);
  // btw, if you want to call other @Action from here or any @MutationAction
  // they work as `this.someAction();` or `this.someMutationAction()`;
}

@Mutation
setItems(items: Item[]) {
  this.items = items;
}

@MutationActions are registered as @Actions, they take a { mutate: [/* full list of props to be mutated*/]} and return an object having all the declared state props which are declared in the array of props to be mutated.

That's about it.

* Note 1: I had to use that check when I used two different inputs (a normal one and a slider input) on the same get/set v-model. Without that check, each of them would trigger a set when updated, resulting in a stack-overflow error. You normally don't need that check when you only have 1 input.

* Note 2: here's how my main.ts typically looks like

import ...
Vue.use(...);
Vue.config...

const Instance = new Vue({
  ...
}).$mount(App);

// anything I might want to import in components, store modules or tests:
export { $store, $t, $http, $bus } = Instance;
/* I'd say I use these imports more for correct typing than for anything else
 (since they're already available on `this` in any component). But they're
 quite useful outside of components (in services, helpers, store, translation
 files, tests, etc...)
 */


问:
JScript JSON Array access
I have a JSON array stored in a file data.json - I used the code that was recommended here for a similar problem, explain why when I try to access the array later in the program it tells me it is undefined.

```<code>    var chartData = (function () {
                var chartData = null;
                $.ajax({
                    'async': false,
                    'global': false,
                    'url': "data.json",
                    'dataType': "json",
                    'success': function (data) {
                        chartData = data;
                    }
             });
             return chartData;
        })();
</code>```

Help appreciated!

Edit; For accessing, I'm using the array as a series in dojo-chart: http://dojotoolkit.org/grids-charts

After I attempt to initialize var chartData, the only other point I use it is in:

```<code>    chart.addSeries("Name",chartData);
</code>```

Edit #2; In case it matters the data.json file is formatted like:

```<code>    [#, #, #, ... , #]
</code>```

答:
I guess it should work somehow as you set async: false. But better is to use it asynchronously:

```<code>function handler(chartData) {
    // all the code here that deals with chartData
}

$.ajax({
    url: "data.json",
    dataType: "json",
    success: handler
});
</code>```

Title: JScript JSON Array access

Body:
I have a JSON array stored in a file data.json - I used the code that was recommended here for a similar problem, explain why when I try to access the array later in the program it tells me it is undefined.

    var chartData = (function () {
                var chartData = null;
                $.ajax({
                    'async': false,
                    'global': false,
                    'url': "data.json",
                    'dataType': "json",
                    'success': function (data) {
                        chartData = data;
                    }
             });
             return chartData;
        })();

Help appreciated!

Edit; For accessing, I'm using the array as a series in dojo-chart: http://dojotoolkit.org/grids-charts

After I attempt to initialize var chartData, the only other point I use it is in:

    chart.addSeries("Name",chartData);

Edit #2; In case it matters the data.json file is formatted like:

    [#, #, #, ... , #]

Body:
I guess it should work somehow as you set async: false. But better is to use it asynchronously:

function handler(chartData) {
    // all the code here that deals with chartData
}

$.ajax({
    url: "data.json",
    dataType: "json",
    success: handler
});


问:
How can I avoid DTOs duplication without inheritance?
I am connecting with many social networks for login in my application.
I have one DTO for each social network response.

```<code>public class GoogleUserInfo {
    private String id;
    private String firstName;
    private String lastName;
    private String email;
    private AgeRange ageRange;
    // more specific fields
}

public class FacebookUserInfo {
    private String id;
    private String firstName;
    private String lastName;
    private String email;
    private String picture;
    // more specific fields
}

public class AppleUserInfo {
    private String id;
    private String firstName;
    private String lastName;
    private String email;
    private Boolean emailVerified;
    // more specific fields
}
</code>```

In each social network connector, I make similar steps to fetch the information, so I thought I could go with some DTO as follows:

```<code>public class SocialNetworkInfo {
    protected String id;
    protected String firstName;
    protected String lastName;
    protected String email;
}
</code>```

Social networks DTOs could extend this to obtain the common fields. Then I could use this generic DTO to implement an abstract connector that deals with all the duplicate logic between connectors (make request, parse response, etc...):

```<code>abstract class AbstractConnector {
    abstract SocialNetworkInfo fetchUserInfo(String networkId);
    ...
}
</code>```

But I realized that above, in my service layer, I would need those specific fields to make some changes and operations.

```<code>SocialNetworkInfo networkUserInfo = facebookConnector.fetchUserInfo(facebookId);
facebookService.updatePicture(networkUserInfo.getPicture()); // can't access this specific field
</code>```

What do you think that's the best way to go through this situation without casting and avoiding logic or DTO duplication?

Would love to hear your thoughts.

Thanks!

答:
If you don't want to use inheritance, I'd suggest to consider composition. The code can look as follows:

```<code>public class SocialNetworkInfo {
    private String id;
    private String firstName;
    private String lastName;
    private String email;
}

public class GoogleUserInfo {
    private SocialNetworkInfo socialNetworkInfo;
    private AgeRange ageRange;
    // more specific fields
}

public class FacebookUserInfo {
    private SocialNetworkInfo socialNetworkInfo;
    private String picture;
    // more specific fields
}

public class AppleUserInfo {
    private SocialNetworkInfo socialNetworkInfo;
    private Boolean emailVerified;
    // more specific fields
}
</code>```

Body:
I am connecting with many social networks for login in my application.
I have one DTO for each social network response.

public class GoogleUserInfo {
    private String id;
    private String firstName;
    private String lastName;
    private String email;
    private AgeRange ageRange;
    // more specific fields
}

public class FacebookUserInfo {
    private String id;
    private String firstName;
    private String lastName;
    private String email;
    private String picture;
    // more specific fields
}

public class AppleUserInfo {
    private String id;
    private String firstName;
    private String lastName;
    private String email;
    private Boolean emailVerified;
    // more specific fields
}

In each social network connector, I make similar steps to fetch the information, so I thought I could go with some DTO as follows:

public class SocialNetworkInfo {
    protected String id;
    protected String firstName;
    protected String lastName;
    protected String email;
}

Social networks DTOs could extend this to obtain the common fields. Then I could use this generic DTO to implement an abstract connector that deals with all the duplicate logic between connectors (make request, parse response, etc...):

abstract class AbstractConnector {
    abstract SocialNetworkInfo fetchUserInfo(String networkId);
    ...
}

But I realized that above, in my service layer, I would need those specific fields to make some changes and operations.

SocialNetworkInfo networkUserInfo = facebookConnector.fetchUserInfo(facebookId);
facebookService.updatePicture(networkUserInfo.getPicture()); // can't access this specific field

What do you think that's the best way to go through this situation without casting and avoiding logic or DTO duplication?

Would love to hear your thoughts.

Thanks!

Body:
If you don't want to use inheritance, I'd suggest to consider composition. The code can look as follows:

public class SocialNetworkInfo {
    private String id;
    private String firstName;
    private String lastName;
    private String email;
}

public class GoogleUserInfo {
    private SocialNetworkInfo socialNetworkInfo;
    private AgeRange ageRange;
    // more specific fields
}

public class FacebookUserInfo {
    private SocialNetworkInfo socialNetworkInfo;
    private String picture;
    // more specific fields
}

public class AppleUserInfo {
    private SocialNetworkInfo socialNetworkInfo;
    private Boolean emailVerified;
    // more specific fields
}


问:
Can I have lodash omit return a specific type instead of a partial type?
In the code below

```<code>import omit from "lodash/fp/omit";

type EnhancerProps = {
  serializedSvg: string;
  svgSourceId: string;
  containerId: string;
};

const rest = omit(["serializedSvg", "containerId"])(props);
</code>```

rest is typed as Partial. What can I do to have omit return something more specific, like {svgSourceId: string} instead.

答:
Weird that omit doesn't infer types on its own. I'm not sure if there's a reason for that, but I was able to come up with a helper function that should do the trick.

```<code>function omitWithTypes<A extends ReadonlyArray<keyof B>, B extends Object>(
  typeArray: A,
  obj: B
) {
  return omit(typeArray)(obj) as Omit<B, A[number]>;
}
</code>```

The Omit utility type will allow you to narrow properties of a type. However if you want to convert the values of an array to a union type and pass to Omit, the array must be read only, which you can satisfy with the as const assertion to tell the TS compiler that it won't mutate.

```<code>const filter = ["serializedSvg", "svgSourceId"] as const;
const exclusive = omitWithTypes(filter, props);
</code>```

OR

```<code>const exclusive = omitWithTypes(["serializedSvg", "svgSourceId"] as const, props);
</code>```

You will get correct inferred types (though it is a little verbose since it's using the Pick utility type behind the scenes):

You will even get an error if you try to exclude values that aren't properties of the object being picked from:

Body:
In the code below

import omit from "lodash/fp/omit";

type EnhancerProps = {
  serializedSvg: string;
  svgSourceId: string;
  containerId: string;
};

const rest = omit(["serializedSvg", "containerId"])(props);

rest is typed as Partial. What can I do to have omit return something more specific, like {svgSourceId: string} instead.

Body:
Weird that omit doesn't infer types on its own. I'm not sure if there's a reason for that, but I was able to come up with a helper function that should do the trick.

function omitWithTypes<A extends ReadonlyArray<keyof B>, B extends Object>(
  typeArray: A,
  obj: B
) {
  return omit(typeArray)(obj) as Omit<B, A[number]>;
}

The Omit utility type will allow you to narrow properties of a type. However if you want to convert the values of an array to a union type and pass to Omit, the array must be read only, which you can satisfy with the as const assertion to tell the TS compiler that it won't mutate.

const filter = ["serializedSvg", "svgSourceId"] as const;
const exclusive = omitWithTypes(filter, props);

OR

const exclusive = omitWithTypes(["serializedSvg", "svgSourceId"] as const, props);

You will get correct inferred types (though it is a little verbose since it's using the Pick utility type behind the scenes):

You will even get an error if you try to exclude values that aren't properties of the object being picked from:


问:
I want to figure out the error - TypeError: 'builtin_function_or_method' object is not subscriptable
Good afternoon.

Announced the ADX indicator function
(link Python: Average Directional Index (ADX) 2 Directional Movement System Calculation - https://www.youtube.com/watch?v=joOWm-GcHTw).

An error occurs during operation - "TypeError: 'builtin_function_or_method' object is not subscriptable".

on this line -
    TRDate,TrueRange = TR(date[x],closep[x],highp[x],lowp[x],openp[x],closep[x-1])
TypeError: 'builtin_function_or_method' object is not subscriptable

I will be glad of any help.
Thank.
The code is below.

```<code>def TR(d,c,h,l,o,yc):
    x = h-l
    y = abs(h-yc)
    z = abs(l-yc)

    if y <= x >= z:
        TR = x
    elif x <= y >= z:
        TR = y
    elif x <= z >= y:
        TR = z
    return d, TR

def DM(d,o,h,l,c,yo,yh,yl,yc):
    moveUp = h-yh
    moveDown = yl-l

    if 0 < moveUp > moveDown:
        PDM = moveUp
    else:
        PDM = 0

    if 0 < moveDown > moveUp:
        NDM = moveDown
    else:
        NDM = 0
    return d,PDM,NDM

def calcDIs(date,openp,highp,lowp,closep,openpy,highpy,lowpy,closepy,tf):
    x = 1
    TRDates = []
    TrueRanges = []
    PosDMs = []
    NegDMs = []

    while x < len(date):
        TRDate,TrueRange = TR(date[x],closep[x],highp[x],lowp[x],openp[x],closep[x-1]) << error
        TRDates.append(TRDate)
        TrueRanges.append(TrueRange)

        DMdate,PosDM,NegDM = DM(date[x],openp[x],highp[x],lowp[x],closep[x],openp[x-1],highp[x-1],lowp[-1],closep[x-1]) << I assume that there will be the same error
        PosDMs.append(PosDM)
        NegDMs.append(NegDM)

        x +=1

    expPosDM = ExpMovingAverage(PosDMs,14)
    expNegDM = ExpMovingAverage(NegDMs,14)
    ATR = ExpMovingAverage(TrueRanges,14)

    xx = 0
    PDIs = []
    NDIs = []

    while xx < len(ATR):
        PDI = 100*(expPosDM[xx]/ATR[xx])
        PDIs.append(PDI)

        NDI = 100*(expNegDM[xx]/ATR[xx])
        NDIs.append(NDI)

        xx +=1

    return PDIs,NDIs
</code>```

答:
Can you show all your import statements?

Also can you change your date variable to something else?

Body:
Good afternoon.

Announced the ADX indicator function
(link Python: Average Directional Index (ADX) 2 Directional Movement System Calculation - https://www.youtube.com/watch?v=joOWm-GcHTw).

An error occurs during operation - "TypeError: 'builtin_function_or_method' object is not subscriptable".

on this line -
    TRDate,TrueRange = TR(date[x],closep[x],highp[x],lowp[x],openp[x],closep[x-1])
TypeError: 'builtin_function_or_method' object is not subscriptable

I will be glad of any help.
Thank.
The code is below.

def TR(d,c,h,l,o,yc):
    x = h-l
    y = abs(h-yc)
    z = abs(l-yc)

    if y <= x >= z:
        TR = x
    elif x <= y >= z:
        TR = y
    elif x <= z >= y:
        TR = z
    return d, TR

def DM(d,o,h,l,c,yo,yh,yl,yc):
    moveUp = h-yh
    moveDown = yl-l

    if 0 < moveUp > moveDown:
        PDM = moveUp
    else:
        PDM = 0

    if 0 < moveDown > moveUp:
        NDM = moveDown
    else:
        NDM = 0
    return d,PDM,NDM

def calcDIs(date,openp,highp,lowp,closep,openpy,highpy,lowpy,closepy,tf):
    x = 1
    TRDates = []
    TrueRanges = []
    PosDMs = []
    NegDMs = []

    while x < len(date):
        TRDate,TrueRange = TR(date[x],closep[x],highp[x],lowp[x],openp[x],closep[x-1]) << error
        TRDates.append(TRDate)
        TrueRanges.append(TrueRange)

        DMdate,PosDM,NegDM = DM(date[x],openp[x],highp[x],lowp[x],closep[x],openp[x-1],highp[x-1],lowp[-1],closep[x-1]) << I assume that there will be the same error
        PosDMs.append(PosDM)
        NegDMs.append(NegDM)

        x +=1

    expPosDM = ExpMovingAverage(PosDMs,14)
    expNegDM = ExpMovingAverage(NegDMs,14)
    ATR = ExpMovingAverage(TrueRanges,14)

    xx = 0
    PDIs = []
    NDIs = []

    while xx < len(ATR):
        PDI = 100*(expPosDM[xx]/ATR[xx])
        PDIs.append(PDI)

        NDI = 100*(expNegDM[xx]/ATR[xx])
        NDIs.append(NDI)

        xx +=1

    return PDIs,NDIs


问:
"pathMatch": "full" for empty-path route causes blank view
I have the following routes:

app-routing.module.ts:

[
    ...
    {
        path: "",
        loadChildren: () => import("./tabs/tabs.module").then(m => m.TabsPageModule),
        // "pathMatch": "full",
    },
    {
        path: "**",
        redirectTo: "",
        "pathMatch": "full",
    },
]
```

<p>tabs-routing.module.ts:</p>

<pre class="lang-js prettyprint-override"><code>[
    {
        path: "tabs",
        component: TabsPage,
        children: [
            {
                path: "products",
                loadChildren: () => import("../tab1/tab1.module").then(m => m.Tab1PageModule),
                "pathMatch": "full",
            },
            {
                path: "catalogue",
                loadChildren: () => import("../tab2/tab2.module").then(m => m.Tab2PageModule),
                "pathMatch": "full",
            },
            {
                path: "account",
                loadChildren: () => import("../tab3/tab3.module").then(m => m.Tab3PageModule),
                "pathMatch": "full",
            },
            {
                path: "",
                redirectTo: "products",
                "pathMatch": "full",
            },
        ],
    },
    {
        path: "",
        redirectTo: "tabs",
        "pathMatch": "full",
    },
]
</code>```

The documentation for Route.pathMatch states:

The path-match strategy 'full' matches against the entire URL. It is important to do this when redirecting empty-path routes. Otherwise, because an empty path is a prefix of any URL, the router would apply the redirect even when navigating to the redirect destination, creating an endless loop.

So that's what I've tried, adding "pathMatch": "full", to my path: "", in my app routing module (the line that is commented out in the snippet above). However, doing so breaks my app and I cannot figure out why.

Broken paths such as localhost:8100/foo correctly redirect me to localhost:8100/tabs/products, but the view is completely blank (an empty ion-router-outlet). No errors are logged in my browser console (or IDE's integrated terminal). My app so far is just a small edit of the ionic start tabs template and I have not touched any router outlets. Help would be much appreciated.

答:
In tabs-routing.module.ts:

```<code>[
{
    path: "tabs",
    component: TabsPage,
    children: [
        {
            path: "products",
            loadChildren: () => import("../tab1/tab1.module").then(m => m.Tab1PageModule)
        },
        {
            path: "catalogue",
            loadChildren: () => import("../tab2/tab2.module").then(m => m.Tab2PageModule)
        },
        {
            path: "account",
            loadChildren: () => import("../tab3/tab3.module").then(m => m.Tab3PageModule)
        },
        {
            path: "",
            redirectTo: "products",
            "pathMatch": "full",
        },
    ],
},
{
    path: "",
    redirectTo: "tabs",
    "pathMatch": "full",
},
]
</code>```

This will work for you

Body:
I have the following routes:

app-routing.module.ts:

[
    ...
    {
        path: "",
        loadChildren: () => import("./tabs/tabs.module").then(m => m.TabsPageModule),
        // "pathMatch": "full",
    },
    {
        path: "**",
        redirectTo: "",
        "pathMatch": "full",
    },
]

tabs-routing.module.ts:

[
    {
        path: "tabs",
        component: TabsPage,
        children: [
            {
                path: "products",
                loadChildren: () => import("../tab1/tab1.module").then(m => m.Tab1PageModule),
                "pathMatch": "full",
            },
            {
                path: "catalogue",
                loadChildren: () => import("../tab2/tab2.module").then(m => m.Tab2PageModule),
                "pathMatch": "full",
            },
            {
                path: "account",
                loadChildren: () => import("../tab3/tab3.module").then(m => m.Tab3PageModule),
                "pathMatch": "full",
            },
            {
                path: "",
                redirectTo: "products",
                "pathMatch": "full",
            },
        ],
    },
    {
        path: "",
        redirectTo: "tabs",
        "pathMatch": "full",
    },
]

The documentation for Route.pathMatch states:

The path-match strategy 'full' matches against the entire URL. It is important to do this when redirecting empty-path routes. Otherwise, because an empty path is a prefix of any URL, the router would apply the redirect even when navigating to the redirect destination, creating an endless loop.

So that's what I've tried, adding "pathMatch": "full", to my path: "", in my app routing module (the line that is commented out in the snippet above). However, doing so breaks my app and I cannot figure out why.

Broken paths such as localhost:8100/foo correctly redirect me to localhost:8100/tabs/products, but the view is completely blank (an empty ion-router-outlet). No errors are logged in my browser console (or IDE's integrated terminal). My app so far is just a small edit of the ionic start tabs template and I have not touched any router outlets. Help would be much appreciated.

Body:
In tabs-routing.module.ts:

[
{
    path: "tabs",
    component: TabsPage,
    children: [
        {
            path: "products",
            loadChildren: () => import("../tab1/tab1.module").then(m => m.Tab1PageModule)
        },
        {
            path: "catalogue",
            loadChildren: () => import("../tab2/tab2.module").then(m => m.Tab2PageModule)
        },
        {
            path: "account",
            loadChildren: () => import("../tab3/tab3.module").then(m => m.Tab3PageModule)
        },
        {
            path: "",
            redirectTo: "products",
            "pathMatch": "full",
        },
    ],
},
{
    path: "",
    redirectTo: "tabs",
    "pathMatch": "full",
},
]

This will work for you


问:
ld: framework not found Pods
I'm trying to add a framework to my IOS project but when I build I always got the same message :

ld: framework not found Pods

clang: error: linker command failed with exit code 1 (use -v to see invocation)

I tried to remove my Pods directory and then run pod install
I open the .xcworkspace like it is written in the logs on the pod install, I clean the project on xcode and then try to build but it won't works..

My podfile looks like this :

```<code>xcodeproj '/Users/guillaume/project/Mobile/iOS/FoodPin/FoodPin.xcodeproj'
source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '8.0'
use_frameworks!
pod 'SwiftHTTP', '~> 0.9.2'
</code>```

My version of xcode is 6.3.1

Thank you,

答: In my case, I created the workspace before installing the pods, so when I installed the pods, the workspace included my project only, add the Pods project to your workspace, clean and rebuild solved the issue in my case</p>

Title: ld: framework not found Pods

Body:
I'm trying to add a framework to my IOS project but when I build I always got the same message :

ld: framework not found Pods

clang: error: linker command failed with exit code 1 (use -v to see invocation)

I tried to remove my Pods directory and then run pod install
I open the .xcworkspace like it is written in the logs on the pod install, I clean the project on xcode and then try to build but it won't works..

My podfile looks like this :

xcodeproj '/Users/guillaume/project/Mobile/iOS/FoodPin/FoodPin.xcodeproj'
source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '8.0'
use_frameworks!
pod 'SwiftHTTP', '~> 0.9.2'

My version of xcode is 6.3.1

Thank you,


问:
Is it possible to have 3 delimiters for the explode function
Option 1 (spaces)

```<code>keyword keyword keyword
</code>```

Option 2 (line breaks)

```<code>keyword
keyword
keyword
</code>```

Option 3 (commas)

```<code>keyword, keyword, keyword
</code>```

Or would I have to use the split function instead? And if so, how?

答:
Try using preg_split but notice that this will explode on all of your examples at once.

```<code>$parts = preg_split("/[ ,\n]/", $string);
</code>```

Edit: For the third example you give you'll get empty array elements as it's being split on both the comma and the space. Pass $parts through array_filter() to strip these out.

Body:
Option 1 (spaces)

keyword keyword keyword

Option 2 (line breaks)

keyword
keyword
keyword

Option 3 (commas)

keyword, keyword, keyword

Or would I have to use the split function instead? And if so, how?

Body:
Try using preg_split but notice that this will explode on all of your examples at once.

$parts = preg_split("/[ ,\n]/", $string);

Edit: For the third example you give you'll get empty array elements as it's being split on both the comma and the space. Pass $parts through array_filter() to strip these out.


问:
What's default password in docker container mysql-server when you don't set one?
I am try to run a mysql container and connect with mysql client then:

I've used following commands:

```<code>docker run --name=mysql -d mysql/mysql-server:latest
docker exec -it mysql mysql -uroot -p
</code>```

According to tutorial, the last command allow me configure database password but When I introduce the first password it fails...

The first password was root and I get an unusual error, then I try with admin, admin an even my linux user password but They don't work...

I would like to know what's the error?

答:
There are couple of ways to see the password.
First Approach - Don't Run container in daemon mode

Check the below command

```<code>docker run --name=mysql mysql/mysql-server:latest
</code>```

and this will print the password in the terminal as look at the below logs

```<code>2020-05-28T23:41:01.418347Z 0 [System] [MY-011323] [Server] X Plugin ready for connections. Socket: '/var/run/mysqld/mysqlx.sock'
2020-05-28T23:41:01.666070Z 0 [Warning] [MY-010068] [Server] CA certificate ca.pem is self signed.
2020-05-28T23:41:01.714420Z 0 [System] [MY-010931] [Server] /usr/sbin/mysqld: ready for connections. Version: '8.0.20'  socket: '/var/lib/mysql/mysql.sock'  port: 0  MySQL Community
Server - GPL.
Warning: Unable to load '/usr/share/zoneinfo/iso3166.tab' as time zone. Skipping it.
Warning: Unable to load '/usr/share/zoneinfo/leapseconds' as time zone. Skipping it.
Warning: Unable to load '/usr/share/zoneinfo/tzdata.zi' as time zone. Skipping it.
Warning: Unable to load '/usr/share/zoneinfo/zone.tab' as time zone. Skipping it.
Warning: Unable to load '/usr/share/zoneinfo/zone1970.tab' as time zone. Skipping it.
[Entrypoint] GENERATED ROOT PASSWORD: PopiKQIjAS#OGj3x]yJOBLEn80p
[Entrypoint] ignoring /docker-entrypoint-initdb.d/*
2020-05-28T23:41:06.208480Z 10 [System] [MY-013172] [Server] Received SHUTDOWN from user root. Shutting down mysqld (Version: 8.0.20).
2020-05-28T23:41:07.861667Z 0 [System] [MY-010910] [Server] /usr/sbin/mysqld: Shutdown complete (mysqld 8.0.20)  MySQL Community Server - GPL.
[Entrypoint] Server shut down
[Entrypoint] Setting root user as expired. Password will need to be changed before database can be used.
[Entrypoint] MySQL init process done. Ready for start up.
[Entrypoint] Starting MySQL 8.0.20-1.1.16
2020-05-28T23:41:08.534785Z 0 [System] [MY-010116] [Server] /usr/sbin/mysqld (mysqld 8.0.20) starting as process 1
2020-05-28T23:41:08.549216Z 1 [System] [MY-013576] [InnoDB] InnoDB initialization has started.
2020-05-28T23:41:09.135591Z 1 [System] [MY-013577] [InnoDB] InnoDB initialization has ended.
2020-05-28T23:41:09.369412Z 0 [System] [MY-011323] [Server] X Plugin ready for connections. Socket: '/var/run/mysqld/mysqlx.sock' bind-address: '::' port: 33060
2020-05-28T23:41:09.448584Z 0 [Warning] [MY-010068] [Server] CA certificate ca.pem is self signed.
2020-05-28T23:41:09.500464Z 0 [System] [MY-010931] [Server] /usr/sbin/mysqld: ready for connections. Version: '8.0.20'  socket: '/var/lib/mysql/mysql.sock'  port: 3306  MySQL Communi
ty Server - GPL.

</code>```

Second Approach - Run container in daemon mode & fetch the password from logs
Check the below command to run the container

```<code>docker run -d --name=mysql mysql/mysql-server:latest
</code>```

and then run the below command to fetch the password

docker logs mysql 2>&1 | grep GENERATED
```
<p>Output of above command is:</p>
<pre class="lang-sh prettyprint-override"><code>[Entrypoint] GENERATED ROOT PASSWORD: PopiKQIjAS#OGj3x]yJOBLEn80p
</code>```

Once you have the password by one of the above-mentioned methods, you can then login with the below command using that password

docker exec -it mysql mysql -uroot -p
```
<p>When asked, enter the generated root password (see the instructions above on how to find it). Because the <code>MYSQL_ONETIME_PASSWORD</code> option is true by default, after you have connected a mysql client to the server, you must reset the server root password by issuing this statement:</p>
```mysql> ALTER USER 'root'@'localhost' IDENTIFIED BY 'password';
```

Substitute password with the password of your choice. Once the password is reset, the server is ready for use.

Ref: https://hub.docker.com/r/mysql/mysql-server/

Body:
I am try to run a mysql container and connect with mysql client then:

I've used following commands:

docker run --name=mysql -d mysql/mysql-server:latest
docker exec -it mysql mysql -uroot -p

According to tutorial, the last command allow me configure database password but When I introduce the first password it fails...

The first password was root and I get an unusual error, then I try with admin, admin an even my linux user password but They don't work...

I would like to know what's the error?

Body:
There are couple of ways to see the password.
First Approach - Don't Run container in daemon mode

Check the below command

docker run --name=mysql mysql/mysql-server:latest

and this will print the password in the terminal as look at the below logs

2020-05-28T23:41:01.418347Z 0 [System] [MY-011323] [Server] X Plugin ready for connections. Socket: '/var/run/mysqld/mysqlx.sock'
2020-05-28T23:41:01.666070Z 0 [Warning] [MY-010068] [Server] CA certificate ca.pem is self signed.
2020-05-28T23:41:01.714420Z 0 [System] [MY-010931] [Server] /usr/sbin/mysqld: ready for connections. Version: '8.0.20'  socket: '/var/lib/mysql/mysql.sock'  port: 0  MySQL Community
Server - GPL.
Warning: Unable to load '/usr/share/zoneinfo/iso3166.tab' as time zone. Skipping it.
Warning: Unable to load '/usr/share/zoneinfo/leapseconds' as time zone. Skipping it.
Warning: Unable to load '/usr/share/zoneinfo/tzdata.zi' as time zone. Skipping it.
Warning: Unable to load '/usr/share/zoneinfo/zone.tab' as time zone. Skipping it.
Warning: Unable to load '/usr/share/zoneinfo/zone1970.tab' as time zone. Skipping it.
[Entrypoint] GENERATED ROOT PASSWORD: PopiKQIjAS#OGj3x]yJOBLEn80p
[Entrypoint] ignoring /docker-entrypoint-initdb.d/*
2020-05-28T23:41:06.208480Z 10 [System] [MY-013172] [Server] Received SHUTDOWN from user root. Shutting down mysqld (Version: 8.0.20).
2020-05-28T23:41:07.861667Z 0 [System] [MY-010910] [Server] /usr/sbin/mysqld: Shutdown complete (mysqld 8.0.20)  MySQL Community Server - GPL.
[Entrypoint] Server shut down
[Entrypoint] Setting root user as expired. Password will need to be changed before database can be used.
[Entrypoint] MySQL init process done. Ready for start up.
[Entrypoint] Starting MySQL 8.0.20-1.1.16
2020-05-28T23:41:08.534785Z 0 [System] [MY-010116] [Server] /usr/sbin/mysqld (mysqld 8.0.20) starting as process 1
2020-05-28T23:41:08.549216Z 1 [System] [MY-013576] [InnoDB] InnoDB initialization has started.
2020-05-28T23:41:09.135591Z 1 [System] [MY-013577] [InnoDB] InnoDB initialization has ended.
2020-05-28T23:41:09.369412Z 0 [System] [MY-011323] [Server] X Plugin ready for connections. Socket: '/var/run/mysqld/mysqlx.sock' bind-address: '::' port: 33060
2020-05-28T23:41:09.448584Z 0 [Warning] [MY-010068] [Server] CA certificate ca.pem is self signed.
2020-05-28T23:41:09.500464Z 0 [System] [MY-010931] [Server] /usr/sbin/mysqld: ready for connections. Version: '8.0.20'  socket: '/var/lib/mysql/mysql.sock'  port: 3306  MySQL Communi
ty Server - GPL.

Second Approach - Run container in daemon mode & fetch the password from logs
Check the below command to run the container

docker run -d --name=mysql mysql/mysql-server:latest

and then run the below command to fetch the password

docker logs mysql 2>&1 | grep GENERATED

Output of above command is:

[Entrypoint] GENERATED ROOT PASSWORD: PopiKQIjAS#OGj3x]yJOBLEn80p

Once you have the password by one of the above-mentioned methods, you can then login with the below command using that password

docker exec -it mysql mysql -uroot -p

When asked, enter the generated root password (see the instructions above on how to find it). Because the MYSQL_ONETIME_PASSWORD option is true by default, after you have connected a mysql client to the server, you must reset the server root password by issuing this statement:

mysql> ALTER USER 'root'@'localhost' IDENTIFIED BY 'password';

Substitute password with the password of your choice. Once the password is reset, the server is ready for use.

Ref: https://hub.docker.com/r/mysql/mysql-server/


问:
noob struggle with jekyll syntax highlighting: HTML is rendered but the stylesheet seems to be missing
I'm getting started with Jekyll. I carefully followed the step-by-step tutorial https://jekyllrb.com/docs/step-by-step/01-setup/ like a good person, and everything is brilliant except that syntax highlighting is not working out of the box like the advertisement seems to imply. I've read jekyll syntax highlighter not working but the answer didn't do it for me.

Where my markdown says, e.g.,

```<code>```php

namespace Foo;
use My\Thing;

$thing = new Thing();

```
</code>```

the output is

namespace Foo;
            use My\Thing;
            $thing = new Thing();
            ```</div>
        </div>
</code>```

but I'm not seeing any pretty colors. Obviously I am missing the CSS resource that defines highlighter-rouge and all that good stuff, but for all my searching I haven't been able to figure out where to get it or what I might be doing wrong.

I have tried multiple permutations of _config.yml with no luck, but I shouldn't need any special settings there because the default is what I want.

Suggestions?

Thanks.

答: You can find custom syntax highlighting libraries on GitHub and elsewhere, but you may want to start with https://prismjs.com/</p>

Body:
I'm getting started with Jekyll. I carefully followed the step-by-step tutorial https://jekyllrb.com/docs/step-by-step/01-setup/ like a good person, and everything is brilliant except that syntax highlighting is not working out of the box like the advertisement seems to imply. I've read jekyll syntax highlighter not working but the answer didn't do it for me.

Where my markdown says, e.g.,

```php

namespace Foo;
use My\Thing;

$thing = new Thing();

```

the output is

namespace Foo;
            use My\Thing;
            $thing = new Thing();

but I'm not seeing any pretty colors. Obviously I am missing the CSS resource that defines highlighter-rouge and all that good stuff, but for all my searching I haven't been able to figure out where to get it or what I might be doing wrong.

I have tried multiple permutations of _config.yml with no luck, but I shouldn't need any special settings there because the default is what I want.

Suggestions?

Thanks.


问:
React return component onclick
I'm trying to return a component when I click on a button.
(a delete button with a confirmation popup) I've tried some examples I found online but none really worked for me.

Here is my code:

```<code>class DeleteTask extends React.Component {
  handleClick() {
        return <TaskDeleteModal />
    }
  render() {
    return (
        <div>
            <button type="button" className={styles.deletetask} onClick={() => this.handleClick()}>Verwijderen</button>;
        </div>
    )
  }
}
</code>```

Thanks for reading, I hope you can assist me.

答:
class DeleteTask extends React.Component {
  this.state = {
    showModal: false
  }
  handleClick() {
        this.setState({showModal: true})
    }
  render() {
    return (

            <button type="button" className={styles.deletetask} onClick={() => this.handleClick()}>Verwijderen</button>;
            {/* In TaskDeleteModal you might have a button, when you click on that button call this.setState({showModal: false}) to hide the modal */}
         {this.state.showModal && <TaskDeleteModal />}

    )
  }
}```

Title: React return component onclick

Body:
I'm trying to return a component when I click on a button.
(a delete button with a confirmation popup) I've tried some examples I found online but none really worked for me.

Here is my code:

class DeleteTask extends React.Component {
  handleClick() {
        return <TaskDeleteModal />
    }
  render() {
    return (

            <button type="button" className={styles.deletetask} onClick={() => this.handleClick()}>Verwijderen</button>;

    )
  }
}

Thanks for reading, I hope you can assist me.

Body:
class DeleteTask extends React.Component {
  this.state = {
    showModal: false
  }
  handleClick() {
        this.setState({showModal: true})
    }
  render() {
    return (
        <div>
            <button type="button" className={styles.deletetask} onClick={() => this.handleClick()}>Verwijderen</button>;
            {/* In TaskDeleteModal you might have a button, when you click on that button call this.setState({showModal: false}) to hide the modal */}
         {this.state.showModal && <TaskDeleteModal />}
        </div>
    )
  }
}


问:
group list of dict by tuple value
I tried to solve this with list comprehension, itemgetter and groupby but I don't seem close.  Given this type of list of dict:

```<code>test_list = [{'text': "Hi",'bbox': (0,0)},
          {'text': "There.",'bbox': (1,0)},
          {'text': "Im",'bbox': (0,1)},
          {'text': "John.",'bbox': (1,1)},
         ]
</code>```

I am looking for this result:

```<code>[['Hi',"There."],['Im','John.']]
</code>```

Where the 'text' values are grouped by the second tuple element in the 'bbox'.  Thanks

答:
You can easly achieve this task using defaultdict from collections module:

```<code>from collections import defaultdict

test_list = [
    {'text': "Hi",'bbox': (0,0)},
    {'text': "There.",'bbox': (1,0)},
    {'text': "Im",'bbox': (0,1)},
    {'text': "John.",'bbox': (1,1)},
]

out = defaultdict(list)
for k in test_list:
    out[k['bbox'][1]].append(k['text'])

# print(out.values())
print(list(out.values()))
# [['Hi', 'There.'], ['Im', 'John.']]
</code>```

Update:

You can also use Python's default dict object like this example:

```<code>out = {}
for k in test_list:
    key, value = k['bbox'][1], k['text']
    if key in out:
        out[key].append(value)
    else:
        out[key] = [value]

print(list(out.values()))
# [['Hi', 'There.'], ['Im', 'John.']]
</code>```

Title: group list of dict by tuple value

Body:
I tried to solve this with list comprehension, itemgetter and groupby but I don't seem close.  Given this type of list of dict:

test_list = [{'text': "Hi",'bbox': (0,0)},
          {'text': "There.",'bbox': (1,0)},
          {'text': "Im",'bbox': (0,1)},
          {'text': "John.",'bbox': (1,1)},
         ]

I am looking for this result:

[['Hi',"There."],['Im','John.']]

Where the 'text' values are grouped by the second tuple element in the 'bbox'.  Thanks

Body:
You can easly achieve this task using defaultdict from collections module:

from collections import defaultdict

test_list = [
    {'text': "Hi",'bbox': (0,0)},
    {'text': "There.",'bbox': (1,0)},
    {'text': "Im",'bbox': (0,1)},
    {'text': "John.",'bbox': (1,1)},
]

out = defaultdict(list)
for k in test_list:
    out[k['bbox'][1]].append(k['text'])

# print(out.values())
print(list(out.values()))
# [['Hi', 'There.'], ['Im', 'John.']]

Update:

You can also use Python's default dict object like this example:

out = {}
for k in test_list:
    key, value = k['bbox'][1], k['text']
    if key in out:
        out[key].append(value)
    else:
        out[key] = [value]

print(list(out.values()))
# [['Hi', 'There.'], ['Im', 'John.']]


问:
Not able to change the action (parameter) attribute in form tag (method get), in Spring MVC 4.3.9
I want to share some SpringMVC form action unchangeable issue solutions, that I could not find on the internet including here. (might be duplicate)

But I'm almost a freshman in StackOverflow, so I'm just here to ask myself and answer myself right away.

// I have tried to share the solution public on GitHub issue, I could not use it well, too.

// asking to be excused...

I found something like a bug, in Spring MVC 4.3.9.

When I try to change the action attribute of the form tag (method get) in a javascript function,

the URL mapping in the address window of the web browser (I'm using Firefox)
is always typed as the action +  the name of the input tag inside the form tag.

```<code><form action="mappingInControllerToSend" method="get" id="theForm">
  <input type="text" name="test1"/>
</form>
<button onclick="formActionChange()"/>
<!-- blah blah -->
<script>
  function formActionChange(){
   var theForm = document.getElementById("theForm");
   var newParam = "test2";
   theForm.action = "mappingInControllerToSend?" + newParam;
  }
</script>

<!-- the default value of the 'method' attribute in form tag is "get",
so if you don't write the method attribute at all,
then you are using get method, so getting this same wrong result. -->
</code>```

In this case, by the book, I should connect to "mappingInControllerToSend?test2" in Controller
(with the parameter, test2).

But I always connect to "mappingInControllerToSend?test1" in Controller
(with the parameter, test1).

答:
** Solution **

=> You should change the method of the form tag, form "get" to "post"

=> When the method is "post", now it goes to "mappingInControllerToSend?test1" in Controller, as coded.

// P.S.

-- I'm not sure if it is a bug. (I am sorry if it is a planned feature in Spring MVC.)

-- But I at least hope this might be helpful to people who are stuck in the same problem.

Body:
I want to share some SpringMVC form action unchangeable issue solutions, that I could not find on the internet including here. (might be duplicate)

But I'm almost a freshman in StackOverflow, so I'm just here to ask myself and answer myself right away.

// I have tried to share the solution public on GitHub issue, I could not use it well, too.

// asking to be excused...

I found something like a bug, in Spring MVC 4.3.9.

When I try to change the action attribute of the form tag (method get) in a javascript function,

the URL mapping in the address window of the web browser (I'm using Firefox)
is always typed as the action +  the name of the input tag inside the form tag.

<form action="mappingInControllerToSend" method="get" id="theForm">
  <input type="text" name="test1"/>
</form>
<button onclick="formActionChange()"/>

In this case, by the book, I should connect to "mappingInControllerToSend?test2" in Controller
(with the parameter, test2).

But I always connect to "mappingInControllerToSend?test1" in Controller
(with the parameter, test1).