问:
Subsetting out rows using pandas
I have two sets of dataframes: datamax, datamax2015 and datamin, datamin2015.

Snippet of data:

```<code>print(datamax.head())
print(datamin.head())
print(datamax2015.head())
print(datamin2015.head())

Date           ID Element  Data_Value
0  2005-01-01  USW00094889    TMAX         156
1  2005-01-02  USW00094889    TMAX         139
2  2005-01-03  USW00094889    TMAX         133
3  2005-01-04  USW00094889    TMAX          39
4  2005-01-05  USW00094889    TMAX          33
         Date           ID Element  Data_Value
0  2005-01-01  USC00200032    TMIN         -56
1  2005-01-02  USC00200032    TMIN         -56
2  2005-01-03  USC00200032    TMIN           0
3  2005-01-04  USC00200032    TMIN         -39
4  2005-01-05  USC00200032    TMIN         -94
         Date           ID Element  Data_Value
0  2015-01-01  USW00094889    TMAX          11
1  2015-01-02  USW00094889    TMAX          39
2  2015-01-03  USW00014853    TMAX          39
3  2015-01-04  USW00094889    TMAX          44
4  2015-01-05  USW00094889    TMAX          28
         Date           ID Element  Data_Value
0  2015-01-01  USC00200032    TMIN        -133
1  2015-01-02  USC00200032    TMIN        -122
2  2015-01-03  USC00200032    TMIN         -67
3  2015-01-04  USC00200032    TMIN         -88
4  2015-01-05  USC00200032    TMIN        -155
</code>```

For datamax, datamax2015, I want to compare their Data_Value columns and create a dataframe of entries in datamax2015 whose Data_Value is greater than all entries in datamax for the same day of the year. Thus, the expected output should be a dataframe with rows from 2015-01-01 to 2015-12-31 but with dates only where the values in the Data_Value column are greater than those in the Data_Value column of the datamax dataframe.

i.e 4 rows and anything from 1 to 364 columns depending on the condition above.

I want the converse (min) for the datamin and datamin2015 dataframes.

I have tried the following code:

```<code>upper = []
for row in datamax.iterrows():
    for j in datamax2015["Data_Value"]:
        if j > row["Data_Value"]:
            upper.append(row)
lower = []
for row in datamin.iterrows():
    for j in datamin2015["Data_Value"]:
        if j < row["Data_Value"]:
            lower.append(row)
</code>```

Could anyone give me a helping hand as to where I am going wrong?

答:
Python code which returns a line graph of the record high and record low temperatures by day of the year over the period 2005-2014. The area between the record high and record low temperatures for each day should be shaded.

Overlay a scatter of the 2015 data for any points (highs and lows) for which the ten year record (2005-2014) record high or record low was broken in 2015.

Remove leap year dates (i.e. 29th February).

```<code>from datetime import datetime
import pandas as pd
import matplotlib.pyplot as plt

pd.set_option("display.max_rows",None,"display.max_columns",None)
data = pd.read_csv('data/C2A2_data/BinnedCsvs_d400/fb441e62df2d58994928907a91895ec62c2c42e6cd075c2700843b89.csv')
newdata = data[(data['Date'] >= '2005-01-01') & (data['Date'] <= '2014-12-12')]
datamax = newdata[newdata['Element']=='TMAX']
datamin = newdata[newdata['Element']=='TMIN']
datamax['Date'] = pd.to_datetime(datamax['Date'])
datamin['Date'] = pd.to_datetime(datamin['Date'])
datamax["day_of_year"] = datamax["Date"].dt.dayofyear
datamax = datamax.groupby('day_of_year').max()
datamin["day_of_year"] = datamin["Date"].dt.dayofyear
datamin = datamin.groupby('day_of_year').min()
datamax = datamax.reset_index()
datamin = datamin.reset_index()
datamin['Date'] = datamin['Date'].dt.strftime('%Y-%m-%d')
datamax['Date'] = datamax['Date'].dt.strftime('%Y-%m-%d')
datamax = datamax[~datamax['Date'].str.contains("02-29")]
datamin = datamin[~datamin['Date'].str.contains("02-29")]

breakoutdata = data[(data['Date']  > '2014-12-31')]
datamax2015 = breakoutdata[breakoutdata['Element']=='TMAX']
datamin2015 = breakoutdata[breakoutdata['Element']=='TMIN']
datamax2015['Date'] = pd.to_datetime(datamax2015['Date'])
datamin2015['Date'] = pd.to_datetime(datamin2015['Date'])
datamax2015["day_of_year"] = datamax2015["Date"].dt.dayofyear
datamax2015 = datamax2015.groupby('day_of_year').max()
datamin2015["day_of_year"] = datamin2015["Date"].dt.dayofyear
datamin2015 = datamin2015.groupby('day_of_year').min()
datamax2015 = datamax2015.reset_index()
datamin2015 = datamin2015.reset_index()
datamin2015['Date'] = datamin2015['Date'].dt.strftime('%Y-%m-%d')
datamax2015['Date'] = datamax2015['Date'].dt.strftime('%Y-%m-%d')
datamax2015 = datamax2015[~datamax2015['Date'].str.contains("02-29")]
datamin2015 = datamin2015[~datamin2015['Date'].str.contains("02-29")]

dataminappend = datamin2015.join(datamin,on="day_of_year",rsuffix="_new")
lower = dataminappend.loc[dataminappend["Data_Value_new"]>dataminappend["Data_Value"]]
datamaxappend = datamax2015.join(datamax,on="day_of_year",rsuffix="_new")
upper = datamaxappend.loc[datamaxappend["Data_Value_new"]<datamaxappend["Data_Value"]]

upper['Date'] = pd.to_datetime(upper['Date'])
lower['Date'] = pd.to_datetime(lower['Date'])
datamax['Date'] = pd.to_datetime(datamax['Date'])
datamin['Date'] = pd.to_datetime(datamin['Date'])

ax = plt.gca()
plt.plot(datamax['day_of_year'],datamax['Data_Value'],color='red')
plt.plot(datamin['day_of_year'],datamin['Data_Value'], color='blue')
plt.scatter(upper['day_of_year'],upper['Data_Value'],color='purple')
plt.scatter(lower['day_of_year'],lower['Data_Value'], color='cyan')

plt.ylabel("Temperature (degrees C)",color='navy')
plt.xlabel("Date",color='navy',labelpad=15)
plt.title('Record high and low temperatures by day (2005-2014)', alpha=1.0,color='brown',y=1.08)
ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.35),fancybox=False,labels=['Record high','Record low'])
plt.xticks(rotation=30)
plt.fill_between(range(len(datamax['Date'])), datamax['Data_Value'], datamin['Data_Value'],color='yellow',alpha=0.8)
plt.show()
</code>```

I have converted the 'Date' column to a string using Datamin['Date'] = datamin['Date'].dt.strftime('%Y-%m-%d').

I have then converted this back to 'datetime' format using upper['Date'] = pd.to_datetime(upper['Date'])

I then used 'date of year' as the x-value.

Title: Subsetting out rows using pandas

Body:
I have two sets of dataframes: datamax, datamax2015 and datamin, datamin2015.

Snippet of data:

print(datamax.head())
print(datamin.head())
print(datamax2015.head())
print(datamin2015.head())

Date           ID Element  Data_Value
0  2005-01-01  USW00094889    TMAX         156
1  2005-01-02  USW00094889    TMAX         139
2  2005-01-03  USW00094889    TMAX         133
3  2005-01-04  USW00094889    TMAX          39
4  2005-01-05  USW00094889    TMAX          33
         Date           ID Element  Data_Value
0  2005-01-01  USC00200032    TMIN         -56
1  2005-01-02  USC00200032    TMIN         -56
2  2005-01-03  USC00200032    TMIN           0
3  2005-01-04  USC00200032    TMIN         -39
4  2005-01-05  USC00200032    TMIN         -94
         Date           ID Element  Data_Value
0  2015-01-01  USW00094889    TMAX          11
1  2015-01-02  USW00094889    TMAX          39
2  2015-01-03  USW00014853    TMAX          39
3  2015-01-04  USW00094889    TMAX          44
4  2015-01-05  USW00094889    TMAX          28
         Date           ID Element  Data_Value
0  2015-01-01  USC00200032    TMIN        -133
1  2015-01-02  USC00200032    TMIN        -122
2  2015-01-03  USC00200032    TMIN         -67
3  2015-01-04  USC00200032    TMIN         -88
4  2015-01-05  USC00200032    TMIN        -155

For datamax, datamax2015, I want to compare their Data_Value columns and create a dataframe of entries in datamax2015 whose Data_Value is greater than all entries in datamax for the same day of the year. Thus, the expected output should be a dataframe with rows from 2015-01-01 to 2015-12-31 but with dates only where the values in the Data_Value column are greater than those in the Data_Value column of the datamax dataframe.

i.e 4 rows and anything from 1 to 364 columns depending on the condition above.

I want the converse (min) for the datamin and datamin2015 dataframes.

I have tried the following code:

upper = []
for row in datamax.iterrows():
    for j in datamax2015["Data_Value"]:
        if j > row["Data_Value"]:
            upper.append(row)
lower = []
for row in datamin.iterrows():
    for j in datamin2015["Data_Value"]:
        if j < row["Data_Value"]:
            lower.append(row)

Could anyone give me a helping hand as to where I am going wrong?

Body:
Python code which returns a line graph of the record high and record low temperatures by day of the year over the period 2005-2014. The area between the record high and record low temperatures for each day should be shaded.

Overlay a scatter of the 2015 data for any points (highs and lows) for which the ten year record (2005-2014) record high or record low was broken in 2015.

Remove leap year dates (i.e. 29th February).

from datetime import datetime
import pandas as pd
import matplotlib.pyplot as plt

pd.set_option("display.max_rows",None,"display.max_columns",None)
data = pd.read_csv('data/C2A2_data/BinnedCsvs_d400/fb441e62df2d58994928907a91895ec62c2c42e6cd075c2700843b89.csv')
newdata = data[(data['Date'] >= '2005-01-01') & (data['Date'] <= '2014-12-12')]
datamax = newdata[newdata['Element']=='TMAX']
datamin = newdata[newdata['Element']=='TMIN']
datamax['Date'] = pd.to_datetime(datamax['Date'])
datamin['Date'] = pd.to_datetime(datamin['Date'])
datamax["day_of_year"] = datamax["Date"].dt.dayofyear
datamax = datamax.groupby('day_of_year').max()
datamin["day_of_year"] = datamin["Date"].dt.dayofyear
datamin = datamin.groupby('day_of_year').min()
datamax = datamax.reset_index()
datamin = datamin.reset_index()
datamin['Date'] = datamin['Date'].dt.strftime('%Y-%m-%d')
datamax['Date'] = datamax['Date'].dt.strftime('%Y-%m-%d')
datamax = datamax[~datamax['Date'].str.contains("02-29")]
datamin = datamin[~datamin['Date'].str.contains("02-29")]

