问:
VSCode: How can I execute an arbitrary task using the JavaScript API?
In newer versions of VSCode I can create bindings to any task I define in tasks.json. For example, with the 3 tasks below

{
  "version": "2.0.0",
  "tasks": [
    {
      "label": "Clean",
      "type": "shell",
      "command": "clean.cmd",
      "problemMatcher": []
    },
    {
      "label": "Build",
      "type": "shell",
      "command": "build.cmd",
      "problemMatcher": [],
      "group": { "kind": "build", "isDefault": true }
    },
    {
      "label": "Flash",
      "type": "shell",
      "command": "flash.cmd",
      "problemMatcher": []
    }
  ]
}
```

<p>I can create key bindings with</p>

<pre class="lang-json prettyprint-override"><code>[
  {
    "key": "alt+f9",
    "command": "workbench.action.tasks.runTask",
    "args": "Clean"
  },
  {
    "key": "ctrl+f9",
    "command": "workbench.action.tasks.build"
  },
  {
    "key": "f9",
    "command": "workbench.action.tasks.runTask",
    "args": "Flash"
  }
]
</code>```

and everything works as expected. I am trying to do the same thing from within an extension (for example with Script Commands) using the VSCode API but it works only for the build and test tasks.

Calling

vscode.commands.executeCommand("workbench.action.tasks.build")
```

<p>works but</p>

<pre class="lang-ts prettyprint-override"><code>vscode.commands.executeCommand("workbench.action.tasks.runTask", ["Clean"])
</code>```

opens the task selection list.

How could I directly start other tasks beyond build and test using JavaScript code?

答:
Your tasks config file looks old. If you're using a new version of Visual Studio Code then you should upgrade.

I think the api is expecting the task to have a "label" field.

https://code.visualstudio.com/docs/editor/tasks#_convert-from-010-to-200

So intsead of:

```<code>{
   "taskName": "Clean",
   "type": "shell",
   "command": "clean.cmd",
   "problemMatcher": []
},
</code>```

It should be:

```<code>{
  "label": "Clean",
  "type": "shell",
  "command": "clean.cmd",
  "problemMatcher": []
},
</code>```

Update: Try invoking it with just the string instead of wrapping it in an Array like this:

```<code>vscode.commands.executeCommand("workbench.action.tasks.runTask", "Clean")
</code>```

Body:
In newer versions of VSCode I can create bindings to any task I define in tasks.json. For example, with the 3 tasks below

{
  "version": "2.0.0",
  "tasks": [
    {
      "label": "Clean",
      "type": "shell",
      "command": "clean.cmd",
      "problemMatcher": []
    },
    {
      "label": "Build",
      "type": "shell",
      "command": "build.cmd",
      "problemMatcher": [],
      "group": { "kind": "build", "isDefault": true }
    },
    {
      "label": "Flash",
      "type": "shell",
      "command": "flash.cmd",
      "problemMatcher": []
    }
  ]
}

I can create key bindings with

[
  {
    "key": "alt+f9",
    "command": "workbench.action.tasks.runTask",
    "args": "Clean"
  },
  {
    "key": "ctrl+f9",
    "command": "workbench.action.tasks.build"
  },
  {
    "key": "f9",
    "command": "workbench.action.tasks.runTask",
    "args": "Flash"
  }
]

and everything works as expected. I am trying to do the same thing from within an extension (for example with Script Commands) using the VSCode API but it works only for the build and test tasks.

Calling

vscode.commands.executeCommand("workbench.action.tasks.build")

works but

vscode.commands.executeCommand("workbench.action.tasks.runTask", ["Clean"])

opens the task selection list.

How could I directly start other tasks beyond build and test using JavaScript code?

Body:
Your tasks config file looks old. If you're using a new version of Visual Studio Code then you should upgrade.

I think the api is expecting the task to have a "label" field.

https://code.visualstudio.com/docs/editor/tasks#_convert-from-010-to-200

So intsead of:

{
   "taskName": "Clean",
   "type": "shell",
   "command": "clean.cmd",
   "problemMatcher": []
},

It should be:

{
  "label": "Clean",
  "type": "shell",
  "command": "clean.cmd",
  "problemMatcher": []
},

Update: Try invoking it with just the string instead of wrapping it in an Array like this:

vscode.commands.executeCommand("workbench.action.tasks.runTask", "Clean")


来源: stackexchange

问:
pybitcointools pushtx TypeError: expected string or buffer
I am in the process of creating a raw transaction using pybitcointools, however when I tried to push the transaction into the network using pushtx(tx)

I got the ff. error:

```<code>Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/site-packages/bitcoin-1.1.42-py2.7.egg/bitcoin/bci.py", line 311, in pushtx
return f(*args)
File "/usr/local/lib/python2.7/site-packages/bitcoin-1.1.42-py2.7.egg/bitcoin/bci.py", line 261, in bci_pushtx
  if not re.match('^[0-9a-fA-F]*$', tx):
File "/usr/local/lib/python2.7/re.py", line 141, in match
return _compile(pattern, flags).match(string)
TypeError: expected string or buffer
</code>```

by the way my privatekey is in base58 (51 characters) format

Here's the code:

```<code>from bitcoin.main import *
from bitcoin.transactions import *
from bitcoin.bci import *
>>> addr
'1CXW5bqMNQZ3sftXCtiRf3HGTPJmpd2xvq' #I just edited the address for security purpose

>>> unspent(addr)
[{'output': '23e81960ba8bb95c33c2336c84c126e378e4d1123921f881da9287c25f624161:1', 'value': 300000}]

>>> source = '32GkPB9XjMAELR4Q2Hr31Jdz2tntY18zCe'
>>> unspent(source)
[{'output': '8602122a7044b8795b5829b6b48fb1960a124f42ab1c003e769bbaad31cb2afd:0', 'value': 677200}, {'output': 'bd992789fd8cff1a2e515ce2c3473f510df933e1f44b3da6a8737630b82d0786:0', 'value': 5000000}]

>>> ins = unspent(addr) + unspent(target)
>>> amount = 300000 + 5000000 + 677200
>>> amount -= 10000

>>> outs = [{'address': addr, 'value': value}]

>>> tx = mktx(ins, outs)
>>> tx = sign(tx, 0, priv)
>>> tx = deserialize(tx)

>>> tx['ins'][1]['script'] = '00483045022100dfcfafcea73d83e1c54d444a19fb30d17317f922c19e2ff92dcda65ad09cba24022001e7a805c5672c49b222c5f2f1e67bb01f87215fb69df184e7c16f66c1f87c290347304402204a657ab8358a2edb8fd5ed8a45f846989a43655d2e8f80566b385b8f5a70dab402207362f870ce40f942437d43b6b99343419b14fb18fa69bee801d696a39b3410b8034c695221023927b5cd7facefa7b85d02f73d1e1632b3aaf8dd15d4f9f359e37e39f05611962103d2c0e82979b8aba4591fe39cffbf255b3b9c67b3d24f94de79c5013420c67b802103ec010970aae2e3d75eef0b44eaa31d7a0d13392513cd0614ff1c136b3b1020df53ae'
>>> tx['ins'][2]['script'] = '00483045022100dfcfafcea73d83e1c54d444a19fb30d17317f922c19e2ff92dcda65ad09cba24022001e7a805c5672c49b222c5f2f1e67bb01f87215fb69df184e7c16f66c1f87c290347304402204a657ab8358a2edb8fd5ed8a45f846989a43655d2e8f80566b385b8f5a70dab402207362f870ce40f942437d43b6b99343419b14fb18fa69bee801d696a39b3410b8034c695221023927b5cd7facefa7b85d02f73d1e1632b3aaf8dd15d4f9f359e37e39f05611962103d2c0e82979b8aba4591fe39cffbf255b3b9c67b3d24f94de79c5013420c67b802103ec010970aae2e3d75eef0b44eaa31d7a0d13392513cd0614ff1c136b3b1020df53ae'
>>> serialize(tx)
'01000000036141525fc24792da81f8213912d1e478e326c18...'
>>> pushtx(tx)
</code>```

答:
From the looks of it, you need to pass tx to pushtx() in serialized form.

The re.match('^[0-9a-fA-F]*$', tx) test accepts a hex string, exactly what serialize() returns.

This is all the more likely considering that mktx() and sign() produce the result in serialized form.

ContentLicense: CC BY-SA 3.0

Body:
I am in the process of creating a raw transaction using pybitcointools, however when I tried to push the transaction into the network using pushtx(tx)

I got the ff. error:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/site-packages/bitcoin-1.1.42-py2.7.egg/bitcoin/bci.py", line 311, in pushtx
return f(*args)
File "/usr/local/lib/python2.7/site-packages/bitcoin-1.1.42-py2.7.egg/bitcoin/bci.py", line 261, in bci_pushtx
  if not re.match('^[0-9a-fA-F]*$', tx):
File "/usr/local/lib/python2.7/re.py", line 141, in match
return _compile(pattern, flags).match(string)
TypeError: expected string or buffer

by the way my privatekey is in base58 (51 characters) format

Here's the code:

from bitcoin.main import *
from bitcoin.transactions import *
from bitcoin.bci import *
>>> addr
'1CXW5bqMNQZ3sftXCtiRf3HGTPJmpd2xvq' #I just edited the address for security purpose

>>> unspent(addr)
[{'output': '23e81960ba8bb95c33c2336c84c126e378e4d1123921f881da9287c25f624161:1', 'value': 300000}]

>>> source = '32GkPB9XjMAELR4Q2Hr31Jdz2tntY18zCe'
>>> unspent(source)
[{'output': '8602122a7044b8795b5829b6b48fb1960a124f42ab1c003e769bbaad31cb2afd:0', 'value': 677200}, {'output': 'bd992789fd8cff1a2e515ce2c3473f510df933e1f44b3da6a8737630b82d0786:0', 'value': 5000000}]

>>> ins = unspent(addr) + unspent(target)
>>> amount = 300000 + 5000000 + 677200
>>> amount -= 10000

>>> outs = [{'address': addr, 'value': value}]

>>> tx = mktx(ins, outs)
>>> tx = sign(tx, 0, priv)
>>> tx = deserialize(tx)

>>> tx['ins'][1]['script'] = '00483045022100dfcfafcea73d83e1c54d444a19fb30d17317f922c19e2ff92dcda65ad09cba24022001e7a805c5672c49b222c5f2f1e67bb01f87215fb69df184e7c16f66c1f87c290347304402204a657ab8358a2edb8fd5ed8a45f846989a43655d2e8f80566b385b8f5a70dab402207362f870ce40f942437d43b6b99343419b14fb18fa69bee801d696a39b3410b8034c695221023927b5cd7facefa7b85d02f73d1e1632b3aaf8dd15d4f9f359e37e39f05611962103d2c0e82979b8aba4591fe39cffbf255b3b9c67b3d24f94de79c5013420c67b802103ec010970aae2e3d75eef0b44eaa31d7a0d13392513cd0614ff1c136b3b1020df53ae'
>>> tx['ins'][2]['script'] = '00483045022100dfcfafcea73d83e1c54d444a19fb30d17317f922c19e2ff92dcda65ad09cba24022001e7a805c5672c49b222c5f2f1e67bb01f87215fb69df184e7c16f66c1f87c290347304402204a657ab8358a2edb8fd5ed8a45f846989a43655d2e8f80566b385b8f5a70dab402207362f870ce40f942437d43b6b99343419b14fb18fa69bee801d696a39b3410b8034c695221023927b5cd7facefa7b85d02f73d1e1632b3aaf8dd15d4f9f359e37e39f05611962103d2c0e82979b8aba4591fe39cffbf255b3b9c67b3d24f94de79c5013420c67b802103ec010970aae2e3d75eef0b44eaa31d7a0d13392513cd0614ff1c136b3b1020df53ae'
>>> serialize(tx)
'01000000036141525fc24792da81f8213912d1e478e326c18...'
>>> pushtx(tx)


问:
AWS Elastic Beanstalk - how to get URL though CLI
I am fairly new to AWS, I wrote a script to create a ElasticBeanstalk server and deploy code to it which works fine

