问:
How to compile Tensorflow with SSE4.2 and AVX instructions?
This is the message received from running a script to check if Tensorflow is working:

```<code>I tensorflow/stream_executor/dso_loader.cc:125] successfully opened CUDA library libcublas.so.8.0 locally
I tensorflow/stream_executor/dso_loader.cc:125] successfully opened CUDA library libcudnn.so.5 locally
I tensorflow/stream_executor/dso_loader.cc:125] successfully opened CUDA library libcufft.so.8.0 locally
I tensorflow/stream_executor/dso_loader.cc:125] successfully opened CUDA library libcuda.so.1 locally
I tensorflow/stream_executor/dso_loader.cc:125] successfully opened CUDA library libcurand.so.8.0 locally
W tensorflow/core/platform/cpu_feature_guard.cc:95] The TensorFlow library wasn't compiled to use SSE4.2 instructions, but these are available on your machine and could speed up CPU computations.
W tensorflow/core/platform/cpu_feature_guard.cc:95] The TensorFlow library wasn't compiled to use AVX instructions, but these are available on your machine and could speed up CPU computations.
I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:910] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero
</code>```

I noticed that it has mentioned SSE4.2 and AVX,

What are SSE4.2 and AVX?

How do these SSE4.2 and AVX improve CPU computations for Tensorflow tasks.

How to make Tensorflow compile using the two libraries?

答:
Let me answer your 3rd question first:

If you want to run a self-compiled version within a conda-env, you can. These are the general instructions I run to get tensorflow to install on my system with additional instructions. Note: This build was for an AMD A10-7850 build (check your CPU for what instructions are supported...it may differ) running Ubuntu 16.04 LTS. I use Python 3.5 within my conda-env. Credit goes to the tensorflow source install page and the answers provided above.

```<code>git clone https://github.com/tensorflow/tensorflow
# Install Bazel
# https://bazel.build/versions/master/docs/install.html
sudo apt-get install python3-numpy python3-dev python3-pip python3-wheel
# Create your virtual env with conda.
source activate YOUR_ENV
pip install six numpy wheel, packaging, appdir
# Follow the configure instructions at:
# https://www.tensorflow.org/install/install_sources
# Build your build like below. Note: Check what instructions your CPU
# support. Also. If resources are limited consider adding the following
# tag --local_resources 2048,.5,1.0 . This will limit how much ram many
# local resources are used but will increase time to compile.
bazel build -c opt --copt=-mavx --copt=-msse4.1 --copt=-msse4.2  -k //tensorflow/tools/pip_package:build_pip_package
# Create the wheel like so:
bazel-bin/tensorflow/tools/pip_package/build_pip_package /tmp/tensorflow_pkg
# Inside your conda env:
pip install /tmp/tensorflow_pkg/NAME_OF_WHEEL.whl
# Then install the rest of your stack
pip install keras jupyter etc. etc.
</code>```

As to your 2nd question:

A self-compiled version with optimizations are well worth the effort in my opinion. On my particular setup, calculations that used to take 560-600 seconds now only take about 300 seconds! Although the exact numbers will vary, I think you can expect about a 35-50% speed increase in general on your particular setup.

Lastly your 1st question:

A lot of the answers have been provided above already. To summarize: AVX, SSE4.1, SSE4.2, MFA are different kinds of extended instruction sets on X86 CPUs. Many contain optimized instructions for processing matrix or vector operations.

I will highlight my own misconception to hopefully save you some time: It's not that SSE4.2 is a newer version of instructions superseding SSE4.1. SSE4 = SSE4.1 (a set of 47 instructions) + SSE4.2 (a set of 7 instructions).

In the context of tensorflow compilation, if you computer supports AVX2 and AVX, and SSE4.1 and SSE4.2, you should put those optimizing flags in for all. Don't do like I did and just go with SSE4.2 thinking that it's newer and should superseed SSE4.1. That's clearly WRONG! I had to recompile because of that which cost me a good 40 minutes.

Body:
This is the message received from running a script to check if Tensorflow is working:

I tensorflow/stream_executor/dso_loader.cc:125] successfully opened CUDA library libcublas.so.8.0 locally
I tensorflow/stream_executor/dso_loader.cc:125] successfully opened CUDA library libcudnn.so.5 locally
I tensorflow/stream_executor/dso_loader.cc:125] successfully opened CUDA library libcufft.so.8.0 locally
I tensorflow/stream_executor/dso_loader.cc:125] successfully opened CUDA library libcuda.so.1 locally
I tensorflow/stream_executor/dso_loader.cc:125] successfully opened CUDA library libcurand.so.8.0 locally
W tensorflow/core/platform/cpu_feature_guard.cc:95] The TensorFlow library wasn't compiled to use SSE4.2 instructions, but these are available on your machine and could speed up CPU computations.
W tensorflow/core/platform/cpu_feature_guard.cc:95] The TensorFlow library wasn't compiled to use AVX instructions, but these are available on your machine and could speed up CPU computations.
I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:910] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero

I noticed that it has mentioned SSE4.2 and AVX,

What are SSE4.2 and AVX?

How do these SSE4.2 and AVX improve CPU computations for Tensorflow tasks.

How to make Tensorflow compile using the two libraries?

Body:
Let me answer your 3rd question first:

If you want to run a self-compiled version within a conda-env, you can. These are the general instructions I run to get tensorflow to install on my system with additional instructions. Note: This build was for an AMD A10-7850 build (check your CPU for what instructions are supported...it may differ) running Ubuntu 16.04 LTS. I use Python 3.5 within my conda-env. Credit goes to the tensorflow source install page and the answers provided above.

git clone https://github.com/tensorflow/tensorflow
# Install Bazel
# https://bazel.build/versions/master/docs/install.html
sudo apt-get install python3-numpy python3-dev python3-pip python3-wheel
# Create your virtual env with conda.
source activate YOUR_ENV
pip install six numpy wheel, packaging, appdir
# Follow the configure instructions at:
# https://www.tensorflow.org/install/install_sources
# Build your build like below. Note: Check what instructions your CPU
# support. Also. If resources are limited consider adding the following
# tag --local_resources 2048,.5,1.0 . This will limit how much ram many
# local resources are used but will increase time to compile.
bazel build -c opt --copt=-mavx --copt=-msse4.1 --copt=-msse4.2  -k //tensorflow/tools/pip_package:build_pip_package
# Create the wheel like so:
bazel-bin/tensorflow/tools/pip_package/build_pip_package /tmp/tensorflow_pkg
# Inside your conda env:
pip install /tmp/tensorflow_pkg/NAME_OF_WHEEL.whl
# Then install the rest of your stack
pip install keras jupyter etc. etc.

As to your 2nd question:

A self-compiled version with optimizations are well worth the effort in my opinion. On my particular setup, calculations that used to take 560-600 seconds now only take about 300 seconds! Although the exact numbers will vary, I think you can expect about a 35-50% speed increase in general on your particular setup.

Lastly your 1st question:

A lot of the answers have been provided above already. To summarize: AVX, SSE4.1, SSE4.2, MFA are different kinds of extended instruction sets on X86 CPUs. Many contain optimized instructions for processing matrix or vector operations.

I will highlight my own misconception to hopefully save you some time: It's not that SSE4.2 is a newer version of instructions superseding SSE4.1. SSE4 = SSE4.1 (a set of 47 instructions) + SSE4.2 (a set of 7 instructions).

In the context of tensorflow compilation, if you computer supports AVX2 and AVX, and SSE4.1 and SSE4.2, you should put those optimizing flags in for all. Don't do like I did and just go with SSE4.2 thinking that it's newer and should superseed SSE4.1. That's clearly WRONG! I had to recompile because of that which cost me a good 40 minutes.


来源: stackexchange

问:
How can I show only method name in xUnit in Test Explorer?
If I run unit tests in Visual Studio:

If I use NUnit, Test Explorer shows the method names.

If I use xUnit, Test Explorer shows the fully qualified name including namespace, class name and method name. That's a bit too long.

I would like to show the method name only. I've seen that you can specify a setting in the App.config to show just the method name, but that is based on App.config.

How do I do the same thing in .NET Core, which has a completely different configuration model?

答:
According the official docs, you can provide the settings for your .Net Core application with json file named

xunit.runner.json or <AssemblyName>.xunit.runner.json, where <AssemblyName> is the name of your unit test assembly, without the file extension like .dll or .exe

You should only need to use this longer name format if your unit tests DLLs will all be placed into the same output folder, and you need to disambiguate the various configuration files.

The assembly-specific filename takes precedence over the non-specific filename; there is no merging of values between files.

Supported configuration items are (The configuration elements are placed inside a top-level object):

appDomain

diagnosticMessages

longRunningTestSeconds

maxParallelThreads

methodDisplay

Set this to override the default display name for test cases. If you set this to method, the display name will be just the method (without the class name); if this set this value to classAndMethod, the default display name will be the fully qualified class name and method name.

JSON schema type: enum

Default value: classAndMethod

parallelizeAssembly

parallelizeTestCollections

preEnumerateTheories

shadowCopy

Edit: as you can see in docs, there are only two options: classAndMethod and method. According the github issue #524, there is no difference from class name and namespace in Xunit API, so you need to find a workaround.

For example, this answer approach:

```<code>public class MyFactAttribute : FactAttribute
{
    public MyFactAttribute([CallerMemberName] string memberName = null)
    {
        DisplayName = memberName;
    }
}
</code>```

Some useful links:

[Proposal] Support Automatic "Pretty" Display Name for Test Cases, Issue #759

Pretty Display Name Implementation for Test Cases, PR #828

NuGet package with PR

ContentLicense: CC BY-SA 3.0

Body:
According the official docs, you can provide the settings for your .Net Core application with json file named

xunit.runner.json or <AssemblyName>.xunit.runner.json, where <AssemblyName> is the name of your unit test assembly, without the file extension like .dll or .exe

You should only need to use this longer name format if your unit tests DLLs will all be placed into the same output folder, and you need to disambiguate the various configuration files.

The assembly-specific filename takes precedence over the non-specific filename; there is no merging of values between files.

Supported configuration items are (The configuration elements are placed inside a top-level object):

appDomain

diagnosticMessages

longRunningTestSeconds

maxParallelThreads

methodDisplay

Set this to override the default display name for test cases. If you set this to method, the display name will be just the method (without the class name); if this set this value to classAndMethod, the default display name will be the fully qualified class name and method name.

JSON schema type: enum

Default value: classAndMethod

parallelizeAssembly

parallelizeTestCollections

preEnumerateTheories

shadowCopy

Edit: as you can see in docs, there are only two options: classAndMethod and method. According the github issue #524, there is no difference from class name and namespace in Xunit API, so you need to find a workaround.

For example, this answer approach:

public class MyFactAttribute : FactAttribute
{
    public MyFactAttribute([CallerMemberName] string memberName = null)
    {
        DisplayName = memberName;
    }
}

Some useful links:

[Proposal] Support Automatic "Pretty" Display Name for Test Cases, Issue #759

Pretty Display Name Implementation for Test Cases, PR #828

NuGet package with PR

ContentLicense: CC BY-SA 4.0


问:
Passing an array with dynamic number of elements into Start-Job in powershell
I have a two-dimensional array which contains dynamic number of elements in both axes.

```<code>$h = @(@(1,2,3), @(4,5,6,7))

$h | %{

  $ScriptBlock = {

    param($var1, $var2)
    Write-Host "[processing '$var1' inside the job]"  # I want a variable which can access $h[0], or $h[1] here

  }

  Write-Host "processing $_..."
  Start-Job $ScriptBlock -ArgumentList $_
}

# Wait for all to complete
While (Get-Job -State "Running") { Start-Sleep 2 }

# Display output from all jobs
Get-Job | Receive-Job

# Cleanup
Remove-Job *
</code>```