breakoutdata = data[(data['Date']  > '2014-12-31')]
datamax2015 = breakoutdata[breakoutdata['Element']=='TMAX']
datamin2015 = breakoutdata[breakoutdata['Element']=='TMIN']
datamax2015['Date'] = pd.to_datetime(datamax2015['Date'])
datamin2015['Date'] = pd.to_datetime(datamin2015['Date'])
datamax2015["day_of_year"] = datamax2015["Date"].dt.dayofyear
datamax2015 = datamax2015.groupby('day_of_year').max()
datamin2015["day_of_year"] = datamin2015["Date"].dt.dayofyear
datamin2015 = datamin2015.groupby('day_of_year').min()
datamax2015 = datamax2015.reset_index()
datamin2015 = datamin2015.reset_index()
datamin2015['Date'] = datamin2015['Date'].dt.strftime('%Y-%m-%d')
datamax2015['Date'] = datamax2015['Date'].dt.strftime('%Y-%m-%d')
datamax2015 = datamax2015[~datamax2015['Date'].str.contains("02-29")]
datamin2015 = datamin2015[~datamin2015['Date'].str.contains("02-29")]

dataminappend = datamin2015.join(datamin,on="day_of_year",rsuffix="_new")
lower = dataminappend.loc[dataminappend["Data_Value_new"]>dataminappend["Data_Value"]]
datamaxappend = datamax2015.join(datamax,on="day_of_year",rsuffix="_new")
upper = datamaxappend.loc[datamaxappend["Data_Value_new"]<datamaxappend["Data_Value"]]

upper['Date'] = pd.to_datetime(upper['Date'])
lower['Date'] = pd.to_datetime(lower['Date'])
datamax['Date'] = pd.to_datetime(datamax['Date'])
datamin['Date'] = pd.to_datetime(datamin['Date'])

ax = plt.gca()
plt.plot(datamax['day_of_year'],datamax['Data_Value'],color='red')
plt.plot(datamin['day_of_year'],datamin['Data_Value'], color='blue')
plt.scatter(upper['day_of_year'],upper['Data_Value'],color='purple')
plt.scatter(lower['day_of_year'],lower['Data_Value'], color='cyan')

plt.ylabel("Temperature (degrees C)",color='navy')
plt.xlabel("Date",color='navy',labelpad=15)
plt.title('Record high and low temperatures by day (2005-2014)', alpha=1.0,color='brown',y=1.08)
ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.35),fancybox=False,labels=['Record high','Record low'])
plt.xticks(rotation=30)
plt.fill_between(range(len(datamax['Date'])), datamax['Data_Value'], datamin['Data_Value'],color='yellow',alpha=0.8)
plt.show()

I have converted the 'Date' column to a string using Datamin['Date'] = datamin['Date'].dt.strftime('%Y-%m-%d').

I have then converted this back to 'datetime' format using upper['Date'] = pd.to_datetime(upper['Date'])

I then used 'date of year' as the x-value.


来源: stackexchange

问:
Compare two lists of hasmaps in java unittests
What is the most efficient way how to assert in (java, spring) unittests that these two lists of hashmaps are equal?

```<code>list1 = [{COUNT=5, AUTHOR=William Shakespare}, {COUNT=1, AUTHOR= Mark Helprin}]
list2 = [{AUTHOR=Mark Helprin, COUNT=1}, {AUTHOR=William Shakespare, COUNT=5}]
</code>```

I am testing a DAO method (if there are 2 books with the same title in the db, it will count how many entries belong to which author and return a list of maps with the names and counts)

the original DAO method

```<code>    public List<Map<String, Object>> countQuotesByAuthor(String title) {
    return jdbcTemplate.queryForList("SELECT author, COUNT(*) as count FROM Quote WHERE title = ? GROUP BY author",
            new Object[] { title });
}
</code>```

the test method (does not consider the list1 and list2 as equal)

```<code>    @Test
public void testCountQuotesByAuthor() throws Exception {
    List<Map<String, Object>> counts = QuoteDAOImpl.countQuotesByAuthor("Winter's Tale");
    for (Map<String, Object> count : counts) {
        Object aut = ((String) count.get("AUTHOR")).trim();
        count.put("AUTHOR", aut);
    }

    List<Map<String, Object>> result =  new ArrayList<>();
     Map<String,Object> shake=new HashMap<>();
     shake.put("AUTHOR", "William Shakespeare");
     shake.put("COUNT","2");

     Map<String,Object> help=new HashMap<>();
     help.put("AUTHOR", "Mark Helprin");
     help.put("COUNT","1");

     result.add(shake);
     result.add(help);

     Assert.assertTrue(new HashSet<>(result).equals(new HashSet<>(counts)));
}
</code>```

I get error message

```<code>java.lang.AssertionError
at org.junit.Assert.fail(Assert.java:87)
at org.junit.Assert.assertTrue(Assert.java:42)
at org.junit.Assert.assertTrue(Assert.java:53)
at com.quotes.QuoteIntegrationTest.testCountQuotesByAuthor(QuoteIntegrationTest.java:86)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:567)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:84)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
at org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)
at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
at org.junit.runners.ParentRunner.run(ParentRunner.java:413)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at org.junit.runner.JUnitCore.run(JUnitCore.java:115)
at org.junit.vintage.engine.execution.RunnerExecutor.execute(RunnerExecutor.java:43)
at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:183)
at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:195)
at java.base/java.util.Iterator.forEachRemaining(Iterator.java:133)
at java.base/java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801)
at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484)
at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474)
at java.base/java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:150)
at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:173)
at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.base/java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:497)
at org.junit.vintage.engine.VintageTestEngine.executeAllChildren(VintageTestEngine.java:82)
at org.junit.vintage.engine.VintageTestEngine.execute(VintageTestEngine.java:73)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:248)
at org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$5(DefaultLauncher.java:211)
at org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:226)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:199)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:141)
at org.eclipse.jdt.internal.junit5.runner.JUnit5TestReference.run(JUnit5TestReference.java:98)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:542)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:770)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:464)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:210)
</code>```

答:
Depends what you mean by efficient, but if "efficient" means "quickly implemented" here are some quick options.

If you know you don't have duplicates (two identical maps in one or the other list) you can convert those Lists to Sets and then use equals:

```<code>new HashSet<>(list1).equals(new HashSet<>(list2))
</code>```

If you know at least one of them won't have duplicates, additionally check the sizes are the same.

If you may have duplicates in both, you could use Guava's MultiSets.

ContentLicense: CC BY-SA 4.0

Body:
What is the most efficient way how to assert in (java, spring) unittests that these two lists of hashmaps are equal?

list1 = [{COUNT=5, AUTHOR=William Shakespare}, {COUNT=1, AUTHOR= Mark Helprin}]
list2 = [{AUTHOR=Mark Helprin, COUNT=1}, {AUTHOR=William Shakespare, COUNT=5}]

I am testing a DAO method (if there are 2 books with the same title in the db, it will count how many entries belong to which author and return a list of maps with the names and counts)

the original DAO method

    public List<Map<String, Object>> countQuotesByAuthor(String title) {
    return jdbcTemplate.queryForList("SELECT author, COUNT(*) as count FROM Quote WHERE title = ? GROUP BY author",
            new Object[] { title });
}

the test method (does not consider the list1 and list2 as equal)

    @Test
public void testCountQuotesByAuthor() throws Exception {
    List<Map<String, Object>> counts = QuoteDAOImpl.countQuotesByAuthor("Winter's Tale");
    for (Map<String, Object> count : counts) {
        Object aut = ((String) count.get("AUTHOR")).trim();
        count.put("AUTHOR", aut);
    }

    List<Map<String, Object>> result =  new ArrayList<>();
     Map<String,Object> shake=new HashMap<>();
     shake.put("AUTHOR", "William Shakespeare");
     shake.put("COUNT","2");

     Map<String,Object> help=new HashMap<>();
     help.put("AUTHOR", "Mark Helprin");
     help.put("COUNT","1");

     result.add(shake);
     result.add(help);

     Assert.assertTrue(new HashSet<>(result).equals(new HashSet<>(counts)));
}

I get error message

java.lang.AssertionError
at org.junit.Assert.fail(Assert.java:87)
at org.junit.Assert.assertTrue(Assert.java:42)
at org.junit.Assert.assertTrue(Assert.java:53)
at com.quotes.QuoteIntegrationTest.testCountQuotesByAuthor(QuoteIntegrationTest.java:86)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:567)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:84)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
at org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)
at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
at org.junit.runners.ParentRunner.run(ParentRunner.java:413)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at org.junit.runner.JUnitCore.run(JUnitCore.java:115)
at org.junit.vintage.engine.execution.RunnerExecutor.execute(RunnerExecutor.java:43)
at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:183)
at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:195)
at java.base/java.util.Iterator.forEachRemaining(Iterator.java:133)
at java.base/java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801)
at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484)
at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474)
at java.base/java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:150)
at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:173)
at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.base/java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:497)
at org.junit.vintage.engine.VintageTestEngine.executeAllChildren(VintageTestEngine.java:82)
at org.junit.vintage.engine.VintageTestEngine.execute(VintageTestEngine.java:73)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:248)
at org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$5(DefaultLauncher.java:211)
at org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:226)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:199)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:141)
at org.eclipse.jdt.internal.junit5.runner.JUnit5TestReference.run(JUnit5TestReference.java:98)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:542)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:770)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:464)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:210)

Body:
Depends what you mean by efficient, but if "efficient" means "quickly implemented" here are some quick options.

If you know you don't have duplicates (two identical maps in one or the other list) you can convert those Lists to Sets and then use equals:

new HashSet<>(list1).equals(new HashSet<>(list2))

If you know at least one of them won't have duplicates, additionally check the sizes are the same.

If you may have duplicates in both, you could use Guava's MultiSets.


问:
How can I access data which is returned by a websocket in Python?
This question still has my attention. I edited it a bit to maybe attract more problem-solvers ;)

I am currently trying to set up a websocket connection to fetch data from a third party. The connection is set up and runs just well.

However, I am not able to access and use the returned data finally... How can I do this?

My code:

```<code># Websocket Endpoint
socket = 'wss://data.alpaca.markets/stream'

# Websocket authentication dictionary
socket_login_message = {
    "action": "authenticate",
    "data": {
        "key_id": key,
        "secret_key": secret_key
    }
}

# Open Connection
ws = create_connection("wss://data.alpaca.markets/stream")

# Convert dictionary to str -> bytes object to transfer it via websocket
sck_login_credentials = json.dumps(socket_login_message).encode('utf-8')

# Send the credentials over the socket
ws.send(sck_login_credentials)

# Check if connected
result = ws.recv()
print(result)

# Define Stocks to listen
listen_stocks = {
    "action": "listen",
    "data": {
        "streams": ["Q.AAPl", "Q.CMRE", "Q.PLOW"]
    }
}

# Convert dictionary to str -> bytes object to transfer it via websocket
sck_listen_quotes = json.dumps(listen_stocks).encode('utf-8')

# Initialize Listen Process
ws.send(sck_listen_quotes)

# grab response
quotes_response = ws.recv()

# Decode bytes object again
response_str = json.loads(quotes_response)

print(type(quotes_response))
# Prints <class 'str'>

print(type(response_str))
# Prints <class 'dict'>

print(response_str)
# Prints {'stream': 'listening', 'data': {'streams': ['Q.AAPl', 'Q.CMRE', 'Q.PLOW']}}

# Now how to get the data of each stock in streams dict?!
</code>```

The transferred structure for each stream according to the documentation of the third party is as follows:

```<code>{
  "ev": "Q",
  "T": "APPL",
  "x": 17,
  "p": 283.35,
  "s": 1,
  "X": 17,
  "P": 283.4,
  "S": 1,
  "c": [
    1
  ],
  "t": 1587407015152775000
}
</code>```

So how can I assign e.g. T to the variable symbol for each item in streams?

答:
Use json.loads()

```<code># to load the JSON and convert it to a Python dictionary which you can access
response_ = json.loads(str(quotes_response))  # note the str(...), not
                                              # sure which type this var
                                              # is but most times str()
                                              # works

# e.g you want to print out the value of "stream"
print(response_['stream'])   # output: listening
</code>```

Note, it's important that quotes_response is a string if you do json.loads(quotes_response)

Body:
This question still has my attention. I edited it a bit to maybe attract more problem-solvers ;)

I am currently trying to set up a websocket connection to fetch data from a third party. The connection is set up and runs just well.

However, I am not able to access and use the returned data finally... How can I do this?

My code:

# Websocket Endpoint
socket = 'wss://data.alpaca.markets/stream'

# Websocket authentication dictionary
socket_login_message = {
    "action": "authenticate",
    "data": {
        "key_id": key,
        "secret_key": secret_key
    }
}

# Open Connection
ws = create_connection("wss://data.alpaca.markets/stream")

# Convert dictionary to str -> bytes object to transfer it via websocket
sck_login_credentials = json.dumps(socket_login_message).encode('utf-8')

# Send the credentials over the socket
ws.send(sck_login_credentials)

# Check if connected
result = ws.recv()
print(result)

# Define Stocks to listen
listen_stocks = {
    "action": "listen",
    "data": {
        "streams": ["Q.AAPl", "Q.CMRE", "Q.PLOW"]
    }
}

# Convert dictionary to str -> bytes object to transfer it via websocket
sck_listen_quotes = json.dumps(listen_stocks).encode('utf-8')

# Initialize Listen Process
ws.send(sck_listen_quotes)

# grab response
quotes_response = ws.recv()

# Decode bytes object again
response_str = json.loads(quotes_response)

print(type(quotes_response))
# Prints <class 'str'>

print(type(response_str))
# Prints <class 'dict'>

print(response_str)
# Prints {'stream': 'listening', 'data': {'streams': ['Q.AAPl', 'Q.CMRE', 'Q.PLOW']}}

# Now how to get the data of each stock in streams dict?!

The transferred structure for each stream according to the documentation of the third party is as follows:

{
  "ev": "Q",
  "T": "APPL",
  "x": 17,
  "p": 283.35,
  "s": 1,
  "X": 17,
  "P": 283.4,
  "S": 1,
  "c": [
    1
  ],
  "t": 1587407015152775000
}

So how can I assign e.g. T to the variable symbol for each item in streams?

Body:
Use json.loads()

# to load the JSON and convert it to a Python dictionary which you can access
response_ = json.loads(str(quotes_response))  # note the str(...), not
                                              # sure which type this var
                                              # is but most times str()
                                              # works

# e.g you want to print out the value of "stream"
print(response_['stream'])   # output: listening

Note, it's important that quotes_response is a string if you do json.loads(quotes_response)


问:
Converting channel last to channel first image
I have an image tensor of the following dimensions

```<code>TensorShape([Dimension(1), Dimension(96), Dimension(96), Dimension(3)])
</code>```

I want this tensor to be in following  channel first dimension

```<code>TensorShape([Dimension(1), Dimension(2), Dimension(96), Dimension(96)])
</code>```

I have tried

```<code>tf.transpose (image, perm = [0,3,1,2])
</code>```

but it did not work It is returning in the same as previous.

Since, this is the requirement of Facenet algorithm , please suggest the way to do it.

答: You can try to convert the tensor into NumPy array and then use np.rollaxis and convert back to Tensorflow tensor.</p>

Body:
I have an image tensor of the following dimensions

TensorShape([Dimension(1), Dimension(96), Dimension(96), Dimension(3)])

I want this tensor to be in following  channel first dimension

TensorShape([Dimension(1), Dimension(2), Dimension(96), Dimension(96)])

I have tried

tf.transpose (image, perm = [0,3,1,2])

but it did not work It is returning in the same as previous.

Since, this is the requirement of Facenet algorithm , please suggest the way to do it.


问:
Play multiple instances of an html5's Audio object
I'm making a small game in Javascript and it requires some audio for better user experience.
The main issue I have is that I have to play 1 song/sound multiple times, and sometimes at the same time.
However, if I cloneNode the Audio object, the audio is downloaded one more time from the server, and so is only played latter, as it has to be downloaded first. So the sound can be downloaded over 100 times during normal game !

As I coulnd't find an answer on Internet, I'm asking you :)

Please note, that I want to do that with my own code, and not with a library.

答:
The way to fix this is to make a function that makes and plays an audio element, all in a function. I think it would be something like this:

```<code>var makePlayAudio = function(src) {
var aud = new Audio();
aud.src = src;
aud.play();
}
</code>```

Then, you can call it whenever you want.

Note: I have only tested it in Chrome.

ContentLicense: CC BY-SA 2.5

Body:
The way to fix this is to make a function that makes and plays an audio element, all in a function. I think it would be something like this:

var makePlayAudio = function(src) {
var aud = new Audio();
aud.src = src;
aud.play();
}

Then, you can call it whenever you want.

Note: I have only tested it in Chrome.


问:
Laravel artisan: listen command every second
I have two microservices which communicate with help AMQP.

I use bschmitt/laravel-amqp https://github.com/bschmitt/laravel-amqp.

I created one action for publish message to queue.

Then I created artisan command which consume message from queue.
Example of publisher:

Amqp::publish('', $user->toJson() , ['queue' => 'MS:USER:CREATED']);

Example of consumer:

```<code>Amqp::consume('MS:USER:CREATED', function ($message, $resolver) {
                $result = json_decode($message->body);
                    Log::info($result);
                    $resolver->acknowledge($message);

                    $resolver->stopWhenProcessed();

            });

</code>```

I need to listen this command every second. For this I use supervisor.

Example of supervisor configuration:

```<code>[program:laravel-worker]
process_name=%(program_name)s_%(process_num)02d
command=php /home/user/Projects/other/user/artisan ms:user:created
autostart=true
autorestart=true
user=user
numprocs=8
redirect_stderr=true
stdout_logfile=/home/user/Projects/other/user/worker.log
</code>```

But supervisor start and after few second down.
This is output of error when I restart supervisor:

```<code>laravel-worker:laravel-worker_02: ERROR (spawn error)
laravel-worker:laravel-worker_06: ERROR (spawn error)
laravel-worker:laravel-worker_00: ERROR (spawn error)
laravel-worker:laravel-worker_01: ERROR (spawn error)
laravel-worker:laravel-worker_04: ERROR (spawn error)
laravel-worker:laravel-worker_07: ERROR (spawn error)
laravel-worker:laravel-worker_03: ERROR (spawn error)
laravel-worker:laravel-worker_05: ERROR (spawn error)
</code>```

Then in order to get the messages I need to restart the supervisor every time.

Also I know another approach:

Wrap Amqp::consume  and use crontab for this.

Example:

```<code> while (true) {
            Amqp::consume('MS:USER:CREATED', function ($message, $resolver) {

//some part of code
});
   sleep(1);
        }
</code>```

This approach work, but I don't think that this is good idea.

Maybe in approach with supervisor I have wrong configuration for this case.

I will be grateful for any help

答:
You can do that by using a while loop in Bash in the supervisor configuration command</p>

```<code>[program:ms-user-created]
process_name=%(program_name)s_%(process_num)02d
command=/bin/sh -c "while [ true ]; do (php /home/user/Projects/other/user/artisan ms:user:created &); sleep 1; done"
autostart=true
autorestart=true
numprocs=2
user=www-data
redirect_stderr=true
</code>```

Body:
I have two microservices which communicate with help AMQP.

I use bschmitt/laravel-amqp https://github.com/bschmitt/laravel-amqp.

I created one action for publish message to queue.

Then I created artisan command which consume message from queue.
Example of publisher:

Amqp::publish('', $user->toJson() , ['queue' => 'MS:USER:CREATED']);

Example of consumer:

Amqp::consume('MS:USER:CREATED', function ($message, $resolver) {
                $result = json_decode($message->body);
                    Log::info($result);
                    $resolver->acknowledge($message);

                    $resolver->stopWhenProcessed();

            });

I need to listen this command every second. For this I use supervisor.

Example of supervisor configuration:

[program:laravel-worker]
process_name=%(program_name)s_%(process_num)02d
command=php /home/user/Projects/other/user/artisan ms:user:created
autostart=true
autorestart=true
user=user
numprocs=8
redirect_stderr=true
stdout_logfile=/home/user/Projects/other/user/worker.log

But supervisor start and after few second down.
This is output of error when I restart supervisor:

laravel-worker:laravel-worker_02: ERROR (spawn error)
laravel-worker:laravel-worker_06: ERROR (spawn error)
laravel-worker:laravel-worker_00: ERROR (spawn error)
laravel-worker:laravel-worker_01: ERROR (spawn error)
laravel-worker:laravel-worker_04: ERROR (spawn error)
laravel-worker:laravel-worker_07: ERROR (spawn error)
laravel-worker:laravel-worker_03: ERROR (spawn error)
laravel-worker:laravel-worker_05: ERROR (spawn error)

Then in order to get the messages I need to restart the supervisor every time.

Also I know another approach:

Wrap Amqp::consume  and use crontab for this.

Example:

 while (true) {
            Amqp::consume('MS:USER:CREATED', function ($message, $resolver) {

//some part of code
});
   sleep(1);
        }

This approach work, but I don't think that this is good idea.

Maybe in approach with supervisor I have wrong configuration for this case.

I will be grateful for any help

Body:
You can do that by using a while loop in Bash in the supervisor configuration command

