问:
Spark Avro throws exception on file write: NoSuchMethodError
Any file write attempt of Avro format fails with the stack trace below.

We are using Spark 2.4.3 (with user provided Hadoop), Scala 2.12, and we load the Avro package at runtime with either spark-shell:

spark-shell --packages org.apache.spark:spark-avro_2.12:2.4.3

or spark-submit:

spark-submit --packages org.apache.spark:spark-avro_2.12:2.4.3 ...

The spark Session reports loading the Avro package successfully.

... in either case, the moment we attempt to write any data to an avro format, like:

```<code>df.write.format("avro").save("hdfs:///path/to/outputfile.avro")
</code>```

or with a select:

```<code>df.select("recordidstring").write.format("avro").save("hdfs:///path/to/outputfile.avro")
</code>```

... produces the same stacktrace error (this copy from spark-shell):

```<code>java.lang.NoSuchMethodError: org.apache.avro.Schema.createUnion([Lorg/apache/avro/Schema;)Lorg/apache/avro/Schema;
  at org.apache.spark.sql.avro.SchemaConverters$.toAvroType(SchemaConverters.scala:185)
  at org.apache.spark.sql.avro.SchemaConverters$.$anonfun$toAvroType$1(SchemaConverters.scala:176)
  at scala.collection.Iterator.foreach(Iterator.scala:941)
  at scala.collection.Iterator.foreach$(Iterator.scala:941)
  at scala.collection.AbstractIterator.foreach(Iterator.scala:1429)
  at scala.collection.IterableLike.foreach(IterableLike.scala:74)
  at scala.collection.IterableLike.foreach$(IterableLike.scala:73)
  at org.apache.spark.sql.types.StructType.foreach(StructType.scala:99)
  at org.apache.spark.sql.avro.SchemaConverters$.toAvroType(SchemaConverters.scala:174)
  at org.apache.spark.sql.avro.AvroFileFormat.$anonfun$prepareWrite$2(AvroFileFormat.scala:119)
  at scala.Option.getOrElse(Option.scala:138)
  at org.apache.spark.sql.avro.AvroFileFormat.prepareWrite(AvroFileFormat.scala:118)
  at org.apache.spark.sql.execution.datasources.FileFormatWriter$.write(FileFormatWriter.scala:103)
  at org.apache.spark.sql.execution.datasources.InsertIntoHadoopFsRelationCommand.run(InsertIntoHadoopFsRelationCommand.scala:170)
  at org.apache.spark.sql.execution.command.DataWritingCommandExec.sideEffectResult$lzycompute(commands.scala:104)
  at org.apache.spark.sql.execution.command.DataWritingCommandExec.sideEffectResult(commands.scala:102)
  at org.apache.spark.sql.execution.command.DataWritingCommandExec.doExecute(commands.scala:122)
  at org.apache.spark.sql.execution.SparkPlan.$anonfun$execute$1(SparkPlan.scala:131)
  at org.apache.spark.sql.execution.SparkPlan.$anonfun$executeQuery$1(SparkPlan.scala:155)
  at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
  at org.apache.spark.sql.execution.SparkPlan.executeQuery(SparkPlan.scala:152)
  at org.apache.spark.sql.execution.SparkPlan.execute(SparkPlan.scala:127)
  at org.apache.spark.sql.execution.QueryExecution.toRdd$lzycompute(QueryExecution.scala:80)
  at org.apache.spark.sql.execution.QueryExecution.toRdd(QueryExecution.scala:80)
  at org.apache.spark.sql.DataFrameWriter.$anonfun$runCommand$1(DataFrameWriter.scala:676)
  at org.apache.spark.sql.execution.SQLExecution$.$anonfun$withNewExecutionId$1(SQLExecution.scala:78)
  at org.apache.spark.sql.execution.SQLExecution$.withSQLConfPropagated(SQLExecution.scala:125)
  at org.apache.spark.sql.execution.SQLExecution$.withNewExecutionId(SQLExecution.scala:73)
  at org.apache.spark.sql.DataFrameWriter.runCommand(DataFrameWriter.scala:676)
  at org.apache.spark.sql.DataFrameWriter.saveToV1Source(DataFrameWriter.scala:290)
  at org.apache.spark.sql.DataFrameWriter.save(DataFrameWriter.scala:271)
  at org.apache.spark.sql.DataFrameWriter.save(DataFrameWriter.scala:229)
</code>```

We are able to write other formats (text-delimited, json, ORC, parquet) without any trouble.

We are using HDFS (Hadoop v3.1.2) as the filestore.

I have experimented with different package versions of Avro (e.g. 2.11, lower) which either raises the same error or fails to load entirely due to incompatibility.  This error occurs with all of Python, Scala (using shell or spark-submit) and Java (using spark-submit).

There appears to be an Open Issue on apache.org JIRA for this, but this is a year old now without any resolution.  I've bumped that issue, but also wondering if the community had a fix?  Any help much appreciated.

答: buddy, I met the same error as yours, but I updated my spark version to 2.11 2.4.4 and the problem disappeared.</p>

Body:
Any file write attempt of Avro format fails with the stack trace below.

We are using Spark 2.4.3 (with user provided Hadoop), Scala 2.12, and we load the Avro package at runtime with either spark-shell:

spark-shell --packages org.apache.spark:spark-avro_2.12:2.4.3

or spark-submit:

spark-submit --packages org.apache.spark:spark-avro_2.12:2.4.3 ...

The spark Session reports loading the Avro package successfully.

... in either case, the moment we attempt to write any data to an avro format, like:

df.write.format("avro").save("hdfs:///path/to/outputfile.avro")

or with a select:

df.select("recordidstring").write.format("avro").save("hdfs:///path/to/outputfile.avro")

... produces the same stacktrace error (this copy from spark-shell):