Is it possible to have a single variable inside $ScriptBlock that can access $h[0], or $h[1]?

I know that in my code, $var1, and $var2 can have access to $h[0][0], $h[0][1] and $h[1][0], $h[1][1]. But because the dimension of $h is dynamic,  using param($var1, $var2) is not able to have access to all of the elements in $h.

Anyone how to do this?

答:
I found that using $args can get access to $h[0], and $h[1].

Remember to remove param($var1, $var2) line.

```<code>$h = @(@(1,2,3), @(4,5,6,7))

$h | %{

  $ScriptBlock = {

    write-host $args     # access $h[0], $h[1]
    write-host $args[0]  # access $h[0][0], $h[1][0]
  }

  Write-Host "processing $_..."
  Start-Job $ScriptBlock -ArgumentList $_
}

# Wait for all to complete
While (Get-Job -State "Running") { Start-Sleep 2 }

# Display output from all jobs
Get-Job | Receive-Job

# Cleanup
Remove-Job *
</code>```

Body:
I have a two-dimensional array which contains dynamic number of elements in both axes.

$h = @(@(1,2,3), @(4,5,6,7))

$h | %{

  $ScriptBlock = {

    param($var1, $var2)
    Write-Host "[processing '$var1' inside the job]"  # I want a variable which can access $h[0], or $h[1] here

  }

  Write-Host "processing $_..."
  Start-Job $ScriptBlock -ArgumentList $_
}

# Wait for all to complete
While (Get-Job -State "Running") { Start-Sleep 2 }

# Display output from all jobs
Get-Job | Receive-Job

# Cleanup
Remove-Job *

Is it possible to have a single variable inside $ScriptBlock that can access $h[0], or $h[1]?

I know that in my code, $var1, and $var2 can have access to $h[0][0], $h[0][1] and $h[1][0], $h[1][1]. But because the dimension of $h is dynamic,  using param($var1, $var2) is not able to have access to all of the elements in $h.

Anyone how to do this?

Body:
I found that using $args can get access to $h[0], and $h[1].

Remember to remove param($var1, $var2) line.

$h = @(@(1,2,3), @(4,5,6,7))

$h | %{

  $ScriptBlock = {

    write-host $args     # access $h[0], $h[1]
    write-host $args[0]  # access $h[0][0], $h[1][0]
  }

  Write-Host "processing $_..."
  Start-Job $ScriptBlock -ArgumentList $_
}

# Wait for all to complete
While (Get-Job -State "Running") { Start-Sleep 2 }

# Display output from all jobs
Get-Job | Receive-Job

# Cleanup
Remove-Job *


问:
Remove duplicated elements List<Vector3> Mono / C# - Unity3D
I need to remove the duplicates of elements in my Vector3 list.
For Example, here is a list:

```<code>List<Vector3> PointsToGo = new List<Vector3>();

PointsToGo.Add(new Vector3(1, 1, 1));
PointsToGo.Add(new Vector3(2, 2, 2));
PointsToGo.Add(new Vector3(1, 1, 1)); // Get this one or the first one out
PointsToGo.Add(new Vector3(4, 4, 4));
</code>```

Do you know how to solve this problem ? Maybe Linq can help me ?

Thanks for your answer!

答:
If you don't want to use Linq (which is a good thing according to Unity doc) you an use the following:

```<code>List<Vector3> list = new List<Vector3>(new HashSet<Vector3>(originalListWithDuplicate));
</code>```

The other solution is to use HashSet collection instead. This is the purpose of that collection, avoiding duplicates. You may have to implement IEqualityComparer so it behaves exactly as you need it.

Body:
I need to remove the duplicates of elements in my Vector3 list.
For Example, here is a list:

List<Vector3> PointsToGo = new List<Vector3>();

PointsToGo.Add(new Vector3(1, 1, 1));
PointsToGo.Add(new Vector3(2, 2, 2));
PointsToGo.Add(new Vector3(1, 1, 1)); // Get this one or the first one out
PointsToGo.Add(new Vector3(4, 4, 4));

Do you know how to solve this problem ? Maybe Linq can help me ?

Thanks for your answer!

Body:
If you don't want to use Linq (which is a good thing according to Unity doc) you an use the following:

List<Vector3> list = new List<Vector3>(new HashSet<Vector3>(originalListWithDuplicate));

The other solution is to use HashSet collection instead. This is the purpose of that collection, avoiding duplicates. You may have to implement IEqualityComparer so it behaves exactly as you need it.


问:
Java Thread Count doesn't work
Why is count 0? </p>

<p>I start the thread 1 then I start thread 2. Count should be 2000. But it shows count to be 0. Someone please explain in simple terms.     </p>

```<code>public class App {
    private int count = 0;

    public static void main(String[] args) {
        App app = new App();
        app.doWork();
    }

    public void doWork(){
        Thread t1 = new Thread(new Runnable(){
            public void run(){
                for(int i = 0;i < 10000;i++){
                    count++;
                }
            }
        });

        Thread t2 = new Thread(new Runnable(){
            public void run(){
                for(int i = 0;i < 10000;i++){
                    count++;
                }
            }
        });
        t1.start();
        t2.start();

        System.out.println("Count is: " + count);
    }
}
</code>```

答:
At the time you're printing out your thread count, the threads have not finished executing yet.

To demonstrate, add a Thread.sleep() instruction before printing out the thread count:

```<code>public class App {
    private int count = 0;

    public static void main(String[] args) throws InterruptedException {
        App app = new App();
        app.doWork();
    }

    public void doWork() throws InterruptedException {
        Thread t1 = new Thread(new Runnable() {
            public void run() {
                for (int i = 0; i < 10000; i++) {
                    count++;
                }
            }
        });
        Thread t2 = new Thread(new Runnable() {
            public void run() {
                for (int i = 0; i < 10000; i++) {
                    count++;
                }
            }
        });

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

        Thread.sleep(5000);

        System.out.println("Count is: " + count); // Count is: 20000
    }
}
</code>```

Also note that operations on primitives are not thread-safe and that the count++ operation is not atomic. You should synchronize access to your count variable, or use an AtomicInteger or LongAdder instead of an int. As it stands, you might end up with a count anywhere between zero and 20,000.

Title: Java Thread Count doesn't work

Body:
Why is count 0?

I start the thread 1 then I start thread 2. Count should be 2000. But it shows count to be 0. Someone please explain in simple terms.

public class App {
    private int count = 0;

    public static void main(String[] args) {
        App app = new App();
        app.doWork();
    }

    public void doWork(){
        Thread t1 = new Thread(new Runnable(){
            public void run(){
                for(int i = 0;i < 10000;i++){
                    count++;
                }
            }
        });

        Thread t2 = new Thread(new Runnable(){
            public void run(){
                for(int i = 0;i < 10000;i++){
                    count++;
                }
            }
        });
        t1.start();
        t2.start();

        System.out.println("Count is: " + count);
    }
}

Body:
At the time you're printing out your thread count, the threads have not finished executing yet.

To demonstrate, add a Thread.sleep() instruction before printing out the thread count:

public class App {
    private int count = 0;

    public static void main(String[] args) throws InterruptedException {
        App app = new App();
        app.doWork();
    }

    public void doWork() throws InterruptedException {
        Thread t1 = new Thread(new Runnable() {
            public void run() {
                for (int i = 0; i < 10000; i++) {
                    count++;
                }
            }
        });
        Thread t2 = new Thread(new Runnable() {
            public void run() {
                for (int i = 0; i < 10000; i++) {
                    count++;
                }
            }
        });

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

        Thread.sleep(5000);

        System.out.println("Count is: " + count); // Count is: 20000
    }
}

Also note that operations on primitives are not thread-safe and that the count++ operation is not atomic. You should synchronize access to your count variable, or use an AtomicInteger or LongAdder instead of an int. As it stands, you might end up with a count anywhere between zero and 20,000.


问:
Apply query total for variable
I have sum query with active record, and assign with total filed.

I select one record is ok, so show as ActiveDataProvider, that total not show.

This my query:

```<code>$sumQuery = 'sum(Condition) total';
</code>```

And select sum:

```<code> $query->select(['*', $sumQuery]);
</code>```

So how can i get it's in Data Provinder.

答:
Try:

```<code>$sumQuery = new yii\db\Expression('sum(Condition) AS total');

$query->select(['*', $sumQuery]);
</code>```

Also, I think you have to declare the $total in your model class.

Title: Apply query total for variable

Body:
I have sum query with active record, and assign with total filed.

I select one record is ok, so show as ActiveDataProvider, that total not show.

This my query:

$sumQuery = 'sum(Condition) total';

And select sum:

 $query->select(['*', $sumQuery]);

So how can i get it's in Data Provinder.

Body:
Try:

$sumQuery = new yii\db\Expression('sum(Condition) AS total');

$query->select(['*', $sumQuery]);

Also, I think you have to declare the $total in your model class.


答:
It is because you are printing count in main thread.
Main thread executed in its normal way , before child thread started.
That's why your count is 0 ,
 try to print count after a while , like put Thread.sleep(2000) before printing it.</p>

Title: Java Thread Count doesn't work


问:
Is something wrong with the way that I'm generating this NLTK grammar?
I wrote this simple program with NLTK that's just supposed to print out the syntax tree. However, it prints nothing out even though the RecursiveDescentParser is being created. What's my problem? Am I defining the grammar incorrectly? Is something wrong with the way that I'm trying to iterate through the parser? Thank you in advance.

```<code>import nltk

'''The price of peace is rising.'''

grammar = nltk.CFG.fromstring("""
  S -> NP VP
  VP -> V NP | V NP PP
  PP -> P NP
  V -> "is" | "rising"
  NP -> Det N | Det N PP
  Det -> "the" | "of"
  N -> "price" | "peace"
  P -> "in" | "on" | "by" | "with"
  """)

sentence = "the price of peace is rising"
wordArray = sentence.split()

print(wordArray)

parser = nltk.RecursiveDescentParser(grammar)

for tree in parser.parse(wordArray):
    print(tree)
</code>```

答:
Firstly, always start writing grammar in bite-size.

Let's start with an easy sentence Peace is rising.

We want the structure S -> NP VP, where:

VP is an intransitive verb phrase, in this particular case, is rising comes with an auxiliary is and rise comes with the -ing progressive inflection.

NP is simply a single noun.

[code]:

```<code>import nltk

your_grammar = nltk.CFG.fromstring("""
S -> NP VP
VP -> AUX V
V -> "rising"
AUX -> "is"
NP -> N
N -> "peace"
""")

parser = nltk.RecursiveDescentParser(your_grammar)
sentence = "peace is rising".split()

for tree in parser.parse(sentence):
    print (list(tree))
</code>```

[out]:

```<code>[Tree('NP', [Tree('N', ['peace'])]), Tree('VP', [Tree('AUX', ['is']), Tree('V', ['rising'])])]
</code>```

Now to add the determiner to the NP with NP -> DT NP | N:

```<code>import nltk

your_grammar = nltk.CFG.fromstring("""
S -> NP VP
VP -> AUX V
V -> "rising"
AUX -> "is"
NP -> N | DT NP
N -> "peace" | "price"
DT -> "the"
""")

parser = nltk.RecursiveDescentParser(your_grammar)
sentence = "the price is rising".split()

for tree in parser.parse(sentence):
    print (list(tree))
</code>```

[out]:

```<code>[Tree('NP', [Tree('DT', ['the']), Tree('NP', [Tree('N', ['price'])])]), Tree('VP', [Tree('AUX', ['is']), Tree('V', ['rising'])])]
</code>```