[program:ms-user-created]
process_name=%(program_name)s_%(process_num)02d
command=/bin/sh -c "while [ true ]; do (php /home/user/Projects/other/user/artisan ms:user:created &); sleep 1; done"
autostart=true
autorestart=true
numprocs=2
user=www-data
redirect_stderr=true


问:
Any other suggestions for adding blank dates?
Optional with date. For this reason, I want to save it as null if it is empty. Normally it is accepted when I enter NULL from MSQL server program. But it doesn't happen with coding. I applied the following method. but there must be a simpler way. If anyone knows, I would be happy.</p>

```<code>try {
    Harcama u = (Harcama) t; // t yi Uye formatına çevirdim

    Session session = sessionFactory.openSession();
    Transaction transaction = session.beginTransaction();

    if (u.getBitis() == null) {
        SQLQuery insertQuery = session.createSQLQuery("INSERT INTO Harcama (turId,altId,basl,nott,harcananTL) VALUES (?,?,?,?,?)");

        insertQuery.setParameter(0, u.getTurId());
        insertQuery.setParameter(1, u.getAltId());
        insertQuery.setParameter(2, u.getBasl());
        insertQuery.setParameter(3, u.getNott());
        insertQuery.setParameter(4, u.getHarcananTl());
        insertQuery.executeUpdate();

        session.getTransaction().commit();

        sonuc=true;

        Gnl.MesajVer.Sonuc("Kayıt ekleme işlemi başarı ile Tamamlandı");

    } else {
        SQLQuery insertQuery = session.createSQLQuery("INSERT INTO Harcama (turId,altId,basl,bitis,nott,harcananTL) VALUES (?,?,?,?,?,?)");

        insertQuery.setParameter(0, u.getTurId());
        insertQuery.setParameter(1, u.getAltId());
        insertQuery.setParameter(2, u.getBasl());
        insertQuery.setParameter(3, u.getBitis());
        insertQuery.setParameter(4, u.getNott());
        insertQuery.setParameter(5, u.getHarcananTl());
        insertQuery.executeUpdate();
        session.getTransaction().commit();

        sonuc=true;

        Gnl.MesajVer.Sonuc("Kayıt ekleme işlemi başarı ile Tamamlandı");
   }
}
</code>```

答:
In order to set null value in the SQLQuery parameter you need to provide its type, so you can get rid of if/else statement:

```<code>Harcama u = (Harcama) t; // t yi Uye formatına çevirdim

Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();

SQLQuery insertQuery = session.createSQLQuery("INSERT INTO Harcama (turId,altId,basl,bitis,nott,harcananTL) VALUES (?,?,?,?,?,?)");

insertQuery.setParameter(0, u.getTurId());
insertQuery.setParameter(1, u.getAltId());
insertQuery.setParameter(2, u.getBasl());
// insertQuery.setParameter(3, u.getBitis(), new DateType()); // indicate hibernate type for nullable value
insertQuery.setParameter(3, u.getBitis(), StandardBasicTypes.DateType); // or use the type listed in Hibernate type registry
insertQuery.setParameter(4, u.getNott());
insertQuery.setParameter(5, u.getHarcananTl());
insertQuery.executeUpdate();
transaction.commit();

sonuc = true;

Gnl.MesajVer.Sonuc("Kayıt ekleme işlemi başarı ile Tamamlandı");
</code>```

Body:
Optional with date. For this reason, I want to save it as null if it is empty. Normally it is accepted when I enter NULL from MSQL server program. But it doesn't happen with coding. I applied the following method. but there must be a simpler way. If anyone knows, I would be happy.

try {
    Harcama u = (Harcama) t; // t yi Uye formatına çevirdim

    Session session = sessionFactory.openSession();
    Transaction transaction = session.beginTransaction();

    if (u.getBitis() == null) {
        SQLQuery insertQuery = session.createSQLQuery("INSERT INTO Harcama (turId,altId,basl,nott,harcananTL) VALUES (?,?,?,?,?)");

        insertQuery.setParameter(0, u.getTurId());
        insertQuery.setParameter(1, u.getAltId());
        insertQuery.setParameter(2, u.getBasl());
        insertQuery.setParameter(3, u.getNott());
        insertQuery.setParameter(4, u.getHarcananTl());
        insertQuery.executeUpdate();

        session.getTransaction().commit();

        sonuc=true;

        Gnl.MesajVer.Sonuc("Kayıt ekleme işlemi başarı ile Tamamlandı");

    } else {
        SQLQuery insertQuery = session.createSQLQuery("INSERT INTO Harcama (turId,altId,basl,bitis,nott,harcananTL) VALUES (?,?,?,?,?,?)");

        insertQuery.setParameter(0, u.getTurId());
        insertQuery.setParameter(1, u.getAltId());
        insertQuery.setParameter(2, u.getBasl());
        insertQuery.setParameter(3, u.getBitis());
        insertQuery.setParameter(4, u.getNott());
        insertQuery.setParameter(5, u.getHarcananTl());
        insertQuery.executeUpdate();
        session.getTransaction().commit();

        sonuc=true;

        Gnl.MesajVer.Sonuc("Kayıt ekleme işlemi başarı ile Tamamlandı");
   }
}

Body:
In order to set null value in the SQLQuery parameter you need to provide its type, so you can get rid of if/else statement:

Harcama u = (Harcama) t; // t yi Uye formatına çevirdim

Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();

SQLQuery insertQuery = session.createSQLQuery("INSERT INTO Harcama (turId,altId,basl,bitis,nott,harcananTL) VALUES (?,?,?,?,?,?)");

insertQuery.setParameter(0, u.getTurId());
insertQuery.setParameter(1, u.getAltId());
insertQuery.setParameter(2, u.getBasl());
// insertQuery.setParameter(3, u.getBitis(), new DateType()); // indicate hibernate type for nullable value
insertQuery.setParameter(3, u.getBitis(), StandardBasicTypes.DateType); // or use the type listed in Hibernate type registry
insertQuery.setParameter(4, u.getNott());
insertQuery.setParameter(5, u.getHarcananTl());
insertQuery.executeUpdate();
transaction.commit();

sonuc = true;

Gnl.MesajVer.Sonuc("Kayıt ekleme işlemi başarı ile Tamamlandı");


问:
What's the fastest way to load big image on iPhone?
HI there,

I am building a scrollview which swipes through 100 images of houses.
It works. But.... For every image viewed the allocated memory increases by 2.5 MB. In the end the app crashed because it ran out of memory.

I use the code for decompress the image.....
- (void)decompress {
    const CGImageRef cgImage = [self CGImage];

```<code>const int width = CGImageGetWidth(cgImage);
const int height = CGImageGetHeight(cgImage);

const CGColorSpaceRef colorspace = CGImageGetColorSpace(cgImage);
const CGContextRef context = CGBitmapContextCreate(
                                                   NULL, /* Where to store the data. NULL = don’t care */
                                                   width, height, /* width & height */
                                                   8, width * 4, /* bits per component, bytes per row */
                                                   colorspace, kCGImageAlphaNoneSkipFirst);

CGContextDrawImage(context, CGRectMake(0, 0, width, height), cgImage);
CGContextRelease(context);
</code>```

}

but its not working,very time to take load the image.

答:
I also face the same problem The solution I opted was I resize the image in 320*460 dimension and then the image size become approx 50 kb not more than that.You can also do the same thing.

Code for resizing image:-

suppose you have your image in image variable of UIImage and new image is stored in editedImage which is also UIImage object.