I am able to get the IP Address and Instance ID using

```<code>aws ec2 describe-instances
</code>```

I know a typical HTTP URL looks like this

```<code>http://(cname-prefix).(region).elasticbeanstalk.com
</code>```

and I used it to "generate" the URL in the script

But I want to check if we can get the URL using CLI

答:
The AWS CLI has a command for this, it describes the elastic beanstalk environment and one of the resulting values is the Endpoint URL

For load-balanced, autoscaling environments, it returns the URL to the LoadBalancer. For single-instance environments, the IP address of the instance is returned.

See docs

aws elasticbeanstalk describe-environments --environment-names my-env

The output looks like this:

```<code>{
"Environments": [
    {
        "ApplicationName": "my-app",
        "EnvironmentName": "my-env",
        "VersionLabel": "7f58-stage-150812_025409",
        "Status": "Ready",
        "EnvironmentId": "e-rpqsewtp2j",
        "EndpointURL": "awseb-e-w-AWSEBLoa-1483140XB0Q4L-109QXY8121.us-west-2.elb.amazonaws.com",
        "SolutionStackName": "64bit Amazon Linux 2015.03 v2.0.0 running Tomcat 8 Java 8",
        "CNAME": "my-env.elasticbeanstalk.com",
        "Health": "Green",
        "AbortableOperationInProgress": false,
        "Tier": {
            "Version": " ",
            "Type": "Standard",
            "Name": "WebServer"
        },
        "DateUpdated": "2015-08-12T18:16:55.019Z",
        "DateCreated": "2015-08-07T20:48:49.599Z"
    }
]
}
</code>```

Body:
I am fairly new to AWS, I wrote a script to create a ElasticBeanstalk server and deploy code to it which works fine

I am able to get the IP Address and Instance ID using

aws ec2 describe-instances

I know a typical HTTP URL looks like this

http://(cname-prefix).(region).elasticbeanstalk.com

and I used it to "generate" the URL in the script

But I want to check if we can get the URL using CLI

Body:
The AWS CLI has a command for this, it describes the elastic beanstalk environment and one of the resulting values is the Endpoint URL

For load-balanced, autoscaling environments, it returns the URL to the LoadBalancer. For single-instance environments, the IP address of the instance is returned.

See docs

aws elasticbeanstalk describe-environments --environment-names my-env

The output looks like this:

{
"Environments": [
    {
        "ApplicationName": "my-app",
        "EnvironmentName": "my-env",
        "VersionLabel": "7f58-stage-150812_025409",
        "Status": "Ready",
        "EnvironmentId": "e-rpqsewtp2j",
        "EndpointURL": "awseb-e-w-AWSEBLoa-1483140XB0Q4L-109QXY8121.us-west-2.elb.amazonaws.com",
        "SolutionStackName": "64bit Amazon Linux 2015.03 v2.0.0 running Tomcat 8 Java 8",
        "CNAME": "my-env.elasticbeanstalk.com",
        "Health": "Green",
        "AbortableOperationInProgress": false,
        "Tier": {
            "Version": " ",
            "Type": "Standard",
            "Name": "WebServer"
        },
        "DateUpdated": "2015-08-12T18:16:55.019Z",
        "DateCreated": "2015-08-07T20:48:49.599Z"
    }
]
}


问:
c++ - error with DXGI.h when try include d3d11.h
When I try compile code with Code::Block and Visual Studio, i get error in DXGI.h

error: '__in' has not been declared|

error: expected ',' or '...' before '&' token|
and so on

Why it's going on and how can i fix that?

```<code>#include <windows.h>
#include <windowsx.h>
#include <d3d11.h>
#include <d3dx11.h>
#include <d3dx10.h>
</code>```

答:
You can hit a number of issues when mixing the legacy DirectX SDK headers with the Windows 8.0 SDK, Windows 8.1 SDK, or the Windows 10 SDK. The problems are because the legacy DirectX SDK has some older headers that conflict with the new SDKs.

You likely need two fixes:

First, make sure that you add the DirectX SDK include and lib paths at the end of the search path rather than the beginning so you get the newer ones listed first.

For x86/Win32 configurations:

```<code>$(ExecutablePath);$(DXSDK_DIR)Utilities\bin\x86
$(IncludePath);$(DXSDK_DIR)Include
$(LibraryPath);$(DXSDK_DIR)Lib\x86
</code>```

For x64 native configurations:

```<code>$(ExecutablePath);$(DXSDK_DIR)Utilities\bin\x64;$(DXSDK_DIR)Utilities\bin\x86
$(IncludePath);$(DXSDK_DIR)Include
$(LibraryPath);$(DXSDK_DIR)Lib\x64
</code>```

Second, explicitly include the dependent header so you don't end up with the older one:

```<code>#include <windows.h>
#include <windowsx.h>
#include <d3d11.h>
#include <dxgi.h>    // <-- make sure you pick up the Windows SDK version
#include <d3dx11.h>  //     and not from the DXSDK
</code>```

If you let d3dx11.h pull in dxgi.h then you'll end up with the wrong one!

See MSDN, Where is the DirectX SDK (2015 Edition)?, and The Zombie DirectX SDK

Two other things to note here about your code. First, there's no reason at all to use DirectX 10 or d3dx10.h. Use DirectX 11 only.

Second, D3DX itself is deprecated including D3DX9, D3DX10, and D3DX11. See Living without D3DX for Direct3D 11 open source replacements.

Body:
When I try compile code with Code::Block and Visual Studio, i get error in DXGI.h

error: '__in' has not been declared|

error: expected ',' or '...' before '&' token|
and so on

Why it's going on and how can i fix that?

#include <windows.h>
#include <windowsx.h>
#include <d3d11.h>
#include <d3dx11.h>
#include <d3dx10.h>

Body:
You can hit a number of issues when mixing the legacy DirectX SDK headers with the Windows 8.0 SDK, Windows 8.1 SDK, or the Windows 10 SDK. The problems are because the legacy DirectX SDK has some older headers that conflict with the new SDKs.

You likely need two fixes:

First, make sure that you add the DirectX SDK include and lib paths at the end of the search path rather than the beginning so you get the newer ones listed first.

For x86/Win32 configurations:

$(ExecutablePath);$(DXSDK_DIR)Utilities\bin\x86
$(IncludePath);$(DXSDK_DIR)Include
$(LibraryPath);$(DXSDK_DIR)Lib\x86

For x64 native configurations:

$(ExecutablePath);$(DXSDK_DIR)Utilities\bin\x64;$(DXSDK_DIR)Utilities\bin\x86
$(IncludePath);$(DXSDK_DIR)Include
$(LibraryPath);$(DXSDK_DIR)Lib\x64

Second, explicitly include the dependent header so you don't end up with the older one:

#include <windows.h>
#include <windowsx.h>
#include <d3d11.h>
#include <dxgi.h>    // <-- make sure you pick up the Windows SDK version
#include <d3dx11.h>  //     and not from the DXSDK

If you let d3dx11.h pull in dxgi.h then you'll end up with the wrong one!

See MSDN, Where is the DirectX SDK (2015 Edition)?, and The Zombie DirectX SDK

Two other things to note here about your code. First, there's no reason at all to use DirectX 10 or d3dx10.h. Use DirectX 11 only.

Second, D3DX itself is deprecated including D3DX9, D3DX10, and D3DX11. See Living without D3DX for Direct3D 11 open source replacements.


问:
How does BigQuery caching on time partitioned tables work?
In contrast with the BigQuery documentation, we see that it DOES cache the results when selecting data from a streaming, data partitioned table (Standard SQL).

Example:
When we perform a deterministic date scan on the streaming, data partitioned table using:

where (_PARTITIONTIME > '2017-11-12'  or _PARTITIONTIME is null)

...BigQuery caches the data for 5 to 20 minutes if we fire the same exact query within that time frame.

While in my interpretation of the documentation it states that it SHOULD NOT cache the data:

'When any of the tables referenced by the query have recently received streaming inserts (a streaming buffer is attached to the table) even if no new rows have arrived'

Important notes:

Our test query queries heartbeat events that really arrive at us continuously

We actually want this caching behavior, because we do not always need to have data to be actual to the last second. We just want to know if we really can depend on this behavior.

Our Questions:

What is going on here / Why does the BQ caching happen at all?

The time this data stays in the BQ cache is 'random' (between 5-20 minutes). What does this mean?

答:
Thanks for clarifying the question. I think it's an overlook that we didn't disabled caching for partitioned tables with streaming data. It should as otherwise the query might return outdated results.

We invalidate the cache when the table is changed. Streaming into the table will cause the table to be changed. I guess that's why the cache is invalidated between 5 to 20 minutes.


问:
PyCharm interpreting backward slashes wrong when checking regex expressions
The expression is:

```<code>re.search("(%s)\\(%d)([0-9]+)".format(newspaper, year2))
</code>```

where newspaper is a string and year2 is an integer.