Finally, we can simply add the PP construction within the NP, with NP -> NP PP and PP -> P NP:

```<code>import nltk

your_grammar = nltk.CFG.fromstring("""
S -> NP VP
VP -> AUX V
V -> "rising"
AUX -> "is"
NP -> N | DT NP | NP PP
N -> "peace" | "price"
DT -> "the"
PP -> P NP
P -> "of"
""")

parser = nltk.RecursiveDescentParser(your_grammar)
sentence = "the price of peace is rising".split()

for tree in parser.parse(sentence):
    print (list(tree))
</code>```

which gives us the best possible parse in the top results.

[out]:

```<code>[Tree('NP', [Tree('DT', ['the']), Tree('NP', [Tree('NP', [Tree('N', ['price'])]), Tree('PP', [Tree('P', ['of']), Tree('NP', [Tree('N', ['peace'])])])])]), Tree('VP', [Tree('AUX', ['is']), Tree('V', ['rising'])])]
</code>```

But it also comes with some nasty recursive loop errors, that looks something like this:

```<code>  File "/usr/local/lib/python3.5/site-packages/nltk/tree.py", line 158, in __getitem__
    return self[index[0]][index[1:]]
  File "/usr/local/lib/python3.5/site-packages/nltk/tree.py", line 156, in __getitem__
    return self[index[0]]
  File "/usr/local/lib/python3.5/site-packages/nltk/tree.py", line 150, in __getitem__
    if isinstance(index, (int, slice)):
RecursionError: maximum recursion depth exceeded in __instancecheck__
</code>```

It's because the nltk.RecursiveDescentParser tries to look for a parse recursively since NP -> NP PP and PP -> P NP rules can infinitely recur. If you would like to know why, try asking that as a separate question on StackOverflow ;P

One easy solution is to use try-except:

```<code>try:
    for tree in parser.parse(sentence):
        print (list(tree))
except RecursionError:
    exit()
</code>```

But that's ugly! Instead, you could use a ChartParser:

```<code>import nltk

your_grammar = nltk.CFG.fromstring("""
S -> NP VP
VP -> AUX V
V -> "rising"
AUX -> "is"
NP -> N | DT NP | NP PP
N -> "peace" | "price"
DT -> "the"
PP -> P NP
P -> "of"
""")

parser = nltk.ChartParser(your_grammar)
sentence = "the price of peace is rising".split()

for tree in parser.parse(sentence):
    print (list(tree))
</code>```

[out]:

```<code>[Tree('NP', [Tree('NP', [Tree('DT', ['the']), Tree('NP', [Tree('N', ['price'])])]), Tree('PP', [Tree('P', ['of']), Tree('NP', [Tree('N', ['peace'])])])]), Tree('VP', [Tree('AUX', ['is']), Tree('V', ['rising'])])]
[Tree('NP', [Tree('DT', ['the']), Tree('NP', [Tree('NP', [Tree('N', ['price'])]), Tree('PP', [Tree('P', ['of']), Tree('NP', [Tree('N', ['peace'])])])])]), Tree('VP', [Tree('AUX', ['is']), Tree('V', ['rising'])])]
</code>```

Body:
I wrote this simple program with NLTK that's just supposed to print out the syntax tree. However, it prints nothing out even though the RecursiveDescentParser is being created. What's my problem? Am I defining the grammar incorrectly? Is something wrong with the way that I'm trying to iterate through the parser? Thank you in advance.

import nltk

'''The price of peace is rising.'''

grammar = nltk.CFG.fromstring("""
  S -> NP VP
  VP -> V NP | V NP PP
  PP -> P NP
  V -> "is" | "rising"
  NP -> Det N | Det N PP
  Det -> "the" | "of"
  N -> "price" | "peace"
  P -> "in" | "on" | "by" | "with"
  """)

sentence = "the price of peace is rising"
wordArray = sentence.split()

print(wordArray)

parser = nltk.RecursiveDescentParser(grammar)

for tree in parser.parse(wordArray):
    print(tree)

Body:
Firstly, always start writing grammar in bite-size.

Let's start with an easy sentence Peace is rising.

We want the structure S -> NP VP, where:

VP is an intransitive verb phrase, in this particular case, is rising comes with an auxiliary is and rise comes with the -ing progressive inflection.

NP is simply a single noun.

[code]:

import nltk

your_grammar = nltk.CFG.fromstring("""
S -> NP VP
VP -> AUX V
V -> "rising"
AUX -> "is"
NP -> N
N -> "peace"
""")

parser = nltk.RecursiveDescentParser(your_grammar)
sentence = "peace is rising".split()

for tree in parser.parse(sentence):
    print (list(tree))

[out]:

[Tree('NP', [Tree('N', ['peace'])]), Tree('VP', [Tree('AUX', ['is']), Tree('V', ['rising'])])]

Now to add the determiner to the NP with NP -> DT NP | N:

import nltk

your_grammar = nltk.CFG.fromstring("""
S -> NP VP
VP -> AUX V
V -> "rising"
AUX -> "is"
NP -> N | DT NP
N -> "peace" | "price"
DT -> "the"
""")

parser = nltk.RecursiveDescentParser(your_grammar)
sentence = "the price is rising".split()

for tree in parser.parse(sentence):
    print (list(tree))

[out]:

[Tree('NP', [Tree('DT', ['the']), Tree('NP', [Tree('N', ['price'])])]), Tree('VP', [Tree('AUX', ['is']), Tree('V', ['rising'])])]

Finally, we can simply add the PP construction within the NP, with NP -> NP PP and PP -> P NP:

import nltk

your_grammar = nltk.CFG.fromstring("""
S -> NP VP
VP -> AUX V
V -> "rising"
AUX -> "is"
NP -> N | DT NP | NP PP
N -> "peace" | "price"
DT -> "the"
PP -> P NP
P -> "of"
""")

parser = nltk.RecursiveDescentParser(your_grammar)
sentence = "the price of peace is rising".split()

for tree in parser.parse(sentence):
    print (list(tree))

which gives us the best possible parse in the top results.

[out]:

[Tree('NP', [Tree('DT', ['the']), Tree('NP', [Tree('NP', [Tree('N', ['price'])]), Tree('PP', [Tree('P', ['of']), Tree('NP', [Tree('N', ['peace'])])])])]), Tree('VP', [Tree('AUX', ['is']), Tree('V', ['rising'])])]

But it also comes with some nasty recursive loop errors, that looks something like this:

  File "/usr/local/lib/python3.5/site-packages/nltk/tree.py", line 158, in __getitem__
    return self[index[0]][index[1:]]
  File "/usr/local/lib/python3.5/site-packages/nltk/tree.py", line 156, in __getitem__
    return self[index[0]]
  File "/usr/local/lib/python3.5/site-packages/nltk/tree.py", line 150, in __getitem__
    if isinstance(index, (int, slice)):
RecursionError: maximum recursion depth exceeded in __instancecheck__

It's because the nltk.RecursiveDescentParser tries to look for a parse recursively since NP -> NP PP and PP -> P NP rules can infinitely recur. If you would like to know why, try asking that as a separate question on StackOverflow ;P

One easy solution is to use try-except:

try:
    for tree in parser.parse(sentence):
        print (list(tree))
except RecursionError:
    exit()

But that's ugly! Instead, you could use a ChartParser:

import nltk

your_grammar = nltk.CFG.fromstring("""
S -> NP VP
VP -> AUX V
V -> "rising"
AUX -> "is"
NP -> N | DT NP | NP PP
N -> "peace" | "price"
DT -> "the"
PP -> P NP
P -> "of"
""")

parser = nltk.ChartParser(your_grammar)
sentence = "the price of peace is rising".split()

for tree in parser.parse(sentence):
    print (list(tree))

[out]:

[Tree('NP', [Tree('NP', [Tree('DT', ['the']), Tree('NP', [Tree('N', ['price'])])]), Tree('PP', [Tree('P', ['of']), Tree('NP', [Tree('N', ['peace'])])])]), Tree('VP', [Tree('AUX', ['is']), Tree('V', ['rising'])])]
[Tree('NP', [Tree('DT', ['the']), Tree('NP', [Tree('NP', [Tree('N', ['price'])]), Tree('PP', [Tree('P', ['of']), Tree('NP', [Tree('N', ['peace'])])])])]), Tree('VP', [Tree('AUX', ['is']), Tree('V', ['rising'])])]


问:
PHP - How to get the value of json api using Php?
I have a question regarding on json.. I tried to get an api from other site and downloaded it as json file..I've already decoded this file using this code below..

```<code>$str = file_get_contents('../trelloApi.json');
$json = json_decode($str, true);
echo '```' . print_r($json, true) . '```';
</code>```

From this image attached, how do I get or print the value of the [list] => Array, [board] => Array and [card] => Array?