```<code>if (self.image.size.height>460 || self.image.size.width>320) {
        UIGraphicsBeginImageContext(CGSizeMake(320,480));
        [self.image drawInRect: CGRectMake(0, 0,320,480)];
         self.editedImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();

        NSLog(@"smallImage%f",self.editedImage.size.height);
        NSLog(@"smallImage%f",self.editedImage.size.width);
    }
    else {
        self.editedImage=self.image;
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
HI there,

I am building a scrollview which swipes through 100 images of houses.
It works. But.... For every image viewed the allocated memory increases by 2.5 MB. In the end the app crashed because it ran out of memory.

I use the code for decompress the image.....
- (void)decompress {
    const CGImageRef cgImage = [self CGImage];

const int width = CGImageGetWidth(cgImage);
const int height = CGImageGetHeight(cgImage);

const CGColorSpaceRef colorspace = CGImageGetColorSpace(cgImage);
const CGContextRef context = CGBitmapContextCreate(
                                                   NULL, /* Where to store the data. NULL = don’t care */
                                                   width, height, /* width & height */
                                                   8, width * 4, /* bits per component, bytes per row */
                                                   colorspace, kCGImageAlphaNoneSkipFirst);

CGContextDrawImage(context, CGRectMake(0, 0, width, height), cgImage);
CGContextRelease(context);

}

but its not working,very time to take load the image.

Body:
I also face the same problem The solution I opted was I resize the image in 320*460 dimension and then the image size become approx 50 kb not more than that.You can also do the same thing.

Code for resizing image:-

suppose you have your image in image variable of UIImage and new image is stored in editedImage which is also UIImage object.

if (self.image.size.height>460 || self.image.size.width>320) {
        UIGraphicsBeginImageContext(CGSizeMake(320,480));
        [self.image drawInRect: CGRectMake(0, 0,320,480)];
         self.editedImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();

        NSLog(@"smallImage%f",self.editedImage.size.height);
        NSLog(@"smallImage%f",self.editedImage.size.width);
    }
    else {
        self.editedImage=self.image;
    }


问:
multiple Promises in nodejs wait till they all finish
I have this snippet of code in my nodejs application.

The problem is that it doesn't wait before it renders the config page and passes the object thebalances.

```<code>app.get("/config", (req, res) => {
    var thebalances = [];
    client.rest.account.listAccounts().then(accounts => {

        accounts.forEach(element => {
            client.rest.product.getProductTicker(element.currency + '-USD').then(priceInfo => {

                thebalances.push({
                    currency: element.currency
            });
        });
        res.render("config", { balance: thebalances });
    })
});
</code>```

I have modified it to this now: but i think it errors out on some and like mentioned below it is all failing.

```<code>// GET /about
app.get("/config", (req, res) => {
    let thebalances = [];
    client.rest.account.listAccounts().then(async accounts => {
        let promises = [];
        accounts.forEach(element => {
            promises.push(client.rest.product.getProductTicker(element.currency + '-USD'));
        });
        await Promise.all(promises).then(
            results => {
                results.forEach(priceInfo => {
                    thebalances.push({ currency: element.currency });
                });
            }
        ).catch(
            error => {}
        )
        console.log(results);
        res.render("config", { balances: thebalances });
    })
});
</code>```

I'm not sure how i can handle the multiple variable# of promises inside the foreach loop. I need to let that do its thing first before i can render the config page.

Any help would be greatly appreciated. I'm using coinbase api.

答:
```<code>client.rest.account.listAccounts().then(async accounts => {
    let promises = [];
    accounts.forEach(element => {
        promises.push(client.rest.product.getProductTicker(element.currency + '-USD'));
    });
    await Promise.all(promises).then(
        results => {
            results.forEach(priceInfo  => {
                thebalances.push({currency: element.currency});
            });
        }
    ).catch(
        error => {
        }
    )
    res.render("config", { balance: thebalances });
</code>```

Please read up on this ... https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

There's some con with using Promise.all if one fail its fail.

edit: missing await

Body:
I have this snippet of code in my nodejs application.

The problem is that it doesn't wait before it renders the config page and passes the object thebalances.

app.get("/config", (req, res) => {
    var thebalances = [];
    client.rest.account.listAccounts().then(accounts => {

        accounts.forEach(element => {
            client.rest.product.getProductTicker(element.currency + '-USD').then(priceInfo => {

                thebalances.push({
                    currency: element.currency
            });
        });
        res.render("config", { balance: thebalances });
    })
});

I have modified it to this now: but i think it errors out on some and like mentioned below it is all failing.

// GET /about
app.get("/config", (req, res) => {
    let thebalances = [];
    client.rest.account.listAccounts().then(async accounts => {
        let promises = [];
        accounts.forEach(element => {
            promises.push(client.rest.product.getProductTicker(element.currency + '-USD'));
        });
        await Promise.all(promises).then(
            results => {
                results.forEach(priceInfo => {
                    thebalances.push({ currency: element.currency });
                });
            }
        ).catch(
            error => {}
        )
        console.log(results);
        res.render("config", { balances: thebalances });
    })
});

I'm not sure how i can handle the multiple variable# of promises inside the foreach loop. I need to let that do its thing first before i can render the config page.

Any help would be greatly appreciated. I'm using coinbase api.

Body:
client.rest.account.listAccounts().then(async accounts => {
    let promises = [];
    accounts.forEach(element => {
        promises.push(client.rest.product.getProductTicker(element.currency + '-USD'));
    });
    await Promise.all(promises).then(
        results => {
            results.forEach(priceInfo  => {
                thebalances.push({currency: element.currency});
            });
        }
    ).catch(
        error => {
        }
    )
    res.render("config", { balance: thebalances });

Please read up on this ... https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

There's some con with using Promise.all if one fail its fail.

edit: missing await


问:
Emailing with an attachment with Python
```<code>import smtplib
import mechanize
import os
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders

def sem():
    if not os.path.isfile('key.txt'):
        print('below details are req to send report')
        gmail_user = input('enter your email=')
        gmail_app_password = input('enter your email password=')
        print('pls accept the login in your gmail account ')
        ke = open('key.txt',mode="w+")
        ke.write(gmail_user)
        ke.write(':')
        ke.write(gmail_app_password)
        ke.close()
    if not os.path.isfile('sto.txt'):
        gmai = input('enter the  email to send report=')
        ke = open('sto.txt',mode="w+")
        ke.write(gmai)
        ke.close()

    with open('key.txt',mode="r")as f:
        ds=f.readlines()
        d=''.join(ds)
        r=d.split(':')
    with open('sto.txt',mode="r")as f:
        ds=f.readlines()

    f=ds
    print(f)
    gmail_user = r[0]
    gmail_app_password = r[1]

    sent_from = gmail_user
    sent_to = ds
    sent_subject = "hey amo lio ,how are ?"
    sent_body = ("Hey, what's up? friend!")

    email_text = """\
    To: %s
    Subject: %s

    %s
    """ % (", ".join(sent_to), sent_subject, sent_body)
    mail = MIMEMultipart()
    mail["Subject"] = sent_subject
    mail["From"] = sent_from
    mail["To"] = sent_to
    mail.attach[MIMEText(sent_body,'html')]

    ctype, encoding = mimetypes.guess_type(_file)
    maintype, subtype = ctype.split('/', 1)
    fp = open("./data/mood.txt")
    msg = MIMEText(fp.read(), _subtype=subtype)
    fp.close()
    filename = os.path.basename(_file)
    msg.add_header('Content-Disposition', 'attachment', filename=filename)
    mail.attach(msg)
    print('done')
    server.sendmail(sent_from, sent_to, mail.as_string())
    try:
        server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
        server.ehlo()
        server.login(gmail_user, gmail_app_password)
        server.sendmail(sent_from, sent_to, email_text)
        server.close()

        print('Email sent!')
    except Exception as exception:
        print("Error: %s!\n\n" % exception)

sem()
</code>```

How can I attach the helloword.txt file in this email? This code is working fine, I just want to send an attachment along with it. This code lets me me send the body without any attachment. Also, how do I encrypt the key.txt file which store email address and password, and to send email it it requires the password to be entered (diff pass)?

答:
You need to use the 'MIMEMultipart' module to attach files.</p>

```<code>    from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

mail = MIMEMultipart()
mail["Subject"] = sent_subject
mail["From"] = sent_from
mail["To"] = sent_to
mail.attach(MIMEText(sent_body,'html'))

ctype, encoding = mimetypes.guess_type(_file)
maintype, subtype = ctype.split('/', 1)
fp = open("/path/to/attachment/file.txt")
# If file mimetype is video/audio use respective email.mime module.
# Here assuming 'maintype' == 'text' we will use MIMEText
msg = MIMEText(fp.read(), _subtype=subtype)
fp.close()
filename = os.path.basename(_file)
msg.add_header('Content-Disposition', 'attachment', filename=filename)
mail.attach(msg)

server.sendmail(sent_from, sent_to, mail.as_string())
</code>```

Title: Emailing with an attachment with Python

Body:
import smtplib
import mechanize
import os
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders

def sem():
    if not os.path.isfile('key.txt'):
        print('below details are req to send report')
        gmail_user = input('enter your email=')
        gmail_app_password = input('enter your email password=')
        print('pls accept the login in your gmail account ')
        ke = open('key.txt',mode="w+")
        ke.write(gmail_user)
        ke.write(':')
        ke.write(gmail_app_password)
        ke.close()
    if not os.path.isfile('sto.txt'):
        gmai = input('enter the  email to send report=')
        ke = open('sto.txt',mode="w+")
        ke.write(gmai)
        ke.close()

    with open('key.txt',mode="r")as f:
        ds=f.readlines()
        d=''.join(ds)
        r=d.split(':')
    with open('sto.txt',mode="r")as f:
        ds=f.readlines()

    f=ds
    print(f)
    gmail_user = r[0]
    gmail_app_password = r[1]

    sent_from = gmail_user
    sent_to = ds
    sent_subject = "hey amo lio ,how are ?"
    sent_body = ("Hey, what's up? friend!")

    email_text = """\
    To: %s
    Subject: %s

    %s
    """ % (", ".join(sent_to), sent_subject, sent_body)
    mail = MIMEMultipart()
    mail["Subject"] = sent_subject
    mail["From"] = sent_from
    mail["To"] = sent_to
    mail.attach[MIMEText(sent_body,'html')]

    ctype, encoding = mimetypes.guess_type(_file)
    maintype, subtype = ctype.split('/', 1)
    fp = open("./data/mood.txt")
    msg = MIMEText(fp.read(), _subtype=subtype)
    fp.close()
    filename = os.path.basename(_file)
    msg.add_header('Content-Disposition', 'attachment', filename=filename)
    mail.attach(msg)
    print('done')
    server.sendmail(sent_from, sent_to, mail.as_string())
    try:
        server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
        server.ehlo()
        server.login(gmail_user, gmail_app_password)
        server.sendmail(sent_from, sent_to, email_text)
        server.close()

        print('Email sent!')
    except Exception as exception:
        print("Error: %s!\n\n" % exception)

sem()

How can I attach the helloword.txt file in this email? This code is working fine, I just want to send an attachment along with it. This code lets me me send the body without any attachment. Also, how do I encrypt the key.txt file which store email address and password, and to send email it it requires the password to be entered (diff pass)?

Body:
You need to use the 'MIMEMultipart' module to attach files.

    from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

mail = MIMEMultipart()
mail["Subject"] = sent_subject
mail["From"] = sent_from
mail["To"] = sent_to
mail.attach(MIMEText(sent_body,'html'))

ctype, encoding = mimetypes.guess_type(_file)
maintype, subtype = ctype.split('/', 1)
fp = open("/path/to/attachment/file.txt")
# If file mimetype is video/audio use respective email.mime module.
# Here assuming 'maintype' == 'text' we will use MIMEText
msg = MIMEText(fp.read(), _subtype=subtype)
fp.close()
filename = os.path.basename(_file)
msg.add_header('Content-Disposition', 'attachment', filename=filename)
mail.attach(msg)

server.sendmail(sent_from, sent_to, mail.as_string())


问:
MYSQL Adding plus one in loop or for each
I have next quarry:

```<code>    UPDATE PREDMETIF t
CROSS JOIN (select COALESCE(MAX(predf_aa),0) max_predf_aa from PREDMETIF) m
set t.predf_aa = m.max_predf_aa + 1
where t.strf_ID = '1';
</code>```

Witch gives me result of:

```<code>| predf_aa | strp_ID |
| -------- | ------- |
| 1        | 1       |
| 1        | 1       |
| null     | 2       |
</code>```

And I need:

```<code>| predf_aa | strp_ID |
| -------- | ------- |
| 1        | 1       |
| 2        | 1       |
| null     | 2       |
</code>```

I have made Example fiddle

I find that closest thing to for each is PROCEDURE with LOOP but never used that and it seems a bit overkill. What is simplest way to achieve this with given example?

And if LOOP Statement  is what I need I would appreciate if someone would write it for me on this example and ill decode it for future references.

答:
I think you want variables:

```<code>select @rn := COALESCE(MAX(predf_aa), 0) as max_predf_aa
from PREDMETIF;

update PREDMETIF t
    set t.predf_aa = (@rn := @rn + 1)
    where t.strf_ID = 1;
</code>```

That said, if you want a unique id on each row, then perhaps you want an auto_increment column.  Of course, you would not have null in that column, so it is not clear if that is a viable solution for you.

Body:
I have next quarry:

    UPDATE PREDMETIF t
CROSS JOIN (select COALESCE(MAX(predf_aa),0) max_predf_aa from PREDMETIF) m
set t.predf_aa = m.max_predf_aa + 1
where t.strf_ID = '1';

Witch gives me result of:

| predf_aa | strp_ID |
| -------- | ------- |
| 1        | 1       |
| 1        | 1       |
| null     | 2       |

And I need:

| predf_aa | strp_ID |
| -------- | ------- |
| 1        | 1       |
| 2        | 1       |
| null     | 2       |

I have made Example fiddle

I find that closest thing to for each is PROCEDURE with LOOP but never used that and it seems a bit overkill. What is simplest way to achieve this with given example?

And if LOOP Statement  is what I need I would appreciate if someone would write it for me on this example and ill decode it for future references.

Body:
I think you want variables:

select @rn := COALESCE(MAX(predf_aa), 0) as max_predf_aa
from PREDMETIF;

update PREDMETIF t
    set t.predf_aa = (@rn := @rn + 1)
    where t.strf_ID = 1;

That said, if you want a unique id on each row, then perhaps you want an auto_increment column.  Of course, you would not have null in that column, so it is not clear if that is a viable solution for you.


问:
Is there a problem using scriptlet tags for aspx page?
I have made an aspx page in which much of the content gets generated on the logic that I have written in scriptlet tags.
For eg

```<code><%
  foreach(var data in dataCollection)
  {
    int i=0;
%>
   <div>Enter value :   <input id="<%=i %>" type="text" /></div>

<% } %>
</code>```

like this I have built the whole page based on the logic of how the data is coming from back and how the data is to be appropriately shown on the page.

So, is there an issue with having scriptlets in aspx page? Is there something like best practice which advises against the use of scriptlets in aspx page?

Thanks
Saarthak

答:
First of all "scriptlet" is a Java concept, isn't it? Every technology has its terminology and one of best practices is call things by their proper name.

This is inline server code.

About if there's some issue with that, certainly this isn't the recommended approach for ASP.NET, but for earlier classic ASP like 3.0 which share the name but ASP and ASP.NET are absolutely different things.

In ASP.NET, in any page there's a markup code (page declaration, control registration, standard XHTML client-side code and user and custom server controls).

Any logic, processing or anything handling client interaction and rendering must be placed in a System.Web.UI.Page derived class, usually called "code-behind" (for example, Default.aspx.cs).

ASP.NET enforces a total separation of markup and client-side scripting from server-side backend.

Body:
I have made an aspx page in which much of the content gets generated on the logic that I have written in scriptlet tags.
For eg

<%
  foreach(var data in dataCollection)
  {
    int i=0;
%>

Enter value :   <input id="<%=i %>" type="text" />

<% } %>

like this I have built the whole page based on the logic of how the data is coming from back and how the data is to be appropriately shown on the page.

So, is there an issue with having scriptlets in aspx page? Is there something like best practice which advises against the use of scriptlets in aspx page?

Thanks
Saarthak


问:
CSS Opacity on entire body tag except on one div
I am trying to make a loading page. My html code looks like the below.

<!doctype html>

   <meta charset="utf-8">
   <title>Coba</title>

      Test

```

When I run this, my loading image also get the opacity : 0.2. How can I exclude it?

答:
I have figured out this problem using huge outline:</p>

```<code>.highlighted {
    outline: 10000px solid rgba(0, 0, 0, 0.3);
}
</code>```

Body:
I am trying to make a loading page. My html code looks like the below.

<!doctype html>

   <meta charset="utf-8">
   <title>Coba</title>

      Test

When I run this, my loading image also get the opacity : 0.2. How can I exclude it?

Body:
I have figured out this problem using huge outline:

.highlighted {
    outline: 10000px solid rgba(0, 0, 0, 0.3);
}


问:
filter object of objects dynamic key value
how can i filter object of objects with dynamic key value in javaScript or lodash.

my data is :

```<code>var names = [
  {
    name: 'c1',
    tags: {
      key1: 'value1-1',
      key2: 'value1-2',
    },
  },
  {
    name: 'c2',
    tags: {
      key1: 'value2-1',
      key2: 'value1-2',
    },
  },
  {
    name: 'c3',
    tags: {
      key3: 'value3-1',
      key4: 'value3-2',
    },
  }
]
</code>```

and filter data is:

```<code>var filterData = {
  key3: { 0: 'value3-1' },
  key4: { 0: 'value3-2' }
}
</code>```

and i expect filter and after filter show like this:

```<code>afterFilter = [
      {
        name: 'c3',
        tags: {
          key3: 'value3-1',
          key4: 'value3-2',
        }
      }
    ]
</code>```

答:
I'm not sure about the format of your filter data, so I am assuming this will also work:

```<code>var filterdata = {
   key3: 'value3-1',
   key4: 'value3-2',
};
</code>```

With this, you can then do a .filter() on your names data set:

```<code>const keys = Object.keys(filterData);
const res = names.filter((name) => {
   let flag = true;

   keys.forEach((key) => {
      if (filterData[key] !== name.tags[key]) flag = false;
   });

   return flag;
});

// res === afterFilter
</code>```

If you keep the key names the same you will be able to leave some things out.

Hope this helps.

Body:
how can i filter object of objects with dynamic key value in javaScript or lodash.

my data is :

var names = [
  {
    name: 'c1',
    tags: {
      key1: 'value1-1',
      key2: 'value1-2',
    },
  },
  {
    name: 'c2',
    tags: {
      key1: 'value2-1',
      key2: 'value1-2',
    },
  },
  {
    name: 'c3',
    tags: {
      key3: 'value3-1',
      key4: 'value3-2',
    },
  }
]

and filter data is:

var filterData = {
  key3: { 0: 'value3-1' },
  key4: { 0: 'value3-2' }
}

and i expect filter and after filter show like this:

afterFilter = [
      {
        name: 'c3',
        tags: {
          key3: 'value3-1',
          key4: 'value3-2',
        }
      }
    ]

Body:
I'm not sure about the format of your filter data, so I am assuming this will also work:

var filterdata = {
   key3: 'value3-1',
   key4: 'value3-2',
};

With this, you can then do a .filter() on your names data set:

const keys = Object.keys(filterData);
const res = names.filter((name) => {
   let flag = true;

   keys.forEach((key) => {
      if (filterData[key] !== name.tags[key]) flag = false;
   });

   return flag;
});

// res === afterFilter

If you keep the key names the same you will be able to leave some things out.

Hope this helps.


问:
How to monitor Fastify app with Prometheus and Grafana?
I am learning to monitor my Fastify app with Prometheus and Grafana. First, I installed fastify-metrics package and registered in Fastify app.

// app.ts

import metrics from 'fastify-metrics'

...
app.register(metrics, {
  endpoint: '/metrics',
})
```

<p>Then I setup Prometheus and Grafana in <code>docker-compose.yml</code>:</p>

<pre class="lang-yaml prettyprint-override"><code>version: "3.7"
services:

  prometheus:
    image: prom/prometheus:latest
    volumes:
      - prometheus_data:/prometheus
      - ./prometheus/prometheus.yml:/etc/prometheus/prometheus.yml
    command:
      - '--config.file=/etc/prometheus/prometheus.yml'
    network_mode: host
    ports:
      - '9090:9090'

  grafana:
    image: grafana/grafana:latest
    volumes:
      - grafana_data:/var/lib/grafana
      # - ./grafana/provisioning:/etc/grafana/provisioning
      # - ./grafana/config.ini:/etc/grafana/config.ini
      # - ./grafana/dashboards:/var/lib/grafana/dashboards
    environment:
      - GF_SECURITY_ADMIN_PASSWORD=ohno
    depends_on:
      - prometheus
    network_mode: host
    ports:
      - '3000:3000'

volumes:
  prometheus_data: {}
  grafana_data: {}
</code>```

I added network_mode=host because Fastfy app will be running at localhost:8081.

Here's the Prometheus config:

# prometheus.yml

global:
  scrape_interval: 15s
  scrape_timeout: 10s
  evaluation_interval: 1m
scrape_configs:
  - job_name: 'prometheus'
    # metrics_path: /metrics
    static_configs:
      - targets: [
        'app:8081',
      ]
  - job_name: 'node_exporter'
    static_configs:
      - targets: [
        'localhost:8081',
      ]
```

After docker-compose up and npm run dev, Fastify app is up and running and target localhost:8081 is UP in Prometheus dashboard, localhost:9090, I tried executing some metrics.

I imported Node Exporter Full and Node Exporter Server Metrics dashboards. And added Prometheus datasource localhost:9090, named Fastify, and saved successfully, showed Data source is working.

However, when I go to the Node Exporter Full dashboard, it shows no data. I selected Fastify in datasource but it shows None in others selections at upper left corner.

Please help, what I am doing wrong?

答:
you should specify the metrics_path in the job as defined in your 'fastify-metrics' endpoint and also update the targets param:</p>
```<code>- job_name: 'node_exporter'
    scrape_interval: 5s
    metrics_path: /metrics
    scheme: http
    static_configs:
      - targets: ['localhost:8081']
        labels:
          group: 'node_exporter'
</code>```

Body:
I am learning to monitor my Fastify app with Prometheus and Grafana. First, I installed fastify-metrics package and registered in Fastify app.

// app.ts

import metrics from 'fastify-metrics'

...
app.register(metrics, {
  endpoint: '/metrics',
})

Then I setup Prometheus and Grafana in docker-compose.yml:

version: "3.7"
services:

  prometheus:
    image: prom/prometheus:latest
    volumes:
      - prometheus_data:/prometheus
      - ./prometheus/prometheus.yml:/etc/prometheus/prometheus.yml
    command:
      - '--config.file=/etc/prometheus/prometheus.yml'
    network_mode: host
    ports:
      - '9090:9090'

  grafana:
    image: grafana/grafana:latest
    volumes:
      - grafana_data:/var/lib/grafana
      # - ./grafana/provisioning:/etc/grafana/provisioning
      # - ./grafana/config.ini:/etc/grafana/config.ini
      # - ./grafana/dashboards:/var/lib/grafana/dashboards
    environment:
      - GF_SECURITY_ADMIN_PASSWORD=ohno
    depends_on:
      - prometheus
    network_mode: host
    ports:
      - '3000:3000'

volumes:
  prometheus_data: {}
  grafana_data: {}

I added network_mode=host because Fastfy app will be running at localhost:8081.

Here's the Prometheus config:

# prometheus.yml

global:
  scrape_interval: 15s
  scrape_timeout: 10s
  evaluation_interval: 1m
scrape_configs:
  - job_name: 'prometheus'
    # metrics_path: /metrics
    static_configs:
      - targets: [
        'app:8081',
      ]
  - job_name: 'node_exporter'
    static_configs:
      - targets: [
        'localhost:8081',
      ]

After docker-compose up and npm run dev, Fastify app is up and running and target localhost:8081 is UP in Prometheus dashboard, localhost:9090, I tried executing some metrics.

I imported Node Exporter Full and Node Exporter Server Metrics dashboards. And added Prometheus datasource localhost:9090, named Fastify, and saved successfully, showed Data source is working.

However, when I go to the Node Exporter Full dashboard, it shows no data. I selected Fastify in datasource but it shows None in others selections at upper left corner.

Please help, what I am doing wrong?

Body:
you should specify the metrics_path in the job as defined in your 'fastify-metrics' endpoint and also update the targets param:

- job_name: 'node_exporter'
    scrape_interval: 5s
    metrics_path: /metrics
    scheme: http
    static_configs:
      - targets: ['localhost:8081']
        labels:
          group: 'node_exporter'


问:
Can't make Stack of Widgets clickable after exporting Widget from Adobe XD
I want to add one widget I've exported from Adobe XD to ListView.separated and in that widget I want two places to be clickable, however I cannot completely understand where should I put InkWell() or GestureDetector() or maybe another widget to make two places clickable
Here is the code:

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

class TestPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: Container(
          margin: EdgeInsets.only(
            top: 30.0,
          ),
          width: double.infinity,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              Container(
                margin: EdgeInsets.only(),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: <Widget>[
                    SizedBox(
                      width: 100.0,
                      child: Text(
                        'Logout',
                        textAlign: TextAlign.center,
                        textScaleFactor: 1.0,
                        style: TextStyle(
                          color: Colors.blueGrey,
                          fontSize: 22.0,
                          fontWeight: FontWeight.w300,
                        ),
                      ),
                    ),
                    Image.asset(
                      'assets/call_info_logo.png',
                      width: 60.0,
                    ),
                    Row(
                      children: <Widget>[
                        SizedBox(
                          width: 100.0,
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: <Widget>[
                              Image.asset(
                                'assets/support.png',
                                width: 55.0,
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
              Flexible(
                child: Container(
                  margin: EdgeInsets.only(top: 55.0),
                  child: ListView.separated(
                    padding: EdgeInsets.only(
                      left: 30.0,
                      right: 30.0,
                      bottom: 30.0,
                    ),
                    itemCount: 6,
                    separatorBuilder: (context, index) => SizedBox(
                      height: 40.0,
                    ),
                    itemBuilder: (context, index) => Stack(
                      children: <Widget>[
                        Transform.translate(
                          offset: Offset(-21.0, -259.0),
                          child: Stack(
                            children: <Widget>[
                              Transform.translate(
                                offset: Offset(85.0, 259.0),
                                child: SvgPicture.string(
                                  _svg_chij22,
                                  allowDrawingOutsideViewBox: true,
                                ),
                              ),
                              Transform.translate(
                                offset: Offset(-7.0, 139.0),
                                child: Stack(
                                  children: <Widget>[
                                    Transform.translate(
                                      offset: Offset(102.0, 132.0),
                                      child: SizedBox(
                                        width: 171.0,
                                        height: 57.0,
                                        child: SingleChildScrollView(
                                            child: Text(
                                          'г. Нур-Султан, ул.  Кордай, д.2, под.4 ',
                                          style: TextStyle(
                                            fontFamily: 'Bahnschrift',
                                            fontSize: 18,
                                            color: const Color(0xffffffff),
                                          ),
                                          textAlign: TextAlign.center,
                                        )),
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                            ],
                          ),
                        ),
                        Transform.translate(
                          offset: Offset(-21.0, -259.0),
                          child: Stack(
                            children: <Widget>[
                              Transform.translate(
                                offset: Offset(281.0, 259.0),
                                child: SvgPicture.string(
                                  _svg_fep8be,
                                  allowDrawingOutsideViewBox: true,
                                ),
                              ),
                            ],
                          ),
                        ),
                        Transform.translate(
                          offset: Offset(-21.0, -259.0),
                          child: Stack(
                            children: <Widget>[
                              Transform.translate(
                                offset: Offset(21.0, 259.0),
                                child: Container(
                                  width: 61.0,
                                  height: 80.0,
                                  decoration: BoxDecoration(
                                    borderRadius: BorderRadius.only(
                                      topLeft: Radius.circular(25.0),
                                      bottomLeft: Radius.circular(25.0),
                                    ),
                                    color: const Color(0xffcfdb24),
                                  ),
                                ),
                              ),
                              Transform.translate(
                                offset: Offset(37.0, 280.0),
                                child:
                                    // Adobe XD layer: 'Icon awesome-file-v…' (shape)
                                    SvgPicture.string(
                                  _svg_xqnie9,
                                  allowDrawingOutsideViewBox: true,
                                ),
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

const String _svg_chij22 =
    '<svg viewBox="85.0 259.0 193.0 80.0" ><path transform="translate(85.0, 259.0)" d="M 0 0 L 193 0 L 193 80 L 0 80 L 0 0 Z" fill="#2a7ac6" fill-opacity="0.85" stroke="none" stroke-width="1" stroke-miterlimit="4" stroke-linecap="butt" /></svg>';
const String _svg_fep8be =
    '<svg viewBox="281.0 259.0 61.0 80.0" ><path transform="matrix(-1.0, 0.0, 0.0, -1.0, 342.0, 339.0)" d="M 25 0 L 60 0 C 60.55228424072266 0 61 0.4477152228355408 61 1 L 61 79 C 61 79.55228424072266 60.55228424072266 80 60 80 L 25 80 C 11.19288063049316 80 0 68.80712127685547 0 55 L 0 25 C 0 11.19288063049316 11.19288063049316 0 25 0 Z" fill="#16cf2f" stroke="none" stroke-width="1" stroke-miterlimit="4" stroke-linecap="butt" /><path transform="translate(295.0, 276.0)" d="M 29.01785659790039 20.07470893859863 L 11.0267858505249 20.07470893859863 L 11.0267858505249 11.98993682861328 C 11.0267858505249 8.884631156921387 13.32645130157471 6.304718494415283 16.19921875 6.273351669311523 C 19.10100364685059 6.241985321044922 21.47321510314941 8.790531158447266 21.47321510314941 11.91936206817627 L 21.47321510314941 13.17403030395508 C 21.47321510314941 14.21697330474854 22.24944305419922 15.05603408813477 23.21428489685059 15.05603408813477 L 25.53571510314941 15.05603408813477 C 26.50055694580078 15.05603408813477 27.27678489685059 14.21697330474854 27.27678489685059 13.17403030395508 L 27.27678489685059 11.91936206817627 C 27.27678489685059 5.332350254058838 22.3074779510498 -0.02351734600961208 16.2137279510498 7.694517080381047e-06 C 10.1199779510498 0.02353273518383503 5.223214149475098 5.449975490570068 5.223214149475098 12.0369873046875 L 5.223214149475098 20.07470893859863 L 3.482142925262451 20.07470893859863 C 1.559709787368774 20.07470893859863 0 21.76066970825195 0 23.83871650695801 L 0 36.38540267944336 C 0 38.46344757080078 1.559709787368774 40.14941024780273 3.482142925262451 40.14941024780273 L 29.01785659790039 40.14941024780273 C 30.9402904510498 40.14941024780273 32.5 38.46344757080078 32.5 36.38540267944336 L 32.5 23.83871650695801 C 32.5 21.76066970825195 30.9402904510498 20.07470893859863 29.01785659790039 20.07470893859863 Z" fill="#ffffff" stroke="none" stroke-width="1" stroke-miterlimit="4" stroke-linecap="butt" /></svg>';
const String _svg_xqnie9 =
    '<svg viewBox="37.0 280.0 30.0 39.0" ><path transform="translate(37.0, 280.0)" d="M 29.99999809265137 9.288474082946777 L 29.99999809265137 9.75 L 19.99999809265137 9.75 L 19.99999809265137 0 L 20.47335815429688 0 C 20.97062301635742 0 21.44757461547852 0.1926386654376984 21.79921913146973 0.535412073135376 L 29.45085716247559 7.995761394500732 C 29.80244445800781 8.338640213012695 29.99996948242188 8.803627014160156 29.9999942779541 9.288474082946777 Z M 17.49999618530273 10.359375 L 17.49999618530273 0 L 1.87499988079071 0 C 0.8394531011581421 0 0 0.8184667825698853 0 1.828125 L 0 37.171875 C 0 38.18153381347656 0.8394531011581421 39 1.87499988079071 39 L 28.12499809265137 39 C 29.16054344177246 39 29.99999809265137 38.18153381347656 29.99999809265137 37.171875 L 29.99999809265137 12.1875 L 19.37499618530273 12.1875 C 18.34374809265137 12.1875 17.49999618530273 11.36484432220459 17.49999618530273 10.359375 Z M 24.99999618530273 21.329345703125 L 24.99999618530273 29.8577766418457 C 24.99999618530273 31.49127960205078 22.97320175170898 32.29512405395508 21.79913711547852 31.15048980712891 L 17.49999618530273 26.96035003662109 L 17.49999618530273 29.859375 C 17.49999618530273 30.86903190612793 16.66054725646973 31.6875 15.62499904632568 31.6875 L 6.874999523162842 31.6875 C 5.839452743530273 31.6875 4.999999523162842 30.86903190612793 4.999999523162842 29.859375 L 4.999999523162842 21.328125 C 4.999999523162842 20.31846809387207 5.839452743530273 19.5 6.874999523162842 19.5 L 15.62499904632568 19.5 C 16.66054725646973 19.5 17.49999618530273 20.31846809387207 17.49999618530273 21.328125 L 17.49999618530273 24.22715187072754 L 21.79913711547852 20.03670692443848 C 22.97187042236328 18.89336776733398 24.99999618530273 19.69462013244629 24.99999618530273 21.329345703125 Z" fill="#ffffff" stroke="none" stroke-width="1" stroke-miterlimit="4" stroke-linecap="butt" /></svg>';
</code>```

I want to make these two buttons clickable

答:
This is the most simple way to add any kind of action to the specific widget - wrap it with InkWell. In your case, it will look something like this:</p>

```<code>InkWell(
  onTap: () {},
  child: Transform.translate(
    offset: Offset(85.0, 259.0),
    child: SvgPicture.string(
      _svg_chij22,
      allowDrawingOutsideViewBox: true,
     ),
   ),
 ),
</code>```

Body:
I want to add one widget I've exported from Adobe XD to ListView.separated and in that widget I want two places to be clickable, however I cannot completely understand where should I put InkWell() or GestureDetector() or maybe another widget to make two places clickable
Here is the code:

import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';

class TestPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: Container(
          margin: EdgeInsets.only(
            top: 30.0,
          ),
          width: double.infinity,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              Container(
                margin: EdgeInsets.only(),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: <Widget>[
                    SizedBox(
                      width: 100.0,
                      child: Text(
                        'Logout',
                        textAlign: TextAlign.center,
                        textScaleFactor: 1.0,
                        style: TextStyle(
                          color: Colors.blueGrey,
                          fontSize: 22.0,
                          fontWeight: FontWeight.w300,
                        ),
                      ),
                    ),
                    Image.asset(
                      'assets/call_info_logo.png',
                      width: 60.0,
                    ),
                    Row(
                      children: <Widget>[
                        SizedBox(
                          width: 100.0,
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: <Widget>[
                              Image.asset(
                                'assets/support.png',
                                width: 55.0,
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
              Flexible(
                child: Container(
                  margin: EdgeInsets.only(top: 55.0),
                  child: ListView.separated(
                    padding: EdgeInsets.only(
                      left: 30.0,
                      right: 30.0,
                      bottom: 30.0,
                    ),
                    itemCount: 6,
                    separatorBuilder: (context, index) => SizedBox(
                      height: 40.0,
                    ),
                    itemBuilder: (context, index) => Stack(
                      children: <Widget>[
                        Transform.translate(
                          offset: Offset(-21.0, -259.0),
                          child: Stack(
                            children: <Widget>[
                              Transform.translate(
                                offset: Offset(85.0, 259.0),
                                child: SvgPicture.string(
                                  _svg_chij22,
                                  allowDrawingOutsideViewBox: true,
                                ),
                              ),
                              Transform.translate(
                                offset: Offset(-7.0, 139.0),
                                child: Stack(
                                  children: <Widget>[
                                    Transform.translate(
                                      offset: Offset(102.0, 132.0),
                                      child: SizedBox(
                                        width: 171.0,
                                        height: 57.0,
                                        child: SingleChildScrollView(
                                            child: Text(
                                          'г. Нур-Султан, ул.  Кордай, д.2, под.4 ',
                                          style: TextStyle(
                                            fontFamily: 'Bahnschrift',
                                            fontSize: 18,
                                            color: const Color(0xffffffff),
                                          ),
                                          textAlign: TextAlign.center,
                                        )),
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                            ],
                          ),
                        ),
                        Transform.translate(
                          offset: Offset(-21.0, -259.0),
                          child: Stack(
                            children: <Widget>[
                              Transform.translate(
                                offset: Offset(281.0, 259.0),
                                child: SvgPicture.string(
                                  _svg_fep8be,
                                  allowDrawingOutsideViewBox: true,
                                ),
                              ),
                            ],
                          ),
                        ),
                        Transform.translate(
                          offset: Offset(-21.0, -259.0),
                          child: Stack(
                            children: <Widget>[
                              Transform.translate(
                                offset: Offset(21.0, 259.0),
                                child: Container(
                                  width: 61.0,
                                  height: 80.0,
                                  decoration: BoxDecoration(
                                    borderRadius: BorderRadius.only(
                                      topLeft: Radius.circular(25.0),
                                      bottomLeft: Radius.circular(25.0),
                                    ),
                                    color: const Color(0xffcfdb24),
                                  ),
                                ),
                              ),
                              Transform.translate(
                                offset: Offset(37.0, 280.0),
                                child:
                                    // Adobe XD layer: 'Icon awesome-file-v…' (shape)
                                    SvgPicture.string(
                                  _svg_xqnie9,
                                  allowDrawingOutsideViewBox: true,
                                ),
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

const String _svg_chij22 =
    '<svg viewBox="85.0 259.0 193.0 80.0" ><path transform="translate(85.0, 259.0)" d="M 0 0 L 193 0 L 193 80 L 0 80 L 0 0 Z" fill="#2a7ac6" fill-opacity="0.85" stroke="none" stroke-width="1" stroke-miterlimit="4" stroke-linecap="butt" /></svg>';
const String _svg_fep8be =
    '<svg viewBox="281.0 259.0 61.0 80.0" ><path transform="matrix(-1.0, 0.0, 0.0, -1.0, 342.0, 339.0)" d="M 25 0 L 60 0 C 60.55228424072266 0 61 0.4477152228355408 61 1 L 61 79 C 61 79.55228424072266 60.55228424072266 80 60 80 L 25 80 C 11.19288063049316 80 0 68.80712127685547 0 55 L 0 25 C 0 11.19288063049316 11.19288063049316 0 25 0 Z" fill="#16cf2f" stroke="none" stroke-width="1" stroke-miterlimit="4" stroke-linecap="butt" /><path transform="translate(295.0, 276.0)" d="M 29.01785659790039 20.07470893859863 L 11.0267858505249 20.07470893859863 L 11.0267858505249 11.98993682861328 C 11.0267858505249 8.884631156921387 13.32645130157471 6.304718494415283 16.19921875 6.273351669311523 C 19.10100364685059 6.241985321044922 21.47321510314941 8.790531158447266 21.47321510314941 11.91936206817627 L 21.47321510314941 13.17403030395508 C 21.47321510314941 14.21697330474854 22.24944305419922 15.05603408813477 23.21428489685059 15.05603408813477 L 25.53571510314941 15.05603408813477 C 26.50055694580078 15.05603408813477 27.27678489685059 14.21697330474854 27.27678489685059 13.17403030395508 L 27.27678489685059 11.91936206817627 C 27.27678489685059 5.332350254058838 22.3074779510498 -0.02351734600961208 16.2137279510498 7.694517080381047e-06 C 10.1199779510498 0.02353273518383503 5.223214149475098 5.449975490570068 5.223214149475098 12.0369873046875 L 5.223214149475098 20.07470893859863 L 3.482142925262451 20.07470893859863 C 1.559709787368774 20.07470893859863 0 21.76066970825195 0 23.83871650695801 L 0 36.38540267944336 C 0 38.46344757080078 1.559709787368774 40.14941024780273 3.482142925262451 40.14941024780273 L 29.01785659790039 40.14941024780273 C 30.9402904510498 40.14941024780273 32.5 38.46344757080078 32.5 36.38540267944336 L 32.5 23.83871650695801 C 32.5 21.76066970825195 30.9402904510498 20.07470893859863 29.01785659790039 20.07470893859863 Z" fill="#ffffff" stroke="none" stroke-width="1" stroke-miterlimit="4" stroke-linecap="butt" /></svg>';
const String _svg_xqnie9 =
    '<svg viewBox="37.0 280.0 30.0 39.0" ><path transform="translate(37.0, 280.0)" d="M 29.99999809265137 9.288474082946777 L 29.99999809265137 9.75 L 19.99999809265137 9.75 L 19.99999809265137 0 L 20.47335815429688 0 C 20.97062301635742 0 21.44757461547852 0.1926386654376984 21.79921913146973 0.535412073135376 L 29.45085716247559 7.995761394500732 C 29.80244445800781 8.338640213012695 29.99996948242188 8.803627014160156 29.9999942779541 9.288474082946777 Z M 17.49999618530273 10.359375 L 17.49999618530273 0 L 1.87499988079071 0 C 0.8394531011581421 0 0 0.8184667825698853 0 1.828125 L 0 37.171875 C 0 38.18153381347656 0.8394531011581421 39 1.87499988079071 39 L 28.12499809265137 39 C 29.16054344177246 39 29.99999809265137 38.18153381347656 29.99999809265137 37.171875 L 29.99999809265137 12.1875 L 19.37499618530273 12.1875 C 18.34374809265137 12.1875 17.49999618530273 11.36484432220459 17.49999618530273 10.359375 Z M 24.99999618530273 21.329345703125 L 24.99999618530273 29.8577766418457 C 24.99999618530273 31.49127960205078 22.97320175170898 32.29512405395508 21.79913711547852 31.15048980712891 L 17.49999618530273 26.96035003662109 L 17.49999618530273 29.859375 C 17.49999618530273 30.86903190612793 16.66054725646973 31.6875 15.62499904632568 31.6875 L 6.874999523162842 31.6875 C 5.839452743530273 31.6875 4.999999523162842 30.86903190612793 4.999999523162842 29.859375 L 4.999999523162842 21.328125 C 4.999999523162842 20.31846809387207 5.839452743530273 19.5 6.874999523162842 19.5 L 15.62499904632568 19.5 C 16.66054725646973 19.5 17.49999618530273 20.31846809387207 17.49999618530273 21.328125 L 17.49999618530273 24.22715187072754 L 21.79913711547852 20.03670692443848 C 22.97187042236328 18.89336776733398 24.99999618530273 19.69462013244629 24.99999618530273 21.329345703125 Z" fill="#ffffff" stroke="none" stroke-width="1" stroke-miterlimit="4" stroke-linecap="butt" /></svg>';

I want to make these two buttons clickable

Body:
This is the most simple way to add any kind of action to the specific widget - wrap it with InkWell. In your case, it will look something like this:

InkWell(
  onTap: () {},
  child: Transform.translate(
    offset: Offset(85.0, 259.0),
    child: SvgPicture.string(
      _svg_chij22,
      allowDrawingOutsideViewBox: true,
     ),
   ),
 ),


问:
How to Access Installed python directory/'site-packages' Folder for a VM Instance on Google Cloud Platform (GCP)
I am currently using GCP through a VM instance to run python 3.6. I can see my notebooks and data I've added/created, however I can't see my root folder or package details and need to edit a core module under site-packages, which would normally be under Python3.6 folder. Is there a way to access this through SSH or terminal?

I have tried to basic Pushd to where I expected it to be, no luck:

答: as mentioned by @Albert Albesa in comments, typing python3 -m site --user-site will give you the adress and you can use pushd to navigate to it


问:
Get the post thumbnail URL and assign to variable
I'm having a very strange issue. All I want to do is get the thumbnail url and assign it to a variable. Here is my code.

```<code><?php /* Template for displaying content of MH Posts Large widget */ ?>

<article class="post-<?php the_ID(); ?> mh-posts-large-item">
<figure class="mh-posts-large-thumb">

<?php

$form_image = 'blank';

if (has_post_thumbnail()) {
        $form_image = the_post_thumbnail_url('mh-magazine-lite-content');

?>
</code>```

Basically, if the post has a thumbnail I want to store the actual URL of the thumbnail used in that variable for later use. However, instead of doing that it just prints the URL on screen and doesn't actually seem to put it in the variable.

I don't understand why and I would definitely appreciate any help! :)

答:
Looking at the official documentation:

```<code>function the_post_thumbnail_url( $size = 'post-thumbnail' ) {
    $url = get_the_post_thumbnail_url( null, $size );
    if ( $url ) {
        echo esc_url( $url );
    }
}
</code>```

So the_post_thumbnail_url only outputs the URL it gets from get_the_post_thumbnail_url and doesn't return anything. Thus the solution is to use get_the_post_thumbnail_url directly.

Body:
I'm having a very strange issue. All I want to do is get the thumbnail url and assign it to a variable. Here is my code.

<?php /* Template for displaying content of MH Posts Large widget */ ?>

<article class="post-<?php the_ID(); ?> mh-posts-large-item">

<?php

$form_image = 'blank';

if (has_post_thumbnail()) {
        $form_image = the_post_thumbnail_url('mh-magazine-lite-content');

?>

Basically, if the post has a thumbnail I want to store the actual URL of the thumbnail used in that variable for later use. However, instead of doing that it just prints the URL on screen and doesn't actually seem to put it in the variable.

I don't understand why and I would definitely appreciate any help! :)

Body:
Looking at the official documentation:

function the_post_thumbnail_url( $size = 'post-thumbnail' ) {
    $url = get_the_post_thumbnail_url( null, $size );
    if ( $url ) {
        echo esc_url( $url );
    }
}

So the_post_thumbnail_url only outputs the URL it gets from get_the_post_thumbnail_url and doesn't return anything. Thus the solution is to use get_the_post_thumbnail_url directly.