java.lang.NoSuchMethodError: org.apache.avro.Schema.createUnion([Lorg/apache/avro/Schema;)Lorg/apache/avro/Schema;
  at org.apache.spark.sql.avro.SchemaConverters$.toAvroType(SchemaConverters.scala:185)
  at org.apache.spark.sql.avro.SchemaConverters$.$anonfun$toAvroType$1(SchemaConverters.scala:176)
  at scala.collection.Iterator.foreach(Iterator.scala:941)
  at scala.collection.Iterator.foreach$(Iterator.scala:941)
  at scala.collection.AbstractIterator.foreach(Iterator.scala:1429)
  at scala.collection.IterableLike.foreach(IterableLike.scala:74)
  at scala.collection.IterableLike.foreach$(IterableLike.scala:73)
  at org.apache.spark.sql.types.StructType.foreach(StructType.scala:99)
  at org.apache.spark.sql.avro.SchemaConverters$.toAvroType(SchemaConverters.scala:174)
  at org.apache.spark.sql.avro.AvroFileFormat.$anonfun$prepareWrite$2(AvroFileFormat.scala:119)
  at scala.Option.getOrElse(Option.scala:138)
  at org.apache.spark.sql.avro.AvroFileFormat.prepareWrite(AvroFileFormat.scala:118)
  at org.apache.spark.sql.execution.datasources.FileFormatWriter$.write(FileFormatWriter.scala:103)
  at org.apache.spark.sql.execution.datasources.InsertIntoHadoopFsRelationCommand.run(InsertIntoHadoopFsRelationCommand.scala:170)
  at org.apache.spark.sql.execution.command.DataWritingCommandExec.sideEffectResult$lzycompute(commands.scala:104)
  at org.apache.spark.sql.execution.command.DataWritingCommandExec.sideEffectResult(commands.scala:102)
  at org.apache.spark.sql.execution.command.DataWritingCommandExec.doExecute(commands.scala:122)
  at org.apache.spark.sql.execution.SparkPlan.$anonfun$execute$1(SparkPlan.scala:131)
  at org.apache.spark.sql.execution.SparkPlan.$anonfun$executeQuery$1(SparkPlan.scala:155)
  at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
  at org.apache.spark.sql.execution.SparkPlan.executeQuery(SparkPlan.scala:152)
  at org.apache.spark.sql.execution.SparkPlan.execute(SparkPlan.scala:127)
  at org.apache.spark.sql.execution.QueryExecution.toRdd$lzycompute(QueryExecution.scala:80)
  at org.apache.spark.sql.execution.QueryExecution.toRdd(QueryExecution.scala:80)
  at org.apache.spark.sql.DataFrameWriter.$anonfun$runCommand$1(DataFrameWriter.scala:676)
  at org.apache.spark.sql.execution.SQLExecution$.$anonfun$withNewExecutionId$1(SQLExecution.scala:78)
  at org.apache.spark.sql.execution.SQLExecution$.withSQLConfPropagated(SQLExecution.scala:125)
  at org.apache.spark.sql.execution.SQLExecution$.withNewExecutionId(SQLExecution.scala:73)
  at org.apache.spark.sql.DataFrameWriter.runCommand(DataFrameWriter.scala:676)
  at org.apache.spark.sql.DataFrameWriter.saveToV1Source(DataFrameWriter.scala:290)
  at org.apache.spark.sql.DataFrameWriter.save(DataFrameWriter.scala:271)
  at org.apache.spark.sql.DataFrameWriter.save(DataFrameWriter.scala:229)

We are able to write other formats (text-delimited, json, ORC, parquet) without any trouble.

We are using HDFS (Hadoop v3.1.2) as the filestore.

I have experimented with different package versions of Avro (e.g. 2.11, lower) which either raises the same error or fails to load entirely due to incompatibility.  This error occurs with all of Python, Scala (using shell or spark-submit) and Java (using spark-submit).

There appears to be an Open Issue on apache.org JIRA for this, but this is a year old now without any resolution.  I've bumped that issue, but also wondering if the community had a fix?  Any help much appreciated.


来源: stackexchange

问:
Python: URLError: <urlopen error [Errno 10060]
OS: Windows 7; Python 2.7.3 using the Python GUI Shell

I'm trying to read a website through Python, and several authors use the urllib and urllib2 libraries.  To store the site in a variable, I've seen a similar approach proposed:

```<code>import urllib
import urllib2
g = "http://www.google.com/"
read = urllib2.urlopen(g)
</code>```

The last line generates an error after a 120+ seconds:

```<code>> Traceback (most recent call last):   File "<pyshell#27>", line 1, in
> <module>
>     r = urllib2.urlopen(o)   File "C:\Python27\lib\urllib2.py", line 126, in urlopen
>     return _opener.open(url, data, timeout)   File "C:\Python27\lib\urllib2.py", line 400, in open
>     response = self._open(req, data)   File "C:\Python27\lib\urllib2.py", line 418, in _open
>     '_open', req)   File "C:\Python27\lib\urllib2.py", line 378, in _call_chain
>     result = func(*args)   File "C:\Python27\lib\urllib2.py", line 1207, in http_open
>     return self.do_open(httplib.HTTPConnection, req)   File "C:\Python27\lib\urllib2.py", line 1177, in do_open
>     raise URLError(err) URLError: <urlopen error [Errno 10060] A connection attempt failed because the connected party did not properly
> respond after a period of time, or established connection failed
> because connected host has failed to respond>
</code>```

I tried bypassing the g variable and trying to urlopen("http://www.google.com/") with no success either (it generates the same error after the same length of time).

答:
Answer (Basic is advance!):

Error: 10060
Adding a timeout parameter to request solved the issue for me.

Example 1

```<code>import urllib
import urllib2
g = "http://www.google.com/"
read = urllib2.urlopen(g, timeout=20)
</code>```

Example 2

A similar error also occurred while I was making a GET request. Again, passing a timeout parameter solved the 10060 Error.

```<code>response = requests.get(param_url, timeout=20)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
OS: Windows 7; Python 2.7.3 using the Python GUI Shell

I'm trying to read a website through Python, and several authors use the urllib and urllib2 libraries.  To store the site in a variable, I've seen a similar approach proposed:

import urllib
import urllib2
g = "http://www.google.com/"
read = urllib2.urlopen(g)

The last line generates an error after a 120+ seconds:

> Traceback (most recent call last):   File "<pyshell#27>", line 1, in
> <module>
>     r = urllib2.urlopen(o)   File "C:\Python27\lib\urllib2.py", line 126, in urlopen
>     return _opener.open(url, data, timeout)   File "C:\Python27\lib\urllib2.py", line 400, in open
>     response = self._open(req, data)   File "C:\Python27\lib\urllib2.py", line 418, in _open
>     '_open', req)   File "C:\Python27\lib\urllib2.py", line 378, in _call_chain
>     result = func(*args)   File "C:\Python27\lib\urllib2.py", line 1207, in http_open
>     return self.do_open(httplib.HTTPConnection, req)   File "C:\Python27\lib\urllib2.py", line 1177, in do_open
>     raise URLError(err) URLError: <urlopen error [Errno 10060] A connection attempt failed because the connected party did not properly
> respond after a period of time, or established connection failed
> because connected host has failed to respond>

I tried bypassing the g variable and trying to urlopen("http://www.google.com/") with no success either (it generates the same error after the same length of time).

Body:
Answer (Basic is advance!):

Error: 10060
Adding a timeout parameter to request solved the issue for me.

Example 1

import urllib
import urllib2
g = "http://www.google.com/"
read = urllib2.urlopen(g, timeout=20)

Example 2

A similar error also occurred while I was making a GET request. Again, passing a timeout parameter solved the 10060 Error.

response = requests.get(param_url, timeout=20)

ContentLicense: CC BY-SA 4.0


问:
IndexError in reading a csv file with pandas
I have a CSV file that I am trying to read through with the pandas module in python..(i am coding in Ubuntu).

```<code>pd.read_csv("filename.csv",skiprows=2)
</code>```

I want to skip two rows so I am using skiprows argument here.
(The file named filename.csv is created through a C program.)
The problem which I am facing is that when I try to read the file directly then I am getting an IndexError as follows:

```<code>IndexError: index 0 is out of bounds for axis 0 with size 0
</code>```

and one warning as

```<code>FutureWarning: elementwise comparison failed; returning scalar instead, but in the future will perform elementwise comparison
res_values = method(rvalues)
</code>```

But at the same time if I open my CSV file and just save it without doing any editing in it..my error gets resolved.
So for every time, I need to read my CSV file I need to open it once through Libre Office(in Ubuntu) and save that file using ctrl+s and further in the option save as CSV text. Then, my program read it without any errors.
But on not saving, it produces the above-mentioned error.
Please help me with this issue.
Thanks in Advance.

答: I think it is about the format of csv file when exporting. Because of after open csv and save it, it gets the correct format. Check the file with notepad++ to correct the delimiter of csv file.</p>

Body:
I have a CSV file that I am trying to read through with the pandas module in python..(i am coding in Ubuntu).

pd.read_csv("filename.csv",skiprows=2)

I want to skip two rows so I am using skiprows argument here.
(The file named filename.csv is created through a C program.)
The problem which I am facing is that when I try to read the file directly then I am getting an IndexError as follows:

IndexError: index 0 is out of bounds for axis 0 with size 0

and one warning as

FutureWarning: elementwise comparison failed; returning scalar instead, but in the future will perform elementwise comparison
res_values = method(rvalues)

But at the same time if I open my CSV file and just save it without doing any editing in it..my error gets resolved.
So for every time, I need to read my CSV file I need to open it once through Libre Office(in Ubuntu) and save that file using ctrl+s and further in the option save as CSV text. Then, my program read it without any errors.
But on not saving, it produces the above-mentioned error.
Please help me with this issue.
Thanks in Advance.


问:
Change role color
I'm new in discord api and I want to make a bot for discord. I want to make a command that changes role's color.
I use this code to change color:

```<code>class MyClient(discord.Client):
    async def on_message(self, message):
        server = client.get_guild('')
        for role in server.roles:
            if role.name == 'Цвет':
                await client.edit_role(server=server, role=role, colour=0x0080000)
                break
</code>```

I got 2 errors:

```<code>Instance of 'MyClient' has no 'edit_role' member

File ".\mybot.py", line 10, in on_message
    for role in server.roles:
AttributeError: 'NoneType' object has no attribute 'roles'
</code>```

答:
You are looking at an outdated API documentation, see: https://discordpy.readthedocs.io/en/latest/migrating.html?highlight=edit_role

Client.edit_role() was used before v1.0. You need an instance of class Role and do Role.edit()

https://discordpy.readthedocs.io/en/latest/api.html?highlight=role#discord.Role.edit

```<code>async def on_message(self, message):
    server = client.get_guild('')
    for role in server.roles:
        if role.name == 'Цвет':
            await role.edit(color=0x080000)
</code>```

Title: Change role color

Body:
I'm new in discord api and I want to make a bot for discord. I want to make a command that changes role's color.
I use this code to change color:

class MyClient(discord.Client):
    async def on_message(self, message):
        server = client.get_guild('')
        for role in server.roles:
            if role.name == 'Цвет':
                await client.edit_role(server=server, role=role, colour=0x0080000)
                break

I got 2 errors:

Instance of 'MyClient' has no 'edit_role' member

File ".\mybot.py", line 10, in on_message
    for role in server.roles:
AttributeError: 'NoneType' object has no attribute 'roles'

Body:
You are looking at an outdated API documentation, see: https://discordpy.readthedocs.io/en/latest/migrating.html?highlight=edit_role

Client.edit_role() was used before v1.0. You need an instance of class Role and do Role.edit()

https://discordpy.readthedocs.io/en/latest/api.html?highlight=role#discord.Role.edit

async def on_message(self, message):
    server = client.get_guild('')
    for role in server.roles:
        if role.name == 'Цвет':
            await role.edit(color=0x080000)


问:
Where is my output when debugging C code in Visual Studio Code?
I have a simple c program, with prints something to screen.
When I debug the program I can see the DEBUG CONSOLE, however as soon as I use fgets I don't see any output. Where does my program run when debugging using VS Code?

If I just run my compiled .exe, everything is printed as expected.

```<code>#include <stdio.h>
#include <stdlib.h>

int main() {
  printf("Hello World!\n");
  printf("Enter your name\n");

  char name[100];
  // fgets(name, sizeof(name), stdin); // as soon as I uncomment this, no output is in the output console
  printf("You name %s", name);

  return 0;
}
</code>```

my launch.json:

```<code>{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "(Windows) Launch",
      "type": "cppvsdbg",
      "request": "launch",
      "program": "${workspaceFolder}/app.exe",
      "args": [],
      "stopAtEntry": false,
      "cwd": "${workspaceFolder}",
      "environment": [],
      "externalConsole": false
    }
  ]
}
</code>```

答:
Just add externalConsole": true to you configuration in launch.json.

For example:

launch.json

```<code>{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "(Windows) Launch",
      "type": "cppvsdbg",
      "request": "launch",
      "program": "${fileDirname}\\${fileBasenameNoExtension}.exe",
      "args": [],
      "stopAtEntry": false,
      "cwd": "${workspaceFolder}",
      "environment": [],
      "externalConsole": true,
      "preLaunchTask": "cl.exe build active file",
    }
  ]
}
</code>```

tasks.json

```<code>{
  "version": "2.0.0",
  "tasks": [
    {
      "type": "shell",
      "label": "cl.exe build active file",
      "command": "cl.exe",
      "args": [
        "/Zi",
        "/EHsc",
        "/Fe:",
        "${fileDirname}\\${fileBasenameNoExtension}.exe",
        "${file}"
      ],
      "problemMatcher": ["$msCompile"],
      "group": {
        "kind": "build",
        "isDefault": true
      },
    }
  ]
}
</code>```

Body:
I have a simple c program, with prints something to screen.
When I debug the program I can see the DEBUG CONSOLE, however as soon as I use fgets I don't see any output. Where does my program run when debugging using VS Code?

If I just run my compiled .exe, everything is printed as expected.

#include <stdio.h>
#include <stdlib.h>

int main() {
  printf("Hello World!\n");
  printf("Enter your name\n");

  char name[100];
  // fgets(name, sizeof(name), stdin); // as soon as I uncomment this, no output is in the output console
  printf("You name %s", name);

  return 0;
}

my launch.json:

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "(Windows) Launch",
      "type": "cppvsdbg",
      "request": "launch",
      "program": "${workspaceFolder}/app.exe",
      "args": [],
      "stopAtEntry": false,
      "cwd": "${workspaceFolder}",
      "environment": [],
      "externalConsole": false
    }
  ]
}

Body:
Just add externalConsole": true to you configuration in launch.json.

For example:

launch.json

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "(Windows) Launch",
      "type": "cppvsdbg",
      "request": "launch",
      "program": "${fileDirname}\\${fileBasenameNoExtension}.exe",
      "args": [],
      "stopAtEntry": false,
      "cwd": "${workspaceFolder}",
      "environment": [],
      "externalConsole": true,
      "preLaunchTask": "cl.exe build active file",
    }
  ]
}

tasks.json

{
  "version": "2.0.0",
  "tasks": [
    {
      "type": "shell",
      "label": "cl.exe build active file",
      "command": "cl.exe",
      "args": [
        "/Zi",
        "/EHsc",
        "/Fe:",
        "${fileDirname}\\${fileBasenameNoExtension}.exe",
        "${file}"
      ],
      "problemMatcher": ["$msCompile"],
      "group": {
        "kind": "build",
        "isDefault": true
      },
    }
  ]
}


问:
WPF DataGrid column style ignores IsTabStop false
I have an usercontrol with a datagrid which contains two columns.

The user wants 1. clicks in the second column cell, 2. edit the value, 3. presses the tab key to get in the next row (second column cell), 4. edit the call value in second row

But the user has to press the tab key twice, so I assume the "IsTabStop" in the first column is not working.

I browsed through the internet, everybody claims following lines should work, but they are not working for me. Does anybody knows why?

```<code><UserControl.Resources>
    ...
    <Style x:Key="DataGridLabelCellStyle" TargetType="{x:Type DataGridCell}">
            <Setter Property="IsTabStop" Value="false"/>
    </Style>
    <Style x:Key="DataGridValueCellStyle" TargetType="{x:Type DataGridCell}">
        <Style.Triggers>
            <DataTrigger Binding="{Binding ValueType}" Value="Text">
                ...
                <TextBox Text="{Binding DataContext.Value, .../>
                ...
            </DataTrigger>
            <DataTrigger Binding="{Binding ValueType}" Value="DateTime">
                ...
                <c1:C1DatePicker Text="{Binding Value}" />
                ...
            </DataTrigger>
            ...
        </Style.Triggers>
    </Style>
</UserControl.Resources>

...
<DataGrid>
    <DataGrid.Columns>
        <DataGridTextColumn Header="Name" Width="100" IsReadOnly="True" Binding="{Binding Name}" CellStyle="{StaticResource DataGridLabelCellStyle}" />
        <DataGridTextColumn Header="Value" Width="*" IsReadOnly="False" CellStyle="{StaticResource DataGridValueCellStyle}" />
    </DataGrid.Columns>
</DataGrid>
...
</code>```

答:
I found it by myself, it is my fault.

I inserted an additional TextBox control (via DataTemplate)

So I have to add simply an additional IsTabStop = false for the second datagrid column

Then it is working

```<code> <Style x:Key="DataGridLabelCellStyle" TargetType="{x:Type DataGridCell}">
     <Setter Property="IsTabStop" Value="false"/>
 </Style>
 <Style x:Key="DataGridValueCellStyle" TargetType="{x:Type DataGridCell}">
     **<Setter Property="IsTabStop" Value="false"/>**
     <Style.Triggers>
          ...