Please help me :(

答:
You can access list array like below:

$list = $json['data']['list']

So access board array:

$board = $json['data']['board']

To access card array:

$card = $json['data']['card']

Body:
I have a question regarding on json.. I tried to get an api from other site and downloaded it as json file..I've already decoded this file using this code below..

$str = file_get_contents('../trelloApi.json');
$json = json_decode($str, true);
echo '
' . print_r($json, true) . '
';

From this image attached, how do I get or print the value of the [list] => Array, [board] => Array and [card] => Array?

Please help me :(


问:
Using VBA to create a dynamic query after importing a SQL database table in MS Excel
This is a problem that has stumped me for a couple of days, and one I've been trying to work on. Unfortunately I very new to working on this stuff, and don't have a lot of resources trying to solve this problem, so if I am unclear or you have a question please post a comment about it.

The problem I am trying to tackle is this:

After getting external data from a SQL Server and having a table in a spreadsheet, say the is called Products, and has columns for productid (column A), productname (column B), supplierid (column C), and categoryname (column D). Is there a way to define a cell, say E1 where you use  can use VBA to create a dynamic query. In this dynamic query you would enter some value of categoryname where it would query the table, and give you the results?

答:
It is possible to perform a dynamic query without using any VBA.

Base your table on "From Microsoft Query" (under the "Get External Data" group on the Data tab). Build your query using the Query Wizard, selecting the table columns of interest. On the "Query Wizard - Filter Data" tab, where you would normally say a particular column must have a specific value, instead of the specific value, use just a question mark (for any and all columns that need to be used to filter). When you return your data to Excel, you will be prompted to "Enter Parameter Value" for each ? you used. Just click OK at this stage.

When the Excel "Import Data" dialog appears, click "Properties...". On the Definition tab click the button labelled "Parameters...". For each parameter, choose to "Get the value from the following cell" and to "Refresh automatically when cell value changes". Click the red arrow button (to select a cell) and click in the cell where each parameter will get its value from.

It's a good idea to have a label alongside each cell, and maybe special formatting for the data entry cell. The results table can be on the same worksheet as the parameter entry cells, when you enter a value in the entry cell, a new query will be run and the result will be displayed.


问:
node-sass-middleware not compiling
Im trying to get the node-sass-middleware working with with express. The app runs with no errors

```<code>...(modules)
var sassMiddleware = require('node-sass-middleware');

var routes = require('./routes/index');

var app = express();

// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
//---- LOAD SASS -----//
// adding the sass middleware
var srcPath = __dirname + '/scss';
var destPath = __dirname + '/public/stylesheets';
app.use(sassMiddleware({
  src: srcPath,
  dest: destPath,
  debug: true,
  outputStyle: 'compressed'
}));

app.use(express.static(path.join(__dirname, 'public')));
</code>```

Can anyone see anything wrong with the way I'm attempting to compile the sass?

file structure :

```<code>app
controllers
routes
public
-stylesheets
scss
...
</code>```

答:
A problem could also be that you want to compile scss

instead of sass. Therefore set indentedSyntax to false.

```<code>app.use(require('node-sass-middleware')({
  src: path.join(__dirname, 'scss'),
  dest: path.join(__dirname, 'public'),
  indentedSyntax : false,
  sourceMap: true
}));
</code>```

Or remove it completly. Express-generator adds this value on default.

Title: node-sass-middleware not compiling

Body:
Im trying to get the node-sass-middleware working with with express. The app runs with no errors

...(modules)
var sassMiddleware = require('node-sass-middleware');

var routes = require('./routes/index');

var app = express();

// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
//---- LOAD SASS -----//
// adding the sass middleware
var srcPath = __dirname + '/scss';
var destPath = __dirname + '/public/stylesheets';
app.use(sassMiddleware({
  src: srcPath,
  dest: destPath,
  debug: true,
  outputStyle: 'compressed'
}));

app.use(express.static(path.join(__dirname, 'public')));

Can anyone see anything wrong with the way I'm attempting to compile the sass?

file structure :

app
controllers
routes
public
-stylesheets
scss
...

Body:
A problem could also be that you want to compile scss

instead of sass. Therefore set indentedSyntax to false.

app.use(require('node-sass-middleware')({
  src: path.join(__dirname, 'scss'),
  dest: path.join(__dirname, 'public'),
  indentedSyntax : false,
  sourceMap: true
}));

Or remove it completly. Express-generator adds this value on default.


问:
Substitute formal arguments in a function factory r
I'm trying to make a function factory to make functions with custom formal argument names. The idea is to supply a string to the factory, which in turn substitutes it both in the formals and in the body of the function returned. I've managed to do it using eval(parse(text=paste())) , but I read elsewhere that this bad practice. How can I get the same output while avoiding doing evalparse?</p>

```<code>MyLinearRateFunctions<-function(varX){

  eval(parse(text=paste("function(a,b,",
                    varX,
                    ") 1/(a + b*",
                    varX,
                    ")",sep="")
  ))

 }

(LinearRateMPG<-MyLinearRateFunctions('mpg'))

# function(a,b,mpg) 1/(a + b*mpg)
# <environment: 0x11c2f2a00>

(LinearRateCYL<-MyLinearRateFunctions('cyl'))

# function(a,b,cyl) 1/(a + b*cyl)
# <environment: 0x11e4cb908>

(LinearRateDISP<-MyLinearRateFunctions('disp'))

# function(a,b,disp) 1/(a + b*disp)
# <environment: 0x11e47eae8>
</code>```

答:
This uses only base R and no eval.  First set up a function to use as a template and then change the formals, set up the body and set the environment.

```<code>factory <- function(x, envir = parent.frame()) {
  fun <- function(a, b, x) {}
  names(formals(fun))[[3]] <- x
  body(fun) <- substitute(1/(a+b*x), list(x = as.name(x)))
  environment(fun) <- envir
  fun
}

# test
myfun <- factory("m")
</code>```

giving:

```<code>> myfun
function (a, b, m)
1/(a + b * m)
</code>```

Body:
I'm trying to make a function factory to make functions with custom formal argument names. The idea is to supply a string to the factory, which in turn substitutes it both in the formals and in the body of the function returned. I've managed to do it using eval(parse(text=paste())) , but I read elsewhere that this bad practice. How can I get the same output while avoiding doing evalparse?

MyLinearRateFunctions<-function(varX){

  eval(parse(text=paste("function(a,b,",
                    varX,
                    ") 1/(a + b*",
                    varX,
                    ")",sep="")
  ))

 }

(LinearRateMPG<-MyLinearRateFunctions('mpg'))

# function(a,b,mpg) 1/(a + b*mpg)
# <environment: 0x11c2f2a00>

(LinearRateCYL<-MyLinearRateFunctions('cyl'))

# function(a,b,cyl) 1/(a + b*cyl)
# <environment: 0x11e4cb908>

(LinearRateDISP<-MyLinearRateFunctions('disp'))

# function(a,b,disp) 1/(a + b*disp)
# <environment: 0x11e47eae8>

Body:
This uses only base R and no eval.  First set up a function to use as a template and then change the formals, set up the body and set the environment.

factory <- function(x, envir = parent.frame()) {
  fun <- function(a, b, x) {}
  names(formals(fun))[[3]] <- x
  body(fun) <- substitute(1/(a+b*x), list(x = as.name(x)))
  environment(fun) <- envir
  fun
}

# test
myfun <- factory("m")

giving:

> myfun
function (a, b, m)
1/(a + b * m)


问:
TextBox with maxvalue
I want to make a TextBox which does not allow to enter a value above 100. Only numbers allowed, And a Numeric TextBox is not an option. This is my code for now:

```<code>private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar)) { e.Handled = true; }  // only numbers
}
</code>```

Any ideas?

答:
Hello, here is my solution.</p>

```<code>

    private void textBox_KeyPress(object sender, KeyPressEventArgs e)
            {
                char c = e.KeyChar;
                if ((!char.IsDigit(c) ||
                    Convert.ToInt32(textBox.Text + e.KeyChar) >= 101 ||
                    textBox.Text == "0") && c != '\b')
                    e.Handled = true;

            }

</code>```

Title: TextBox with maxvalue

Body:
I want to make a TextBox which does not allow to enter a value above 100. Only numbers allowed, And a Numeric TextBox is not an option. This is my code for now:

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar)) { e.Handled = true; }  // only numbers
}

Any ideas?

Body:
Hello, here is my solution.

    private void textBox_KeyPress(object sender, KeyPressEventArgs e)
            {
                char c = e.KeyChar;
                if ((!char.IsDigit(c) ||
                    Convert.ToInt32(textBox.Text + e.KeyChar) >= 101 ||
                    textBox.Text == "0") && c != '\b')
                    e.Handled = true;

            }


问:
Spring JavaConfig and Tomcat 8
I have a Spring 4 web application (webapp-module.war) working and running locally in eclipse using Java 8, tomcat 8 and JavaConfig (no web.xml):

But when I deploy to tomcat 8 (same version I am using locally in eclipse) on a remote Ubuntu server I get:

I verified host and port which are correct. There is no error in the log (/var/lib/tomcat8/logs/catalina.out)

```<code>Jun 21, 2016 10:32:44 PM org.apache.catalina.startup.HostConfig undeploy
INFO: Undeploying context [/webapp-module]
Jun 21, 2016 10:32:44 PM org.apache.catalina.startup.HostConfig deployWAR
INFO: Deploying web application archive /var/lib/tomcat8/webapps/webapp-module.war
Jun 21, 2016 10:32:46 PM org.apache.jasper.servlet.TldScanner scanJars
INFO: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
Jun 21, 2016 10:32:46 PM org.apache.catalina.startup.HostConfig deployWAR
INFO: Deployment of web application archive /var/lib/tomcat8/webapps/webapp-module.war has finished in 1,870 ms
root@vmi63860:/var/lib/tomcat8/logs#
</code>```

The access log contains:

```<code>root@vmi63860:/var/log/tomcat8# cat localhost_access_log.2016-06-22.txt
xx.xxx.xxx.xx - - [22/Jun/2016:22:36:00 +0200] "GET /webapp-module/ HTTP/1.1" 404 1040
xx.xxx.xxx.xx - - [22/Jun/2016:22:36:00 +0200] "GET /favicon.ico HTTP/1.1" 404 1034
xx.xxx.xxx.xx - - [22/Jun/2016:22:36:50 +0200] "GET /webapp-module/hello HTTP/1.1" 404 1050
</code>```

Where xx.xxx.xxx.xx is the IP of my local machine from where I try to access the web app in my browser.

I took a look at:
Spring Java Config: Tomcat deploy without web.xml but it does not really provide a solution.

Details on my project below:

Sources

Config.java

```<code>@Configuration // Marks this class as configuration
// Specifies which package to scan
@ComponentScan("com.samples")
// Enables Spring's annotations
@EnableWebMvc
public class Config {

  @Bean
  public UrlBasedViewResolver setupViewResolver() {
    UrlBasedViewResolver resolver = new UrlBasedViewResolver();
    resolver.setPrefix("/WEB-INF/jsp/");
    resolver.setSuffix(".jsp");
    resolver.setViewClass(JstlView.class);
    return resolver;
  }

}
</code>```

WebInitializer.java

```<code>public class WebInitializer implements WebApplicationInitializer {

  @Override
  public void onStartup(ServletContext servletContext) throws ServletException {

    AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
    ctx.register(Config.class);
    ctx.setServletContext(servletContext);

    Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx));
    servlet.addMapping("/");
    servlet.setLoadOnStartup(1);

  }

}
</code>```

HelloController.java

```<code>@Controller
public class HelloController {

  @RequestMapping("/")
  public String home() {
    return "index";
  }

  @RequestMapping("/hello")
  public String showhello(ModelMap model) {
    model.addAttribute("message", "Hello Spring MVC Framework!");
    return "hello";
  }

}
</code>```

答:
Add finalName as ROOT in your pom.xml. This will create ROOT.war file in your target folder.

```<code>    <build>
        <plugins>
<!--All plugins are here -->
        </plugins>
        <finalName>ROOT</finalName>
    </build>
</code>```

After that if you deploy ROOT.war file in your tomcat. Then your accessing url will be
http://localhost:8080

Hope it will solve your issue.

For further checking, please go through http://localhost:8080/manager/html
it will call for username and password. Check that is set or not.

If not set, please go through this tutorial: Can't access Tomcat 8 Manager App as suggested by E-Riz

For full example, go through this tutorial: http://websystique.com/springmvc/spring-4-mvc-helloworld-tutorial-annotation-javaconfig-full-example/

Title: Spring JavaConfig and Tomcat 8

Body:
I have a Spring 4 web application (webapp-module.war) working and running locally in eclipse using Java 8, tomcat 8 and JavaConfig (no web.xml):

But when I deploy to tomcat 8 (same version I am using locally in eclipse) on a remote Ubuntu server I get:

I verified host and port which are correct. There is no error in the log (/var/lib/tomcat8/logs/catalina.out)

Jun 21, 2016 10:32:44 PM org.apache.catalina.startup.HostConfig undeploy
INFO: Undeploying context [/webapp-module]
Jun 21, 2016 10:32:44 PM org.apache.catalina.startup.HostConfig deployWAR
INFO: Deploying web application archive /var/lib/tomcat8/webapps/webapp-module.war
Jun 21, 2016 10:32:46 PM org.apache.jasper.servlet.TldScanner scanJars
INFO: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
Jun 21, 2016 10:32:46 PM org.apache.catalina.startup.HostConfig deployWAR
INFO: Deployment of web application archive /var/lib/tomcat8/webapps/webapp-module.war has finished in 1,870 ms
root@vmi63860:/var/lib/tomcat8/logs#

The access log contains:

root@vmi63860:/var/log/tomcat8# cat localhost_access_log.2016-06-22.txt
xx.xxx.xxx.xx - - [22/Jun/2016:22:36:00 +0200] "GET /webapp-module/ HTTP/1.1" 404 1040
xx.xxx.xxx.xx - - [22/Jun/2016:22:36:00 +0200] "GET /favicon.ico HTTP/1.1" 404 1034
xx.xxx.xxx.xx - - [22/Jun/2016:22:36:50 +0200] "GET /webapp-module/hello HTTP/1.1" 404 1050

Where xx.xxx.xxx.xx is the IP of my local machine from where I try to access the web app in my browser.

I took a look at:
Spring Java Config: Tomcat deploy without web.xml but it does not really provide a solution.

Details on my project below:

Sources