Instead of interpreting \\ as an escape to the \ character, PyCharm interprets this as escaping ( and warns that I have an unmatched closing parenthesis in (%d). It also highlights the opening parenthesis in orange as well. When I replaced this with \\\, there is no warning but I'm not able to find my matches with this regex.

Is this how \ supposed to be escaped or am I missing another character?

答:
You need to make it a raw string.

\\ is interpreted as a single escaped slash in the string, which would escape the (, so PyCharm is correctly reporting it as an error.

So, do one of:

```<code>r"(%s)\\(%d)([0-9]+)"
# or
"(%s)\\\\(%d)([0-9]+)"
</code>```

Also, you probably meant:

```<code>r"({})\\({})([0-9]+)".format(newspaper, year2)
# or
r"(%s)\\(%d)([0-9]+)" % (newspaper, year2)
</code>```

Body:
The expression is:

re.search("(%s)\\(%d)([0-9]+)".format(newspaper, year2))

where newspaper is a string and year2 is an integer.

Instead of interpreting \\ as an escape to the \ character, PyCharm interprets this as escaping ( and warns that I have an unmatched closing parenthesis in (%d). It also highlights the opening parenthesis in orange as well. When I replaced this with \\\, there is no warning but I'm not able to find my matches with this regex.

Is this how \ supposed to be escaped or am I missing another character?

Body:
You need to make it a raw string.

\\ is interpreted as a single escaped slash in the string, which would escape the (, so PyCharm is correctly reporting it as an error.

So, do one of:

r"(%s)\\(%d)([0-9]+)"
# or
"(%s)\\\\(%d)([0-9]+)"

Also, you probably meant:

r"({})\\({})([0-9]+)".format(newspaper, year2)
# or
r"(%s)\\(%d)([0-9]+)" % (newspaper, year2)


问:
Multiple characters replace in Linux using sed
I have a variable in Linux like below. This is not a valid variable I just created to test how to replace characters with some new characters.

```<code>table=123~!@#$%^&*()+|}{:"?><-=[]\;',./
</code>```

Want to replace all the special characters in this table variable like below

```<code>table1=123_____________________________
</code>```

How can I do that in Linux?

答:
same with tr

```<code>tr -c '[:alnum:]' _  <file
</code>```

Body:
I have a variable in Linux like below. This is not a valid variable I just created to test how to replace characters with some new characters.

table=123~!@#$%^&*()+|}{:"?><-=[]\;',./

Want to replace all the special characters in this table variable like below

table1=123_____________________________

How can I do that in Linux?

Body:
same with tr

tr -c '[:alnum:]' _  <file


问:
Count number of records by date
Given this model:

```<code>Foo(models.Model):
    some_fields
        ...
    date = models.DateTimeField(db_index=True, auto_now_add=True)
</code>```

I want to show the data in a graph where X axis is time (HH:MM) and Y axis is the number of instances at that time.

I've tried this:

```<code>Foo.objects.extra({'date_created' : "date(date)"}).annotate(created_count=Count('id')).values('date_created', 'created_count')
</code>```

But the value of created_count is always 1, even if I create 2 instances at the same time (bulk_create).

Any idea to accomplish this in Django 1.8?

UPDATE: Since the field DateTimeField stores the milliseconds, the query doesn't count the records of the same day and time as if they were created at the same time, so I finally settled to zero the milliseconds.

答:
You need to order it before annotating it. Only one answer on stackoverflow mentioned this, so here you go.

```<code>Foo.objects.extra({'date_created' : "date(date)"}).order_by("date_created").annotate(created_count=Count('id'))
</code>```

Title: Count number of records by date

Body:
Given this model:

Foo(models.Model):
    some_fields
        ...
    date = models.DateTimeField(db_index=True, auto_now_add=True)

I want to show the data in a graph where X axis is time (HH:MM) and Y axis is the number of instances at that time.

I've tried this:

Foo.objects.extra({'date_created' : "date(date)"}).annotate(created_count=Count('id')).values('date_created', 'created_count')

But the value of created_count is always 1, even if I create 2 instances at the same time (bulk_create).

Any idea to accomplish this in Django 1.8?

UPDATE: Since the field DateTimeField stores the milliseconds, the query doesn't count the records of the same day and time as if they were created at the same time, so I finally settled to zero the milliseconds.

Body:
You need to order it before annotating it. Only one answer on stackoverflow mentioned this, so here you go.

Foo.objects.extra({'date_created' : "date(date)"}).order_by("date_created").annotate(created_count=Count('id'))


问:
How to Prevent Caching When using PDF Streaming with Acrobar Reader 10.0 (HTTP1.0/HTTP1.1)
I was trying to find a way to prevent browsers from caching PDF that is being loaded using a streaming methods.

FireFox and Chorme deals just fine with the following headers and doesn't cache any pdf file:

Response.AddHeader("Pragma", "no-cache, no-store");
Response.AddHeader("Cache-Control", "no-cache, no-store, must-revalidate, max-age=0");
Response.AddHeader("Expires", "-1");

Although, IE 7 (with acrobat reader 9.4.1) works only with the following headers and prevent the caching of the PDF doc:

Response.AddHeader("Pragma", "no-cache, no-store");
Response.AddHeader("Cache-Control", "private, must-revalidate, max-age=0");
Response.AddHeader("Expires", "-1");

When i was trying to use IE 7 with Acrobat Reader 10, the above header didn't make any different and cached the PDF no matter what i tried.

When i am trying to put Cache-Control: no-cache, no-store, the pdf was not loaded at all.
According to my understanding, IE use the cache mechanism to load the PDF documents.

Is there anyone familiar with a global or specific way (by using other headers for example) that can help prevent caching of PDF documents?

答: Controlling the cache settings down the pipe is not fool proof. The alternative is to encode the realtime and date in the file name of the PDF.</p>

ContentLicense: CC BY-SA 2.5


问:
Python 2.X : Regex to find all company names ending in ".inc"
I'm trying to extract the company names from press releases. As an example, below there is a snippet (in French) of a press release containing a list of seven companies ending in .inc.

En effet, Revenu Québec avait des motifs raisonnables de croire que ces entreprises avaient utilisé de fausses factures provenant de plusieurs sociétés, dont Asphalte Vrac Transport inc., 9163-6704 Québec inc., Entreprise Denis Dupré inc., Gestion Jean M. Machado inc., Impact Technologie Environnementale inc., Les entreprises Luc Clément inc. et Transport Vrac Globe International inc.

I'm trying to extract all the names using the following code:

```<code>aa = re.findall('inc\.,? (.*?inc\.)', text)
</code>```

I do manage to capture quite a few, but for some reason I can't figure, I can't extract them all. It seems trivial but it has stomped me for a few hours....

Any help is appreciated !

答:
Brief

Using the regex module (instead of re) you can use this solution.

Code

Option 1

This is the original regex and only matches inc.. This also doesn't allow company names that contain et. See Option 2 for a more comprehensive regular expression.

See regex in use here

```<code>[\p{Lu}\p{N}](?:(?!et)[^,])*inc\.
</code>```

Option 2

For a more comprehensive regular expression that also checks for other company entities such as ltd. or sons, you can use the following regex.

See regex in use here

```<code>(?:et|,)[^,]*?([\p{Lu}\p{N}][^,]*?\s(?:inc\.|sons|ltd\.))
</code>```

Note: In some flavours of regex you can use the \K token. This token resets the starting point of the reported match (any previously consumed characters are no longer included in the final match). If your regex engine supports the \K token (and doesn't convert it to a literal K), you can use the following (effectively eliminating the need for capture groups).

See regex in use here

```<code>(?:et|,)[^,]*?\K[\p{Lu}\p{N}][^,]*?\s(?:inc\.|sons|ltd\.)
              ^^
</code>```

Results

Input

En effet, Revenu Québec avait des motifs raisonnables de croire que
  ces entreprises avaient utilisé de fausses factures provenant de
  plusieurs sociétés, dont Asphalte Vrac Transport inc., 9163-6704
  Québec inc., Entreprise Denis Dupré inc., Gestion Jean M. Machado
  inc., Impact Technologie Environnementale inc., Les entreprises Luc
  Clément inc. et Transport Vrac Globe International inc.

Output

```<code>Asphalte Vrac Transport inc.
9163-6704 Québec inc.
Entreprise Denis Dupré inc.
Gestion Jean M. Machado inc.
Impact Technologie Environnementale inc.
Les entreprises Luc Clément inc.
Transport Vrac Globe International inc.
</code>```

Explanation

Option 1

[\p{Lu}\p{N}] Match anything in the set (in this case \p{Lu} - any uppercase character in any language (includes Unicode for uppercase French characters and numbers for number companies)

(?:(?!et)[^,])* Match the following any number of times (tempered greedy token)

(?!et) Negative lookahead ensuring what follows does not match et literally

[^,] Match any character except comma , literally

inc\. Match inc. literally

Option 2

(?:et|,) Match either et or comma , literally

[^,]*? Match any character not present in the set (any character except comma , any number of times, but as few as possible

([\p{Lu}\p{N}][^,]*?\s(?:inc\.|sons|ltd\.)) Capture the following into capture group 1

[\p{Lu}\p{N}] Match any Unicode uppercase character or Unicode number (for number companies)

[^,]*?Match any character not present in the set (any character except comma , any number of times, but as few as possible

\s Match a whitespace character

(?:inc\.|sons|ltd\.) Match either of the following

inc\. Match inc. literally

sons Match sons literally

ltd\. Match ltd. literally

Notes

Regex module vs re

Using regex module allows us to use Unicode character classes such as \p{Lu} to ensure we also catch the possibility of company names beginning with uppercase Unicode characters such as É.

Catching Special Cases

The regular expression links (under Code) include an additional string to test against:

```<code>, Étoile Simpsons et sons, Étoile Simpsons inc., Étoile et Simpsons inc.
</code>```

With this additional line added only the following strings should be caught (valid company name according to the OP's specifications):

Étoile Simpsons et sons

Étoile Simpsons inc.

Étoile et Simpsons ltd.

This presents a few challenges including:

Company name begins with uppercase Unicode character É.

This means we must ensure Unicode uppercase letter compatibility, thus using something like [A-Z] is not possible for ensuring a name begins uppercase characters.

Company ends with sons, but also includes sons (cannot stop at first match for sons).

Take the case of Étoile Simpsons et sons for example.

This should not end at sons in Simpsons. A natural instinct (at least in regex) might be to use \b to assert a word boundary. As much as this might be the preferred method, it doesn't work in this case. Take the French word blésons as an example. Using \b will actually match in blésons since regex engines very seldom match \b correctly with Unicode characters even with u flag enabled (this is why I use \s instead).

The word sons appears after the company name ends (in the sentence Their sons et sons, les sons.). It must not extend past the company name's ending.

This is a great case for using lazy quantifiers i.e. .*?. Making it lazy will allow it to stop at the first match instead of matching the whole sentence incorrectly.

The string Their sons et sons, les sons. contains all the parts of a valid company name (a word starting with an uppercase character, followed by the word sons), but this should not match as it's not a company name.

Since the OP specified a , before each company name, I use this to determine what is and is not a company name.

Body:
I'm trying to extract the company names from press releases. As an example, below there is a snippet (in French) of a press release containing a list of seven companies ending in .inc.

En effet, Revenu Québec avait des motifs raisonnables de croire que ces entreprises avaient utilisé de fausses factures provenant de plusieurs sociétés, dont Asphalte Vrac Transport inc., 9163-6704 Québec inc., Entreprise Denis Dupré inc., Gestion Jean M. Machado inc., Impact Technologie Environnementale inc., Les entreprises Luc Clément inc. et Transport Vrac Globe International inc.

I'm trying to extract all the names using the following code:

aa = re.findall('inc\.,? (.*?inc\.)', text)

I do manage to capture quite a few, but for some reason I can't figure, I can't extract them all. It seems trivial but it has stomped me for a few hours....

Any help is appreciated !

Body:
Brief

Using the regex module (instead of re) you can use this solution.

Code

Option 1

This is the original regex and only matches inc.. This also doesn't allow company names that contain et. See Option 2 for a more comprehensive regular expression.

See regex in use here

[\p{Lu}\p{N}](?:(?!et)[^,])*inc\.

Option 2

For a more comprehensive regular expression that also checks for other company entities such as ltd. or sons, you can use the following regex.

See regex in use here

(?:et|,)[^,]*?([\p{Lu}\p{N}][^,]*?\s(?:inc\.|sons|ltd\.))

Note: In some flavours of regex you can use the \K token. This token resets the starting point of the reported match (any previously consumed characters are no longer included in the final match). If your regex engine supports the \K token (and doesn't convert it to a literal K), you can use the following (effectively eliminating the need for capture groups).

See regex in use here

(?:et|,)[^,]*?\K[\p{Lu}\p{N}][^,]*?\s(?:inc\.|sons|ltd\.)
              ^^

Results

Input

En effet, Revenu Québec avait des motifs raisonnables de croire que
  ces entreprises avaient utilisé de fausses factures provenant de
  plusieurs sociétés, dont Asphalte Vrac Transport inc., 9163-6704
  Québec inc., Entreprise Denis Dupré inc., Gestion Jean M. Machado
  inc., Impact Technologie Environnementale inc., Les entreprises Luc
  Clément inc. et Transport Vrac Globe International inc.

Output

Asphalte Vrac Transport inc.
9163-6704 Québec inc.
Entreprise Denis Dupré inc.
Gestion Jean M. Machado inc.
Impact Technologie Environnementale inc.
Les entreprises Luc Clément inc.
Transport Vrac Globe International inc.

Explanation

Option 1

[\p{Lu}\p{N}] Match anything in the set (in this case \p{Lu} - any uppercase character in any language (includes Unicode for uppercase French characters and numbers for number companies)

(?:(?!et)[^,])* Match the following any number of times (tempered greedy token)

(?!et) Negative lookahead ensuring what follows does not match et literally

[^,] Match any character except comma , literally

inc\. Match inc. literally

Option 2

(?:et|,) Match either et or comma , literally

[^,]*? Match any character not present in the set (any character except comma , any number of times, but as few as possible

([\p{Lu}\p{N}][^,]*?\s(?:inc\.|sons|ltd\.)) Capture the following into capture group 1

[\p{Lu}\p{N}] Match any Unicode uppercase character or Unicode number (for number companies)

[^,]*?Match any character not present in the set (any character except comma , any number of times, but as few as possible

\s Match a whitespace character

(?:inc\.|sons|ltd\.) Match either of the following

inc\. Match inc. literally

sons Match sons literally

ltd\. Match ltd. literally

Notes

Regex module vs re

Using regex module allows us to use Unicode character classes such as \p{Lu} to ensure we also catch the possibility of company names beginning with uppercase Unicode characters such as É.

Catching Special Cases

The regular expression links (under Code) include an additional string to test against:

, Étoile Simpsons et sons, Étoile Simpsons inc., Étoile et Simpsons inc.

With this additional line added only the following strings should be caught (valid company name according to the OP's specifications):

Étoile Simpsons et sons

Étoile Simpsons inc.

Étoile et Simpsons ltd.

This presents a few challenges including:

Company name begins with uppercase Unicode character É.

This means we must ensure Unicode uppercase letter compatibility, thus using something like [A-Z] is not possible for ensuring a name begins uppercase characters.

Company ends with sons, but also includes sons (cannot stop at first match for sons).

Take the case of Étoile Simpsons et sons for example.

This should not end at sons in Simpsons. A natural instinct (at least in regex) might be to use \b to assert a word boundary. As much as this might be the preferred method, it doesn't work in this case. Take the French word blésons as an example. Using \b will actually match in blésons since regex engines very seldom match \b correctly with Unicode characters even with u flag enabled (this is why I use \s instead).

The word sons appears after the company name ends (in the sentence Their sons et sons, les sons.). It must not extend past the company name's ending.

This is a great case for using lazy quantifiers i.e. .*?. Making it lazy will allow it to stop at the first match instead of matching the whole sentence incorrectly.

The string Their sons et sons, les sons. contains all the parts of a valid company name (a word starting with an uppercase character, followed by the word sons), but this should not match as it's not a company name.

Since the OP specified a , before each company name, I use this to determine what is and is not a company name.


问:
Adding Two Numbers using Two Threads

I want to add just two numbers using two threads,but i didn't understand where i am wrong.

   My output is wrong.And i know problem is with synchronized but not able solve.

```<code>import java.io.*;

class GFG {
public static void main (String[] args) throws InterruptedException {
    final Addition a=new Addition();

    Thread t1 = new Thread(new Runnable()
    {
        public void run(){
            try {
               a.add(1,10);
            } catch(Exception e) {
            }
        }
    });

    Thread t2 = new Thread(new Runnable()
    {
        public void run(){
            try {
                a.add(1,4);
            } catch(Exception e) {
            }
        }
    });

    t1.start();
    t2.start();

    t1.join();
    t2.join();
}

public static class Addition{
    int a, b;
    int sum=0;
    public void add(int a, int b) throws InterruptedException{
        synchronized(this){
            for (int i=a;i<=b;i++){
                sum=sum+i;
                Thread.sleep(1000);
            }
            System.out.println("Sum="+sum);
        }
     }
  }
}
</code>```

Output:

```<code> Sum=55
 Sum=65
</code>```

And by seeing output I can say that... After completing the task of THREAD t1, THREAD t2 is adding its result to the t1...??

答:
The two threads use the same instance of class Addition.

The unique instance of  class Addition has the variable sum which is share between threads t1 and t2.

According each thread is running they are changing the value of sum and the result is merged.

I ran your program and made some change to add logs, as you can see:

```<code>  public static class Addition{
    int a, b;
    private int sum=0;

    public void add(int a, int b, int id) throws InterruptedException{
        System.out.println("INIT ADD t:[" + id + "]");

        synchronized(this){
            for (int i=a;i<=b;i++){
                System.out.println("Sum Before t:[" + id + "] i:[" + i + "]=" + sum);
                sum=sum + i;
                System.out.println("Sum After t:[" + id + "] i:[" + i + "]=" + sum);
                Thread.sleep(1000);
            }
        }
        System.out.println("Sum t:[" + id + "]=" + sum);
     }

  }
</code>```

The log confirms that i told you, the variable sum is affected each time by each tread. Here the log:

```<code>INIT ADD t:[1]
Sum Before t:[1] i:[1]=0
INIT ADD t:[2]
Sum After t:[1] i:[1]=1
Sum Before t:[1] i:[2]=1
Sum After t:[1] i:[2]=3
Sum Before t:[1] i:[3]=3
Sum After t:[1] i:[3]=6
Sum Before t:[1] i:[4]=6
Sum After t:[1] i:[4]=10
Sum Before t:[1] i:[5]=10
Sum After t:[1] i:[5]=15
Sum Before t:[1] i:[6]=15
Sum After t:[1] i:[6]=21
Sum Before t:[1] i:[7]=21
Sum After t:[1] i:[7]=28
Sum Before t:[1] i:[8]=28
Sum After t:[1] i:[8]=36
Sum Before t:[1] i:[9]=36
Sum After t:[1] i:[9]=45
Sum Before t:[1] i:[10]=45
Sum After t:[1] i:[10]=55
Sum t:[1]=55
Sum Before t:[2] i:[1]=55
Sum After t:[2] i:[1]=56
Sum Before t:[2] i:[2]=56
Sum After t:[2] i:[2]=58
Sum Before t:[2] i:[3]=58
Sum After t:[2] i:[3]=61
Sum Before t:[2] i:[4]=61
Sum After t:[2] i:[4]=65
Sum t:[2]=65
</code>```

As you synchronized for block, the second thread (t2) start to add and store the result into sum, but sum has the result of t1(55) at the begin of for.

So, according with this log, what is the behavior that you want to get?

Title: Adding Two Numbers using Two Threads

Body:
I want to add just two numbers using two threads,but i didn't understand where i am wrong.

   My output is wrong.And i know problem is with synchronized but not able solve.

import java.io.*;

class GFG {
public static void main (String[] args) throws InterruptedException {
    final Addition a=new Addition();

    Thread t1 = new Thread(new Runnable()
    {
        public void run(){
            try {
               a.add(1,10);
            } catch(Exception e) {
            }
        }
    });

    Thread t2 = new Thread(new Runnable()
    {
        public void run(){
            try {
                a.add(1,4);
            } catch(Exception e) {
            }
        }
    });

    t1.start();
    t2.start();

    t1.join();
    t2.join();
}

public static class Addition{
    int a, b;
    int sum=0;
    public void add(int a, int b) throws InterruptedException{
        synchronized(this){
            for (int i=a;i<=b;i++){
                sum=sum+i;
                Thread.sleep(1000);
            }
            System.out.println("Sum="+sum);
        }
     }
  }
}

Output:

 Sum=55
 Sum=65

And by seeing output I can say that... After completing the task of THREAD t1, THREAD t2 is adding its result to the t1...??

Body:
The two threads use the same instance of class Addition.

The unique instance of  class Addition has the variable sum which is share between threads t1 and t2.

According each thread is running they are changing the value of sum and the result is merged.

I ran your program and made some change to add logs, as you can see:

  public static class Addition{
    int a, b;
    private int sum=0;

    public void add(int a, int b, int id) throws InterruptedException{
        System.out.println("INIT ADD t:[" + id + "]");

        synchronized(this){
            for (int i=a;i<=b;i++){
                System.out.println("Sum Before t:[" + id + "] i:[" + i + "]=" + sum);
                sum=sum + i;
                System.out.println("Sum After t:[" + id + "] i:[" + i + "]=" + sum);
                Thread.sleep(1000);
            }
        }
        System.out.println("Sum t:[" + id + "]=" + sum);
     }

  }

The log confirms that i told you, the variable sum is affected each time by each tread. Here the log:

INIT ADD t:[1]
Sum Before t:[1] i:[1]=0
INIT ADD t:[2]
Sum After t:[1] i:[1]=1
Sum Before t:[1] i:[2]=1
Sum After t:[1] i:[2]=3
Sum Before t:[1] i:[3]=3
Sum After t:[1] i:[3]=6
Sum Before t:[1] i:[4]=6
Sum After t:[1] i:[4]=10
Sum Before t:[1] i:[5]=10
Sum After t:[1] i:[5]=15
Sum Before t:[1] i:[6]=15
Sum After t:[1] i:[6]=21
Sum Before t:[1] i:[7]=21
Sum After t:[1] i:[7]=28
Sum Before t:[1] i:[8]=28
Sum After t:[1] i:[8]=36
Sum Before t:[1] i:[9]=36
Sum After t:[1] i:[9]=45
Sum Before t:[1] i:[10]=45
Sum After t:[1] i:[10]=55
Sum t:[1]=55
Sum Before t:[2] i:[1]=55
Sum After t:[2] i:[1]=56
Sum Before t:[2] i:[2]=56
Sum After t:[2] i:[2]=58
Sum Before t:[2] i:[3]=58
Sum After t:[2] i:[3]=61
Sum Before t:[2] i:[4]=61
Sum After t:[2] i:[4]=65
Sum t:[2]=65

As you synchronized for block, the second thread (t2) start to add and store the result into sum, but sum has the result of t1(55) at the begin of for.

So, according with this log, what is the behavior that you want to get?


问:
Facebook Messenger Bot - How to disable bot and allow human to chat
so this is something I've been trying to think through for about 16 hours. I am coding with PHP / CuRl / etc - the bot works and everything is fine. My current issue is figuring out how to disable the bot and allow a human to begin chatting with the customer/sender.

Has anyone successfully, created a route for this ? I mean it's pretty hard from what I see, you'd have to disable etc etc. A lot of effort for my clients.

Thanks for any input.

答:
Facebook has rolled out a "Handover Protocol" which is supposed to facilitate a combined human/bot Messenger implementation.

https://developers.facebook.com/docs/messenger-platform/handover-protocol

It is a little unclear what actually occurs in step 5:

Pass thread control: At some point in the conversation, a user may choose to do something like interact with a live agent. To handle this, pass thread control from the Primary Receiver to the Secondary Receiver. The Secondary Receiver will receive a messaging_handovers webhook event to notify it that is now controls the conversation.

This doesn't actually disable the bot (as the OP requested), and isn't in the control of the Page owner but rather of the user. It seems FB envisions the user typing something like 'I would like to chat with a human' triggering the bot to pass control...but it would be nice to let the page owner simply put the app in standby and handle the messages herself.


问:
Javascript pull content from variable by id
I am trying to pull content inside a variable using plain java script.
I am trying to get only part of the variable with an id.
In this example I am trying to pull only part of html with id ‘container’.

My fiddle
https://jsfiddle.net/a2ngc9jv/2/

```<code>var htmlPage = `
<html>
<div>
testing but not required
</div>
  <div id="container">
    <p>
     i want to pull this whole block from parent
    </p>
    <p>
      test 2
    </p>
  </div>

</html>`;

console.log(htmlPage.getElementById("container"))
console.log(document.getElementById("container"))
</code>```

答:
htmlPage is a string not a document node.  However it's easy to put it into one:

var htmlPage = `

testing but not required

     i want to pull this whole block from parent

      test 2

`;

// it might not be "allowed" to put a html tag inside a div but it works for this purpose.
var n = document.createElement('div');
n.innerHTML = htmlPage;

var content = n.querySelector('#container p:first-child').innerHTML;

console.log(content);```

Body:
I am trying to pull content inside a variable using plain java script.
I am trying to get only part of the variable with an id.
In this example I am trying to pull only part of html with id ‘container’.

My fiddle
https://jsfiddle.net/a2ngc9jv/2/

var htmlPage = `

testing but not required

     i want to pull this whole block from parent

      test 2

`;

console.log(htmlPage.getElementById("container"))
console.log(document.getElementById("container"))

Body:
htmlPage is a string not a document node.  However it's easy to put it into one:

var htmlPage = `
<html>
<div>
testing but not required
</div>
  <div id="container">
    <p>
     i want to pull this whole block from parent
    </p>
    <p>
      test 2
    </p>
  </div>

</html>`;

// it might not be "allowed" to put a html tag inside a div but it works for this purpose.
var n = document.createElement('div');
n.innerHTML = htmlPage;

var content = n.querySelector('#container p:first-child').innerHTML;

console.log(content);


问:
What Happens to Non-Awaited Tasks In Try/Catch Block
What happens when a method returns a Task that is contained in a try/catch block? If that non-awaited Task throws an exception, is the exception caught/handled?

For example, if DoSomethingAsync() throws an exception, can I handle it in the try/catch block in TryCatchMethod()?

```<code>Task TryCatchMethod()
{
    try
    {
        return DoSomethingAsync();
    }
    catch(Exception e)
    {
        //Handle Exception
    }
}

async Task DoSomethingAsync()
{
   await Task.Delay(10000);
   throw new System.Exception();
}
</code>```

答:
If DoSomethingAsync throws an exception, the exception is caught.  If it returns a faulted task, instead of throwing, then there is no exception to catch until you try to get the task's result (by awaiting it).  Since you don't do that in your try block, it won't run your catch block.

Note that if the method is marked as async any exceptions thrown in the body of that method are caught and result in the method returning a faulted task, rather than the method throwing an exception.  For the method to throw an exception the method would need to return a Task without being marked as async.

ContentLicense: CC BY-SA 4.0

Body:
What happens when a method returns a Task that is contained in a try/catch block? If that non-awaited Task throws an exception, is the exception caught/handled?

For example, if DoSomethingAsync() throws an exception, can I handle it in the try/catch block in TryCatchMethod()?

Task TryCatchMethod()
{
    try
    {
        return DoSomethingAsync();
    }
    catch(Exception e)
    {
        //Handle Exception
    }
}

async Task DoSomethingAsync()
{
   await Task.Delay(10000);
   throw new System.Exception();
}


问:
Jade multiline Object / Array
I need to know how to split into lines objects / arrays in jade.

This works fine:

```<code>object = [{foo: bar, bar:foo},{foo: bar, bar:foo},{foo: bar, bar:foo}]
</code>```

This doesn't:

```<code>object = [
   {foo: bar, bar:foo},
   {foo: bar, bar:foo},
   {foo: bar, bar:foo}
]
</code>```

This doesn't either:

```<code>- object = [
-       {foo: bar, bar:foo},
-       {foo: bar, bar:foo},
-       {foo: bar, bar:foo}
- ]
</code>```

答:
Documentation on pug site says that this should work (keep track of the white spaces) :

```<code>-
  var object = [
    {foo: bar, bar:foo},
    {foo: bar, bar:foo},
    {foo: bar, bar:foo}
  ]
</code>```

Title: Jade multiline Object / Array

Body:
I need to know how to split into lines objects / arrays in jade.

This works fine:

object = [{foo: bar, bar:foo},{foo: bar, bar:foo},{foo: bar, bar:foo}]

This doesn't:

object = [
   {foo: bar, bar:foo},
   {foo: bar, bar:foo},
   {foo: bar, bar:foo}
]

This doesn't either:

- object = [
-       {foo: bar, bar:foo},
-       {foo: bar, bar:foo},
-       {foo: bar, bar:foo}
- ]

Body:
Documentation on pug site says that this should work (keep track of the white spaces) :

-
  var object = [
    {foo: bar, bar:foo},
    {foo: bar, bar:foo},
    {foo: bar, bar:foo}
  ]


问:
Compare two list's values and get the difference
I created a method that compares two lists' values and outputs the difference:

```<code>public static List<OT_Contact> Comparer(
    List<OT_Contact> security_owner,
    List<OT_Contact> borrower)
{
   List<OT_Contact> nonborrowertrustor = security_owner.Except(borrower).ToList();

   foreach (var nbt_list in nonborrowertrustor)
   {
      var list = nbt_list;
   }

   return nonborrowertrustor;
}
</code>```

Can anyone tell me if there is something wrong with my code and how can I assign it to a variable, for example:

```<code>var result = Comparer(list1, list2);
</code>```

答:
Why are you not using Linq?

```<code>var trustys = security_owner
    .Where(o => !borrower.Any(b=> b.Name == o.Name /* && compare more attributes from o and b */))
    .ToList();

return trustys;
</code>```

this will filter all items from security owner which aren't in borrower, using

```<code>(b=> b.Name == o.Name && .....)
</code>```

as "equality measure".

Example:

```<code>using System.Collections.Generic;
using System.Linq;

internal class Program
{
    public class OT_Contact
    {
        public int Age;
        public string Email;
        public string Name;

        public OT_Contact(string name, string email, int age = int.MinValue)
        {
            Name = name;
            Email = email;
            Age = age;
        }

        public override string ToString()
        {
            return ($"{Name} {Email} " + (Age != int.MinValue ? Age.ToString() : "")).Trim();
        }
    }

    static void Main(string[] args)
    {
        var owner = new List<OT_Contact>
            {
                new OT_Contact("paul","p@o", 5),
                new OT_Contact("paul","pppp@o"),
                new OT_Contact("mani","kkk"),
                new OT_Contact("olaf", "olaf", 22)
            };

        var borr = new List<OT_Contact>
            {
                new OT_Contact("paul","popel@o", 5),
                new OT_Contact("paul","pppp@o"),
                new OT_Contact("mani","kkk",99),
                new OT_Contact("olaf", "", 22)
            };

        var trust = owner.Where(o => !borr.Any(b => b.Name == o.Name && b.Email == o.Email)).ToList();

        System.Console.WriteLine("Owner:\n    " + string.Join("\n    ", owner));
        System.Console.WriteLine("\nBorrower:\n    " + string.Join("\n    ", borr));
        System.Console.WriteLine("\nTrustys:\n    " + string.Join("\n    ", trust));

        System.Console.ReadLine();
    }
}
</code>```

Output (Age is not important for equality, hence not inside the Any-Clause):

```<code>Owner:
    paul p@o 5
    paul pppp@o
    mani kkk
    olaf olaf 22

Borrower:
    paul popel@o 5
    paul pppp@o
    mani kkk 99
    olaf  22

Trustys:
    paul p@o 5
    olaf olaf 22
</code>```

This example models the IEnumerable.Except(..) used in the question. It will find any owner that is not found in the borrower list. The euqality-condition only takes Name and Email under consideration. If it finds an borrower with the same Name and Email it will not output him in the resulting list.

Any borrower that is only in the owner list won't make it into to the result either - getting any borrower that is not in owner could be accomplished by simply swapping the lists around:

```<code>var onlyBorr = borr.Where(b => !owner.Any(o => o.Name == b.Name && o.Email == b.Email)).ToList();
</code>```

A feasable implementation of an IEqualityComparer for this contrieved example could be

```<code>public class OT_ContactEqualityComparer : IEqualityComparer<OT_Contact>
{
    public bool Equals(OT_Contact x, OT_Contact y)
    {
        if (x == null || y == null)
            return false;

        return (x.Name == y.Name && x.Email == y.Email);
    }

    public int GetHashCode(OT_Contact c)
        => (c.Name ?? "").GetHashCode() ^ (c.Email ?? "").GetHashCode();
}
</code>```

which would allow the usage of IEnumerable.Except like this:

```<code>System.Console.WriteLine("\nIEquality:\n    " + string.Join("\n    ",

    owner.Except(borr, new OT_ContactEqualityComparer())));
</code>```

Body:
I created a method that compares two lists' values and outputs the difference:

public static List<OT_Contact> Comparer(
    List<OT_Contact> security_owner,
    List<OT_Contact> borrower)
{
   List<OT_Contact> nonborrowertrustor = security_owner.Except(borrower).ToList();

   foreach (var nbt_list in nonborrowertrustor)
   {
      var list = nbt_list;
   }

   return nonborrowertrustor;
}

Can anyone tell me if there is something wrong with my code and how can I assign it to a variable, for example:

var result = Comparer(list1, list2);

Body:
Why are you not using Linq?

var trustys = security_owner
    .Where(o => !borrower.Any(b=> b.Name == o.Name /* && compare more attributes from o and b */))
    .ToList();

return trustys;

this will filter all items from security owner which aren't in borrower, using

(b=> b.Name == o.Name && .....)

as "equality measure".

Example:

using System.Collections.Generic;
using System.Linq;

internal class Program
{
    public class OT_Contact
    {
        public int Age;
        public string Email;
        public string Name;

        public OT_Contact(string name, string email, int age = int.MinValue)
        {
            Name = name;
            Email = email;
            Age = age;
        }

        public override string ToString()
        {
            return ($"{Name} {Email} " + (Age != int.MinValue ? Age.ToString() : "")).Trim();
        }
    }

    static void Main(string[] args)
    {
        var owner = new List<OT_Contact>
            {
                new OT_Contact("paul","p@o", 5),
                new OT_Contact("paul","pppp@o"),
                new OT_Contact("mani","kkk"),
                new OT_Contact("olaf", "olaf", 22)
            };

        var borr = new List<OT_Contact>
            {
                new OT_Contact("paul","popel@o", 5),
                new OT_Contact("paul","pppp@o"),
                new OT_Contact("mani","kkk",99),
                new OT_Contact("olaf", "", 22)
            };

        var trust = owner.Where(o => !borr.Any(b => b.Name == o.Name && b.Email == o.Email)).ToList();

        System.Console.WriteLine("Owner:\n    " + string.Join("\n    ", owner));
        System.Console.WriteLine("\nBorrower:\n    " + string.Join("\n    ", borr));
        System.Console.WriteLine("\nTrustys:\n    " + string.Join("\n    ", trust));

        System.Console.ReadLine();
    }
}

Output (Age is not important for equality, hence not inside the Any-Clause):

Owner:
    paul p@o 5
    paul pppp@o
    mani kkk
    olaf olaf 22

Borrower:
    paul popel@o 5
    paul pppp@o
    mani kkk 99
    olaf  22

Trustys:
    paul p@o 5
    olaf olaf 22

This example models the IEnumerable.Except(..) used in the question. It will find any owner that is not found in the borrower list. The euqality-condition only takes Name and Email under consideration. If it finds an borrower with the same Name and Email it will not output him in the resulting list.

Any borrower that is only in the owner list won't make it into to the result either - getting any borrower that is not in owner could be accomplished by simply swapping the lists around:

var onlyBorr = borr.Where(b => !owner.Any(o => o.Name == b.Name && o.Email == b.Email)).ToList();

A feasable implementation of an IEqualityComparer for this contrieved example could be

public class OT_ContactEqualityComparer : IEqualityComparer<OT_Contact>
{
    public bool Equals(OT_Contact x, OT_Contact y)
    {
        if (x == null || y == null)
            return false;

        return (x.Name == y.Name && x.Email == y.Email);
    }

    public int GetHashCode(OT_Contact c)
        => (c.Name ?? "").GetHashCode() ^ (c.Email ?? "").GetHashCode();
}

which would allow the usage of IEnumerable.Except like this:

System.Console.WriteLine("\nIEquality:\n    " + string.Join("\n    ",

    owner.Except(borr, new OT_ContactEqualityComparer())));


问:
Javascript delay between turns
I'm trying to make a turn-based battle system in a RPG I'm building. I want the player to be able to see (through CSS) how his own and enemy's life lowers throughout the fight.
This is my current code:

```<code>// Defining the variables globally for accessibility.
var enemy_max_hp = 0;
var enemy_hp = 0;
var enemy_atk_dmg = 0;
var enemy_def_pwr = 0;
var enemy_crit_chance = 0;
var enemy_crit_pwr = 0.0;

function battle() {
    while(current_hp > 0 || enemy_current_hp <= 0){
        //setTimeout(function(){
            current_hp -= enemy_atk_dmg*enemy_crit_pwr*crit_chance/100 + def_pwr/2;
            enemy_hp -= attack_dmg*crit_power*crit_chance/100 - enemy_def_pwr/2;

            if(current_hp < 0){ current_hp = 0; }
            if(enemy_hp < 0){ enemy_hp = 0; }

            if (current_hp == 0){
                // Die
            }

            if (enemy_current_hp == 0){
                // Win battle, proceed.
                    spawnenemy();
            }
        //}, 1000);
    }
}

function spawnenemy() {
    enemy_max_hp = 150;
    enemy_hp = 150;
    enemy_atk_dmg = 5;
    enemy_def_pwr = 3;
    enemy_crit_chance = 0;
    enemy_crit_pwr = 0;
}
</code>```

I'm updating the user's data via another script:

```<code>var max_hp = 100;
var current_hp = 100;
var attack_dmg = 5;
var defense_power = 4;
var crit_chance = 0;
var crit_power = 0.0;

function showStats(){
    document.getElementById("max_hp").innerHTML = max_hp;
    document.getElementById("current_hp").innerHTML = current_hp;
    document.getElementById("attack_dmg").innerHTML = attack_dmg;
    document.getElementById("defense_power").innerHTML = defense_power;
    document.getElementById("crit_chance").innerHTML = crit_chance + '%';
    document.getElementById("crit_power").innerHTML = crit_power;
}
setInterval(showStats, 5);
</code>```

If I run the code, as is, the battle ends in matter of an eyeblink, and health runs from 100 to 0 in an instance. I figured adding the setTimeout() function would work, but it just crashes the webpage. What should I do?

Also, the battle function is called (per now) via a button onclick call. I tried making a turn() function, but I miserably failed.

On a side note, I try to avoid any use of external packages. I have never touched jQuery or Angular2, and per now I won't use it. If any of you know a solution using it, though, feel free to share it. I don't care much about backwards-compatibility, either, tbh.

答:
Instead of a while loop, use the decision to set a new timeout as the flow control in the program.  Also, I don't see a need for stats to update every 5 ms.  Just include showStats() in the battle when things change.   Something like:

```<code>function battleStep() {
    current_hp -= enemy_atk_dmg*enemy_crit_pwr*crit_chance/100 + def_pwr/2;
    enemy_hp -= attack_dmg*crit_power*crit_chance/100 - enemy_def_pwr/2;
    if(current_hp < 0){ current_hp = 0; }
    if(enemy_hp < 0){ enemy_hp = 0; }
    // now update the DOM with the new values
    showStats();
    if (current_hp == 0){
        // Die
    } else if (enemy_current_hp == 0){
        // Win battle, proceed.
        spawnenemy();
    } else {
        setTimeout(battleStep, 1000);
    }
}

function battle() {
    // initialize anything you need for the battle to start
    battleStep();
}
</code>```

Title: Javascript delay between turns

Body:
I'm trying to make a turn-based battle system in a RPG I'm building. I want the player to be able to see (through CSS) how his own and enemy's life lowers throughout the fight.
This is my current code:

// Defining the variables globally for accessibility.
var enemy_max_hp = 0;
var enemy_hp = 0;
var enemy_atk_dmg = 0;
var enemy_def_pwr = 0;
var enemy_crit_chance = 0;
var enemy_crit_pwr = 0.0;

function battle() {
    while(current_hp > 0 || enemy_current_hp <= 0){
        //setTimeout(function(){
            current_hp -= enemy_atk_dmg*enemy_crit_pwr*crit_chance/100 + def_pwr/2;
            enemy_hp -= attack_dmg*crit_power*crit_chance/100 - enemy_def_pwr/2;

            if(current_hp < 0){ current_hp = 0; }
            if(enemy_hp < 0){ enemy_hp = 0; }

            if (current_hp == 0){
                // Die
            }

            if (enemy_current_hp == 0){
                // Win battle, proceed.
                    spawnenemy();
            }
        //}, 1000);
    }
}

function spawnenemy() {
    enemy_max_hp = 150;
    enemy_hp = 150;
    enemy_atk_dmg = 5;
    enemy_def_pwr = 3;
    enemy_crit_chance = 0;
    enemy_crit_pwr = 0;
}

I'm updating the user's data via another script:

var max_hp = 100;
var current_hp = 100;
var attack_dmg = 5;
var defense_power = 4;
var crit_chance = 0;
var crit_power = 0.0;

function showStats(){
    document.getElementById("max_hp").innerHTML = max_hp;
    document.getElementById("current_hp").innerHTML = current_hp;
    document.getElementById("attack_dmg").innerHTML = attack_dmg;
    document.getElementById("defense_power").innerHTML = defense_power;
    document.getElementById("crit_chance").innerHTML = crit_chance + '%';
    document.getElementById("crit_power").innerHTML = crit_power;
}
setInterval(showStats, 5);

If I run the code, as is, the battle ends in matter of an eyeblink, and health runs from 100 to 0 in an instance. I figured adding the setTimeout() function would work, but it just crashes the webpage. What should I do?

Also, the battle function is called (per now) via a button onclick call. I tried making a turn() function, but I miserably failed.

On a side note, I try to avoid any use of external packages. I have never touched jQuery or Angular2, and per now I won't use it. If any of you know a solution using it, though, feel free to share it. I don't care much about backwards-compatibility, either, tbh.

Body:
Instead of a while loop, use the decision to set a new timeout as the flow control in the program.  Also, I don't see a need for stats to update every 5 ms.  Just include showStats() in the battle when things change.   Something like:

function battleStep() {
    current_hp -= enemy_atk_dmg*enemy_crit_pwr*crit_chance/100 + def_pwr/2;
    enemy_hp -= attack_dmg*crit_power*crit_chance/100 - enemy_def_pwr/2;
    if(current_hp < 0){ current_hp = 0; }
    if(enemy_hp < 0){ enemy_hp = 0; }
    // now update the DOM with the new values
    showStats();
    if (current_hp == 0){
        // Die
    } else if (enemy_current_hp == 0){
        // Win battle, proceed.
        spawnenemy();
    } else {
        setTimeout(battleStep, 1000);
    }
}

function battle() {
    // initialize anything you need for the battle to start
    battleStep();
}


问:
Accessing django models from a new script
I have seen many answers on how to use django models outside the project. But I have no success with any. I was trying to implement this answer but I get an error. I have created a new file "script.py" inside my app.

script.py

```<code>from django.conf import settings
settings.configure(
    DATABASE_ENGINE = 'sqlite3',
    DATABASE_NAME = '/home/shivam/study/Python/automation/project/db.sqlite3',
    DATABASE_USER = '',
    DATABASE_PASSWORD = '',
    DATABASE_HOST = '',
    DATABASE_PORT = '',
    TIME_ZONE = 'America/New_York',
)
from models import *
</code>```

When I run this script, I get an error.

```<code>Traceback (most recent call last):
  File "script.py", line 11, in <module>
    from models import *
  File "/home/shivam/study/Python/automation/project/videos/models.py", line 11, in <module>
    class video(models.Model):
  File "/home/shivam/study/Python/automation/env/local/lib/python2.7/site-packages/django/db/models/base.py", line 105, in __new__
    app_config = apps.get_containing_app_config(module)
  File "/home/shivam/study/Python/automation/env/local/lib/python2.7/site-packages/django/apps/registry.py", line 237, in get_containing_app_config
    self.check_apps_ready()
  File "/home/shivam/study/Python/automation/env/local/lib/python2.7/site-packages/django/apps/registry.py", line 124, in check_apps_ready
    raise AppRegistryNotReady("Apps aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
</code>```

Can somebody help me with this?

答:
The following solution work from a script located in the directory where your manage.py is located:

```<code>import os
from django.conf import settings
from django.apps import apps

conf = {
    'INSTALLED_APPS': [
        'Demo'
    ],
    'DATABASES': {
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': os.path.join('.', 'db.sqlite3'),
        }
    }
}

settings.configure(**conf)
apps.populate(settings.INSTALLED_APPS)
</code>```

Replace Demo with your app name and put the correct database configuration for your app. This solution worked for me on Django 1.9.

Body:
I have seen many answers on how to use django models outside the project. But I have no success with any. I was trying to implement this answer but I get an error. I have created a new file "script.py" inside my app.

script.py

from django.conf import settings
settings.configure(
    DATABASE_ENGINE = 'sqlite3',
    DATABASE_NAME = '/home/shivam/study/Python/automation/project/db.sqlite3',
    DATABASE_USER = '',
    DATABASE_PASSWORD = '',
    DATABASE_HOST = '',
    DATABASE_PORT = '',
    TIME_ZONE = 'America/New_York',
)
from models import *

When I run this script, I get an error.

Traceback (most recent call last):
  File "script.py", line 11, in <module>
    from models import *
  File "/home/shivam/study/Python/automation/project/videos/models.py", line 11, in <module>
    class video(models.Model):
  File "/home/shivam/study/Python/automation/env/local/lib/python2.7/site-packages/django/db/models/base.py", line 105, in __new__
    app_config = apps.get_containing_app_config(module)
  File "/home/shivam/study/Python/automation/env/local/lib/python2.7/site-packages/django/apps/registry.py", line 237, in get_containing_app_config
    self.check_apps_ready()
  File "/home/shivam/study/Python/automation/env/local/lib/python2.7/site-packages/django/apps/registry.py", line 124, in check_apps_ready
    raise AppRegistryNotReady("Apps aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.

Can somebody help me with this?

Body:
The following solution work from a script located in the directory where your manage.py is located:

import os
from django.conf import settings
from django.apps import apps

conf = {
    'INSTALLED_APPS': [
        'Demo'
    ],
    'DATABASES': {
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': os.path.join('.', 'db.sqlite3'),
        }
    }
}

settings.configure(**conf)
apps.populate(settings.INSTALLED_APPS)

Replace Demo with your app name and put the correct database configuration for your app. This solution worked for me on Django 1.9.


问:
Pass Information through TabBarController Swift
Have a Table View Controller that will pass an ID field onto a View Controller in order to retrieve detail however in between the two controllers is a Tab Bar Controller.  I am unsure how I am to get the information passed between the two.  Was attempting to use a Segue but the value is blank once it gets to the detail controller.

EventBarTableViewCell.swift

```<code>override func prepare(for segue: UIStoryboardSegue, sender: Any?)            {
    if segue.identifier == "showEventDetail" {
        if let IndexPath = self.tableView.indexPathForSelectedRow {
            let controller = segue.destination as? eventDetailViewController

            controller?.inTradeShowID = (events?[IndexPath.row].tradeshowID!)!
            controller?.viaSegue = (events?[IndexPath.row].tradeshowID!)!
            //controller?.performSegue(withIdentifier: "tradeShowID", sender: self)
            //if shouldShowSearchResults {
            //    controller?.viaSegue = filteredArray[IndexPath.row].charterNum!
            //} else {
            //    controller?.viaSegue = repositories[IndexPath.row].charterNum!
            //}
        }
    }
}
</code>```

eventDetailViewController.swift

```<code>var viaSegue = ""
var inTradeShowID = ""

 override func viewDidLoad() {
    super.viewDidLoad()

    inTradeShowID = self.viaSegue
}
</code>```

Could use some help.

答:
You are segueing to a Tab Bar Controller, not to your "display" view, so you need to "drill down" so to speak:</p>

```<code>override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    if segue.identifier == "showEventDetail" {

        if let IndexPath = self.tableView.indexPathForSelectedRow {

            // we're segueing to a Tab Bar Controller
            if let tabBarVC = segue.destination as? UITabBarController {

                // get the first view controller of the Tab Bar Controller
                // *that* is where you want to "pass" your data
                if let controller = tabBarVC.viewControllers?.first as? eventDetailViewController {

                    // either should work
                    controller.inTradeShowID = (events?[IndexPath.row].tradeshowID!)!
                    controller.viaSegue = (events?[IndexPath.row].tradeshowID!)!

                }  //end if let controller = tabBarVC.viewControllers?.first as? eventDetailViewController

            }  //end if let tabBarVC = segue.destination as? UITabBarController

        }  //end if let IndexPath = self.tableView.indexPathForSelectedRow

    }  //end if segue.identifier == "showEventDetail"
}
</code>```

Body:
Have a Table View Controller that will pass an ID field onto a View Controller in order to retrieve detail however in between the two controllers is a Tab Bar Controller.  I am unsure how I am to get the information passed between the two.  Was attempting to use a Segue but the value is blank once it gets to the detail controller.

EventBarTableViewCell.swift

override func prepare(for segue: UIStoryboardSegue, sender: Any?)            {
    if segue.identifier == "showEventDetail" {
        if let IndexPath = self.tableView.indexPathForSelectedRow {
            let controller = segue.destination as? eventDetailViewController

            controller?.inTradeShowID = (events?[IndexPath.row].tradeshowID!)!
            controller?.viaSegue = (events?[IndexPath.row].tradeshowID!)!
            //controller?.performSegue(withIdentifier: "tradeShowID", sender: self)
            //if shouldShowSearchResults {
            //    controller?.viaSegue = filteredArray[IndexPath.row].charterNum!
            //} else {
            //    controller?.viaSegue = repositories[IndexPath.row].charterNum!
            //}
        }
    }
}

eventDetailViewController.swift

var viaSegue = ""
var inTradeShowID = ""

 override func viewDidLoad() {
    super.viewDidLoad()

    inTradeShowID = self.viaSegue
}

Could use some help.

Body:
You are segueing to a Tab Bar Controller, not to your "display" view, so you need to "drill down" so to speak:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    if segue.identifier == "showEventDetail" {

        if let IndexPath = self.tableView.indexPathForSelectedRow {

            // we're segueing to a Tab Bar Controller
            if let tabBarVC = segue.destination as? UITabBarController {

                // get the first view controller of the Tab Bar Controller
                // *that* is where you want to "pass" your data
                if let controller = tabBarVC.viewControllers?.first as? eventDetailViewController {

                    // either should work
                    controller.inTradeShowID = (events?[IndexPath.row].tradeshowID!)!
                    controller.viaSegue = (events?[IndexPath.row].tradeshowID!)!

                }  //end if let controller = tabBarVC.viewControllers?.first as? eventDetailViewController

            }  //end if let tabBarVC = segue.destination as? UITabBarController

        }  //end if let IndexPath = self.tableView.indexPathForSelectedRow

    }  //end if segue.identifier == "showEventDetail"
}


问:
Load standart output and parse it to Image
I have graphviz dot.exe file that I call with parameter -Tpng (output type is png, but I don't care if it is in png, bmp, or any other). I start it in C# code:

```<code>ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = path;
psi.UseShellExecute = false;
psi.Arguments = "-Tpng";
psi.RedirectStandardInput = true;
psi.RedirectStandardOutput = true;
psi.CreateNoWindow = true;
Process p = Process.Start(psi);
</code>```

Then, I write input

```<code>p.StandardInput.WriteLine(input);
</code>```

input is defined before, it's a string. Input is valid, tested manually.

Then, I need to read output that graphviz prints into standart output and parse it to Image.

I've tried to read memory stream, but I was either unable to read it, or, after reading, the memory stream was locked (threw exception when tried Image.FromStream(myMemoryStream);).
I was able to load output to string

```<code>string output = "";
while (true)
{
     string newOutput = p.StandardOutput.ReadLine();
     output += newOutput;
     if (newOutput == String.Empty)
        break;
}
</code>```

I've tried to parse this string as described in this answer, but it threw exception (string is not valid).

How can I get Image from the dot.exe output?

答:
From the comments it seems the program is expecting the StandardInput to be finished before returning the content. Close the StandardInput to achieve it:

```<code>p.StandardInput.WriteLine(input);
p.StandardInput.BaseStream.Close();
</code>```

Body:
I have graphviz dot.exe file that I call with parameter -Tpng (output type is png, but I don't care if it is in png, bmp, or any other). I start it in C# code:

ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = path;
psi.UseShellExecute = false;
psi.Arguments = "-Tpng";
psi.RedirectStandardInput = true;
psi.RedirectStandardOutput = true;
psi.CreateNoWindow = true;
Process p = Process.Start(psi);

Then, I write input

p.StandardInput.WriteLine(input);

input is defined before, it's a string. Input is valid, tested manually.

Then, I need to read output that graphviz prints into standart output and parse it to Image.

I've tried to read memory stream, but I was either unable to read it, or, after reading, the memory stream was locked (threw exception when tried Image.FromStream(myMemoryStream);).
I was able to load output to string

string output = "";
while (true)
{
     string newOutput = p.StandardOutput.ReadLine();
     output += newOutput;
     if (newOutput == String.Empty)
        break;
}

I've tried to parse this string as described in this answer, but it threw exception (string is not valid).

How can I get Image from the dot.exe output?

Body:
From the comments it seems the program is expecting the StandardInput to be finished before returning the content. Close the StandardInput to achieve it:

p.StandardInput.WriteLine(input);
p.StandardInput.BaseStream.Close();


问:
XSLT Newbie - Looping and Matching Elements
Brand new to XSLT but managed to hack my way through to extract the data I needed...

I'm now stuck on extracting the data into a required format to upload into a database...  I need to match each PGBLK with its corresponding TASK (please see example below).

Pretty sure I want to use XSLT Looping but to be honest I'm not sure, any assistance would be greatly appreciated!

Here's the source XML:

```<code><?xml version="1.0" encoding="UTF-8"?>
 <PGBLK CHAPNBR="05" CHG="U" CONFNBR="0" PGBLKNBR="2" REVDATE="20160608" SECTNBR="00" SUBJNBR="00">
  <TASK CHAPNBR="05" CHG="R" FUNC="912" PGBLKNBR="2" REVDATE="20160520" SECTNBR="00" SEQ="001"
    SUBJNBR="00"/>
    <EFFECT EFFRG="000" EFFTEXT="ALL"/>
  <TASK CHAPNBR="05" CHG="R" FUNC="910" PGBLKNBR="2" REVDATE="20160520" SECTNBR="00" SEQ="801"
    SUBJNBR="00">
    <EFFECT EFFRG="000" EFFTEXT="ALL"/>
   </TASK>
</PGBLK>
</code>```

Current XSLT:

```<code><xsl:template match="RTM">

 <REFERENCES>
    <xsl:attribute name="DATE">
        <xsl:value-of select="current-date()"/>
    </xsl:attribute>
        <xsl:for-each select="//PGBLK">
            <REF>
             <PGBLK>
              <xsl:value-of select="concat(@CHAPNBR, '-', @SECTNBR, '-', @SUBJNBR, '-', @PGBLKNBR, '-0')"/>
                </PGBLK>
            <TASK>
             <xsl:value-of select="TASK/concat(@CHAPNBR, '-', @SECTNBR, '-', @SUBJNBR, '-', @FUNC, '-', @SEQ, ',')"/>
            </TASK>
            </REF>
        </xsl:for-each>
    </REFERENCES>
</xsl:template>
</code>```

Current XML Output:

```<code><REFERENCES DATE="2017-11-15-06:00">
 <REF>
  <PGBLK>05-00-00-2-0</PGBLK>
  <TASK>05-00-00-912-001, 05-00-00-910-801,</TASK>
 </REF>
</REFERENCES>
</code>```

Desired XML Output:

```<code><REFERENCES DATE="2017-11-15-06:00">
 <REF>
  <PGBLK>05-00-00-2-0</PGBLK><TASK>05-00-00-912-001</TASK>
  <PGBLK>05-00-00-2-0</PGBLK><TASK>05-00-00-910-801</TASK>
 </REF>
</REFERENCES>
</code>```

答:
With respect to your primary question of how to map <TASK> elements to their parent <PGBLK>elements, that's pretty easy: select the <TASK>s for transformation, and inside their template either

access the parent via an XPath expression (e.g. ..)

provide parent data via a variable from a lexically surrounding scope or via a template parameter provided by the template's dynamic scope.

The process is slightly complicated by the possibility that a <PGBLK> might have zero <TASK>'s, but it's not that hard.  Here's a variation that sticks close to your original template:

```<code><xsl:template match="RTM">
  <!-- NOTE: no need for xsl-attribute unless the attribute name
       or namespace is dynamically determined -->
  <REFERENCES DATE="{current-date()}">
    <xsl:for-each select=".//PGBLK">
      <!-- capture the relevant details of the current PGBLK for re-use
           in nested contexts -->
      <xsl:variable name="blk-code"
          select="concat(@CHAPNBR, '-', @SECTNBR, '-', @SUBJNBR, '-', @PGBLKNBR, '-0')"/>

      <REF>

        <!-- transform all the PGBLK's TASKs, providing a PGBLK with each: -->
        <xsl:for-each select="TASK">
          <PGBLK>
            <xsl:value-of select="$blk-code"/>
          </PGBLK>
          <TASK>
            <xsl:value-of select="concat(@CHAPNBR, '-', @SECTNBR, '-', @SUBJNBR, '-', @FUNC, '-', @SEQ)"/>
          </TASK>
        </xsl:for-each>

        <!-- handle the case of a PGBLK without any TASKs (in which case the
             for-each will not have added anything to the result tree: -->
        <xsl:if test="not(TASK)">
          <PGBLK>
            <xsl:value-of select="$blk-code"/>
          </PGBLK>
          <TASK/>
        </xsl:if>

      </REF>
    </xsl:for-each>
  </REFERENCES>
</xsl:template>
</code>```

Body:
Brand new to XSLT but managed to hack my way through to extract the data I needed...

I'm now stuck on extracting the data into a required format to upload into a database...  I need to match each PGBLK with its corresponding TASK (please see example below).

Pretty sure I want to use XSLT Looping but to be honest I'm not sure, any assistance would be greatly appreciated!

Here's the source XML:

<?xml version="1.0" encoding="UTF-8"?>
 <PGBLK CHAPNBR="05" CHG="U" CONFNBR="0" PGBLKNBR="2" REVDATE="20160608" SECTNBR="00" SUBJNBR="00">
  <TASK CHAPNBR="05" CHG="R" FUNC="912" PGBLKNBR="2" REVDATE="20160520" SECTNBR="00" SEQ="001"
    SUBJNBR="00"/>
    <EFFECT EFFRG="000" EFFTEXT="ALL"/>
  <TASK CHAPNBR="05" CHG="R" FUNC="910" PGBLKNBR="2" REVDATE="20160520" SECTNBR="00" SEQ="801"
    SUBJNBR="00">
    <EFFECT EFFRG="000" EFFTEXT="ALL"/>
   </TASK>
</PGBLK>

Current XSLT:

<xsl:template match="RTM">

 <REFERENCES>
    <xsl:attribute name="DATE">
        <xsl:value-of select="current-date()"/>
    </xsl:attribute>
        <xsl:for-each select="//PGBLK">
            <REF>
             <PGBLK>
              <xsl:value-of select="concat(@CHAPNBR, '-', @SECTNBR, '-', @SUBJNBR, '-', @PGBLKNBR, '-0')"/>
                </PGBLK>
            <TASK>
             <xsl:value-of select="TASK/concat(@CHAPNBR, '-', @SECTNBR, '-', @SUBJNBR, '-', @FUNC, '-', @SEQ, ',')"/>
            </TASK>
            </REF>
        </xsl:for-each>
    </REFERENCES>
</xsl:template>

Current XML Output:

<REFERENCES DATE="2017-11-15-06:00">
 <REF>
  <PGBLK>05-00-00-2-0</PGBLK>
  <TASK>05-00-00-912-001, 05-00-00-910-801,</TASK>
 </REF>
</REFERENCES>

Desired XML Output:

<REFERENCES DATE="2017-11-15-06:00">
 <REF>
  <PGBLK>05-00-00-2-0</PGBLK><TASK>05-00-00-912-001</TASK>
  <PGBLK>05-00-00-2-0</PGBLK><TASK>05-00-00-910-801</TASK>
 </REF>
</REFERENCES>

Body:
With respect to your primary question of how to map <TASK> elements to their parent <PGBLK>elements, that's pretty easy: select the <TASK>s for transformation, and inside their template either

access the parent via an XPath expression (e.g. ..)

provide parent data via a variable from a lexically surrounding scope or via a template parameter provided by the template's dynamic scope.

The process is slightly complicated by the possibility that a <PGBLK> might have zero <TASK>'s, but it's not that hard.  Here's a variation that sticks close to your original template:

<xsl:template match="RTM">
  <!-- NOTE: no need for xsl-attribute unless the attribute name
       or namespace is dynamically determined -->
  <REFERENCES DATE="{current-date()}">
    <xsl:for-each select=".//PGBLK">
      <!-- capture the relevant details of the current PGBLK for re-use
           in nested contexts -->
      <xsl:variable name="blk-code"
          select="concat(@CHAPNBR, '-', @SECTNBR, '-', @SUBJNBR, '-', @PGBLKNBR, '-0')"/>

      <REF>

        <!-- transform all the PGBLK's TASKs, providing a PGBLK with each: -->
        <xsl:for-each select="TASK">
          <PGBLK>
            <xsl:value-of select="$blk-code"/>
          </PGBLK>
          <TASK>
            <xsl:value-of select="concat(@CHAPNBR, '-', @SECTNBR, '-', @SUBJNBR, '-', @FUNC, '-', @SEQ)"/>
          </TASK>
        </xsl:for-each>

        <!-- handle the case of a PGBLK without any TASKs (in which case the
             for-each will not have added anything to the result tree: -->
        <xsl:if test="not(TASK)">
          <PGBLK>
            <xsl:value-of select="$blk-code"/>
          </PGBLK>
          <TASK/>
        </xsl:if>

      </REF>
    </xsl:for-each>
  </REFERENCES>
</xsl:template>


问:
Best practice for duration and animationCurve for flip animations on iPhone (UIViewAnimationTransitionFlipFromRIght)?
Sometimes I use a flip animation on the iPhone, and I play with it until I get the animation duration to feel right.

Is there any definite values, or arguments for values, that I should be using to set the duration or curve of the animation?

答: Is there any reason you need to set the duration at all?  If you use the standard [UIView beginAnimations:nil context:nil] it will already have a duration set up of 0.25 seconds.


问:
fade in/out highlight to zebra striped table
I have a table with a number of data rows, which is zebra striped using the following CSS:

```<code>#datatable tr:nth-child(odd) {
background-color: #fff;
}

#datatable tr:nth-child(even) {
background-color: #fafafa;
}
</code>```

The data in the table is continually updated via ajax calls, and I want to add a temporary highlight to particular rows where data has changed.

I want this new colour (red if the data value has decreased, green if the data value has increased), to nicely fade in, stay for a second or two, then fade back out to the original row colour again.

I have this working just now using jQuery and CSS;

```<code>$('#row_id').addClass("temphighlight");
setTimeout(clearHighlighting, 3000);

function clearHighlighting(){
$("#row_id").removeClass("temphighlight");
}

#datatable tr.temphighlight {
background-color: #c6efce;
transition: background 1.0s ease;
}
</code>```

This works for the fade in, but after the delay, the CSS class is removed immediately and there is no fade out.

How can I get this highlighting to have a better effect, where it fades in and also fades out?

I have checked several similar SO questions, but the answers either don't work or don't apply - such as suggestions that you animate a fade to white, which doesn't work for me because my rows are alternatively coloured differently due to the row striping.

答:
you can change opacity

```<code>myFunction();
var val = 1.0;
function myFunction() {

val -= 0.02;
    $('.myDiv').css("opacity", val);
    setTimeout(myFunction, 20);
}
</code>```

https://codepen.io/piscu/pen/LOzNqa

Body:
I have a table with a number of data rows, which is zebra striped using the following CSS:

#datatable tr:nth-child(odd) {
background-color: #fff;
}

#datatable tr:nth-child(even) {
background-color: #fafafa;
}

The data in the table is continually updated via ajax calls, and I want to add a temporary highlight to particular rows where data has changed.

I want this new colour (red if the data value has decreased, green if the data value has increased), to nicely fade in, stay for a second or two, then fade back out to the original row colour again.

I have this working just now using jQuery and CSS;

$('#row_id').addClass("temphighlight");
setTimeout(clearHighlighting, 3000);

function clearHighlighting(){
$("#row_id").removeClass("temphighlight");
}

#datatable tr.temphighlight {
background-color: #c6efce;
transition: background 1.0s ease;
}

This works for the fade in, but after the delay, the CSS class is removed immediately and there is no fade out.

How can I get this highlighting to have a better effect, where it fades in and also fades out?

I have checked several similar SO questions, but the answers either don't work or don't apply - such as suggestions that you animate a fade to white, which doesn't work for me because my rows are alternatively coloured differently due to the row striping.

Body:
you can change opacity

myFunction();
var val = 1.0;
function myFunction() {

val -= 0.02;
    $('.myDiv').css("opacity", val);
    setTimeout(myFunction, 20);
}

https://codepen.io/piscu/pen/LOzNqa


问:
MSSQL to Oracle
I'm having difficulty converting this line of MSSQL:

```<code>Union All
Select 1,table_name,3,4,5,6,7,8
from (select top 1 table_name
      from information_schema.tables
      order by 1) as subname
order by 1 desc
</code>```

to Oracle.

So far I have:

```<code>Union All
Select 1,table_name,3,4,5,6,7,8
from
   (select *
    from
      (select table_name
       from all_tables order by 1)
    where rownum <= 1) as subname
order by 1 desc
</code>```

The error that's thrown is

ORA-00933: SQL command not properly ended

Any help would be appreciated!

Edit:

Solution found, see first comment.

Solution:

```<code>Union All Select 1,table_name,3,4,5,6,7,8 from (select * from (select table_name from all_tables order by 1) where rownum <= 1) subname order by 1 desc--
</code>```

答:
```<code>    SELECT 1,table_name,3,4,5,6,7,8
    FROM (
       SELECT *
       FROM (
          SELECT table_name
          FROM all_tables
          ORDER BY 1)
       WHERE rownum <= 1) subname
    ORDER BY 1 desc;
</code>```

In order to name the subquery in Oracle, you do not use the as keyword. Just place the name directly after the parentheses.

Title: MSSQL to Oracle

Body:
I'm having difficulty converting this line of MSSQL:

Union All
Select 1,table_name,3,4,5,6,7,8
from (select top 1 table_name
      from information_schema.tables
      order by 1) as subname
order by 1 desc

to Oracle.

So far I have:

Union All
Select 1,table_name,3,4,5,6,7,8
from
   (select *
    from
      (select table_name
       from all_tables order by 1)
    where rownum <= 1) as subname
order by 1 desc

The error that's thrown is

ORA-00933: SQL command not properly ended

Any help would be appreciated!

Edit:

Solution found, see first comment.

Solution:

Union All Select 1,table_name,3,4,5,6,7,8 from (select * from (select table_name from all_tables order by 1) where rownum <= 1) subname order by 1 desc--

Body:
    SELECT 1,table_name,3,4,5,6,7,8
    FROM (
       SELECT *
       FROM (
          SELECT table_name
          FROM all_tables
          ORDER BY 1)
       WHERE rownum <= 1) subname
    ORDER BY 1 desc;

In order to name the subquery in Oracle, you do not use the as keyword. Just place the name directly after the parentheses.


问:
Directly delete selected record in gird from database
I want delete selected row directly from database. I wrote this code but it doesn't work correctly.

Here is my code but it doesn't delete record from my SQL server local db;

```<code>MyDataSet.Tables["ProductTable"].Rows[gridView1.GetFocusedDataSourceRowIndex()].Delete();
</code>```

答:
Try this solution :</p>

```<code>myDataSet = myWS.LookUp(sessionUserID, "UserID", "Users"); // Adapt this to the way you populate the dataset
            myDataTable = Tables["ProductTable"];
            DataRow drCurrent =MyDataSet.Tables["ProductTable"].Rows[gridView1.GetFocusedDataSourceRowIndex()]
            myDataSet.AcceptChanges()
            drCurrent.Delete();
            myWS.UpdateDB(myDataSet);
</code>```

Body:
I want delete selected row directly from database. I wrote this code but it doesn't work correctly.

Here is my code but it doesn't delete record from my SQL server local db;

MyDataSet.Tables["ProductTable"].Rows[gridView1.GetFocusedDataSourceRowIndex()].Delete();

Body:
Try this solution :

myDataSet = myWS.LookUp(sessionUserID, "UserID", "Users"); // Adapt this to the way you populate the dataset
            myDataTable = Tables["ProductTable"];
            DataRow drCurrent =MyDataSet.Tables["ProductTable"].Rows[gridView1.GetFocusedDataSourceRowIndex()]
            myDataSet.AcceptChanges()
            drCurrent.Delete();
            myWS.UpdateDB(myDataSet);


答:
If you're in the Browser you can use DOMparser() to turn this into a real dom object, then you can call the method you want to get elements from it.

var htmlPage = `

testing but not required

     i want to pull this whole block from parent

      test 2

`;

var parser=new DOMParser();
var htmlDoc=parser.parseFromString(htmlPage, "text/html");

console.log(htmlDoc.getElementById("container"))
console.log(htmlDoc.getElementById("container").innerHTML)```

Title: Javascript pull content from variable by id

Body:
I am trying to pull content inside a variable using plain java script.
I am trying to get only part of the variable with an id.
In this example I am trying to pull only part of html with id ‘container’.

My fiddle
https://jsfiddle.net/a2ngc9jv/2/

var htmlPage = `

testing but not required

     i want to pull this whole block from parent

      test 2

`;

console.log(htmlPage.getElementById("container"))
console.log(document.getElementById("container"))

Body:
If you're in the Browser you can use DOMparser() to turn this into a real dom object, then you can call the method you want to get elements from it.

var htmlPage = `
<html>
<div>
testing but not required
</div>
  <div id="container">
    <p>
     i want to pull this whole block from parent
    </p>
    <p>
      test 2
    </p>
  </div>

</html>`;

var parser=new DOMParser();
var htmlDoc=parser.parseFromString(htmlPage, "text/html");

console.log(htmlDoc.getElementById("container"))
console.log(htmlDoc.getElementById("container").innerHTML)


问:
App crashes when i apply crashlytics on it
App crashes when i apply crashlytics on it

```<code>FATAL EXCEPTION: main

Process: com.ehs.pk, PID: 20963
java.lang.RuntimeException: Unable to get provider com.crashlytics.android.CrashlyticsInitProvider: java.lang.ClassNotFoundException: Didn't find class "com.crashlytics.android.CrashlyticsInitProvider" on path: DexPathList[[zip file "/data/app/com.ehs.pk-8.apk"],nativeLibraryDirectories=[/data/app-lib/com.ehs.pk-8, /vendor/lib, /system/lib]]
    at android.app.ActivityThread.installProvider(ActivityThread.java:4993)
    at android.app.ActivityThread.installContentProviders(ActivityThread.java:4585)
    at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4499)
    at android.app.ActivityThread.access$1500(ActivityThread.java:157)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1307)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:157)
    at android.app.ActivityThread.main(ActivityThread.java:5293)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:515)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
    at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ClassNotFoundException: Didn't find class "com.crashlytics.android.CrashlyticsInitProvider" on path: DexPathList[[zip file "/data/app/com.ehs.pk-8.apk"],nativeLibraryDirectories=[/data/app-lib/com.ehs.pk-8, /vendor/lib, /system/lib]]
    at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:67)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:497)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:457)
    at android.app.ActivityThread.installProvider(ActivityThread.java:4978)
    at android.app.ActivityThread.installContentProviders(ActivityThread.java:4585)
    at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4499)
    at android.app.ActivityThread.access$1500(ActivityThread.java:157)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1307)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:157)
    at android.app.ActivityThread.main(ActivityThread.java:5293)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:515)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
    at dalvik.system.NativeStart.main(Native Method)
</code>```

答:
By looking at this part...

Didn't find class ... on path: DexPathList ... dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:67)

of the stack trace you can figure out that your test device is probably pre-Lollipop (Android 5.0) and that you just hit the 64k limit. You can fix it as described here.

Body:
App crashes when i apply crashlytics on it

FATAL EXCEPTION: main

Process: com.ehs.pk, PID: 20963
java.lang.RuntimeException: Unable to get provider com.crashlytics.android.CrashlyticsInitProvider: java.lang.ClassNotFoundException: Didn't find class "com.crashlytics.android.CrashlyticsInitProvider" on path: DexPathList[[zip file "/data/app/com.ehs.pk-8.apk"],nativeLibraryDirectories=[/data/app-lib/com.ehs.pk-8, /vendor/lib, /system/lib]]
    at android.app.ActivityThread.installProvider(ActivityThread.java:4993)
    at android.app.ActivityThread.installContentProviders(ActivityThread.java:4585)
    at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4499)
    at android.app.ActivityThread.access$1500(ActivityThread.java:157)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1307)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:157)
    at android.app.ActivityThread.main(ActivityThread.java:5293)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:515)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
    at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ClassNotFoundException: Didn't find class "com.crashlytics.android.CrashlyticsInitProvider" on path: DexPathList[[zip file "/data/app/com.ehs.pk-8.apk"],nativeLibraryDirectories=[/data/app-lib/com.ehs.pk-8, /vendor/lib, /system/lib]]
    at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:67)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:497)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:457)
    at android.app.ActivityThread.installProvider(ActivityThread.java:4978)
    at android.app.ActivityThread.installContentProviders(ActivityThread.java:4585)
    at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4499)
    at android.app.ActivityThread.access$1500(ActivityThread.java:157)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1307)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:157)
    at android.app.ActivityThread.main(ActivityThread.java:5293)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:515)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
    at dalvik.system.NativeStart.main(Native Method)