</code>```

Body:
I have an usercontrol with a datagrid which contains two columns.

The user wants 1. clicks in the second column cell, 2. edit the value, 3. presses the tab key to get in the next row (second column cell), 4. edit the call value in second row

But the user has to press the tab key twice, so I assume the "IsTabStop" in the first column is not working.

I browsed through the internet, everybody claims following lines should work, but they are not working for me. Does anybody knows why?

<UserControl.Resources>
    ...

    </Style>
</UserControl.Resources>

...
<DataGrid>
    <DataGrid.Columns>
        <DataGridTextColumn Header="Name" Width="100" IsReadOnly="True" Binding="{Binding Name}" CellStyle="{StaticResource DataGridLabelCellStyle}" />
        <DataGridTextColumn Header="Value" Width="*" IsReadOnly="False" CellStyle="{StaticResource DataGridValueCellStyle}" />
    </DataGrid.Columns>
</DataGrid>
...

Body:
I found it by myself, it is my fault.

I inserted an additional TextBox control (via DataTemplate)

So I have to add simply an additional IsTabStop = false for the second datagrid column

Then it is working

 <Style x:Key="DataGridLabelCellStyle" TargetType="{x:Type DataGridCell}">
     <Setter Property="IsTabStop" Value="false"/>
 </Style>
 <Style x:Key="DataGridValueCellStyle" TargetType="{x:Type DataGridCell}">
     **<Setter Property="IsTabStop" Value="false"/>**
     <Style.Triggers>
          ...


问:
Egrep acts strange with -f option
I've got a strangely acting egrep -f.

Example:

```<code>$ egrep -f ~/tmp/tmpgrep2 orig_20_L_A_20090228.txt | wc -l
3
$ for lines in `cat ~/tmp/tmpgrep2` ; do  egrep $lines orig_20_L_A_20090228.txt ; done | wc -l
12
</code>```

Could someone give me a hint what could be the problem?
No, the files did not changed between executions. The expected answer for the egrep line count is 12.

UPDATE on file contents: the searched file contains cca 13000 lines, each of them are 500 char long, the pattern file contains 12 lines, each of them are 24 char long. The pattern always (and only) occurs on a fixed position in the seached file (26-49).

UPDATE on pattern contents: every pattern from tmpgrep2 are a 24 char long number.

答: The others have already come up with most of the things I would look at. The next thing I would check is the environment variable GREP_OPTIONS, or whatever it is called on your machine. I've gotten the strangest error messages or behaviors when using a command line argument that interfered with the environment settings.</p>

OwnerDisplayName: Zsolt Botykai

ContentLicense: CC BY-SA 2.5

Title: Egrep acts strange with -f option

Body:
I've got a strangely acting egrep -f.

Example:

$ egrep -f ~/tmp/tmpgrep2 orig_20_L_A_20090228.txt | wc -l
3
$ for lines in `cat ~/tmp/tmpgrep2` ; do  egrep $lines orig_20_L_A_20090228.txt ; done | wc -l
12

Could someone give me a hint what could be the problem?
No, the files did not changed between executions. The expected answer for the egrep line count is 12.

UPDATE on file contents: the searched file contains cca 13000 lines, each of them are 500 char long, the pattern file contains 12 lines, each of them are 24 char long. The pattern always (and only) occurs on a fixed position in the seached file (26-49).

UPDATE on pattern contents: every pattern from tmpgrep2 are a 24 char long number.

LastEditorDisplayName: Jonathan Leffler

OwnerDisplayName: Harold Bamford


问:
Error using xpath expressions with eXist-db
I'm using xpath to query xml files containing shakespeare plays (I'm studying xpath).
Now I want to know how many times juliet responses to romeo (speaks right after him).
I was using this xpath expression:

```<code>1: count(doc('r_and_j.xml')//SPEAKER[. = "JULIET" and ../preceding-sibling::SPEECH[1]/SPEAKER = "ROMEO"])
</code>```

yet this returns me 4, while this obviously can't be correct...
This however does work:

```<code>2: count(doc('r_and_j.xml')//SPEECH[SPEAKER = "JULIET" and (preceding-sibling::SPEECH[1]/SPEAKER = "ROMEO")]
</code>```

another query where thing go icky is the following:
I want to know the titles of the acts that have no speakers in common with the next act in romeo and juliet.

```<code>3: doc('r_and_j.xml')//ACT[not(.//SPEAKER = ./following-sibling::ACT[1]//SPEAKER)]/TITLE
</code>```

fails to deliver the correct result, while this one does:

```<code>4: doc('r_and_j.xml')//ACT[not(distinct-values(.//SPEAKER) = distinct-values(./following-sibling::ACT[1]//SPEAKER))]/TITLE
</code>```

I don't see why xpath expressions 1,3 fail to deliver the answer, while 2,4 does? Could this have something to do with exist, since I was given 3 as a solution, while it does not seem to work.

Since it is hard to answer this (at least for 1,2) if you don't know the xml I'm working on, I will post the dtd here:

```<code><!-- DTD for Shakespeare    J. Bosak    1994.03.01, 1997.01.02 -->
<!-- Revised for case sensitivity 1997.09.10 -->
<!-- Revised for XML 1.0 conformity 1998.01.27 (thanks to Eve Maler) -->

<!ENTITY amp "&#38;">
<!ELEMENT PLAY     (TITLE, FM, PERSONAE, SCNDESCR, PLAYSUBT, INDUCT?,
                             PROLOGUE?, ACT+, EPILOGUE?)>
<!ELEMENT TITLE    (#PCDATA)>
<!ELEMENT FM       (P+)>
<!ELEMENT P        (#PCDATA)>
<!ELEMENT PERSONAE (TITLE, (PERSONA | PGROUP)+)>
<!ELEMENT PGROUP   (PERSONA+, GRPDESCR)>
<!ELEMENT PERSONA  (#PCDATA)>
<!ELEMENT GRPDESCR (#PCDATA)>
<!ELEMENT SCNDESCR (#PCDATA)>
<!ELEMENT PLAYSUBT (#PCDATA)>
<!ELEMENT INDUCT   (TITLE, SUBTITLE*, (SCENE+|(SPEECH|STAGEDIR|SUBHEAD)+))>
<!ELEMENT ACT      (TITLE, SUBTITLE*, PROLOGUE?, SCENE+, EPILOGUE?)>
<!ELEMENT SCENE    (TITLE, SUBTITLE*, (SPEECH | STAGEDIR | SUBHEAD)+)>
<!ELEMENT PROLOGUE (TITLE, SUBTITLE*, (STAGEDIR | SPEECH)+)>
<!ELEMENT EPILOGUE (TITLE, SUBTITLE*, (STAGEDIR | SPEECH)+)>
<!ELEMENT SPEECH   (SPEAKER+, (LINE | STAGEDIR | SUBHEAD)+)>
<!ELEMENT SPEAKER  (#PCDATA)>
<!ELEMENT LINE     (#PCDATA | STAGEDIR)*>
<!ELEMENT STAGEDIR (#PCDATA)>
<!ELEMENT SUBTITLE (#PCDATA)>
<!ELEMENT SUBHEAD  (#PCDATA)>
</code>```

links to xml (and other plays beside romeo and juliet) here: http://metalab.unc.edu/bosak/xml/eg/shaks200.zip

答:
I don't know how you get 4 from the first query, since you are asking (in part) to find SPEAKER elements inside SPEAKER elements, and the DTD does not permit this.

I am using the XML play text available at http://www.ibiblio.org/xml/examples/shakespeare/

If you want to find all the speeches of Juliet preceded by speeches of R, then (let's build this up)

all the speeches:

//SPEECH (returns 841 elements)

all the speeches by Juliet:

//SPEECH[SPEAKER='JULIET'] (returns 118 elements)

and finally:

//SPEECH[SPEAKER='JULIET' and preceding-sibling::SPEECH[1][SPEAKER='ROMEO']] (returns 37 elements)

Your second task is quite challenging, but can be done using the = operator which, when comparing node sets, returns true if any value in the sets is shared, so:

//ACT[ following-sibling::ACT and not(.//SPEAKER = following-sibling::ACT[1]//SPEAKER)]/TITLE

Unsurprisingly, all adjacent Acts in the play have some speakers in common, so nothing is returned.

Body:
I'm using xpath to query xml files containing shakespeare plays (I'm studying xpath).
Now I want to know how many times juliet responses to romeo (speaks right after him).
I was using this xpath expression:

1: count(doc('r_and_j.xml')//SPEAKER[. = "JULIET" and ../preceding-sibling::SPEECH[1]/SPEAKER = "ROMEO"])

yet this returns me 4, while this obviously can't be correct...
This however does work:

2: count(doc('r_and_j.xml')//SPEECH[SPEAKER = "JULIET" and (preceding-sibling::SPEECH[1]/SPEAKER = "ROMEO")]

another query where thing go icky is the following:
I want to know the titles of the acts that have no speakers in common with the next act in romeo and juliet.

3: doc('r_and_j.xml')//ACT[not(.//SPEAKER = ./following-sibling::ACT[1]//SPEAKER)]/TITLE

fails to deliver the correct result, while this one does:

4: doc('r_and_j.xml')//ACT[not(distinct-values(.//SPEAKER) = distinct-values(./following-sibling::ACT[1]//SPEAKER))]/TITLE

I don't see why xpath expressions 1,3 fail to deliver the answer, while 2,4 does? Could this have something to do with exist, since I was given 3 as a solution, while it does not seem to work.

Since it is hard to answer this (at least for 1,2) if you don't know the xml I'm working on, I will post the dtd here:

<!ENTITY amp "&#38;">
<!ELEMENT PLAY     (TITLE, FM, PERSONAE, SCNDESCR, PLAYSUBT, INDUCT?,
                             PROLOGUE?, ACT+, EPILOGUE?)>
<!ELEMENT TITLE    (#PCDATA)>
<!ELEMENT FM       (P+)>
<!ELEMENT P        (#PCDATA)>
<!ELEMENT PERSONAE (TITLE, (PERSONA | PGROUP)+)>
<!ELEMENT PGROUP   (PERSONA+, GRPDESCR)>
<!ELEMENT PERSONA  (#PCDATA)>
<!ELEMENT GRPDESCR (#PCDATA)>
<!ELEMENT SCNDESCR (#PCDATA)>
<!ELEMENT PLAYSUBT (#PCDATA)>
<!ELEMENT INDUCT   (TITLE, SUBTITLE*, (SCENE+|(SPEECH|STAGEDIR|SUBHEAD)+))>
<!ELEMENT ACT      (TITLE, SUBTITLE*, PROLOGUE?, SCENE+, EPILOGUE?)>
<!ELEMENT SCENE    (TITLE, SUBTITLE*, (SPEECH | STAGEDIR | SUBHEAD)+)>
<!ELEMENT PROLOGUE (TITLE, SUBTITLE*, (STAGEDIR | SPEECH)+)>
<!ELEMENT EPILOGUE (TITLE, SUBTITLE*, (STAGEDIR | SPEECH)+)>
<!ELEMENT SPEECH   (SPEAKER+, (LINE | STAGEDIR | SUBHEAD)+)>
<!ELEMENT SPEAKER  (#PCDATA)>
<!ELEMENT LINE     (#PCDATA | STAGEDIR)*>
<!ELEMENT STAGEDIR (#PCDATA)>
<!ELEMENT SUBTITLE (#PCDATA)>
<!ELEMENT SUBHEAD  (#PCDATA)>

links to xml (and other plays beside romeo and juliet) here: http://metalab.unc.edu/bosak/xml/eg/shaks200.zip


问:
R function that counts rows where conditions are met
I am trying to create a new column that counts each column where criteria are met. That is because I want to summarize the number of correct answers by each participant in my master thesis. I am really new to R and in desperate need for help, even on easy tasks.

For Example:

(Participant,    Task1,     Task2,     Task3;   COUNT)

1                  4         8         1    ;   1|

2                  3         8         7    ;   1|

3                  1         3         4    ;   2|

4                  5         6         4    ;   1|

5                  1         8         4    ;   3

The column COUNT should count all correct answers of the rows Task1-Task3. If the correct answers are (1, 8, 4), the COUNT row should result in the numbers shown in the example above.

Can anybody tell me how to create such a variable?

Really appreciated, thanks
Luca

答:
We can use rowSums by making the vector c(1, 8, 4) length same as the 'Task' columns length and do a ==, and get the rowSums

```<code>i1 <- startsWith(names(df1), 'Task')
df1$COUNT <-   rowSums(df1[i1] ==  c(1, 8, 4)[col(df1[i1])])
df1$COUNT
#[1] 1 1 2 1 3
</code>```

Or with sweep

```<code>rowSums(sweep(df1[i1], 2, c(1, 8, 4), `==`))
</code>```

Or another option is apply

```<code>df1$COUNT <- apply(df1[i1], 1, function(x) sum(x == c(1, 8, 4)))
</code>```

NOTE: None of the solutions require any external package

data

```<code>df1 <- data.frame(Participant = 1:5, Task1 = c(4, 3, 1, 5, 1),
   Task2 = c(8, 8, 3, 6, 8), Task3 = c(1, 7, 4, 4, 4))
</code>```

Body:
We can use rowSums by making the vector c(1, 8, 4) length same as the 'Task' columns length and do a ==, and get the rowSums

i1 <- startsWith(names(df1), 'Task')
df1$COUNT <-   rowSums(df1[i1] ==  c(1, 8, 4)[col(df1[i1])])
df1$COUNT
#[1] 1 1 2 1 3

Or with sweep

rowSums(sweep(df1[i1], 2, c(1, 8, 4), `==`))

Or another option is apply

df1$COUNT <- apply(df1[i1], 1, function(x) sum(x == c(1, 8, 4)))

NOTE: None of the solutions require any external package

data

df1 <- data.frame(Participant = 1:5, Task1 = c(4, 3, 1, 5, 1),
   Task2 = c(8, 8, 3, 6, 8), Task3 = c(1, 7, 4, 4, 4))


答:
This is an IndexError in python, which means that we're trying to access an index that isn't there. I wrote is a very simple example to understand this error. Here I try to assign any value to some index.

```<code>import numpy as np

arr = np.array([], dtype=np.int64)
print(arr.shape)
arr[0] = 23
</code>```

It might be There were a few instances of empty data frames that were causing the error. If you have numeric and non-numeric data in your index column. Then numpy gets confused when it tries to check whether the index is ordered.

For Solution:

```<code>df = pd.read_csv('your_file.tsv', sep='\t', header=0)
df.set_index(['0'], inplace=True)
</code>```

Title: IndexError in reading a csv file with pandas

Body:
This is an IndexError in python, which means that we're trying to access an index that isn't there. I wrote is a very simple example to understand this error. Here I try to assign any value to some index.

import numpy as np

arr = np.array([], dtype=np.int64)
print(arr.shape)
arr[0] = 23

It might be There were a few instances of empty data frames that were causing the error. If you have numeric and non-numeric data in your index column. Then numpy gets confused when it tries to check whether the index is ordered.

For Solution:

df = pd.read_csv('your_file.tsv', sep='\t', header=0)
df.set_index(['0'], inplace=True)


问:
Delete last 3 characters if they are equal to something
(without affecting the char level formatting in the cell)

I've already posted a similar question, but I unfortunately I realized I couldn't use any of the solutions because all of them removed all the formatting in the cells :(

I have a code that replaces various text strings. It looks like this (+ some more IFs):

```<code>Sub Fix()
  Dim X As Long, Cell As Range
  For Each Cell In Selection
    For X = Len(Cell.Text) To 1 Step -1
      If Cell.Characters(X, 3).Text = ", ," Then Cell.Characters(X, 3).Text = ","
      If Cell.Characters(X, 3).Text = ", (" Then Cell.Characters(X, 3).Text = " ("
      If Cell.Characters(X, 3).Text = ", [" Then Cell.Characters(X, 3).Text = " ["
      If Cell.Characters(X, 3).Text = ", -" Then Cell.Characters(X, 3).Text = " -"
      If Cell.Characters(1, 3).Text = "abc" Then Cell.Characters(1, 3).Text = ""
    Next
  Next
End Sub
</code>```

The last line of my code deletes abc if this is contained at the beginning of the selected cell(s).

I am looking to find out how to delete abc when this is contained at the end of the selected cell(s).

But it's really important for me to preserve all the original formatting in the cells (text size, colors, bold/italic/underline letters etc).

Please bear in mind that I am a complete beginner and I don't know anything about programming. I've copied the code above from the internet and just changed the values.

Thank you in advance for your help.

答:
Since all your strings are length of 3, you simply need to adjust your loop:

```<code>For X = Len(Cell.Text) - 2 To 1 Step -1
</code>```

Just add a line like:

```<code>If Cell.Characters(X, 3).Text = "abc" Then Cell.Characters(X, 3).Text = ""
</code>```

That would make your last line loking for abc redundant and can be removed. However, it seems you could also use some other construct alltogether if you like too, possibly:

```<code>Sub Fixt()

Dim X As Long, Cell As Range
Dim arr1 As Variant: arr1 = Array("abc", ", ,", ", (", ", [", ", -")
Dim arr2 As Variant: arr2 = Array("", ",", " (", ", [", " -")

For Each Cell In Selection
    For X = Len(Cell.Text) - 2 To 1 Step -1
        Match = Application.Match(Cell.Characters(X, 3).Text, arr1, 0)
        If IsNumeric(Match) Then Cell.Characters(X, 3).Text = arr2(Match - 1)
    Next
Next

End Sub
</code>```

Body:
(without affecting the char level formatting in the cell)

I've already posted a similar question, but I unfortunately I realized I couldn't use any of the solutions because all of them removed all the formatting in the cells :(

I have a code that replaces various text strings. It looks like this (+ some more IFs):

Sub Fix()
  Dim X As Long, Cell As Range
  For Each Cell In Selection
    For X = Len(Cell.Text) To 1 Step -1
      If Cell.Characters(X, 3).Text = ", ," Then Cell.Characters(X, 3).Text = ","
      If Cell.Characters(X, 3).Text = ", (" Then Cell.Characters(X, 3).Text = " ("
      If Cell.Characters(X, 3).Text = ", [" Then Cell.Characters(X, 3).Text = " ["
      If Cell.Characters(X, 3).Text = ", -" Then Cell.Characters(X, 3).Text = " -"
      If Cell.Characters(1, 3).Text = "abc" Then Cell.Characters(1, 3).Text = ""
    Next
  Next
End Sub

The last line of my code deletes abc if this is contained at the beginning of the selected cell(s).

I am looking to find out how to delete abc when this is contained at the end of the selected cell(s).

But it's really important for me to preserve all the original formatting in the cells (text size, colors, bold/italic/underline letters etc).

Please bear in mind that I am a complete beginner and I don't know anything about programming. I've copied the code above from the internet and just changed the values.

Thank you in advance for your help.

Body:
Since all your strings are length of 3, you simply need to adjust your loop:

For X = Len(Cell.Text) - 2 To 1 Step -1

Just add a line like:

If Cell.Characters(X, 3).Text = "abc" Then Cell.Characters(X, 3).Text = ""

That would make your last line loking for abc redundant and can be removed. However, it seems you could also use some other construct alltogether if you like too, possibly:

Sub Fixt()

Dim X As Long, Cell As Range
Dim arr1 As Variant: arr1 = Array("abc", ", ,", ", (", ", [", ", -")
Dim arr2 As Variant: arr2 = Array("", ",", " (", ", [", " -")

For Each Cell In Selection
    For X = Len(Cell.Text) - 2 To 1 Step -1
        Match = Application.Match(Cell.Characters(X, 3).Text, arr1, 0)
        If IsNumeric(Match) Then Cell.Characters(X, 3).Text = arr2(Match - 1)
    Next
Next

End Sub


问:
How should I track down PHP Warning: Input variables exceeded 1000
I have a relatively high traffic site, that about once per day generates the error message:

PHP Warning:  Unknown: Input variables exceeded 1000. To increase the limit change max_input_vars in php.ini. in Unknown on line 0

My guess is that it is caused by some crawler that has found a URL link structure that never ends.  However, I couldn't find any thing in the access logs that would be a problem (e.g. a url with a 1000+ get parameters).

It there an easy way to get insight into this Warning?  It happens before any php scripts are loaded, so I assume it is impossible to introspect with php.  If I had simple details such as the URL, it would be easy to solve.

答:
Attention! This detection won't alert if the input vars are in an sub array:
Array
(
    [foo] => 100
    [bars] => Array
        (
            [0] => 1111
            [1] => 1111
...(more than 1000)
        )
)

The return value of 'count' will be 2 and everything seems ok but PHP won't handle the more than 1000 values in the sub array.


问:
Calculating SVG arc path on circle
i am trying to draw a SVG objects similar to pie chart using the SVG path element. I had earlier used the example from this  stackoverflow post to generate the SVG arc path. But somehow my two arc which are supposed be part of same circle dont form a full circle. here is the code example i used to generate my arcs on a circle.

var draw = SVG('drawing').size(300, 130)

var radi = 20;
var st = {'x':0,'y':0};

var pie1Arc = this.describeArc(this.st.x,this.st.y,this.radi,0,42)
var pie1 = draw.path('M 0 0 '+ pie1Arc)
pie1.fill('none')
pie1.stroke({ color: '#f06', width: 3, linecap: 'round', linejoin: 'round' })
pie1.move(80,80)

var pie2Arc = this.describeArc(this.st.x,this.st.y,this.radi,42,360)
var pie2 = draw.path('M 0 0 '+ pie2Arc)
pie2.fill('none')
pie2.stroke({ color: '#f06', width: 3, linecap: 'round', linejoin: 'round' })
pie2.move(80,80)

function polarToCartesian(centerX, centerY, radius, angleInDegrees) {
  var angleInRadians = (angleInDegrees-90) * Math.PI / 180.0;

  return {
    x: centerX + (radius * Math.cos(angleInRadians)),
    y: centerY + (radius * Math.sin(angleInRadians))
  };
}

function describeArc(x, y, radius, startAngle, endAngle){

    var start = polarToCartesian(x, y, radius, endAngle);
    var end = polarToCartesian(x, y, radius, startAngle);

    var largeArcFlag = endAngle - startAngle <= 180 ? "0" : "1";

    var d = [
        "A", radius, radius, 0, largeArcFlag, 0, end.x, end.y
    ].join(" ");

    return d;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/svg.js/2.5.0/svg.min.js"></script>
<div id="drawing"></div></code>```

答:
I've rewritten the describeArc and also reset the st = {'x':80,'y':80}; instead of moving each arc. If you really need to translate put the 2 arcs in a group and translate the group.

var draw = SVG('drawing').size(300, 130)

var radi = 20;
var st = {'x':80,'y':80};

var pie1Arc = this.describeArc(this.st.x,this.st.y,this.radi,0,42)
var pie1 = draw.path(pie1Arc)
pie1.fill('none')
pie1.stroke({ color: '#f06', width: 3, linecap: 'round', linejoin: 'round' })

var pie2Arc = this.describeArc(this.st.x,this.st.y,this.radi,42,360)
var pie2 = draw.path(pie2Arc)
pie2.fill('none')
pie2.stroke({ color: '#f06', width: 3, linecap: 'round', linejoin: 'round' })

function polarToCartesian(centerX, centerY, radius, angleInDegrees) {
  var angleInRadians = (angleInDegrees-90) * Math.PI / 180.0;

  return {
    x: centerX + (radius * Math.cos(angleInRadians)),
    y: centerY + (radius * Math.sin(angleInRadians))
  };
}

function describeArc(x, y, radius, startAngle, endAngle){

    var start = polarToCartesian(x, y, radius, endAngle);
    var end = polarToCartesian(x, y, radius, startAngle);

    var largeArcFlag = endAngle - startAngle <= 180 ? "0" : "1";

    var d = `M${start.x},${start.y}A${radius}, ${radius}, 0, ${largeArcFlag}, 0, ${end.x}, ${end.y}`;

    return d;
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>svg{border:solid}</code>```

```

Title: Calculating SVG arc path on circle

Body:
I've rewritten the describeArc and also reset the st = {'x':80,'y':80}; instead of moving each arc. If you really need to translate put the 2 arcs in a group and translate the group.

var draw = SVG('drawing').size(300, 130)

var radi = 20;
var st = {'x':80,'y':80};

var pie1Arc = this.describeArc(this.st.x,this.st.y,this.radi,0,42)
var pie1 = draw.path(pie1Arc)
pie1.fill('none')
pie1.stroke({ color: '#f06', width: 3, linecap: 'round', linejoin: 'round' })

var pie2Arc = this.describeArc(this.st.x,this.st.y,this.radi,42,360)
var pie2 = draw.path(pie2Arc)
pie2.fill('none')
pie2.stroke({ color: '#f06', width: 3, linecap: 'round', linejoin: 'round' })

function polarToCartesian(centerX, centerY, radius, angleInDegrees) {
  var angleInRadians = (angleInDegrees-90) * Math.PI / 180.0;

  return {
    x: centerX + (radius * Math.cos(angleInRadians)),
    y: centerY + (radius * Math.sin(angleInRadians))
  };
}

function describeArc(x, y, radius, startAngle, endAngle){

    var start = polarToCartesian(x, y, radius, endAngle);
    var end = polarToCartesian(x, y, radius, startAngle);

    var largeArcFlag = endAngle - startAngle <= 180 ? "0" : "1";

    var d = `M${start.x},${start.y}A${radius}, ${radius}, 0, ${largeArcFlag}, 0, ${end.x}, ${end.y}`;

    return d;
}

svg{border:solid}

<script src="https://cdnjs.cloudflare.com/ajax/libs/svg.js/2.5.0/svg.min.js"></script>
<div id="drawing"></div>


问:
how to get the height and width of image in javascript?
I have a code where I am trying to get all images tag height and width.

```<code>var img = $('.data').find('img');
$.each($(img), function() {
console.log('first', this.height, $(this).height, $(this).height());
console.log('second', $(this).clientHeight, $(this).naturalHeight);
console.log('third',  $(this)[0].height,  $(this)[0].clientHeight,  $(this)[0].naturalHeight);
console.log($(this).attr('height'), $(this).prop('height'));                                                                                });
</code>```

Even i tried for img in loop.

tried the same with width , the result will be either 0 or undefined.
  tried same thing for width.

Can you tell me where I am doing wrong

答:
You are passing $(img) this should be only img inside you $.each.Also you where printing console.log('first',.. instead of this if your image has name attribute use that .

Here is demo code :

var img = $('.data').find('img');
$.each(img, function() {
  console.log($(this).attr("name") + "-> Height: " + $(this)[0].height + " Width:" + $(this)[0].width);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="data">
  <img name="image1" src=" https://twimg0-a.akamaihd.net/a/1350072692/t1/img/front_page/jp-mountain@2x.jpg" style="height:70px;width:70px">
  <img name="image2" src=" https://twimg0-a.akamaihd.net/a/1350072692/t1/img/front_page/jp-mountain@2x.jpg" style="height:40px;width:40px">
  <img name="image3" src=" https://twimg0-a.akamaihd.net/a/1350072692/t1/img/front_page/jp-mountain@2x.jpg" style="height:50px;width:50px">
</div></code>```

Body:
I have a code where I am trying to get all images tag height and width.

var img = $('.data').find('img');
$.each($(img), function() {
console.log('first', this.height, $(this).height, $(this).height());
console.log('second', $(this).clientHeight, $(this).naturalHeight);
console.log('third',  $(this)[0].height,  $(this)[0].clientHeight,  $(this)[0].naturalHeight);
console.log($(this).attr('height'), $(this).prop('height'));                                                                                });

Even i tried for img in loop.

tried the same with width , the result will be either 0 or undefined.
  tried same thing for width.

Can you tell me where I am doing wrong

Body:
You are passing $(img) this should be only img inside you $.each.Also you where printing console.log('first',.. instead of this if your image has name attribute use that .

Here is demo code :

var img = $('.data').find('img');
$.each(img, function() {
  console.log($(this).attr("name") + "-> Height: " + $(this)[0].height + " Width:" + $(this)[0].width);
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="data">
  <img name="image1" src=" https://twimg0-a.akamaihd.net/a/1350072692/t1/img/front_page/jp-mountain@2x.jpg" style="height:70px;width:70px">
  <img name="image2" src=" https://twimg0-a.akamaihd.net/a/1350072692/t1/img/front_page/jp-mountain@2x.jpg" style="height:40px;width:40px">
  <img name="image3" src=" https://twimg0-a.akamaihd.net/a/1350072692/t1/img/front_page/jp-mountain@2x.jpg" style="height:50px;width:50px">
</div>


问:
2D decision variables in PuLP
I am new to PuLP, and I am trying to run an optimization problem where one of my decision variables is 2D. I'm a little confused as to how one can declare 2D decision variables as part of plp.LpVariable? As of now, this is how I am declaring the variable

```<code>a = { k : plp.LpVariable(name='a', lowBound=np.array([0, 0]), \
                         upBound=np.array([2, 3]), \
                         cat=plp.LpContinuous) for k in range(10)}
</code>```

Thanks!

答:
What you are looking for is the dicts method of the LpVariable class. This allows you to pass in multi-dimensional indexes to create an M x N, or M x N x O (etc.) set of variables.

Its use is illustrated in the pulp docs example of solving a sudoku puzzle: https://coin-or.github.io/pulp/CaseStudies/a_sudoku_problem.html?highlight=dicts

And the method itself is documented here:
https://coin-or.github.io/pulp/technical/pulp.html?highlight=dicts#pulp.LpVariable.dicts

As far as I know the method cannot directly accept upperbounds and lowerbounds which are different for each variable, so you'd need to do something like:

```<code>up_bounds = [2,3]
a = pulp.LpVariable.dicts('a', range(2), lowBound=0)
for i in range(2):
    prob += a[i] <= up_bounds[i]
</code>```

Title: 2D decision variables in PuLP

Body:
I am new to PuLP, and I am trying to run an optimization problem where one of my decision variables is 2D. I'm a little confused as to how one can declare 2D decision variables as part of plp.LpVariable? As of now, this is how I am declaring the variable

a = { k : plp.LpVariable(name='a', lowBound=np.array([0, 0]), \
                         upBound=np.array([2, 3]), \
                         cat=plp.LpContinuous) for k in range(10)}

Thanks!

Body:
What you are looking for is the dicts method of the LpVariable class. This allows you to pass in multi-dimensional indexes to create an M x N, or M x N x O (etc.) set of variables.

Its use is illustrated in the pulp docs example of solving a sudoku puzzle: https://coin-or.github.io/pulp/CaseStudies/a_sudoku_problem.html?highlight=dicts

And the method itself is documented here:
https://coin-or.github.io/pulp/technical/pulp.html?highlight=dicts#pulp.LpVariable.dicts

As far as I know the method cannot directly accept upperbounds and lowerbounds which are different for each variable, so you'd need to do something like:

up_bounds = [2,3]
a = pulp.LpVariable.dicts('a', range(2), lowBound=0)
for i in range(2):
    prob += a[i] <= up_bounds[i]


问:
Session Id's, UUID's and GUID's and just ID's in general
I have an idea. It might be bad, for reasons not known by me, but I would really appreciate your feedback on this!

We've been using Session ID's in a PHP project. And for the first time in 4 years, a duplicate sessionid was generated. Luckily enough I randomly decided to go looking through the Customers Table because I was bored and noticed there was a duplicate entry in the sessionid column and changed it, and references to it, before any real problems occured.

Which led (or lead?) me to ask myself this question:

Basically, any type of ID, be it a session id, uuid or guid can eventually be duplicated because the length of them is not infinite. So then I got thinking, because we never want this to happen again.

I thought, What if we use a combination of date and time, as an identifier? This wouldn't be "random", but it would solve the duplication issue. For example:

```<code>14th of May 2011 04:36:05PM
</code>```

If used as an identifier, could be changed to:

```<code>14052011163605
</code>```

The reason this form of ID will never become duplicated is because no date, combined with time in the future will ever be the same as one in the past, or present.

And since, in our case, these ID's are not meant to be seen by anybody, there's no reason for it to be random, is there?

I'd love to hear your thoughts on this, and, how you approach situations like this. What's your best method of generating [practically] unique ID'S?

答:
The reason this form of ID will never become duplicated is because no date, combined with time in the future will ever be the same as one in the past, or present.

If you only had one user, this would be true.

Body:
I have an idea. It might be bad, for reasons not known by me, but I would really appreciate your feedback on this!

We've been using Session ID's in a PHP project. And for the first time in 4 years, a duplicate sessionid was generated. Luckily enough I randomly decided to go looking through the Customers Table because I was bored and noticed there was a duplicate entry in the sessionid column and changed it, and references to it, before any real problems occured.

Which led (or lead?) me to ask myself this question:

Basically, any type of ID, be it a session id, uuid or guid can eventually be duplicated because the length of them is not infinite. So then I got thinking, because we never want this to happen again.

I thought, What if we use a combination of date and time, as an identifier? This wouldn't be "random", but it would solve the duplication issue. For example:

14th of May 2011 04:36:05PM

If used as an identifier, could be changed to:

14052011163605

The reason this form of ID will never become duplicated is because no date, combined with time in the future will ever be the same as one in the past, or present.

And since, in our case, these ID's are not meant to be seen by anybody, there's no reason for it to be random, is there?

I'd love to hear your thoughts on this, and, how you approach situations like this. What's your best method of generating [practically] unique ID'S?


问:
Working with struct data type using pysprak
I am planning to handle struct data type in pyspark, which accounts map data type in dynamodb. Since i am planning to perform transformations in dynamodb table which has a map attribute i want to achieve the same using pyspark.
I want to handle health attribute in this case.</p>

```<code>{
  "file_name": "employeesalarydata",
  "folder_name": "doc_consumption_employeesalarydata",
  "Health": {
    "New version - Veracity unavailable": "A new dataset is available but IDQ rules are not generated yet"
  },
  "last_modified_date": "2020-05-13T10:10:37.519Z",
  "resource_id": "6df1e646-a16d-11ea-a60e-d43b04339964"
}
</code>```

答:
I think https://spark.apache.org/docs/latest/api/python/pyspark.sql.html#pyspark.sql.functions.get_json_object should help you to get object.

Example:

```<code>import pyspark.sql.functions as f

spark.table('schema.table')\
.select(f.get_json_object('column_name', '$.Health').alias('health'))\
.show()
</code>```

Body:
I am planning to handle struct data type in pyspark, which accounts map data type in dynamodb. Since i am planning to perform transformations in dynamodb table which has a map attribute i want to achieve the same using pyspark.
I want to handle health attribute in this case.

{
  "file_name": "employeesalarydata",
  "folder_name": "doc_consumption_employeesalarydata",
  "Health": {
    "New version - Veracity unavailable": "A new dataset is available but IDQ rules are not generated yet"
  },
  "last_modified_date": "2020-05-13T10:10:37.519Z",
  "resource_id": "6df1e646-a16d-11ea-a60e-d43b04339964"
}

Body:
I think https://spark.apache.org/docs/latest/api/python/pyspark.sql.html#pyspark.sql.functions.get_json_object should help you to get object.

Example:

import pyspark.sql.functions as f

spark.table('schema.table')\
.select(f.get_json_object('column_name', '$.Health').alias('health'))\
.show()


问:
Inheriting from linked classes
This question is about OOP in any statically typed language.  Suppose I have two classes whose instances maintain pointers/references to each other.  In my case, one class is a container, and the other a wrapper around a contained object which maintains a pointer to the container in which it lives.

```<code>class Container {
  Element[] elements;
}
class Element {
  // ... data...
  Container holds_me;
}
</code>```

The constructor of Container creates an Element object to wrap each contained object, and sets their holds_me pointers to itself.

Now I want to inherit from these classes.  I want a DerivedContainer class, which inherits from Container and contains DerivedElement objects, where DerivedElement inherits from Element and refers to the containing DerivedContainer object.  What is the right way to do this (or is it the wrong thing to do)?

The most straightforward thing is for the constructor of DerivedContainer to create DerivedElements and store them in elements and set their holds_me pointer to itself.  Then all the methods of Container and Element will work, but any new methods defined in DerivedContainer and DerivedElement will have to downcast the objects held in elements and holds_me in order to invoke any new methods on them that weren't defined in the base classes.  This doesn't seem pretty; so I wonder, is there a better solution?

答:
Yep, this is the right way to do it, without any more information, IMHO. It makes sense if you think that all of the methods in Element can apply to every Element, but the only classes that should know anything about the Derived set of functionality are (ideally only) DerivedElement and (if necessary) DerivedContainer. In other words, to anyone else, Elements and Containers are only Elements and Containers.

You can sometimes do a little better with templates(C++) or generics(Java), since the thought behind these features is that a Container<Element> knows that it holds Elements and a Container<DerivedElement> knows that it holds DerivedElements, but if you have a heterogeneous Container, you really have to have each subclass handle the derived functionality by trying to downcast.

Title: Inheriting from linked classes

Body:
This question is about OOP in any statically typed language.  Suppose I have two classes whose instances maintain pointers/references to each other.  In my case, one class is a container, and the other a wrapper around a contained object which maintains a pointer to the container in which it lives.

class Container {
  Element[] elements;
}
class Element {
  // ... data...
  Container holds_me;
}

The constructor of Container creates an Element object to wrap each contained object, and sets their holds_me pointers to itself.

Now I want to inherit from these classes.  I want a DerivedContainer class, which inherits from Container and contains DerivedElement objects, where DerivedElement inherits from Element and refers to the containing DerivedContainer object.  What is the right way to do this (or is it the wrong thing to do)?

The most straightforward thing is for the constructor of DerivedContainer to create DerivedElements and store them in elements and set their holds_me pointer to itself.  Then all the methods of Container and Element will work, but any new methods defined in DerivedContainer and DerivedElement will have to downcast the objects held in elements and holds_me in order to invoke any new methods on them that weren't defined in the base classes.  This doesn't seem pretty; so I wonder, is there a better solution?


问:
Sending email through powershell issue
When i try to send email through powershell im facing following issues
1.Im not able to change the sender as group mailbox
2.it does not read the attachments i add but the mail gets sent.

code im using :

```<code>    $Outlook = New-Object -ComObject Outlook.Application
    $Mail = $Outlook.CreateItem(0)
    $Mail.To = "xyz@outlook.com"
    $Mail.Subject = "sql"
    $mail.attachments = 'C:\Users\desktop.ini'
    $Mail.Body = ""
    $Mail.Send()
</code>```

error i'm receiving :

```<code>     Property is read-only.
     At C:\Users\Documents\sending email.ps1:5 char:1
     + $mail.attachments = 'C:\Users\desktop.ini'
     + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     + CategoryInfo          : OperationStopped: (:) [], COMException
     + FullyQualifiedErrorId : System.Runtime.InteropServices.COMException
</code>```

But the file is in my local

答:
You are missing an additional parameter

Your script should look something like this:

```<code>$attachment = "C:\Users\YourUser\Documents\test.txt"
$mail.attachments.add($attachment)
</code>```

or, if not with a variable

```<code>$mail.attachments.add("C:\Users\YourUser\Documents\test.txt")
</code>```

As for the group mailbox, the mailbox should be controllable by using

```<code>$mail.sendusingaccount = "mailbox@company.com"
</code>```

As for adding multiple attachments, you will have to have them in one directory:

```<code>$getfiles = Get-ChildItem "C:\Users\YourUser\Attachmentfolder\"
Foreach ($getfile in $getfiles) {
$mail.attachments.add($getfile.FullName)
}
</code>```

Title: Sending email through powershell issue

Body:
When i try to send email through powershell im facing following issues
1.Im not able to change the sender as group mailbox
2.it does not read the attachments i add but the mail gets sent.

code im using :

    $Outlook = New-Object -ComObject Outlook.Application
    $Mail = $Outlook.CreateItem(0)
    $Mail.To = "xyz@outlook.com"
    $Mail.Subject = "sql"
    $mail.attachments = 'C:\Users\desktop.ini'
    $Mail.Body = ""
    $Mail.Send()

error i'm receiving :

     Property is read-only.
     At C:\Users\Documents\sending email.ps1:5 char:1
     + $mail.attachments = 'C:\Users\desktop.ini'
     + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     + CategoryInfo          : OperationStopped: (:) [], COMException
     + FullyQualifiedErrorId : System.Runtime.InteropServices.COMException

But the file is in my local

Body:
You are missing an additional parameter

Your script should look something like this:

$attachment = "C:\Users\YourUser\Documents\test.txt"
$mail.attachments.add($attachment)

or, if not with a variable

$mail.attachments.add("C:\Users\YourUser\Documents\test.txt")

As for the group mailbox, the mailbox should be controllable by using

$mail.sendusingaccount = "mailbox@company.com"

As for adding multiple attachments, you will have to have them in one directory:

$getfiles = Get-ChildItem "C:\Users\YourUser\Attachmentfolder\"
Foreach ($getfile in $getfiles) {
$mail.attachments.add($getfile.FullName)
}


问:
How to convert JSON Object into key value pair in JS?
```<code>{"1":"val1","2":"val2","3":"val3"}
</code>```

i want it to converted like this:

```<code>{"Id":"1","value":"val1","Id":"2","value":"val2","Id":"3","value":"val3"}
</code>```

little Help Please would be much appricated

答:
You can't use the same key name in one object.

instead you can do this.

const origin = {"1":"val1","2":"val2","3":"val3"}

const converted = Object.entries(origin).map( ([key,value]) => ({id: key, value }) );
console.log(converted);```

Body:
{"1":"val1","2":"val2","3":"val3"}

i want it to converted like this:

{"Id":"1","value":"val1","Id":"2","value":"val2","Id":"3","value":"val3"}

little Help Please would be much appricated


问:
CMake is throwing an error while Installing OpenCV
I am using this document as a guide
and i ran through this error </p>

```<code>Install the project...
-- Install configuration: "RELEASE"
CMake Error at cmake_install.cmake:36 (file):
  file cannot create directory: /installation/OpenCV-/share/licenses/opencv4.
  Maybe need administrative privileges.
</code>```

答:
I just encountered the same problem as you. I found out that it is not a permission problem, but a path problem of OpenCV installation.

I use the following method for successfully installing OpenCV4.2.0 to my computer.

Change the path:

-D CMAKE_INSTALL_PREFIX = $cwd/installation/OpenCV-4.2.0

To

-D CMAKE_INSTALL_PREFIX = /usr/local

Body:
I am using this document as a guide
and i ran through this error

Install the project...
-- Install configuration: "RELEASE"
CMake Error at cmake_install.cmake:36 (file):
  file cannot create directory: /installation/OpenCV-/share/licenses/opencv4.
  Maybe need administrative privileges.


答:
What you have posted is invalid.

What you might want is:

const object = {"1":"val1","2":"val2","3":"val3"};

console.log(Object.entries(object));

// or

console.log(Object.keys(object).map(i => ({Id: i, value: object[i]})));```

Title: How to convert JSON Object into key value pair in JS?


问:
Script for automating online tool query
So I had a number of amino acid sequence strings that I wanted to use as input into a tool that studies its interactions with certain components of the human immune system (http://www.cbs.dtu.dk/services/NetMHCcons/).

I wanted to ask what, if any, would be a way of accessing, inputting data and getting the output, via a script (R or python preferably). My main issue was I had a lot of sequences that need to be queried separately so wanted to automate the whole thing. The website has one field that reads "Submission" which takes in the string input. There is another field "select species/loci" which gives a drop down menu from which an option needs to be selected. Lastly there's a "submit" button. The output simply loads on the page after hitting submit.

I've tentatively poked around with RSelenium and Rcurl but wanted to ask if there was a more efficient method.

答:
I took a look at what it'd take to send a POST request to this service from Python, and it looks possible:

this form takes in "multipart/form-data" (see: How to send a "multipart/form-data" with requests in python?), you'll need to send your data in this format. You could inspect a request from the browser (using the dev tools) and copy the fields from there as a starting point.

once the form is submitted, it doesn't give you the result right away. You'd need to get your job ID from the response, and then poll the URL: http://www.cbs.dtu.dk/cgi-bin/webface2.fcgi?jobid={your_job_id}&wait=20 until it gives you the result

the result will then need to be downloaded and parsed

This tool is however available as a portable version for linux/mac: https://services.healthtech.dtu.dk/software.php

Perhaps downloading this version would make it easier?

Title: Script for automating online tool query


问:
Creating a project to be reused
I'm sure you can help such a newbie like I am.
I created a project in android and I want to use it as a model for next 10 and more apps, just changing the raw sources.
I mean I want to make some products i.e. 10 videocharts about norway, I make one project with the needed activity and resources so each app will differ only for the content value.
I will keep of course the same file name too if needed.
How can I save the project?
Cause I tried to make a new project from resource but I get an error on top of the tab saying Manifest is not present in the folder while manifest is actually there, and I cannot proceed further.

Thank you
ANgelo

答: This sounds like a place to use an Android library project.</p>

Title: Creating a project to be reused


问:
No permission error in Firebase Cloud Function
I want to implement a Slack authentication with Passport.js + Firebase Cloud Function. But when I redirected URL, the forbidden error occurs.

The error:

Your client does not have permission to get URL /api/auth/slack?uid=XXXXXXXXXXX&redirectTo=http://localhost:3000 from this server.

The React code:

```<code>const slackAuthorizeURL = (uid) =>
  `https://us-central1-xxxxxxxxx.cloudfunctions.net/api/auth/slack?uid=${uid}&redirectTo=${window.location.href}`

<a href={slackAuthorizeURL}>Sign in with Slack</a>
</code>```

The Server code:

```<code>const express = require('express')
const session = require('express-session')
const app = express()
const allowedOrigins = [
  'http://localhost:3000',
]
const allowCrossDomain = (req, res, next) => {
  const origin = req.headers.origin
  if (allowedOrigins.includes(origin)) {
    res.header('Access-Control-Allow-Origin', origin)
  }
  res.header('Access-Control-Allow-Methods', 'GET,POST')
  res.header('Access-Control-Allow-Headers', 'Content-Type')
  next()
}
app.use(allowCrossDomain)

app.use(session({ secret: config.session.secret }))

const passport = require('passport')

app.use(passport.initialize())
app.use(passport.session())
app.get('/auth/slack', (req, res, next) => {
  req.session.uid = req.query.uid
  req.session.redirectTo = req.query.redirectTo
  passport.authenticate('slack')(req, res, next)
})
</code>```

I have already set up allUsers to Cloud Functions Admin on api in Google Cloud Platform.

答:
I missed to set up allUsers to Cloud Functions Admin on api in Google Cloud Platform correctly.

https://cloud.google.com/functions/docs/securing/managing-access#allowing_unauthenticated_function_invocation

Body:
I want to implement a Slack authentication with Passport.js + Firebase Cloud Function. But when I redirected URL, the forbidden error occurs.

The error:

Your client does not have permission to get URL /api/auth/slack?uid=XXXXXXXXXXX&redirectTo=http://localhost:3000 from this server.

The React code:

const slackAuthorizeURL = (uid) =>
  `https://us-central1-xxxxxxxxx.cloudfunctions.net/api/auth/slack?uid=${uid}&redirectTo=${window.location.href}`

Sign in with Slack

The Server code:

const express = require('express')
const session = require('express-session')
const app = express()
const allowedOrigins = [
  'http://localhost:3000',
]
const allowCrossDomain = (req, res, next) => {
  const origin = req.headers.origin
  if (allowedOrigins.includes(origin)) {
    res.header('Access-Control-Allow-Origin', origin)
  }
  res.header('Access-Control-Allow-Methods', 'GET,POST')
  res.header('Access-Control-Allow-Headers', 'Content-Type')
  next()
}
app.use(allowCrossDomain)

app.use(session({ secret: config.session.secret }))

const passport = require('passport')

app.use(passport.initialize())
app.use(passport.session())
app.get('/auth/slack', (req, res, next) => {
  req.session.uid = req.query.uid
  req.session.redirectTo = req.query.redirectTo
  passport.authenticate('slack')(req, res, next)
})

I have already set up allUsers to Cloud Functions Admin on api in Google Cloud Platform.


问:
How to open shared folder on local network Win10
I have an address for the shared folder in network:

\\SOMEUSER\folder

How can I open that folder?

答:
Following latest update to win10 version 2004, I had a difficulty to re-connect to shared computers that use insecure guest logons.

Initial I tried to enable insecure guest logons through Administrative tools.

Computer Configuration -> Administrative Templates -> Network -> Lanman workstation

and set Enable insecure guest logon to enable

It appears this does not change the registry. You actually have to set this in the registry directly.

regedit

Computer\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\LanmanWorkstation\Parameters

and set AllowInsecureGuestAuth to 1.

et voila I got my access to shared computer working again.


问:
react + mobx example Attempted import error: 'useObservable' is not exported from 'mobx-react-lite'
please suggest the solution. the error which is shown on browser is

Failed to compile
./src/App.js
Attempted import error: 'useObservable' is not exported from 'mobx-react-lite'.

```<code>import React from 'react';
import './App.css';
import {observer, useObservable} from 'mobx-react-lite';

const App = observer(() => {

const store = useObservable({
    count:1,
addOne(){
  store.count++;
},
subOne(){
  store.count--;
}
})

function addOneHandle(){
store.addOne();
}
function subOneHandle(){
store.subOne();
}

return (
 <div className="App">
  <header className="App-header">
   <h1>Count: {store.count}</h1>
   <button onClick={addOneHandle}>Add 1</button>
   <button onClick={subOneHandle}>Sub 1</button>
  </header>
</div>
 );
 })

 export default App;
</code>```

答: import { useObservable } from 'mobx-react-better-use-observable'</p>

Body:
please suggest the solution. the error which is shown on browser is

Failed to compile
./src/App.js
Attempted import error: 'useObservable' is not exported from 'mobx-react-lite'.

import React from 'react';
import './App.css';
import {observer, useObservable} from 'mobx-react-lite';

const App = observer(() => {

const store = useObservable({
    count:1,
addOne(){
  store.count++;
},
subOne(){
  store.count--;
}
})

function addOneHandle(){
store.addOne();
}
function subOneHandle(){
store.subOne();
}

return (

Count: {store.count}

   <button onClick={addOneHandle}>Add 1</button>
   <button onClick={subOneHandle}>Sub 1</button>

 );
 })

 export default App;


问:
Save DateTimePicker value
How can I fix this error? I can't save this value:

private void button1_Click(object sender, EventArgs e)
{
    string rut = textRut.Text;
    string nombres = textNombres.Text;
    string paterno = textPaterno.Text;
    string materno = textMaterno.Text;
    DateTimePicker nacimiento = dateTimePicker1;
    DateTimePicker muerte = dateTimePicker2;
    string causa = causaText.Text;
    int cliente = int.Parse(comboCliente.Text);
    int enterrador = int.Parse(comboEnterrador.Text);
    int derecho = int.Parse(comboDerecho.Text);

    difuntoTableAdapter1.AgregarDifunto(rut, nombres, paterno, materno, nacimiento, muerte, causa, enterrador, cliente, derecho);
    this.difuntoTableAdapter1.FillBy(this.cementerioDataSet1.difunto);
}
```

The type of both nacimiento and muerte in DB is date. How can I save that type of data in DB from DateTimePicker?

答:
this is the correct type...

```<code>    DateTime nacimiento = dateTimePicker1.Value;
    DateTime muerte = dateTimePicker2.Value;
</code>```

and edit the file cementerioDataSetDesigner, AgregarDifunto Method.

Title: Save DateTimePicker value

Body:
How can I fix this error? I can't save this value:

private void button1_Click(object sender, EventArgs e)
{
    string rut = textRut.Text;
    string nombres = textNombres.Text;
    string paterno = textPaterno.Text;
    string materno = textMaterno.Text;
    DateTimePicker nacimiento = dateTimePicker1;
    DateTimePicker muerte = dateTimePicker2;
    string causa = causaText.Text;
    int cliente = int.Parse(comboCliente.Text);
    int enterrador = int.Parse(comboEnterrador.Text);
    int derecho = int.Parse(comboDerecho.Text);

    difuntoTableAdapter1.AgregarDifunto(rut, nombres, paterno, materno, nacimiento, muerte, causa, enterrador, cliente, derecho);
    this.difuntoTableAdapter1.FillBy(this.cementerioDataSet1.difunto);
}

The type of both nacimiento and muerte in DB is date. How can I save that type of data in DB from DateTimePicker?

Body:
this is the correct type...

    DateTime nacimiento = dateTimePicker1.Value;
    DateTime muerte = dateTimePicker2.Value;

and edit the file cementerioDataSetDesigner, AgregarDifunto Method.


问:
Flutter Dismissible causing unnecesary redraw when pushed navigated on top
I'm making an app with Flutter, and I found a weird behaviour that I got to reproduce in a small demo: https://pastebin.com/ZJd2fnHK

The objective is to have a TextField that when in focus should select the whole text. I achieved this with a FocusNode.

Everything was working fine, until I set a Dismissible widget to remove items from a list. For some reason (probably drawing ones) the whole page has a rebuild and the focusnode state is lost.

It's very interesting since the issue only happens when the widget is within a page that has being pushed by the navigator. The same Widget works fine in the root Page.

The Widget is the following:

```<code>Widget build(BuildContext context) {
    textControllerA.text = "Hello";
    textControllerB.text = "World";
    return Column(children: [
      Dismissible(
        key: Key("potatoes"),
        onDismissed: (direction) {},
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Padding(
              child: TextField(
                focusNode: focusNodeA,
                controller: textControllerA,
              ),
              padding: EdgeInsets.all(20),
            ),
          ],
        ),
      ),
      Padding(
        child: TextField(
          focusNode: focusNodeB,
          controller: textControllerB,
        ),
        padding: EdgeInsets.all(20),
      ),
    ]);
  }
</code>```

Maybe I should try to store the focus' state in state, but that'd have some overhead. Or maybe (possibly) I'm doing something very wrong, in which case I would love to have some guidance.

Cheers

答:
You should use StatefulWidget and call setState

```<code> onDismissed: (direccion) {
      setState(() {
          ...
      });
</code>```

Body:
I'm making an app with Flutter, and I found a weird behaviour that I got to reproduce in a small demo: https://pastebin.com/ZJd2fnHK

The objective is to have a TextField that when in focus should select the whole text. I achieved this with a FocusNode.

Everything was working fine, until I set a Dismissible widget to remove items from a list. For some reason (probably drawing ones) the whole page has a rebuild and the focusnode state is lost.

It's very interesting since the issue only happens when the widget is within a page that has being pushed by the navigator. The same Widget works fine in the root Page.

The Widget is the following:

Widget build(BuildContext context) {
    textControllerA.text = "Hello";
    textControllerB.text = "World";
    return Column(children: [
      Dismissible(
        key: Key("potatoes"),
        onDismissed: (direction) {},
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Padding(
              child: TextField(
                focusNode: focusNodeA,
                controller: textControllerA,
              ),
              padding: EdgeInsets.all(20),
            ),
          ],
        ),
      ),
      Padding(
        child: TextField(
          focusNode: focusNodeB,
          controller: textControllerB,
        ),
        padding: EdgeInsets.all(20),
      ),
    ]);
  }

Maybe I should try to store the focus' state in state, but that'd have some overhead. Or maybe (possibly) I'm doing something very wrong, in which case I would love to have some guidance.

Cheers

Body:
You should use StatefulWidget and call setState

 onDismissed: (direccion) {
      setState(() {
          ...
      });


问:
typecast to int in postgres
I am trying to query a table which a json column

```<code>select *
from subscription
where extras->>'end_date' > 1592424632;
</code>```

this errors out saying

ERROR:  invalid input syntax for integer: "end_date"

I have tried type casting

```<code>select *
from subscription
where extras->>'end_date'::int4 > 1592424632;
</code>```

ERROR:  invalid input syntax for integer: "end_date"

and extras column sample input looks like

```<code>{"end_date": 1592425146, "capacity": 1, "start_date": 1584562746, "devices": "", "quantity": 10}
</code>```

答:
You need parentheses. The cast operator :: has a higher precedence than the -> operator. So extras->>'end_date'::int4 is parsed as extras->> ('end_date'::int4) which is the reason for the error.

```<code>select *
from subscription
where (extras->>'end_date')::int4 > 1592424632
</code>```

Title: typecast to int in postgres

Body:
I am trying to query a table which a json column

select *
from subscription
where extras->>'end_date' > 1592424632;

this errors out saying

ERROR:  invalid input syntax for integer: "end_date"

I have tried type casting

select *
from subscription
where extras->>'end_date'::int4 > 1592424632;

ERROR:  invalid input syntax for integer: "end_date"

and extras column sample input looks like

{"end_date": 1592425146, "capacity": 1, "start_date": 1584562746, "devices": "", "quantity": 10}

Body:
You need parentheses. The cast operator :: has a higher precedence than the -> operator. So extras->>'end_date'::int4 is parsed as extras->> ('end_date'::int4) which is the reason for the error.

select *
from subscription
where (extras->>'end_date')::int4 > 1592424632


问:
is there a way to defined two path in JBehave story
I'm have a story where I need to supply the JSON config file path and a tool path and pass these two paths to the python script?

when I try to add a second path next to tool path it uses all the string after the path as path :/
is there a way how to supply two paths in 'Given'?

story looks like

```<code>Scenario: Verify Certificate and Cipher misconfiguration

Given TestSSL tool  path 'C:\Users\Desktop\SSLTLS\testssl.sh-3.0'
Then Certificate and Cipher check should return 0 for successful security-check
</code>```

java code

```<code>@Given("TestSSL tool  path '$path'")
public void get_TestSSL_path(@Named("path") String path)
{
    try
    {
        Paths.get(path);
        toolPath = path;
    }
    catch (InvalidPathException | NullPointerException ex)
    {
    }
}

@Then("Certificate and Cipher check  should return 0 for successful security-check")
public void verify_cipher_and_certificate_attributes() throws IOException, InterruptedException
{
    String pythonFileName = "./scripts/python/security_misconfiguration_SSL_TLS.py";
    String fullcmdCommand = jsonpath + " " + toolPath ;
    System.out.println("Full path : " +fullcmdCommand);
    int script_result = Utilities.runPythonScript(pythonFileName, fullcmdCommand);
    Assert.assertEquals(0, script_result);
}
</code>```

答:
You should change the step input parameter to Collection, for example:

@Given("TestSSL tool paths '$paths'")
public void get_TestSSL_path(@Named("paths") List<String> paths)
...

```

<ol start="2">
<li>Separate input data using comma, for example:</li>
</ol>

<pre class="lang-gherkin prettyprint-override"><code>Given TestSSL tool paths 'C:\Users\Desktop\SSLTLS\testssl.sh-3.0, C:\Users\Desktop\SSLTLS\testssl.sh-4.0'
</code>```

Body:
I'm have a story where I need to supply the JSON config file path and a tool path and pass these two paths to the python script?

when I try to add a second path next to tool path it uses all the string after the path as path :/
is there a way how to supply two paths in 'Given'?

story looks like

Scenario: Verify Certificate and Cipher misconfiguration

Given TestSSL tool  path 'C:\Users\Desktop\SSLTLS\testssl.sh-3.0'
Then Certificate and Cipher check should return 0 for successful security-check

java code

@Given("TestSSL tool  path '$path'")
public void get_TestSSL_path(@Named("path") String path)
{
    try
    {
        Paths.get(path);
        toolPath = path;
    }
    catch (InvalidPathException | NullPointerException ex)
    {
    }
}

@Then("Certificate and Cipher check  should return 0 for successful security-check")
public void verify_cipher_and_certificate_attributes() throws IOException, InterruptedException
{
    String pythonFileName = "./scripts/python/security_misconfiguration_SSL_TLS.py";
    String fullcmdCommand = jsonpath + " " + toolPath ;
    System.out.println("Full path : " +fullcmdCommand);
    int script_result = Utilities.runPythonScript(pythonFileName, fullcmdCommand);
    Assert.assertEquals(0, script_result);
}

Body:
You should change the step input parameter to Collection, for example:

@Given("TestSSL tool paths '$paths'")
public void get_TestSSL_path(@Named("paths") List<String> paths)
...

Separate input data using comma, for example:

Given TestSSL tool paths 'C:\Users\Desktop\SSLTLS\testssl.sh-3.0, C:\Users\Desktop\SSLTLS\testssl.sh-4.0'


问:
Firestore won't write documents if placed at bottom while returning multiple promises
Firestore won't create documents if placed the return statement like this:

```<code>return Promise.all([
  res.status(200).send({
    method: 'sendMessage',
    chat_id,
    text: `${field1Val}`,
    parse_mode: 'HTML'
  }),
  admin.firestore().collection('colName').doc(`docName`).set({ "field1": field1Val }, { merge: true })
])
</code>```

Though the below code will create the Doc:

```<code>return Promise.all([
  admin.firestore().collection('colName').doc(`docName`).set({ "field1": field1Val }, { merge: true }),
  res.status(200).send({
    method: 'sendMessage',
    chat_id,
    text: `${field1Val}`,
    parse_mode: 'HTML'
  })
])
</code>```

I use the first format with realtime database and it works perfectly.
I don't know why Firestore wants the privilege of being at top.

I have waited for 15+ mins and refreshed the page still no sign of the document.

PS: I had re-initialized the project and installed new npm modules too. Didn't help XD

The complete code which I don't think is a problem cause the doc is created if I placed that command at top.

```<code>import * as functions from 'firebase-functions';
import * as express from 'express'
import * as cors from 'cors'
import admin = require('firebase-admin');
admin.initializeApp();

const bot = express()

bot.use(cors({ origin: true }))

bot.post('/', async (req, res) => {

const commandSliced: string = JSON.stringify(req.body.message.text)

  let userMsg: string = ''

  if (commandSliced.startsWith(`!text`)) {
    userMsg = userCommandSliced.replace('!text', '')
    let exclmCmd_array: string[];
    msg_array = userEMsg.split(/\b\s+/, 2)

    const field1val= userMsg.replace(msg_array[0], '')

  return Promise.all([
    res.status(200).send({
      method: 'sendMessage',
      chat_id,
      text: `${field1val}`,
      parse_mode: 'HTML'
    }),
    admin.firestore().collection('colName').doc(`docName`).set({ "field1": field1Val }, { merge: true })
  ])

})
</code>```

EDIT: This worked as suggested by Doug.

```<code>return admin.firestore().collection('colName').doc(`docName`).set({ "field1": field1Val }, { merge: true }).then(() => {
  return res.status(200).send({
    method: 'sendMessage',
    chat_id,
    text: `${field1Val}`,
    parse_mode: 'HTML'
   })
 })
</code>```

答:
The issues are that:

res.status(200).send() doesn't return a promise, so it doesn't make sense to pass its value to Promise.all().

res.status(200).send() also terminates the function immediately, which means that after it executes, you shouldn't expect other asynchronous code (like your Firestore update) to work at all.

What you should do instead is wait until the Firestore update completes (by using the promise it returns), then send the response as the very last thing in the function.

Body:
Firestore won't create documents if placed the return statement like this:

return Promise.all([
  res.status(200).send({
    method: 'sendMessage',
    chat_id,
    text: `${field1Val}`,
    parse_mode: 'HTML'
  }),
  admin.firestore().collection('colName').doc(`docName`).set({ "field1": field1Val }, { merge: true })
])

Though the below code will create the Doc:

return Promise.all([
  admin.firestore().collection('colName').doc(`docName`).set({ "field1": field1Val }, { merge: true }),
  res.status(200).send({
    method: 'sendMessage',
    chat_id,
    text: `${field1Val}`,
    parse_mode: 'HTML'
  })
])

I use the first format with realtime database and it works perfectly.
I don't know why Firestore wants the privilege of being at top.

I have waited for 15+ mins and refreshed the page still no sign of the document.

PS: I had re-initialized the project and installed new npm modules too. Didn't help XD

The complete code which I don't think is a problem cause the doc is created if I placed that command at top.

import * as functions from 'firebase-functions';
import * as express from 'express'
import * as cors from 'cors'
import admin = require('firebase-admin');
admin.initializeApp();

const bot = express()

bot.use(cors({ origin: true }))

bot.post('/', async (req, res) => {

const commandSliced: string = JSON.stringify(req.body.message.text)

  let userMsg: string = ''

  if (commandSliced.startsWith(`!text`)) {
    userMsg = userCommandSliced.replace('!text', '')
    let exclmCmd_array: string[];
    msg_array = userEMsg.split(/\b\s+/, 2)

    const field1val= userMsg.replace(msg_array[0], '')

  return Promise.all([
    res.status(200).send({
      method: 'sendMessage',
      chat_id,
      text: `${field1val}`,
      parse_mode: 'HTML'
    }),
    admin.firestore().collection('colName').doc(`docName`).set({ "field1": field1Val }, { merge: true })
  ])

})

EDIT: This worked as suggested by Doug.

return admin.firestore().collection('colName').doc(`docName`).set({ "field1": field1Val }, { merge: true }).then(() => {
  return res.status(200).send({
    method: 'sendMessage',
    chat_id,
    text: `${field1Val}`,
    parse_mode: 'HTML'
   })
 })


问:
Getting error MSB406 "TypeScript.Tasks.CheckFileSystemCaseSensitive" in Windows Powershell but the same build works in VS Powershell
While trying to build a newly setup project using npm run build, I am facing the below mentioned error in Powershell on Windows, however, it runs fine inside the Visual Studio integrated Powershell.

Error:

C:..\src\packages\Microsoft.Portal.Tools.5.0.303.3330\build\TypeScript\tools\Microsoft.TypeScript.targets(219,5): error MSB406 2: The "TypeScript.Tasks.CheckFileSystemCaseSensitive" task could not be loaded from the assembly C:..\src\packages\Microsoft.Portal.Tools.5.0.303.3330\build\TypeScript\build..\tools\net45\TypeScript.Tasks.dll. Could not load file or assembly 'Microsoft.Build.Utilities.Core, Version=14.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified. Confirm that the  declaration is correct, that the assembly and all its dependencies are available, and that the task contains a public class that implements Microsoft.Build.Framework.ITask[C:..\src\Default\Extension\Extension.csproj]

答:
When you are running it from VS integrated PowerShell it uses correct version of MSBuild but may not find latest one when running from Windows PowerShell.

If you want to use the Latest available MSBuild on any machine; Visual Studio(VS2017 and above) comes with utility called vswhere which can be used to find out latest MSBuild version

You can manually update the PATH in environment variable or write a PS script to find the latest MSBuild version using below code snippet

```<code>$vsWherePath = ${Env:ProgramFiles(x86)} + '\Microsoft Visual Studio\Installer\vswhere.exe'
$detectedMSBuildPath = & $vsWherePath -latest -requires Microsoft.Component.MSBuild -find MSBuild\**\Bin\MSBuild.exe;

Write-Host $detectedMSBuildPath
& $detectedMSBuildPath -version #Command to execute msbuild
</code>```

This way, even if your MSBuild version is updated; it will always find and use latest MSBuild on machine.

Body:
When you are running it from VS integrated PowerShell it uses correct version of MSBuild but may not find latest one when running from Windows PowerShell.

If you want to use the Latest available MSBuild on any machine; Visual Studio(VS2017 and above) comes with utility called vswhere which can be used to find out latest MSBuild version

You can manually update the PATH in environment variable or write a PS script to find the latest MSBuild version using below code snippet

$vsWherePath = ${Env:ProgramFiles(x86)} + '\Microsoft Visual Studio\Installer\vswhere.exe'
$detectedMSBuildPath = & $vsWherePath -latest -requires Microsoft.Component.MSBuild -find MSBuild\**\Bin\MSBuild.exe;

Write-Host $detectedMSBuildPath
& $detectedMSBuildPath -version #Command to execute msbuild

This way, even if your MSBuild version is updated; it will always find and use latest MSBuild on machine.


问:
NotFound() doesn't seem to work as expected
I'm new to ASP.NET core, so I hope you bear with me on this one. This is similar to this unanswered question.

When I'm testing a brand new C# MVC project, and I enter a wrong URL, there's no info. Just a blank page.

To solve this, I have adapted startup.cs adding a UseStatusCodePagesWithReExecute() to return a static 404.html page. This works.

So far, so good.

Now, I am coding a basic login logic. For testing purposes, I'm calling return NotFound(); when the post parameters are missing. This doesn't return anything. I'm aware that 404 is not the correct response, but I have seen NotFound(); in the generated code and I think that's what's returning blank pages, so I want to solve that before moving on.

The app.UseDeveloperException(); doesn't seem to be called for this. I'm not sure how to test that.

Is there a way to override the NotFound(); behavior to get a 404.html somehow?

This is the Tutorial I have used to set up my project.

Edit:
Based on the comments of Alexander Powolozki, I have replaced NotFound(); with Redirect("~/404.html");. This works.

```<code>// Wherever you want to return your standard 404 page
return Redirect("Home/StatusCode?code=404");

public class HomeController : Controller
{
    // This method allows for other status codes as well
    public IActionResult StatusCode(int? code)
    {
        // This method is invoked by Startup.cs >>> app.UseStatusCodePagesWithReExecute("/Home/StatusCode", "?code={0}");
        if (code.HasValue)
        {
            // here is the trick
            this.HttpContext.Response.StatusCode = code.Value;
        }

        //return a static file.
        try
        {
            return File("~/" + code + ".html", "text/html");
        }
        catch (FileNotFoundException)
        {
            return Redirect("Home/StatusCode?code=404");
        }
    }
}
</code>```

答: The first option with the 404.html is invoked when a request can't be processed because of missed routes to ressources like static content or controllers, in this case the preconfigured 404.html is returned. In the second case a routing was successfull and all the remaining processing is done by the logic e.g. the determined and invoked controller, so it's up to you to redirect to your created 404.html.</p>

Body:
I'm new to ASP.NET core, so I hope you bear with me on this one. This is similar to this unanswered question.

When I'm testing a brand new C# MVC project, and I enter a wrong URL, there's no info. Just a blank page.

To solve this, I have adapted startup.cs adding a UseStatusCodePagesWithReExecute() to return a static 404.html page. This works.

So far, so good.

Now, I am coding a basic login logic. For testing purposes, I'm calling return NotFound(); when the post parameters are missing. This doesn't return anything. I'm aware that 404 is not the correct response, but I have seen NotFound(); in the generated code and I think that's what's returning blank pages, so I want to solve that before moving on.

The app.UseDeveloperException(); doesn't seem to be called for this. I'm not sure how to test that.

Is there a way to override the NotFound(); behavior to get a 404.html somehow?

This is the Tutorial I have used to set up my project.

Edit:
Based on the comments of Alexander Powolozki, I have replaced NotFound(); with Redirect("~/404.html");. This works.

// Wherever you want to return your standard 404 page
return Redirect("Home/StatusCode?code=404");

public class HomeController : Controller
{
    // This method allows for other status codes as well
    public IActionResult StatusCode(int? code)
    {
        // This method is invoked by Startup.cs >>> app.UseStatusCodePagesWithReExecute("/Home/StatusCode", "?code={0}");
        if (code.HasValue)
        {
            // here is the trick
            this.HttpContext.Response.StatusCode = code.Value;
        }

        //return a static file.
        try
        {
            return File("~/" + code + ".html", "text/html");
        }
        catch (FileNotFoundException)
        {
            return Redirect("Home/StatusCode?code=404");
        }
    }
}


答:
You could use a loop over Object.entries.

E.g. something like:

```<code>const newObjArr = [];
for(let [key, value] of Object.entries(obj)){
  newObj.push({Id: key, value});
}
</code>```

The above would return an array of objects, but I'm sure you can amend it to your particular use case.

Body:
You could use a loop over Object.entries.

E.g. something like:

const newObjArr = [];
for(let [key, value] of Object.entries(obj)){
  newObj.push({Id: key, value});
}

The above would return an array of objects, but I'm sure you can amend it to your particular use case.