Config.java

@Configuration // Marks this class as configuration
// Specifies which package to scan
@ComponentScan("com.samples")
// Enables Spring's annotations
@EnableWebMvc
public class Config {

  @Bean
  public UrlBasedViewResolver setupViewResolver() {
    UrlBasedViewResolver resolver = new UrlBasedViewResolver();
    resolver.setPrefix("/WEB-INF/jsp/");
    resolver.setSuffix(".jsp");
    resolver.setViewClass(JstlView.class);
    return resolver;
  }

}

WebInitializer.java

public class WebInitializer implements WebApplicationInitializer {

  @Override
  public void onStartup(ServletContext servletContext) throws ServletException {

    AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
    ctx.register(Config.class);
    ctx.setServletContext(servletContext);

    Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx));
    servlet.addMapping("/");
    servlet.setLoadOnStartup(1);

  }

}

HelloController.java

@Controller
public class HelloController {

  @RequestMapping("/")
  public String home() {
    return "index";
  }

  @RequestMapping("/hello")
  public String showhello(ModelMap model) {
    model.addAttribute("message", "Hello Spring MVC Framework!");
    return "hello";
  }

}

Body:
Add finalName as ROOT in your pom.xml. This will create ROOT.war file in your target folder.

    <build>
        <plugins>
<!--All plugins are here -->
        </plugins>
        <finalName>ROOT</finalName>
    </build>

After that if you deploy ROOT.war file in your tomcat. Then your accessing url will be
http://localhost:8080

Hope it will solve your issue.

For further checking, please go through http://localhost:8080/manager/html
it will call for username and password. Check that is set or not.

If not set, please go through this tutorial: Can't access Tomcat 8 Manager App as suggested by E-Riz

For full example, go through this tutorial: http://websystique.com/springmvc/spring-4-mvc-helloworld-tutorial-annotation-javaconfig-full-example/


问:
How to access variables values used in Java Script from Qt code using QtWebEngine
If i have HTML page which have JavaScript variable,

```<code><script type="text/javascript">{myVar = 333;}</script>
</code>```

I need to call this variable from within my C++ code using Qt - QtWebEngine class.
some how i couldn't what to write in the lambda expression to call the JS variable
here is the snippet i used

```<code>QWebEngineView *view = new QWebEngineView();
view->load(QUrl::fromLocalFile("D:/test.html"));
page = view->page();
page->runJavaScript(myVar,[](QVariant myHolder){ ???? });
</code>```

How should i use this method "runJavaScript" to call my JS variable to be valid in my C++ code ?

答:
```<code>page->runJavaScript("myVar",[](const QVariant &myHolder){qDebug()<< myHolder.toInt(); });
</code>```

if you want to pass the value to the class field outside the lambda,use like this:

page->runJavaScript("myVar",[this](const QVariant &myHolder){this->yourClassMethod(myhodler); });

Body:
If i have HTML page which have JavaScript variable,

I need to call this variable from within my C++ code using Qt - QtWebEngine class.
some how i couldn't what to write in the lambda expression to call the JS variable
here is the snippet i used

QWebEngineView *view = new QWebEngineView();
view->load(QUrl::fromLocalFile("D:/test.html"));
page = view->page();
page->runJavaScript(myVar,[](QVariant myHolder){ ???? });

How should i use this method "runJavaScript" to call my JS variable to be valid in my C++ code ?

Body:
page->runJavaScript("myVar",[](const QVariant &myHolder){qDebug()<< myHolder.toInt(); });

if you want to pass the value to the class field outside the lambda,use like this:

page->runJavaScript("myVar",[this](const QVariant &myHolder){this->yourClassMethod(myhodler); });


问:
Create a virtual printer in Java
I would like to create a virtual printer using Java, so that when you go to print a file( using Word or something) the Java printer is listed as a valid printer.  My goal is to get the printer formatted object that the programs (Word, etc..) send directly to the printer. I don't know if this is possible. It seemed like a more logical solution to this question:

Printing multiple file types using java

Any ideas?  I heard this is only possible using C or C++, but I don't know for sure.

答: You will have to write a new printer driver that re-direct API calls to your Java classes.</p>

Title: Create a virtual printer in Java

ContentLicense: CC BY-SA 2.5


问:
Angular JS - How to apply / bind ng-model late (lazy)
I have a simple scenario in a large piece of code:

Angular APP & Controller (all working well)

one ng-model element is dynamically created later (or lets say it comes from an ajax call). How to bind this into that controller?

For example:

```<code>var dtApp = angular.module('App1', []);
dtApp.controller('Cont1', function($scope)
{
  .
  .
  .
  .
  $scope.xyz='1';
}
.
.
.
//element created dynamically on click:
<input type="text" ng-model="xyz" />
.
</code>```

This is just an example, but it will solve the actual and larger problem if I know the solution.

Thanks a lot.

答:
With some help from other posts (and some hints from the other answers), here is the simplest solution:

1. at JS code that triggers new dom element

```<code>angular.element(document.getElementById("Cont1")).scope().bindx('new_field_id');
</code>```

2. inside Controller Cont1

```<code>//first add $compile in the function definition, then the following
$scope.bindx = function(ele_id)
{
    ele = $('#'+ele_id).parent();
    $compile(angular.element(ele).contents())($scope);
}
</code>```

Body:
I have a simple scenario in a large piece of code:

Angular APP & Controller (all working well)

one ng-model element is dynamically created later (or lets say it comes from an ajax call). How to bind this into that controller?

For example:

var dtApp = angular.module('App1', []);
dtApp.controller('Cont1', function($scope)
{
  .
  .
  .
  .
  $scope.xyz='1';
}
.
.
.
//element created dynamically on click:
<input type="text" ng-model="xyz" />
.

This is just an example, but it will solve the actual and larger problem if I know the solution.

Thanks a lot.

Body:
With some help from other posts (and some hints from the other answers), here is the simplest solution:

1. at JS code that triggers new dom element

angular.element(document.getElementById("Cont1")).scope().bindx('new_field_id');

2. inside Controller Cont1

//first add $compile in the function definition, then the following
$scope.bindx = function(ele_id)
{
    ele = $('#'+ele_id).parent();
    $compile(angular.element(ele).contents())($scope);
}


问:
D3 tree drawing with long labels
I'm trying to print some trees, where the node labels are sentences up to around two hundred characters. Is there a way to specify a maximum width for the labels and have longer labels wrap onto multiple lines?

In other words, the labels attached to the nodes in the following picture:

https://github.com/d3/d3-hierarchy/blob/master/README.md#tree

can be up to around two hundred characters long.

ps. Maybe it does so automatically, but I haven't written the code yet in case using this component of D3 is a dead end.

答:
Unfortunately, the SVG specification doesn't allow for "word wrapping" to happen. The best you can do is write your own function that will wrap the text into multiple <tspan></tspan> tags. Here is an example that you can follow:

https://bl.ocks.org/mbostock/7555321

Title: D3 tree drawing with long labels


问:
Tokio Tls Self Signed Certificate
Update: This seems to be more of an issue with generating and trusting a self signed cert properly

I am building a server and client using tokio-rs. I have everything working but am now trying to add SSL/TLS to the system. I've generated a self signed certificate and installed it correctly as far as I know, but every time I try to get the client to connect to the server I get the following error:

```<code>thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: Failure(Ssl(ErrorStack([Error { code: 336134278, library: "SSL routines", function: "ssl3_get_server_certificate", reason: "certificate verify failed", file: "s3_clnt.c", line: 1264 }])))', /buildslave/rust-buildbot/slave/stable-dist-rustc-linux/build/src/libcore/result.rs:837
</code>```

I am using the following script to generate a crt, key and pfx file:

```<code>openssl req -nodes -x509 -newkey rsa:2048 -config ssl.conf -extensions ext -subj /C=CA/ST=EH/L=Canadia/O=Dis/CN=localhost -keyout localhost.key -out localhost.crt -days 365
openssl pkcs12 -export -nodes -inkey localhost.key -in localhost.crt -out localhost.pfx
mv localhost.pfx ../
</code>```

with this conf file

```<code>[req]
distinguished_name=dn
[ dn ]
CN=localhost
[ ext ]
basicConstraints=CA:FALSE,pathlen:0
subjectAltName = @alt_names
[alt_names]
DNS.1 = localhost
</code>```

The pfx file is moved up a level and then copied into the debug folder on build.

I am running Ubuntu and have copied localhost.crt to /etc/ssl/certs and localhost.key to /etc/ssl/private

My server code is using tokio-proto and the tokio-tls tokio-proto Server protocol wrapper

Protocol:

```<code>use tokio_proto::pipeline::ServerProto;
use tokio_io::codec::{Framed};
use tokio_io::{AsyncRead, AsyncWrite};
use tokio_tls::{TlsAcceptorExt};
use rem::codec::CacheCodec;
use std::io;

pub struct CacheProto {}

impl<T: AsyncRead + AsyncWrite + 'static> ServerProto<T> for CacheProto {
    /// For this protocol style, `Request` matches the codec `In` type
    type Request = String;

    /// For this protocol style, `Response` matches the coded `Out` type
    type Response = String;

    /// A bit of boilerplate to hook in the codec:
    type Transport = Framed<T, CacheCodec>;
    type BindTransport = Result<Self::Transport, io::Error>;
    fn bind_transport(&self, io: T) -> Self::BindTransport {
        Ok(io.framed(CacheCodec{}))
    }
}
</code>```

Server:

```<code>use std::string::String;
use std::sync::{Arc, Mutex};

use rem::cache::Cache;
use rem::service::CacheService;
use rem::proto::CacheProto;

use futures_cpupool::CpuPool;

use tokio_tls::{TlsAcceptorExt};
use native_tls::{Pkcs12, TlsAcceptor};

use tokio_tls::proto::Server;
use tokio_proto::TcpServer;

use std::fs::File;
use std::io::{Read};

pub fn launch(ip: String, port: String) {
   // Specify the localhost address
    let addr = format!("{}:{}", ip, port).parse().unwrap();

    let pkcs12 = get_pkcs12();
    let acceptor = TlsAcceptor::builder(pkcs12).unwrap().build().unwrap();

    let proto = Server::new(CacheProto{}, acceptor);

    // The builder requires a protocol and an address
    let server = TcpServer::new(proto, addr);

    let pool = Box::new(CpuPool::new_num_cpus());

    // We provide a way to *instantiate* the service for each new
    // connection; here, we just immediately return a new instance.
    let cache = Arc::new(Mutex::new(Cache::new()));
    let cache_service = CacheService {
        cache: cache.clone(),
        pool : pool
    };

    server.serve( move || Ok(cache_service.clone()));
}

fn get_pkcs12() -> Pkcs12{
    let mut file = File::open("localhost.pfx").unwrap();
    let mut pkcs12 = vec![];
    file.read_to_end(&mut pkcs12).unwrap();
    let pkcs12 = Pkcs12::from_der(&pkcs12, "password").unwrap();
    return pkcs12;
}
</code>```

Client: (Not using tokio-proto, just native tls and TCP)

```<code>use std::io::prelude::*;
use std::io;
use std::string::String;
use std::vec::Vec;
use std::net::{TcpStream};
use std::mem;

use native_tls::{TlsConnector, TlsStream};

use rem::op;
use rem::error::*;

pub fn launch(ip: String, port: String) {
    info!("Connection to {}:{}", ip, port);

    match TcpStream::connect(format!("{}:{}", ip, port).as_str()) {
        Ok(mut tcp_stream) => {
            let connector = TlsConnector::builder().unwrap().build().unwrap();
            let mut stream = connector.connect(ip.as_str(), tcp_stream).unwrap();
            loop {
                // Contine looping, executing any commands from the user
                let handle = io::stdin();
                for line_res in handle.lock().lines() {
                    let line: String = line_res.unwrap();
                    let args:Vec<String> = parse_input(line);
                    if args.len() > 0{
                        let arg_ref = args[0].as_ref();
                        match arg_ref {
                            "write" => {
                                if args.len() == 3 {
                                    match client_exec_write(&args[1], &args[2], &mut stream){
                                        Ok(_) => (),
                                        Err(why) => why.log()
                                    }
                                }else{
                                    error!("Write expects two arguments - key and value");
                                }
                            },
                            "read" => {
                                if args.len() == 2 {
                                    match client_exec_read(&args[1], &mut stream){
                                        Ok(_) => (),
                                        Err(why) => why.log()
                                    }
                                }else{
                                    error!("Read expects one argument - key");
                                }
                            },
                            "delete" => {
                                if args.len() == 2 {
                                    match client_exec_delete(&args[1], &mut stream){
                                        Ok(_) => (),
                                        Err(why) => why.log()
                                    }
                                }else{
                                    error!("Delete expects one argument - key");
                                }
                            }
                            _ => error!("Not a valid command")
                        }
                    }
                }
            }
        }
        Err(e) => {
            panic!("Failed to connect to server. Error '{}'", e);
        }
    }
}

/// Executres a write operation by parsing the client command and converting it to REM format
/// ex: write abc:def would be converted to 9|W$abc:def and sent to the REM server
fn client_exec_write(key:&String, val:&String, mut stream: &mut TlsStream<TcpStream>)-> Result<(), RemError> {
    let sized_val = String::from(format!("W${}:{}", key, val));
    let res = op::write_str_to_stream_with_size(&mut stream, sized_val);
    try!(print_response(&mut stream));
    return res;
}

/// Executres a read operation by parsing the client command and converting it to REM format
/// ex: read abc:def would be converted to 5|R$abc and sent to the REM launch_server
/// The respone from the REM server is writen to stdout
/// If stdout::flush fail a warning will be logged
fn client_exec_read(key: &String, mut stream: &mut TlsStream<TcpStream>)-> Result<(), RemError>{
    let cmd_val = String::from(format!("R${}", key));
    try!(op::write_str_to_stream_with_size(&mut stream, cmd_val));
    try!(print_response(&mut stream));
    return Ok(());
}

/// Executes a delete operation by parsing the client command and converting it to REM format
/// ex: delete abc would be converted to 5|D$abc and sent to the REM server
fn client_exec_delete(key: &String, mut stream: &mut TlsStream<TcpStream>) -> Result<(), RemError>{
    let cmd_val = String::from(format!("D${}", key));
    let res = op::write_str_to_stream_with_size(&mut stream, cmd_val);
    try!(print_response(&mut stream));
    return res;
}

fn print_response(mut stream: &mut TlsStream<TcpStream>) -> Result<(), RemError>{
    let val: String = try!(op::string_from_stream(&mut stream));
    println!("{}", val);
    try!(io::stdout().flush());
    return Ok(());
}

struct InputParser{
    args:Vec<String>,
    current:String,
    consumed_double_quote:bool,
    consumed_single_quote:bool
}

impl InputParser{

    /// Consumes a space charater taking quotes into consideration
    /// If the parser has consumed an opening quote then the space will be consumed as a character
    pub fn consume_space(&mut self){
        // If neither a single quote or a double quote has been consumed then its a new argument
        if !self.consumed_double_quote && !self.consumed_single_quote {
            self.push_current();
        }else{
            self.current.push(' ');
        }
    }

    /// Consumes a double quote, keeping track of whether it is an opening or cloing quote
    /// Takes single quotes into account when determening if the double quote is a delimiter or character
    pub fn consume_double_quote(&mut self){
        // If a single quote hasn't been consumed we're at the end or
        // beginning of an argument in double quotes
        if  !self.consumed_single_quote {
            if self.consumed_double_quote{
                self.push_current();
            }
            // Flip the value so we know the sate for the next double quote that is consumed
            self.consumed_double_quote = !self.consumed_double_quote;
        }else{
            // If we're in double quotes just treat the double quote as a regular character
            self.current.push('"');
        }
    }

    /// Consumes a single quote, keeping track of whether it is an opening or cloing quote
    /// Takes double quotes into account when determening if the single quote is a delimiter or character
    pub fn consume_single_quote(&mut self){
         // If a double quote hasn't been consumed we're at the end or
        // beginning of an argument in single quotes
         if !self.consumed_double_quote {
            if self.consumed_single_quote{
                self.push_current();
            }
            // Flip the value so we know the sate for the next single quote that is consumed
            self.consumed_single_quote = !self.consumed_single_quote;
        }else{
            // If we're in double quotes just treat the single quote as a regular character
            self.current.push('\'');
        }
    }

    /// Adds the character onto the current argument
    pub fn consume_char(&mut self, c:char){
        self.current.push(c);
    }

    /// To be called when everything has been parsed
    pub fn end(&mut self){
        self.push_current();
    }

    /// Pushes the current string into the list of args
    /// If the length of current is 0 no actions are performed
    pub fn push_current(&mut self){
        if self.current.len() > 0 {
            let arg = mem::replace(&mut self.current, String::new());
            self.args.push(arg);
        }
    }

}

/// Parses the arguments out of an input string taking quotes and spaces into consideration
pub fn parse_input(input: String) -> Vec<String>{
    let mut parser = InputParser{
        args:Vec::new(),
        current:String::new(),
        consumed_double_quote:false,
        consumed_single_quote:false
    };
    for c in input.chars(){
        match c {
            '"'  => parser.consume_double_quote(),
            ' '  => parser.consume_space(),
            '\'' => parser.consume_single_quote(),
            _    => parser.consume_char(c)
        }
    }
    parser.end();

    return parser.args;
}
</code>```

Op:

```<code>use std::io::prelude::*;
use std::string::String;
use std::vec::Vec;
use std::net::{TcpStream};
use std::sync::{Mutex};

use native_tls::{TlsConnector, TlsStream};

use rem::cache::Cache;
use rem::error::*;

pub fn read_value_from_cache(key: String,
                         cache_mtx: &Mutex<Cache>)
                         -> Result<(Vec<u8>), RemError> {
    let cache = cache_mtx.lock().unwrap();
    let cache_opt: Option<Box<Vec<u8>>> = try!(cache.read_item(key));
    match cache_opt {
        Some(boxed_val) => {
            let val: Vec<u8> = *boxed_val;
            return Ok(val.clone());
        }
        None => {
            return Err(RemError::with_reason(String::from(REM_00005)));
        }
    }
}

/// Parses a TCP input stream and extracts the data
/// Allocates a 64 byte buffer which is used to read the input info from the stream
/// The expected format is ```{size}|{content}```
/// Ex. ```5|W$a:b```
pub fn string_from_stream(stream: &mut TlsStream<TcpStream>) -> Result<String, RemError> {
    //Read in the first 54 bytes of the stram
    //try!(stream.set_nodelay(true));
    let mut buf_arr: [u8; 64] = [0; 64];
    try!(stream.read(&mut buf_arr));
    // Parse the message size
    let mut size_str = String::new();
    let mut buf_size: usize = 0;
    for i in 0..64 {
        buf_size += 1;
        if buf_arr[i] == '|' as u8 {
            break;
        }
        size_str.push(buf_arr[i as usize] as char);
    }

    // Convert the size string to a usize so it can be used to drain the buffer
    let upper_idx: usize = try!(size_str.parse::<i32>()) as usize;
    let mut buf_temp: Vec<u8> = buf_arr.to_vec();
    // Create a new buffer using the parsed indicies
    let buf: Vec<u8> = buf_temp.drain(buf_size..upper_idx + buf_size).collect();

    stream.flush().unwrap();

    // Return the value as a string
    let buf_str: String = String::from_utf8(buf).unwrap();
    return Ok(buf_str);
}

pub fn write_stream_str_to_cache(stream_str: String,
                             cache_mtx: &Mutex<Cache>)
                             -> Result<(), RemError> {
    let mut key: String = String::new();
    let mut val: String = String::new();
    let mut idx = 0;
    let chars_iter = stream_str.chars();
    for c in chars_iter {
        idx += 1;
        if c == ':' {
            val = String::from(&stream_str[idx..]);
            break;
        }
        key.push(c);
    }
    let bytes = val.into_bytes();
    let mut cache = cache_mtx.lock().unwrap();
    return cache.cache_item(key.as_str(), bytes);
}

pub fn delete_value_from_cache(key: String, cache_mtx: &Mutex<Cache>) -> Result<(), RemError> {
    let mut cache = cache_mtx.lock().unwrap();
    return cache.delete_item(key);
}

pub fn write_str_to_stream_with_size(stream: &mut TlsStream<TcpStream>, value: String) -> Result<(), RemError> {
    let sized_val = String::from(format!("{}|{}", value.len(), value));
    try!(stream.write(String::from(sized_val).as_bytes()));
    try!(stream.flush());
    return Ok(());
}
</code>```

There are more files to this project but I don't think they're relevant, however I can add them if things are unclear

答:
This is more an OpenSSL issue than a Rust issue. Assuming the client is running Ubuntu also, copy the *.crt file to its /usr/local/share/ca-certificates/, then run sudo /usr/sbin/update-ca-certificates. That will tell the client to trust your certificate, and OpenSSL will no longer report an error about it.

(Edit:) You still have a remaining problem, which is that the cert's Common Name (CN) does not match the name the client is using to reach the server. Your ssl.conf gives it a CN of localhost, but the client asks for it by IP. Obviously if the client asks for https://localhost/ it's not going to work. So you should re-generate your cert with a different DNS name, have the client trust the new cert, and then use that name for making requests. If necessary you could just use a name like rustsslserver and put that in your client's /etc/hosts.

I have a git repo that shows a working example here. Note it uses hyper, not tokio, but the results should be the same.

Title: Tokio Tls Self Signed Certificate

Body:
Update: This seems to be more of an issue with generating and trusting a self signed cert properly

I am building a server and client using tokio-rs. I have everything working but am now trying to add SSL/TLS to the system. I've generated a self signed certificate and installed it correctly as far as I know, but every time I try to get the client to connect to the server I get the following error:

thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: Failure(Ssl(ErrorStack([Error { code: 336134278, library: "SSL routines", function: "ssl3_get_server_certificate", reason: "certificate verify failed", file: "s3_clnt.c", line: 1264 }])))', /buildslave/rust-buildbot/slave/stable-dist-rustc-linux/build/src/libcore/result.rs:837

I am using the following script to generate a crt, key and pfx file:

openssl req -nodes -x509 -newkey rsa:2048 -config ssl.conf -extensions ext -subj /C=CA/ST=EH/L=Canadia/O=Dis/CN=localhost -keyout localhost.key -out localhost.crt -days 365
openssl pkcs12 -export -nodes -inkey localhost.key -in localhost.crt -out localhost.pfx
mv localhost.pfx ../

with this conf file

[req]
distinguished_name=dn
[ dn ]
CN=localhost
[ ext ]
basicConstraints=CA:FALSE,pathlen:0
subjectAltName = @alt_names
[alt_names]
DNS.1 = localhost

The pfx file is moved up a level and then copied into the debug folder on build.

I am running Ubuntu and have copied localhost.crt to /etc/ssl/certs and localhost.key to /etc/ssl/private

My server code is using tokio-proto and the tokio-tls tokio-proto Server protocol wrapper

Protocol:

use tokio_proto::pipeline::ServerProto;
use tokio_io::codec::{Framed};
use tokio_io::{AsyncRead, AsyncWrite};
use tokio_tls::{TlsAcceptorExt};
use rem::codec::CacheCodec;
use std::io;

pub struct CacheProto {}

impl<T: AsyncRead + AsyncWrite + 'static> ServerProto<T> for CacheProto {
    /// For this protocol style, `Request` matches the codec `In` type
    type Request = String;

    /// For this protocol style, `Response` matches the coded `Out` type
    type Response = String;

    /// A bit of boilerplate to hook in the codec:
    type Transport = Framed<T, CacheCodec>;
    type BindTransport = Result<Self::Transport, io::Error>;
    fn bind_transport(&self, io: T) -> Self::BindTransport {
        Ok(io.framed(CacheCodec{}))
    }
}

Server:

use std::string::String;
use std::sync::{Arc, Mutex};

use rem::cache::Cache;
use rem::service::CacheService;
use rem::proto::CacheProto;

use futures_cpupool::CpuPool;

use tokio_tls::{TlsAcceptorExt};
use native_tls::{Pkcs12, TlsAcceptor};

use tokio_tls::proto::Server;
use tokio_proto::TcpServer;

use std::fs::File;
use std::io::{Read};

pub fn launch(ip: String, port: String) {
   // Specify the localhost address
    let addr = format!("{}:{}", ip, port).parse().unwrap();

    let pkcs12 = get_pkcs12();
    let acceptor = TlsAcceptor::builder(pkcs12).unwrap().build().unwrap();

    let proto = Server::new(CacheProto{}, acceptor);

    // The builder requires a protocol and an address
    let server = TcpServer::new(proto, addr);

    let pool = Box::new(CpuPool::new_num_cpus());

    // We provide a way to *instantiate* the service for each new
    // connection; here, we just immediately return a new instance.
    let cache = Arc::new(Mutex::new(Cache::new()));
    let cache_service = CacheService {
        cache: cache.clone(),
        pool : pool
    };

    server.serve( move || Ok(cache_service.clone()));
}

fn get_pkcs12() -> Pkcs12{
    let mut file = File::open("localhost.pfx").unwrap();
    let mut pkcs12 = vec![];
    file.read_to_end(&mut pkcs12).unwrap();
    let pkcs12 = Pkcs12::from_der(&pkcs12, "password").unwrap();
    return pkcs12;
}

Client: (Not using tokio-proto, just native tls and TCP)

use std::io::prelude::*;
use std::io;
use std::string::String;
use std::vec::Vec;
use std::net::{TcpStream};
use std::mem;

use native_tls::{TlsConnector, TlsStream};

use rem::op;
use rem::error::*;

pub fn launch(ip: String, port: String) {
    info!("Connection to {}:{}", ip, port);

    match TcpStream::connect(format!("{}:{}", ip, port).as_str()) {
        Ok(mut tcp_stream) => {
            let connector = TlsConnector::builder().unwrap().build().unwrap();
            let mut stream = connector.connect(ip.as_str(), tcp_stream).unwrap();
            loop {
                // Contine looping, executing any commands from the user
                let handle = io::stdin();
                for line_res in handle.lock().lines() {
                    let line: String = line_res.unwrap();
                    let args:Vec<String> = parse_input(line);
                    if args.len() > 0{
                        let arg_ref = args[0].as_ref();
                        match arg_ref {
                            "write" => {
                                if args.len() == 3 {
                                    match client_exec_write(&args[1], &args[2], &mut stream){
                                        Ok(_) => (),
                                        Err(why) => why.log()
                                    }
                                }else{
                                    error!("Write expects two arguments - key and value");
                                }
                            },
                            "read" => {
                                if args.len() == 2 {
                                    match client_exec_read(&args[1], &mut stream){
                                        Ok(_) => (),
                                        Err(why) => why.log()
                                    }
                                }else{
                                    error!("Read expects one argument - key");
                                }
                            },
                            "delete" => {
                                if args.len() == 2 {
                                    match client_exec_delete(&args[1], &mut stream){
                                        Ok(_) => (),
                                        Err(why) => why.log()
                                    }
                                }else{
                                    error!("Delete expects one argument - key");
                                }
                            }
                            _ => error!("Not a valid command")
                        }
                    }
                }
            }
        }
        Err(e) => {
            panic!("Failed to connect to server. Error '{}'", e);
        }
    }
}

/// Executres a write operation by parsing the client command and converting it to REM format
/// ex: write abc:def would be converted to 9|W$abc:def and sent to the REM server
fn client_exec_write(key:&String, val:&String, mut stream: &mut TlsStream<TcpStream>)-> Result<(), RemError> {
    let sized_val = String::from(format!("W${}:{}", key, val));
    let res = op::write_str_to_stream_with_size(&mut stream, sized_val);
    try!(print_response(&mut stream));
    return res;
}

/// Executres a read operation by parsing the client command and converting it to REM format
/// ex: read abc:def would be converted to 5|R$abc and sent to the REM launch_server
/// The respone from the REM server is writen to stdout
/// If stdout::flush fail a warning will be logged
fn client_exec_read(key: &String, mut stream: &mut TlsStream<TcpStream>)-> Result<(), RemError>{
    let cmd_val = String::from(format!("R${}", key));
    try!(op::write_str_to_stream_with_size(&mut stream, cmd_val));
    try!(print_response(&mut stream));
    return Ok(());
}

/// Executes a delete operation by parsing the client command and converting it to REM format
/// ex: delete abc would be converted to 5|D$abc and sent to the REM server
fn client_exec_delete(key: &String, mut stream: &mut TlsStream<TcpStream>) -> Result<(), RemError>{
    let cmd_val = String::from(format!("D${}", key));
    let res = op::write_str_to_stream_with_size(&mut stream, cmd_val);
    try!(print_response(&mut stream));
    return res;
}

fn print_response(mut stream: &mut TlsStream<TcpStream>) -> Result<(), RemError>{
    let val: String = try!(op::string_from_stream(&mut stream));
    println!("{}", val);
    try!(io::stdout().flush());
    return Ok(());
}

struct InputParser{
    args:Vec<String>,
    current:String,
    consumed_double_quote:bool,
    consumed_single_quote:bool
}

impl InputParser{

    /// Consumes a space charater taking quotes into consideration
    /// If the parser has consumed an opening quote then the space will be consumed as a character
    pub fn consume_space(&mut self){
        // If neither a single quote or a double quote has been consumed then its a new argument
        if !self.consumed_double_quote && !self.consumed_single_quote {
            self.push_current();
        }else{
            self.current.push(' ');
        }
    }

    /// Consumes a double quote, keeping track of whether it is an opening or cloing quote
    /// Takes single quotes into account when determening if the double quote is a delimiter or character
    pub fn consume_double_quote(&mut self){
        // If a single quote hasn't been consumed we're at the end or
        // beginning of an argument in double quotes
        if  !self.consumed_single_quote {
            if self.consumed_double_quote{
                self.push_current();
            }
            // Flip the value so we know the sate for the next double quote that is consumed
            self.consumed_double_quote = !self.consumed_double_quote;
        }else{
            // If we're in double quotes just treat the double quote as a regular character
            self.current.push('"');
        }
    }

    /// Consumes a single quote, keeping track of whether it is an opening or cloing quote
    /// Takes double quotes into account when determening if the single quote is a delimiter or character
    pub fn consume_single_quote(&mut self){
         // If a double quote hasn't been consumed we're at the end or
        // beginning of an argument in single quotes
         if !self.consumed_double_quote {
            if self.consumed_single_quote{
                self.push_current();
            }
            // Flip the value so we know the sate for the next single quote that is consumed
            self.consumed_single_quote = !self.consumed_single_quote;
        }else{
            // If we're in double quotes just treat the single quote as a regular character
            self.current.push('\'');
        }
    }

    /// Adds the character onto the current argument
    pub fn consume_char(&mut self, c:char){
        self.current.push(c);
    }

    /// To be called when everything has been parsed
    pub fn end(&mut self){
        self.push_current();
    }

    /// Pushes the current string into the list of args
    /// If the length of current is 0 no actions are performed
    pub fn push_current(&mut self){
        if self.current.len() > 0 {
            let arg = mem::replace(&mut self.current, String::new());
            self.args.push(arg);
        }
    }

}

/// Parses the arguments out of an input string taking quotes and spaces into consideration
pub fn parse_input(input: String) -> Vec<String>{
    let mut parser = InputParser{
        args:Vec::new(),
        current:String::new(),
        consumed_double_quote:false,
        consumed_single_quote:false
    };
    for c in input.chars(){
        match c {
            '"'  => parser.consume_double_quote(),
            ' '  => parser.consume_space(),
            '\'' => parser.consume_single_quote(),
            _    => parser.consume_char(c)
        }
    }
    parser.end();

    return parser.args;
}

Op:

use std::io::prelude::*;
use std::string::String;
use std::vec::Vec;
use std::net::{TcpStream};
use std::sync::{Mutex};

use native_tls::{TlsConnector, TlsStream};

use rem::cache::Cache;
use rem::error::*;

pub fn read_value_from_cache(key: String,
                         cache_mtx: &Mutex<Cache>)
                         -> Result<(Vec<u8>), RemError> {
    let cache = cache_mtx.lock().unwrap();
    let cache_opt: Option<Box<Vec<u8>>> = try!(cache.read_item(key));
    match cache_opt {
        Some(boxed_val) => {
            let val: Vec<u8> = *boxed_val;
            return Ok(val.clone());
        }
        None => {
            return Err(RemError::with_reason(String::from(REM_00005)));
        }
    }
}

/// Parses a TCP input stream and extracts the data
/// Allocates a 64 byte buffer which is used to read the input info from the stream
/// The expected format is ```{size}|{content}```
/// Ex. ```5|W$a:b```
pub fn string_from_stream(stream: &mut TlsStream<TcpStream>) -> Result<String, RemError> {
    //Read in the first 54 bytes of the stram
    //try!(stream.set_nodelay(true));
    let mut buf_arr: [u8; 64] = [0; 64];
    try!(stream.read(&mut buf_arr));
    // Parse the message size
    let mut size_str = String::new();
    let mut buf_size: usize = 0;
    for i in 0..64 {
        buf_size += 1;
        if buf_arr[i] == '|' as u8 {
            break;
        }
        size_str.push(buf_arr[i as usize] as char);
    }

    // Convert the size string to a usize so it can be used to drain the buffer
    let upper_idx: usize = try!(size_str.parse::<i32>()) as usize;
    let mut buf_temp: Vec<u8> = buf_arr.to_vec();
    // Create a new buffer using the parsed indicies
    let buf: Vec<u8> = buf_temp.drain(buf_size..upper_idx + buf_size).collect();

    stream.flush().unwrap();

    // Return the value as a string
    let buf_str: String = String::from_utf8(buf).unwrap();
    return Ok(buf_str);
}

pub fn write_stream_str_to_cache(stream_str: String,
                             cache_mtx: &Mutex<Cache>)
                             -> Result<(), RemError> {
    let mut key: String = String::new();
    let mut val: String = String::new();
    let mut idx = 0;
    let chars_iter = stream_str.chars();
    for c in chars_iter {
        idx += 1;
        if c == ':' {
            val = String::from(&stream_str[idx..]);
            break;
        }
        key.push(c);
    }
    let bytes = val.into_bytes();
    let mut cache = cache_mtx.lock().unwrap();
    return cache.cache_item(key.as_str(), bytes);
}

pub fn delete_value_from_cache(key: String, cache_mtx: &Mutex<Cache>) -> Result<(), RemError> {
    let mut cache = cache_mtx.lock().unwrap();
    return cache.delete_item(key);
}

pub fn write_str_to_stream_with_size(stream: &mut TlsStream<TcpStream>, value: String) -> Result<(), RemError> {
    let sized_val = String::from(format!("{}|{}", value.len(), value));
    try!(stream.write(String::from(sized_val).as_bytes()));
    try!(stream.flush());
    return Ok(());
}

There are more files to this project but I don't think they're relevant, however I can add them if things are unclear


问:
How do I return data from a $http.get() inside a factory in angularjs
I'm having a lot of trouble with this and I can't seem to find anything here on SO or Google that helps me spot what I'm doing wrong

```<code><!DOCTYPE html>
<html data-ng-app="testApp">
   <head>
      <title></title>
   </head>
   <body>
      <div data-ng-controller="myController">
         {{test}}<br/>
         {{test2}}<br/>
         {{test3}}
         <ul>
            <li data-ng-repeat="member in members">{{ member.firstname}}</li>
         </ul>
      </div>
      <script type="text/javascript" src="angular.min.js"></script>
      <script type="text/javascript">
         angular.module('testApp', ['memberFactory']);

         angular.module('testApp',[])
         .factory('memberFactory', function($http){

            var obj = {};
            obj.data = "abcd";
            obj.getResponse = function(){
                var temp = {};
                $http.get('hello.php').success(function(data){
                        alert(data);
                        temp =data;

                });

                return "some return value";
            }

            return obj
         });

         function myController($scope, memberFactory){
            $scope.test= "testString";
            $scope.test2= memberFactory.data;
            $scope.test3= memberFactory.getResponse();

         }
      </script>
   </body>
</html>
</code>```

the return "some return value"; works but when I try to return temp, its null. I have tried various ways to get this to work but I just can't seem to set the temp value inside the $http.get() function

It is probably something simple (or a silly mistake/misguided approach on my part). Any advice would be greatly appreciated

答:
```<code>//in  $httpProvider.interceptors
if (typeof response.data === 'string') {
   return response;
}
else {
  return response.data;
}
</code>```

Body:
I'm having a lot of trouble with this and I can't seem to find anything here on SO or Google that helps me spot what I'm doing wrong

<!DOCTYPE html>

      <title></title>

         {{test}}

         {{test2}}

         {{test3}}

{{ member.firstname}}

the return "some return value"; works but when I try to return temp, its null. I have tried various ways to get this to work but I just can't seem to set the temp value inside the $http.get() function

It is probably something simple (or a silly mistake/misguided approach on my part). Any advice would be greatly appreciated


问:
Why does this array-reshaping routine work outside of a function but not inside of a function?
I am trying to convert a list into a numpy array with a specified number of columns. I can get the code to work outside the function as follows:

```<code>import numpy as np

ls = np.linspace(1,100,100) # Data Sample
ls = np.array(ls) # list --> array

# resize | outside function
ls.resize(ls.shape[0]//2,2)
print(ls)

>> [[   1.    2.]
    [   3.    4.]
           .
           .
           .
    [  97.   98.]
    [  99.  100.]]
</code>```

I do not understand my error when trying to throw the routine in a function. My attempt is as follows:

```<code># resize | inside function
def shapeshift(mylist, num_col):
    num_col = int(num_col)
    return mylist.resize(mylist.shape[0]//num_col,num_col)

ls = shapeshift(ls,2)
print(ls)

>> None
</code>```

I want to define the original function in this way because I want another function, consisting of the same inputs and a third input to loop over rows when extracting values, to call this original function for each loop over rows.

答:
```<code>In [402]: ls = np.linspace(1,100,10)
In [403]: ls
Out[403]: array([   1.,   12.,   23.,   34.,   45.,   56.,   67.,   78.,   89.,  100.])
In [404]: ls.shape
Out[404]: (10,)
</code>```

No need to wrap again in array; it already is one:

```<code>In [405]: np.array(ls)
Out[405]: array([   1.,   12.,   23.,   34.,   45.,   56.,   67.,   78.,   89.,  100.])
</code>```

resize operates in-place.  It returns nothing (or None)

```<code>In [406]: ls.resize(ls.shape[0]//2,2)
In [407]: ls
Out[407]:
array([[   1.,   12.],
       [  23.,   34.],
       [  45.,   56.],
       [  67.,   78.],
       [  89.,  100.]])
In [408]: ls.shape
Out[408]: (5, 2)
</code>```

With this resize you aren't changing the number of elements, so reshape would work just as well.

```<code>In [409]: ls = np.linspace(1,100,10)
In [410]: ls.reshape(-1,2)
Out[410]:
array([[   1.,   12.],
       [  23.,   34.],
       [  45.,   56.],
       [  67.,   78.],
       [  89.,  100.]])
</code>```

reshape in either method or function form returns a value, leaving ls unchanged.  The -1 is a handy short hand, avoiding the // division.

This is the inplace version of reshape:

```<code>In [415]: ls.shape=(-1,2)
</code>```

reshape requires the same total number of elements.  resize allows you to change the number of elements, truncating or repeating values if needed.  We use reshape much more often then resize.  repeat and tile are also more common than resize.

Body:
I am trying to convert a list into a numpy array with a specified number of columns. I can get the code to work outside the function as follows:

import numpy as np

ls = np.linspace(1,100,100) # Data Sample
ls = np.array(ls) # list --> array

# resize | outside function
ls.resize(ls.shape[0]//2,2)
print(ls)

>> [[   1.    2.]
    [   3.    4.]
           .
           .
           .
    [  97.   98.]
    [  99.  100.]]

I do not understand my error when trying to throw the routine in a function. My attempt is as follows:

# resize | inside function
def shapeshift(mylist, num_col):
    num_col = int(num_col)
    return mylist.resize(mylist.shape[0]//num_col,num_col)

ls = shapeshift(ls,2)
print(ls)

>> None

I want to define the original function in this way because I want another function, consisting of the same inputs and a third input to loop over rows when extracting values, to call this original function for each loop over rows.

Body:
In [402]: ls = np.linspace(1,100,10)
In [403]: ls
Out[403]: array([   1.,   12.,   23.,   34.,   45.,   56.,   67.,   78.,   89.,  100.])
In [404]: ls.shape
Out[404]: (10,)

No need to wrap again in array; it already is one:

In [405]: np.array(ls)
Out[405]: array([   1.,   12.,   23.,   34.,   45.,   56.,   67.,   78.,   89.,  100.])

resize operates in-place.  It returns nothing (or None)

In [406]: ls.resize(ls.shape[0]//2,2)
In [407]: ls
Out[407]:
array([[   1.,   12.],
       [  23.,   34.],
       [  45.,   56.],
       [  67.,   78.],
       [  89.,  100.]])
In [408]: ls.shape
Out[408]: (5, 2)

With this resize you aren't changing the number of elements, so reshape would work just as well.

In [409]: ls = np.linspace(1,100,10)
In [410]: ls.reshape(-1,2)
Out[410]:
array([[   1.,   12.],
       [  23.,   34.],
       [  45.,   56.],
       [  67.,   78.],
       [  89.,  100.]])

reshape in either method or function form returns a value, leaving ls unchanged.  The -1 is a handy short hand, avoiding the // division.

This is the inplace version of reshape:

In [415]: ls.shape=(-1,2)

reshape requires the same total number of elements.  resize allows you to change the number of elements, truncating or repeating values if needed.  We use reshape much more often then resize.  repeat and tile are also more common than resize.


问:
How to merge cell using closedxml with a dynamic column count?
This is how to merge cell using ClosedXML based on the documentation.

```<code>worksheet.Range("B2:D3").Row(1).Merge();
</code>```

My problem is my column count is dynamic, I can't set column letter value to merge because i will based the merging of cell on my gridview column count.

Anyone who can help me to merge cell using closedXML?

答:
Have you tried the code below?

```<code> worksheet.Cell("A1").Value = "Title";
 var range = worksheet.Range("A1:F1");
 range.Merge().Style.Font.SetBold().Font.FontSize = 16;
</code>```

It works for me.

Body:
This is how to merge cell using ClosedXML based on the documentation.

worksheet.Range("B2:D3").Row(1).Merge();

My problem is my column count is dynamic, I can't set column letter value to merge because i will based the merging of cell on my gridview column count.

Anyone who can help me to merge cell using closedXML?

Body:
Have you tried the code below?

 worksheet.Cell("A1").Value = "Title";
 var range = worksheet.Range("A1:F1");
 range.Merge().Style.Font.SetBold().Font.FontSize = 16;

It works for me.


问:
How to keep cell's content on screen while scrolling until the cell runs out of available space?
The questions itself does not say much, but what I am trying to say is: how can one move the cell's content (let say a UILabel), so the label can be seen on screen while the collection view is being scrolled, until the collectionView's cell runs out of available space.

But, a picture is worth a thousand words:

I have something like this, a UICollectionViewCell with horizontal scroll.

Normally, when I scroll this is what it will happen:

But, what I would like to achieve is the names in the firsts cells to scroll to the right while there is space available in the cell, without forgetting that when there's no more space available it will start to truncate the tail, like: Keaton Pickett -> Keaton Pick... -> Keaton... -> etc,

I've been thinking about nesting the cell's content inside a UIScrollView and then scroll it by code when the collectionView scrolls.

I also thought changing the CGRect property of the cell's contents (in this case, the UILabel) while the view is scrolling (playing with the width and minX properties.

However, detecting when the, in this case, UILabel is starting to be out of the screen (like Kea in the first cell of the second picture) is turning to be a struggle.

In my real case scenario I have the UICollectionView (horizontal scroll) nested in UITableView (vertical scroll).

I will thank and appreciate your help in this predicament.
Best regards!

答:
I prefer you to use the code

Objective C

```<code>   - (void)checkVisibilityOfCell:(MyCustomUITableViewCell *)cell inScrollView:(UIScrollView *)aScrollView {
        CGRect cellRect = [aScrollView convertRect:cell.frame toView:aScrollView.superview];

        if (CGRectContainsRect(aScrollView.frame, cellRect))
            [cell notifyCompletelyVisible];
           [cells objectAtIndex:i].hidden= YES; // MAKE THE CELL VISIBLE
        else
            [cell notifyNotCompletelyVisible];
           [cells objectAtIndex:i].hidden= NO;   // MAKE THE CELL UNVISIBLE
    }

    - (void)scrollViewDidScroll:(UIScrollView *)aScrollView {
        NSArray* cells = myTableView.visibleCells;

        NSUInteger cellCount = [cells count];
        if (cellCount == 0)
            return;

        // Loop through All  cells
        for (NSUInteger i = 1; i < cellCount - 1; i++)
            [[cells objectAtIndex:i] notifyCompletelyVisible];

    }
</code>```

Body:
I prefer you to use the code

Objective C

   - (void)checkVisibilityOfCell:(MyCustomUITableViewCell *)cell inScrollView:(UIScrollView *)aScrollView {
        CGRect cellRect = [aScrollView convertRect:cell.frame toView:aScrollView.superview];

        if (CGRectContainsRect(aScrollView.frame, cellRect))
            [cell notifyCompletelyVisible];
           [cells objectAtIndex:i].hidden= YES; // MAKE THE CELL VISIBLE
        else
            [cell notifyNotCompletelyVisible];
           [cells objectAtIndex:i].hidden= NO;   // MAKE THE CELL UNVISIBLE
    }

    - (void)scrollViewDidScroll:(UIScrollView *)aScrollView {
        NSArray* cells = myTableView.visibleCells;

        NSUInteger cellCount = [cells count];
        if (cellCount == 0)
            return;

        // Loop through All  cells
        for (NSUInteger i = 1; i < cellCount - 1; i++)
            [[cells objectAtIndex:i] notifyCompletelyVisible];

    }