问:
scalatest - can't expand macros compiled by previous versions of Scala
So we have a Scala program (built using Maven) we want to test using Scalatest. We're running Scala 2.11.8 and Scalatest 3.0.1 (we've tried 3.0.3 to no avail)

When our tests run anything with the assert() macro, we get the following error:

```<code>error: can't expand macros compiled by previous versions of Scala
       assert(true)
              ^
</code>```

It points to the true but the issue is with anything we put into assert(). Our POM has the following dependency for Scalatest:

```<code><dependency>
    <groupId>org.scalatest</groupId>
    <artifactId>scalatest_2.11</artifactId>
    <version>3.0.1</version>
    <scope>test</scope>
</dependency>
</code>```

The code we're trying to execute is:

```<code>import org.scalatest.{FlatSpec, _}
import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner

@RunWith(classOf[JUnitRunner])
class Testing extends FlatSpec {
  //test
  var number = 0;
  "An empty Set" should "have size 0" in {
    assert(true)

  }
}
</code>```

Lot's of folks say this is an issue with using Scala 2.11 but including the 2.10 dependency, but we're using the 2.11 one. Any help would be much appreciated. I should also note we tried it using Scala 2.10, and it worked.

答:
Run mvn dependency:tree and find out which dependencies have _2.10 in it.
Use Dependency management to ensure the _2.11 is included, and _2.10
is excluded.

Body:
So we have a Scala program (built using Maven) we want to test using Scalatest. We're running Scala 2.11.8 and Scalatest 3.0.1 (we've tried 3.0.3 to no avail)

When our tests run anything with the assert() macro, we get the following error:

error: can't expand macros compiled by previous versions of Scala
       assert(true)
              ^

It points to the true but the issue is with anything we put into assert(). Our POM has the following dependency for Scalatest:

<dependency>
    <groupId>org.scalatest</groupId>
    <artifactId>scalatest_2.11</artifactId>
    <version>3.0.1</version>
    <scope>test</scope>
</dependency>

The code we're trying to execute is:

import org.scalatest.{FlatSpec, _}
import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner

@RunWith(classOf[JUnitRunner])
class Testing extends FlatSpec {
  //test
  var number = 0;
  "An empty Set" should "have size 0" in {
    assert(true)

  }
}

Lot's of folks say this is an issue with using Scala 2.11 but including the 2.10 dependency, but we're using the 2.11 one. Any help would be much appreciated. I should also note we tried it using Scala 2.10, and it worked.


来源: stackexchange

问:
How to use findstr to remove lines from a file that match strings found in a list file?
I am trying to use findstr to delete lines that match the search strings found on another file. This is what I have been trying to use but it does not seem to work.

```<code>dir %ProjectDir%TypeScript\*.ts /b /s > Files.txt
findstr /v /i /g:%ProjectDir%TypeScript\strictFiles.txt Files.txt > tsFiles.txt
</code>```

Edit This also does not seem to work:

```<code>dir %ProjectDir%TypeScript\*.ts /b /s | findstr /v /i /g:%ProjectDir%TypeScript\strictFiles.txt > tsFiles.txt
</code>```

答:
The short and incomplete answer is that you missed to specify the /L switch of findstr, which forces to do literal searches. Without it, the first search string determines whether literal search or regular expression mode is chosen. Since there are file names included in the search strings, which hold a period to separate the base name from the name extension, which is also a meta-character in regular expression mode, findstr selects that mode most probably.

In addition, you should also provide the /X switch to not filter out wrong items. For example, a path like D:\Data\some would also match D:\Data\some\file.ext when the /X option is missing.

The long and comprehensive answer regards the fact that findstr does not make life that easy.

Let us assume the command line...:

dir /S /B /A:-D "D:\Project\TypeScript\*.ts" > "Files.txt"
```

<p>...produces a list of file paths in <code>Files.txt</code> like this,...:</p>

<blockquote>
<pre class="lang-cmd prettyprint-override"><code>D:\Project\TypeScript\sample.ts
D:\Project\TypeScript\restricted.ts
D:\Project\TypeScript\excluded.ts
D:\Project\TypeScript\not-excluded.ts
D:\Project\TypeScript\ancillary.ts
D:\Project\TypeScript\[special].ts
D:\Project\TypeScript\data\test.ts
D:\Project\TypeScript\data\confidential.ts
D:\Project\TypeScript\data\arbitrary.ts
D:\Project\TypeScript\data\.config.ts
D:\Project\TypeScript\data\other.config.ts
D:\Project\TypeScript\data.config.ts
D:\Project\TypeScript\conf.ts\wrong.ts
</code>```

...and the file strictFiles.txt contains this...:

D:\Project\TypeScript\restricted.ts
D:\Project\TypeScript\excluded.ts
D:\Project\TypeScript\[special].ts
D:\Project\TypeScript\confidential.ts
D:\Project\TypeScript\data\.config.ts
D:\Project\TypeScript\conf.ts
```
</blockquote>

<p>...to be filtered out from <code>Files.txt</code>.</p>

<p>You would expect the command line...:</p>

<pre class="lang-cmd prettyprint-override"><code>findstr /L /X /I /V /G:"strictFiles.txt" "Files.txt" > "tsFiles.txt"
</code>```

...to return this in the output file tsFiles.txt,...:

D:\Project\TypeScript\sample.ts
D:\Project\TypeScript\not-excluded.ts
D:\Project\TypeScript\ancillary.ts
D:\Project\TypeScript\data\test.ts
D:\Project\TypeScript\data\confidential.ts
D:\Project\TypeScript\data\arbitrary.ts
D:\Project\TypeScript\data\other.config.ts
D:\Project\TypeScript\data.config.ts
D:\Project\TypeScript\conf.ts\wrong.ts
```
</blockquote>

<p>...but it actually writes:</p>

<blockquote>
<pre class="lang-cmd prettyprint-override"><code>D:\Project\TypeScript\sample.ts
D:\Project\TypeScript\not-excluded.ts
D:\Project\TypeScript\ancillary.ts
D:\Project\TypeScript\[special].ts
D:\Project\TypeScript\data\test.ts
D:\Project\TypeScript\data\confidential.ts
D:\Project\TypeScript\data\arbitrary.ts
D:\Project\TypeScript\data\.config.ts
D:\Project\TypeScript\data\other.config.ts
D:\Project\TypeScript\conf.ts\wrong.ts
</code>```

The reason for this is that findstr, although in literal search mode due to the /L option, still detects meta-characters for the regular expression mode and allows to escape them by preceding with \. The period . and the opening bracket [ in the above sample content of strictFiles.txt are such meta-characters, and both are preceded by the path separator \, so they are considered as escaped and are therefore interpreted as . and [, or, in other words, the preceding \ becomes dismissed.

To work around that, you need to escape every \ in strictFiles.txt by preceding with another \, in order to avoid meta-characters to appear escaped to findstr -- see this script for a possible way:

@echo off
setlocal EnableExtensions DisableDelayedExpansion

rem // Define constants here:
set "_ROOT=D:\Project\TypeScript"    & rem // (path of root directory)
set "_MASK=*.ts"                     & rem // (file search pattern)
set "_LIST=.\Files.txt"              & rem // (path to file list)
set "_EXCL=.\strictFiles.txt"        & rem // (path to exclusion list)
set "_TEMP=%TEMP%\%~n0_%RANDOM%.tmp" & rem // (temporary exclusion list)
set "_FILT=.\tsFiles.txt"            & rem // (path to filtered file list)
if not defined _FILT set "_FILT=con"

rem // Generate list of files:
dir /S /B /A:-D "%_ROOT%\%_MASK%" > "%_LIST%"

rem // Modify exclusion list:
rem /* replace every path separator `\` by an escaped one `\\`,
rem    so no other characters can appear escaped to `findstr`: */
> "%_TEMP%" (
    for /F "usebackq delims= eol=|" %%F in ("%_EXCL%") do (
        set "FILE=%%F"
        setlocal EnableDelayedExpansion
        echo(!FILE:\=\\!
        endlocal
    )
)

rem // Filter out files that occur in modified exclusion list:
findstr /L /X /V /I /G:"%_TEMP%" "%_LIST%" > "%_FILT%"

rem // Clean up temporary files:
del "%_LIST%" "%_TEMP%"

endlocal
exit /B
```

<hr>

<p>If your exclusion list, say <code>strictFileNames.txt</code> this time, holds pure file names rather than full file paths, like for example,...:</p>

<blockquote>
<pre class="lang-cmd prettyprint-override"><code>restricted.ts
excluded.ts
[special].ts
confidential.ts
.config.ts
conf.ts
</code>```

...the approach is slightly different, because only the last path element of the file list Files.txt is to be taken into account. To achieve this, you need to precede every file name of the exclusion list by a path separator, again an escaped one like \\ for the aforementioned reason, in order to avoid wrong matches; for instance, file.ext would match both D:\Data\file.ext and D:\Data\X-file.ext, but \file.ext would match the former only, given that the /X option is replaced by /E this time.

Here is a script which accomplishes that:

@echo off
setlocal EnableExtensions DisableDelayedExpansion

rem // Define constants here:
set "_ROOT=D:\Project\TypeScript"    & rem // (path of root directory)
set "_MASK=*.ts"                     & rem // (file search pattern)
set "_LIST=.\Files.txt"              & rem // (path to file list)
set "_EXCL=.\strictFileNames.txt"    & rem // (path to exclusion list)
set "_TEMP=%TEMP%\%~n0_%RANDOM%.tmp" & rem // (temporary exclusion list)
set "_FILT=.\tsFiles.txt"            & rem // (path to filtered file list)
if not defined _FILT set "_FILT=con"

rem // Generate list of files:
dir /S /B /A:-D "%_ROOT%\%_MASK%" > "%_LIST%"

rem // Modify exclusion list:
rem /* precede every file with an escaped path separator `\\`,
rem    so no other characters can appear escaped to `findstr`: */
> "%_TEMP%" (
    for /F "usebackq delims= eol=|" %%F in ("%_EXCL%") do (
        echo(\\%%F
    )
)

rem // Filter out files that occur in modified exclusion list:
findstr /L /E /V /I /G:"%_TEMP%" "%_LIST%" > "%_FILT%"

rem // Clean up temporary files:
del "%_LIST%" "%_TEMP%"

endlocal
exit /B
```

All of the above sample file contents are chosen so that you can easily play around with them and see the differences when using the options /X or /E and when doubling the path separators \ or not.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to use findstr to delete lines that match the search strings found on another file. This is what I have been trying to use but it does not seem to work.

dir %ProjectDir%TypeScript\*.ts /b /s > Files.txt
findstr /v /i /g:%ProjectDir%TypeScript\strictFiles.txt Files.txt > tsFiles.txt

Edit This also does not seem to work:

dir %ProjectDir%TypeScript\*.ts /b /s | findstr /v /i /g:%ProjectDir%TypeScript\strictFiles.txt > tsFiles.txt

Body:
The short and incomplete answer is that you missed to specify the /L switch of findstr, which forces to do literal searches. Without it, the first search string determines whether literal search or regular expression mode is chosen. Since there are file names included in the search strings, which hold a period to separate the base name from the name extension, which is also a meta-character in regular expression mode, findstr selects that mode most probably.

In addition, you should also provide the /X switch to not filter out wrong items. For example, a path like D:\Data\some would also match D:\Data\some\file.ext when the /X option is missing.

The long and comprehensive answer regards the fact that findstr does not make life that easy.

Let us assume the command line...:

dir /S /B /A:-D "D:\Project\TypeScript\*.ts" > "Files.txt"

...produces a list of file paths in Files.txt like this,...:

D:\Project\TypeScript\sample.ts
D:\Project\TypeScript\restricted.ts
D:\Project\TypeScript\excluded.ts
D:\Project\TypeScript\not-excluded.ts
D:\Project\TypeScript\ancillary.ts
D:\Project\TypeScript\[special].ts
D:\Project\TypeScript\data\test.ts
D:\Project\TypeScript\data\confidential.ts
D:\Project\TypeScript\data\arbitrary.ts
D:\Project\TypeScript\data\.config.ts
D:\Project\TypeScript\data\other.config.ts
D:\Project\TypeScript\data.config.ts
D:\Project\TypeScript\conf.ts\wrong.ts

...and the file strictFiles.txt contains this...:

D:\Project\TypeScript\restricted.ts
D:\Project\TypeScript\excluded.ts
D:\Project\TypeScript\[special].ts
D:\Project\TypeScript\confidential.ts
D:\Project\TypeScript\data\.config.ts
D:\Project\TypeScript\conf.ts

...to be filtered out from Files.txt.

You would expect the command line...:

findstr /L /X /I /V /G:"strictFiles.txt" "Files.txt" > "tsFiles.txt"

...to return this in the output file tsFiles.txt,...:

D:\Project\TypeScript\sample.ts
D:\Project\TypeScript\not-excluded.ts
D:\Project\TypeScript\ancillary.ts
D:\Project\TypeScript\data\test.ts
D:\Project\TypeScript\data\confidential.ts
D:\Project\TypeScript\data\arbitrary.ts
D:\Project\TypeScript\data\other.config.ts
D:\Project\TypeScript\data.config.ts
D:\Project\TypeScript\conf.ts\wrong.ts

...but it actually writes:

D:\Project\TypeScript\sample.ts
D:\Project\TypeScript\not-excluded.ts
D:\Project\TypeScript\ancillary.ts
D:\Project\TypeScript\[special].ts
D:\Project\TypeScript\data\test.ts
D:\Project\TypeScript\data\confidential.ts
D:\Project\TypeScript\data\arbitrary.ts
D:\Project\TypeScript\data\.config.ts
D:\Project\TypeScript\data\other.config.ts
D:\Project\TypeScript\conf.ts\wrong.ts

The reason for this is that findstr, although in literal search mode due to the /L option, still detects meta-characters for the regular expression mode and allows to escape them by preceding with \. The period . and the opening bracket [ in the above sample content of strictFiles.txt are such meta-characters, and both are preceded by the path separator \, so they are considered as escaped and are therefore interpreted as . and [, or, in other words, the preceding \ becomes dismissed.

To work around that, you need to escape every \ in strictFiles.txt by preceding with another \, in order to avoid meta-characters to appear escaped to findstr -- see this script for a possible way:

@echo off
setlocal EnableExtensions DisableDelayedExpansion

rem // Define constants here:
set "_ROOT=D:\Project\TypeScript"    & rem // (path of root directory)
set "_MASK=*.ts"                     & rem // (file search pattern)
set "_LIST=.\Files.txt"              & rem // (path to file list)
set "_EXCL=.\strictFiles.txt"        & rem // (path to exclusion list)
set "_TEMP=%TEMP%\%~n0_%RANDOM%.tmp" & rem // (temporary exclusion list)
set "_FILT=.\tsFiles.txt"            & rem // (path to filtered file list)
if not defined _FILT set "_FILT=con"

rem // Generate list of files:
dir /S /B /A:-D "%_ROOT%\%_MASK%" > "%_LIST%"

rem // Modify exclusion list:
rem /* replace every path separator `\` by an escaped one `\\`,
rem    so no other characters can appear escaped to `findstr`: */
> "%_TEMP%" (
    for /F "usebackq delims= eol=|" %%F in ("%_EXCL%") do (
        set "FILE=%%F"
        setlocal EnableDelayedExpansion
        echo(!FILE:\=\\!
        endlocal
    )
)

rem // Filter out files that occur in modified exclusion list:
findstr /L /X /V /I /G:"%_TEMP%" "%_LIST%" > "%_FILT%"

rem // Clean up temporary files:
del "%_LIST%" "%_TEMP%"

endlocal
exit /B

If your exclusion list, say strictFileNames.txt this time, holds pure file names rather than full file paths, like for example,...:

restricted.ts
excluded.ts
[special].ts
confidential.ts
.config.ts
conf.ts

...the approach is slightly different, because only the last path element of the file list Files.txt is to be taken into account. To achieve this, you need to precede every file name of the exclusion list by a path separator, again an escaped one like \\ for the aforementioned reason, in order to avoid wrong matches; for instance, file.ext would match both D:\Data\file.ext and D:\Data\X-file.ext, but \file.ext would match the former only, given that the /X option is replaced by /E this time.

Here is a script which accomplishes that:

@echo off
setlocal EnableExtensions DisableDelayedExpansion

rem // Define constants here:
set "_ROOT=D:\Project\TypeScript"    & rem // (path of root directory)
set "_MASK=*.ts"                     & rem // (file search pattern)
set "_LIST=.\Files.txt"              & rem // (path to file list)
set "_EXCL=.\strictFileNames.txt"    & rem // (path to exclusion list)
set "_TEMP=%TEMP%\%~n0_%RANDOM%.tmp" & rem // (temporary exclusion list)
set "_FILT=.\tsFiles.txt"            & rem // (path to filtered file list)
if not defined _FILT set "_FILT=con"

rem // Generate list of files:
dir /S /B /A:-D "%_ROOT%\%_MASK%" > "%_LIST%"

rem // Modify exclusion list:
rem /* precede every file with an escaped path separator `\\`,
rem    so no other characters can appear escaped to `findstr`: */
> "%_TEMP%" (
    for /F "usebackq delims= eol=|" %%F in ("%_EXCL%") do (
        echo(\\%%F
    )
)

rem // Filter out files that occur in modified exclusion list:
findstr /L /E /V /I /G:"%_TEMP%" "%_LIST%" > "%_FILT%"

rem // Clean up temporary files:
del "%_LIST%" "%_TEMP%"

endlocal
exit /B

All of the above sample file contents are chosen so that you can easily play around with them and see the differences when using the options /X or /E and when doubling the path separators \ or not.


问:
Laravel Queue Worker, RabbitMQ and running jobs generated remotely
I'll preface this by admitting slight sleep-deprivation.

The setup is as follows:

API Endpoint (Server A) receives an incoming call, and adds this to a specific queue on the RabbitMQ Server (Server B).

RabbitMQ (Server B) is simply a RabbitMQ Queue Server. Nothing more, nothing less.

Laravel Installation (Server C) is our actual Laravel install, which is meant to look for jobs on specific queues and do things with them.

We have a RabbitMQ package in the Laravel install, which allows the use of the regular Laravel Queue mechanics over a RabbitMQ connection.

The issue I've come across is that we can spawn a worker for a queue - but since we're not generating the jobs passing a $job class (the job content itself is most often a JSON array), the Laravel install has no idea what to do with the job.

So my question revolves mainly around how to approach a scenario like this. I'm thinking that using the Queue-functionality in Laravel won't do what I need it to do. Can you see an approach that I'm missing? Do I really need to spawn a daemon on a non-framework script to handle this?

Your input is much appreciated!

答: The solution is indeed to replicate the job code onto the one issuing the job. The code will not need every dependency that the job requires to actually function, as it only serializes the job from the one pushing it.</p>


问:
Single Column Finding similar values
I have a column sample data in EXCEL/SQL Table as below.
Want to group similar records. Solution in excel or sql should be fine.

```<code>GOPAL
Ramesh
A.GOPAL
SRINIVAS
Ramesh Reddy
G.SRINVIASA RAO
</code>```

The expected Output maybe sorting on similarity

```<code> GOPAL
 A.GOPAL
 Ramesh
 Ramesh Reddy
 SRINIVAS
 G.SRINVIASA RAO
</code>```

or

```<code>GOPAL  Group1
A.GOPAL Group1
Ramesh Group2
Ramesh Reddy Group2
SRINIVAS Group3
G.SRINVIASA RAO Group3
</code>```

答:
This is more of a comment than a complete answer, but may steer you in the right direction.

You will have to define a similarity metric that compares two strings and returns a value that quantifies the similarity between them.  See, for example, A better similarity ranking algorithm for variable length strings. How you implement that to use in a SQL query depends on what DBMS you're using.  You will also have to establish a threshold value of this metric that you want to define as 'close enough'.

Then you can write a SQL query something like this:

```<code>select
    a_val as group,
    b_val as stringval
from
    (
    select
        a_val,
        b_val,
        similarity
    from
        (
        select
            a.stringval as a_val,
            b.stringval as b_val,
            sim_metric(a.stringval, b.stringval) as similarity
        from
            stringlist as a,
            stringlist as b
        where
            b.stringval >= a.stringval
        ) as sim
    where
        similarity > similarity_threshold
    ) as grp
order by
    a_val;
</code>```

where sim_metric() is your similarity function and similarity_threshold is your chosen threshold.  One name in each group of similar names is used as the group name.

Title: Single Column Finding similar values

Body:
I have a column sample data in EXCEL/SQL Table as below.
Want to group similar records. Solution in excel or sql should be fine.

GOPAL
Ramesh
A.GOPAL
SRINIVAS
Ramesh Reddy
G.SRINVIASA RAO

The expected Output maybe sorting on similarity

 GOPAL
 A.GOPAL
 Ramesh
 Ramesh Reddy
 SRINIVAS
 G.SRINVIASA RAO

or

GOPAL  Group1
A.GOPAL Group1
Ramesh Group2
Ramesh Reddy Group2
SRINIVAS Group3
G.SRINVIASA RAO Group3

Body:
This is more of a comment than a complete answer, but may steer you in the right direction.

You will have to define a similarity metric that compares two strings and returns a value that quantifies the similarity between them.  See, for example, A better similarity ranking algorithm for variable length strings. How you implement that to use in a SQL query depends on what DBMS you're using.  You will also have to establish a threshold value of this metric that you want to define as 'close enough'.

Then you can write a SQL query something like this:

select
    a_val as group,
    b_val as stringval
from
    (
    select
        a_val,
        b_val,
        similarity
    from
        (
        select
            a.stringval as a_val,
            b.stringval as b_val,
            sim_metric(a.stringval, b.stringval) as similarity
        from
            stringlist as a,
            stringlist as b
        where
            b.stringval >= a.stringval
        ) as sim
    where
        similarity > similarity_threshold
    ) as grp
order by
    a_val;

where sim_metric() is your similarity function and similarity_threshold is your chosen threshold.  One name in each group of similar names is used as the group name.


问:
Using typedef inside template specializations
I'am newbie in c++, and i'm trying to write an additional template which contains type char or type int. After that I want to use this template in other template to select the type of data, depending of input data padding.

```<code>template <bool isPadding>
class PaddingTemplate;

template <>
class PaddingTemplate<false>
{
public:
    typedef char Type;
};

template <>
class PaddingTemplate<true>
{
public:
   typedef int Type;
};

template <class T, bool Padding = ((sizeof(T) % sizeof(int)) == 0)>
class ObjectComparator
{
private:
    typedef     PaddingTemplate<Padding>    PaddingTrick;
    typename    PaddingTrick::Type          DataType;

    DataType Shadow[sizeof(T) / sizeof(DataType)];
};
</code>```

I get this compiler error

Compiler msg

How to solve the problem and automate the choice of data type depending on data padding?

答:
DataType isn't actually a type. It's a instance of PaddingTrick::Type, which is why the next line is giving you an error. You need to do:

```<code>typedef typename PaddingTrick::Type DataType;
</code>```

Body:
I'am newbie in c++, and i'm trying to write an additional template which contains type char or type int. After that I want to use this template in other template to select the type of data, depending of input data padding.

template <bool isPadding>
class PaddingTemplate;

template <>
class PaddingTemplate<false>
{
public:
    typedef char Type;
};

template <>
class PaddingTemplate<true>
{
public:
   typedef int Type;
};

template <class T, bool Padding = ((sizeof(T) % sizeof(int)) == 0)>
class ObjectComparator
{
private:
    typedef     PaddingTemplate<Padding>    PaddingTrick;
    typename    PaddingTrick::Type          DataType;

    DataType Shadow[sizeof(T) / sizeof(DataType)];
};

I get this compiler error

Compiler msg

How to solve the problem and automate the choice of data type depending on data padding?

Body:
DataType isn't actually a type. It's a instance of PaddingTrick::Type, which is why the next line is giving you an error. You need to do:

typedef typename PaddingTrick::Type DataType;


问:
Get itunes link for app before submitting
I read in another post that you can submit the app without the binary but I based on what I have seen this is no longer possible. It seems you cannot submit without the binary and the binary is submitted through the application loader. Is there any other known way to get the itunes/app store link to my app before I submit the binary?</p>

答:
If AdWords does not allow a link to iTunes, this will solve it...

If you use the link generated at the bottom of iTunesConnect, and you are selling internationally, you will find /us/ or /gb/ or /de/ etc that indicates the language of the relevant store. Adwords will not approve a link with the language indicated.

Why?

Because Adwords does not accept redirects and unmatched URLs. If the link is to the USA store, but the Adword test originates in Germany, then a redirect is detected. Of course, this behavior is correct because no matter what the link says the user will go to her local app store.

Solution: Edit the link from iTunes Connect. Strip out unneeded info. Simply match the display and final URL, disregarding any message about length in the display URL warning text.

URL copied from iTunes:
https://itunes.apple.com/us/app/this-is-my-app-name/id1111111111?ls=1&mt=8

Edited URL suitable for AdWords

DISPLAY URL
itunes.apple.com/app/id111111111

FINAL URL
http://itunes.apple.com/app/id111111111

notes:
- appstore.com     is a redirect
- itunes.apple.com    by itself is a redirect. Only in full as above does it go directly to your app page.
- When one URL - no matter how valid - redirects, then the result is mismatched URLs.

/gb

ContentLicense: CC BY-SA 2.5


问:
std::set<Key, Comparator, Allocator>
I've tried to use set to keep some configurations in a trie lately.

I've found a doubt on the comparator, for instance :

```<code>    #include <iostream>
    #include <set>

    using namespace std;

    struct Node{
      int position;
      int reference;
      Node(int r, int p){
        this->position = p;
        this->reference = r;
      }
    };

    struct Node_c{
      const bool operator()(const Node& n1, const Node& n2){
        // return n1.reference != n2.reference;
        // i've tried some functions here, like n1.reference != n2.reference ? true : n1.position < n2.position;
      }
    };

    int main(){
      set<Node, Node_c> aNodes;

      aNodes.emplace(1,1);
      aNodes.emplace(1, 2); // i dont want to add this one, the reference already exists and the position is bigger than the last one
      aNodes.emplace(1, 0); // i want to replace the (1,1) for this one

      for(auto nd : aNodes){
        cout << nd.reference << ' ' << nd.position << '\n';
      }
    }
</code>```

How could I keep the nodes with the lesser positions in order but excluding the equals references?

thanks.

答:
```<code>#include <iostream>
#include <set>

struct Node {
    int position;
    int reference;

    Node(int r, int p)
            : position(p), reference(r) {
    }
};

struct NodeSet {
    struct AscendingReference {
        bool operator()(const Node &n1, const Node &n2) const {
            return n1.reference < n2.reference;
        }
    };

    struct SmallerPosition {
        bool operator()(const Node &n1, const Node &n2) const {
            return n1.position < n2.position;
        }
    };

    using Storage = std::set<Node, AscendingReference>;

    auto &propose(Node n) {
        auto ifind = storage_.find(n);
        if (ifind != std::end(storage_)) {
            if (not SmallerPosition()(n, *ifind))
                return *ifind;
            storage_.erase(ifind);
        }
        return *(storage_.insert(std::move(n)).first);
    }

    auto begin() const { return storage_.begin(); }

    auto end() const { return storage_.end(); }

private:
    Storage storage_;
};

int main() {
    NodeSet aNodes;

    aNodes.propose(Node(1, 1));
    aNodes.propose(Node(1, 2));
    aNodes.propose(Node(1, 0));

    for (auto nd : aNodes) {
        std::cout << nd.reference << ' ' << nd.position << '\n';
    }
}
</code>```

Title: std::set<Key, Comparator, Allocator>

Body:
I've tried to use set to keep some configurations in a trie lately.

I've found a doubt on the comparator, for instance :

    #include <iostream>
    #include <set>

    using namespace std;

    struct Node{
      int position;
      int reference;
      Node(int r, int p){
        this->position = p;
        this->reference = r;
      }
    };

    struct Node_c{
      const bool operator()(const Node& n1, const Node& n2){
        // return n1.reference != n2.reference;
        // i've tried some functions here, like n1.reference != n2.reference ? true : n1.position < n2.position;
      }
    };

    int main(){
      set<Node, Node_c> aNodes;

      aNodes.emplace(1,1);
      aNodes.emplace(1, 2); // i dont want to add this one, the reference already exists and the position is bigger than the last one
      aNodes.emplace(1, 0); // i want to replace the (1,1) for this one

      for(auto nd : aNodes){
        cout << nd.reference << ' ' << nd.position << '\n';
      }
    }

How could I keep the nodes with the lesser positions in order but excluding the equals references?

thanks.


问:
Dynamic buttons - Open file, read and insert text into corresponding column
My code dynamically creates a certain amount of buttons given by users input from a QlineEdit box marked self.numberLine. Each button will open file dialog to allow user to specify a file which it searches file then inserts text into the corresponding QlineEdit. The issue I am having is that I can't identify which button is being pressed, so I can't fill the corresponding columns QLineEdit fields.

I have it working somewhat, but when I click the 2nd button it just adds to the 1st column, instead of 2nd column

The clear button does nothing

Example:
if user inputs '3' in numberLine widget and clicks 'ok', it will create 3 columns of widgets, which the top widget will be the button that opens a file dialog for user. The other widgets beneath are the QlineEdit entries

On a side note, when the user changes their number, it creates the right amount of columns, but it doesn't insert anything when I select the file to be searched.

Any clue what I am missing?

Image

```<code>    spacer1 = QtWidgets.QSpacerItem(0, 0, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
    spacer2 = QtWidgets.QSpacerItem(0, 0, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)

    self.hbutton.addItem(spacer1)
    self.hbutton.addItem(spacer2)
    self.hboxlayout = QtWidgets.QHBoxLayout()
    self.hboxlayout0 = QtWidgets.QHBoxLayout()
    self.hboxlayout1 = QtWidgets.QHBoxLayout()
    self.hboxlayout2 = QtWidgets.QHBoxLayout()
    self.hboxlayout3 = QtWidgets.QHBoxLayout()
    self.hboxlayout4 = QtWidgets.QHBoxLayout()
    self.hboxlayout5 = QtWidgets.QHBoxLayout()

    self.gridLayout_12.addLayout(self.hbutton, 1, 1, 1, 1)
    self.gridLayout_12.addLayout(self.hboxlayout, 0, 1, 1, 1)
    self.gridLayout_12.addLayout(self.hboxlayout0, 1, 1, 1, 1)
    self.gridLayout_12.addLayout(self.hboxlayout1, 2, 1, 1, 1)
    self.gridLayout_12.addLayout(self.hboxlayout2, 3, 1, 1, 1)
    self.gridLayout_12.addLayout(self.hboxlayout3, 4, 1, 1, 1)
    self.gridLayout_12.addLayout(self.hboxlayout4, 6, 1, 1, 1)
    self.gridLayout_12.addLayout(self.hboxlayout5, 7, 1, 1, 1)
    self.pushButton_9.clicked.connect(self.addLineEdit)

    self.numberLine = QtWidgets.QLineEdit()
    self.numberLine.setMaximumSize(QtCore.QSize(60, 16777215))
    self.numberLine.setObjectName("self.numberLine")
    self.horizontalLayout_7.addWidget(self.numberLine)
    self.Array = []
    self.PDiffEntryList = []

def clearLayout(self):
    # del self.Array[:]
    while  self.hboxlayout0.count():
        child =  self.hboxlayout.takeAt(0)
        child1 = self.hboxlayout0.takeAt(0)
        child2 = self.hboxlayout1.takeAt(0)
        child3 = self.hboxlayout2.takeAt(0)
        child4 = self.hboxlayout3.takeAt(0)
        child5 = self.hboxlayout4.takeAt(0)
        child6 = self.hboxlayout5.takeAt(0)
        if child.widget():
            child.widget().deleteLater()
        if child1.widget():
            child1.widget().deleteLater()
        if child2.widget():
            child2.widget().deleteLater()
        if child3.widget():
            child3.widget().deleteLater()
        if child4.widget():
            child4.widget().deleteLater()
        if child5.widget():
            child5.widget().deleteLater()
        if child6.widget():
            child6.widget().deleteLater()

def addLineEdit(self):
    try:
        self.clearLayout()
        self.FileButton = {}
        for i in range(int(self.numberLine.text())):
            self.FileButton[i] = QtWidgets.QPushButton(self.centralwidget)
            self.FileButton[i].setText('File')
            self.FileButton[i].setMaximumSize(QtCore.QSize(50, 16777215))
            self.hboxlayout.addWidget(self.FileButton[i])
            self.FileButton[i].clicked.connect(lambda i=i: self.openfile(i))

            self.le = QtWidgets.QLineEdit()
            self.le.setMaximumSize(QtCore.QSize(50, 16777215))
            self.hboxlayout0.addWidget(self.le)

            self.le1 = QtWidgets.QLineEdit()
            self.le1.setMaximumSize(QtCore.QSize(50, 16777215))
            self.hboxlayout1.addWidget(self.le1)

            self.le2 = QtWidgets.QLineEdit()
            self.le2.setMaximumSize(QtCore.QSize(50, 16777215))
            self.hboxlayout2.addWidget(self.le2)

            self.le3 = QtWidgets.QLineEdit()
            self.le3.setMaximumSize(QtCore.QSize(50, 16777215))
            self.hboxlayout3.addWidget(self.le3)

            self.le4 = QtWidgets.QLineEdit()
            self.le4.setMaximumSize(QtCore.QSize(50, 16777215))
            self.hboxlayout4.addWidget(self.le4)

            self.le5 = QtWidgets.QLineEdit()
            self.le5.setMaximumSize(QtCore.QSize(50, 16777215))
            self.hboxlayout5.addWidget(self.le5)
            self.PDiffEntryList.append(self.le)
    except:
        print('')
def searchfile(self,dir):
    try:
        with open(dir) as f:
            content = f.readlines()

            # # Main Info - Ps, Pd, Ts
            MainList = content[44].split()
            RPM = str(round(float(MainList[0]), 2))
            Ps = str(round(float(MainList[1]), 2))
            Ts = str(round(float(MainList[2]), 2))
            Pd = str(round(float(MainList[3]), 2))
            Ratio = str(round(Pd / Ps, 2))
            DiffP = str(round(Pd - Ps, 2))
            self.input(i)
    except:
        print('Only out files')
def input(self,i):
    if i == 0:
        print('0')
    elif i == 1:
        print('1')
def openfile(self,i):
    filename = QtWidgets.QFileDialog.getOpenFileName(self, 'Choose file')
    dir = filename[0]
    directory = os.path.split(dir)[0]
    self.searchfile(dir,i)
</code>```

答:
There are a lot of weird things you are doing. For example, not sure why you are declaring "i" a global or what variable names you are choosing. To address your main question though, you are iterating through a for loop where you create an object with the same name over and over again.

```<code> try:
        self.clearLayout()
        self.file_buttons = {}
        for i in range(int(self.numberLine.text())):
            self.file_buttons[i] = QtWidgets.QPushButton(self.centralwidget)
</code>```

Now you can refer to self.file_buttons[i] for any changes you want to make to the button, but it is actually being stored as a separate object each time. The same applies for all of the Line Edit variables that you create.

In general, you seem to be creating the same objects over and over gain and just writing out different names (object1, object2, etc.). That's a good opportunity to use an array or a dictionary to iterate through and create all of those. It will make it easier to keep track of what is going on and much more flexible.

Body:
My code dynamically creates a certain amount of buttons given by users input from a QlineEdit box marked self.numberLine. Each button will open file dialog to allow user to specify a file which it searches file then inserts text into the corresponding QlineEdit. The issue I am having is that I can't identify which button is being pressed, so I can't fill the corresponding columns QLineEdit fields.

I have it working somewhat, but when I click the 2nd button it just adds to the 1st column, instead of 2nd column

The clear button does nothing

Example:
if user inputs '3' in numberLine widget and clicks 'ok', it will create 3 columns of widgets, which the top widget will be the button that opens a file dialog for user. The other widgets beneath are the QlineEdit entries

On a side note, when the user changes their number, it creates the right amount of columns, but it doesn't insert anything when I select the file to be searched.

Any clue what I am missing?

Image

    spacer1 = QtWidgets.QSpacerItem(0, 0, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
    spacer2 = QtWidgets.QSpacerItem(0, 0, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)

    self.hbutton.addItem(spacer1)
    self.hbutton.addItem(spacer2)
    self.hboxlayout = QtWidgets.QHBoxLayout()
    self.hboxlayout0 = QtWidgets.QHBoxLayout()
    self.hboxlayout1 = QtWidgets.QHBoxLayout()
    self.hboxlayout2 = QtWidgets.QHBoxLayout()
    self.hboxlayout3 = QtWidgets.QHBoxLayout()
    self.hboxlayout4 = QtWidgets.QHBoxLayout()
    self.hboxlayout5 = QtWidgets.QHBoxLayout()

    self.gridLayout_12.addLayout(self.hbutton, 1, 1, 1, 1)
    self.gridLayout_12.addLayout(self.hboxlayout, 0, 1, 1, 1)
    self.gridLayout_12.addLayout(self.hboxlayout0, 1, 1, 1, 1)
    self.gridLayout_12.addLayout(self.hboxlayout1, 2, 1, 1, 1)
    self.gridLayout_12.addLayout(self.hboxlayout2, 3, 1, 1, 1)
    self.gridLayout_12.addLayout(self.hboxlayout3, 4, 1, 1, 1)
    self.gridLayout_12.addLayout(self.hboxlayout4, 6, 1, 1, 1)
    self.gridLayout_12.addLayout(self.hboxlayout5, 7, 1, 1, 1)
    self.pushButton_9.clicked.connect(self.addLineEdit)

    self.numberLine = QtWidgets.QLineEdit()
    self.numberLine.setMaximumSize(QtCore.QSize(60, 16777215))
    self.numberLine.setObjectName("self.numberLine")
    self.horizontalLayout_7.addWidget(self.numberLine)
    self.Array = []
    self.PDiffEntryList = []

def clearLayout(self):
    # del self.Array[:]
    while  self.hboxlayout0.count():
        child =  self.hboxlayout.takeAt(0)
        child1 = self.hboxlayout0.takeAt(0)
        child2 = self.hboxlayout1.takeAt(0)
        child3 = self.hboxlayout2.takeAt(0)
        child4 = self.hboxlayout3.takeAt(0)
        child5 = self.hboxlayout4.takeAt(0)
        child6 = self.hboxlayout5.takeAt(0)
        if child.widget():
            child.widget().deleteLater()
        if child1.widget():
            child1.widget().deleteLater()
        if child2.widget():
            child2.widget().deleteLater()
        if child3.widget():
            child3.widget().deleteLater()
        if child4.widget():
            child4.widget().deleteLater()
        if child5.widget():
            child5.widget().deleteLater()
        if child6.widget():
            child6.widget().deleteLater()

def addLineEdit(self):
    try:
        self.clearLayout()
        self.FileButton = {}
        for i in range(int(self.numberLine.text())):
            self.FileButton[i] = QtWidgets.QPushButton(self.centralwidget)
            self.FileButton[i].setText('File')
            self.FileButton[i].setMaximumSize(QtCore.QSize(50, 16777215))
            self.hboxlayout.addWidget(self.FileButton[i])
            self.FileButton[i].clicked.connect(lambda i=i: self.openfile(i))

            self.le = QtWidgets.QLineEdit()
            self.le.setMaximumSize(QtCore.QSize(50, 16777215))
            self.hboxlayout0.addWidget(self.le)

            self.le1 = QtWidgets.QLineEdit()
            self.le1.setMaximumSize(QtCore.QSize(50, 16777215))
            self.hboxlayout1.addWidget(self.le1)

            self.le2 = QtWidgets.QLineEdit()
            self.le2.setMaximumSize(QtCore.QSize(50, 16777215))
            self.hboxlayout2.addWidget(self.le2)

            self.le3 = QtWidgets.QLineEdit()
            self.le3.setMaximumSize(QtCore.QSize(50, 16777215))
            self.hboxlayout3.addWidget(self.le3)

            self.le4 = QtWidgets.QLineEdit()
            self.le4.setMaximumSize(QtCore.QSize(50, 16777215))
            self.hboxlayout4.addWidget(self.le4)

            self.le5 = QtWidgets.QLineEdit()
            self.le5.setMaximumSize(QtCore.QSize(50, 16777215))
            self.hboxlayout5.addWidget(self.le5)
            self.PDiffEntryList.append(self.le)
    except:
        print('')
def searchfile(self,dir):
    try:
        with open(dir) as f:
            content = f.readlines()

            # # Main Info - Ps, Pd, Ts
            MainList = content[44].split()
            RPM = str(round(float(MainList[0]), 2))
            Ps = str(round(float(MainList[1]), 2))
            Ts = str(round(float(MainList[2]), 2))
            Pd = str(round(float(MainList[3]), 2))
            Ratio = str(round(Pd / Ps, 2))
            DiffP = str(round(Pd - Ps, 2))
            self.input(i)
    except:
        print('Only out files')
def input(self,i):
    if i == 0:
        print('0')
    elif i == 1:
        print('1')
def openfile(self,i):
    filename = QtWidgets.QFileDialog.getOpenFileName(self, 'Choose file')
    dir = filename[0]
    directory = os.path.split(dir)[0]
    self.searchfile(dir,i)

Body:
There are a lot of weird things you are doing. For example, not sure why you are declaring "i" a global or what variable names you are choosing. To address your main question though, you are iterating through a for loop where you create an object with the same name over and over again.

 try:
        self.clearLayout()
        self.file_buttons = {}
        for i in range(int(self.numberLine.text())):
            self.file_buttons[i] = QtWidgets.QPushButton(self.centralwidget)

Now you can refer to self.file_buttons[i] for any changes you want to make to the button, but it is actually being stored as a separate object each time. The same applies for all of the Line Edit variables that you create.

In general, you seem to be creating the same objects over and over gain and just writing out different names (object1, object2, etc.). That's a good opportunity to use an array or a dictionary to iterate through and create all of those. It will make it easier to keep track of what is going on and much more flexible.


问:
How to release memory managed by boost fast_pool_allocator?
I try to use boost::fast_pool_allocator on list to manage memory allocation.
Here is sample code I have,

```<code>    boost::fast_pool_allocator<int> alloc;
    std::list<int, boost::fast_pool_allocator<int>> data_pool(alloc);
    data_pool.push_back(1);
    data_pool.push_back(2);
    data_pool.clear();
    boost::singleton_pool<boost::fast_pool_allocator_tag, sizeof(int)>::purge_memory();
</code>```

But the purge_memory never releases memory. I googled and see somebody mentioned sizeof(int) is not correct size for list node.

But how can I get correct list node size to make purge_memory works?

答: Calling singleton_pool::release_memory() releases the allocated pool.

Body:
I try to use boost::fast_pool_allocator on list to manage memory allocation.
Here is sample code I have,

    boost::fast_pool_allocator<int> alloc;
    std::list<int, boost::fast_pool_allocator<int>> data_pool(alloc);
    data_pool.push_back(1);
    data_pool.push_back(2);
    data_pool.clear();
    boost::singleton_pool<boost::fast_pool_allocator_tag, sizeof(int)>::purge_memory();

But the purge_memory never releases memory. I googled and see somebody mentioned sizeof(int) is not correct size for list node.

But how can I get correct list node size to make purge_memory works?


问:
Microsoft rxNeuralNet acceleration
In Microsoft's R NeuralNet package, there is an option for acceleration, where you can specify "GPU" or "SSE". I know what GPU is, does anyone know what SSE acceleration is?

Thanks!

答:
SSE stands for "Streaming SIMD Extensions".  SIMD stands for "Single Instruction Multiple Data".

https://www.intel.com/content/www/us/en/support/processors/000005779.html

David

Title: Microsoft rxNeuralNet acceleration


问:
Is there any way to know the size of what will be printed to standard output in C++?
For example, if I use the following:

```<code>cout << "hello world";
</code>```

Is there any way to know the size of what's being printed to stdout?

答:
I doubt there is a standard way to determine how much bytes will be written to the standard output before writing it.

What you could do is, write it to an ostringstream and get the size of the stream. This doubles the work, but gives you a standard generic way to determine how many bytes will an object take when written to a stream:

```<code>template <class T>
std::size_t stream_len(const T& t)
{
    std::ostringstream oss;
    oss << t;
    return oss.tellp();
}
</code>```

Here is a demo: http://coliru.stacked-crooked.com/a/3de664b4059250ae

Body:
For example, if I use the following:

cout << "hello world";

Is there any way to know the size of what's being printed to stdout?

Body:
I doubt there is a standard way to determine how much bytes will be written to the standard output before writing it.

What you could do is, write it to an ostringstream and get the size of the stream. This doubles the work, but gives you a standard generic way to determine how many bytes will an object take when written to a stream:

template <class T>
std::size_t stream_len(const T& t)
{
    std::ostringstream oss;
    oss << t;
    return oss.tellp();
}

Here is a demo: http://coliru.stacked-crooked.com/a/3de664b4059250ae


问:
How do you invert scipy quad function to pass in an arc length and receive a value for (t)?
If I were to run something like the code below where I pass in the minor and major arc of an ellipse as 3.05 and 2.23 with the 50 degree angle formed by the arc, how would I be able to take the output of 2.531432761012828 as the arc length and pass it back through to solve for t? Thanks!

```<code>import math
from scipy.integrate import quad
import numpy as np
t = math.atan(3.05*math.tan(5*math.pi/18)/2.23)
Dx = lambda t: -3.05 * np.sin(t)
Dy = lambda t: 2.23 * np.cos(t)
quad(lambda t: np.sqrt(Dx(t)**2 + Dy(t)**2), 0, t)
</code>```

The output of the last one was: (2.531432761012828, 2.810454936566873e-14)

答:
To find the upper limit of integration, given the value of the integral, one can apply fsolve to the function which calculates that integral for variable upper limits. Example (not repeating the lines you already have):

```<code>from scipy.optimize import fsolve
target = 2.531432761012828
fun = lambda s: quad(lambda t: np.sqrt(Dx(t)**2 + Dy(t)**2), 0, s)[0] - target
s0 = fsolve(fun, 0)[0]
print(s0)
</code>```

This prints 1.02051.

I dislike having both the variable of integration and the upper limit denoted by the same letter, so in my code the upper limit is called s.

Body:
If I were to run something like the code below where I pass in the minor and major arc of an ellipse as 3.05 and 2.23 with the 50 degree angle formed by the arc, how would I be able to take the output of 2.531432761012828 as the arc length and pass it back through to solve for t? Thanks!

import math
from scipy.integrate import quad
import numpy as np
t = math.atan(3.05*math.tan(5*math.pi/18)/2.23)
Dx = lambda t: -3.05 * np.sin(t)
Dy = lambda t: 2.23 * np.cos(t)
quad(lambda t: np.sqrt(Dx(t)**2 + Dy(t)**2), 0, t)

The output of the last one was: (2.531432761012828, 2.810454936566873e-14)

Body:
To find the upper limit of integration, given the value of the integral, one can apply fsolve to the function which calculates that integral for variable upper limits. Example (not repeating the lines you already have):

from scipy.optimize import fsolve
target = 2.531432761012828
fun = lambda s: quad(lambda t: np.sqrt(Dx(t)**2 + Dy(t)**2), 0, s)[0] - target
s0 = fsolve(fun, 0)[0]
print(s0)

This prints 1.02051.

I dislike having both the variable of integration and the upper limit denoted by the same letter, so in my code the upper limit is called s.


问:
kibana-time-plugin downloaded but bower install not working and even kibana not working
I wanted to have a Widget to view and edit the time range from within dashboards of kibana. So after lot of research i found a plugin as Kibana-time-plugin. Ref: https://github.com/nreese/kibana-time-plugin

Currently i am using kibana 5.4.0 in my local. After installing the plugin i have tried "bower install" as per the command specified in git page. But getting an error as :-

$ bower install

/usr/bin/env: ‘node’: No such file or directory

And even if Kibana is not running and giving an error as below attached image:-
kibana5.4.0

Can anyone Guide me on this ?

Thanks in Advance !!!!!!!!!!!!!!!

答:
I think the optimization failures may be due to file permissions, the plugin files need to be accessible by the kibana user. Specifically check this instruction:
Installing plugins with linux packages

Here is a complete script that worked for me. I am new to Kibana and Kibana plugins so any feedback appreciated. Two important notes:
1) I am pulling the zip file from S3 so you will need to edit that.
2) Be sure to restart kibana afterwards and check the logs

```<code>#!/bin/bash
# install nodejs and npm
sudo curl --silent --location https://rpm.nodesource.com/setup_6.x | sudo bash -
sudo yum install -y nodejs
sudo npm install -g bower

# copy the plugin zip and unzip it and fix the name
cd /usr/share/kibana/plugins
sudo aws s3 cp s3://<YOUR-BUCKET>/kibana-time-plugin-master.zip .
sudo unzip kibana-time-plugin-master.zip
sudo mv kibana-time-plugin-master kibana-time-plugin

# install the plugin
cd /usr/share/kibana/plugins/kibana-time-plugin
sudo sed -i -e 's/5.0.0/5.4.2/' package.json
sudo chown -R kibana:kibana *
sudo mkdir -p /home/kibana
sudo chown -R kibana:kibana /home/kibana
sudo -u kibana bower install
</code>```

Body:
I think the optimization failures may be due to file permissions, the plugin files need to be accessible by the kibana user. Specifically check this instruction:
Installing plugins with linux packages

Here is a complete script that worked for me. I am new to Kibana and Kibana plugins so any feedback appreciated. Two important notes:
1) I am pulling the zip file from S3 so you will need to edit that.
2) Be sure to restart kibana afterwards and check the logs

#!/bin/bash
# install nodejs and npm
sudo curl --silent --location https://rpm.nodesource.com/setup_6.x | sudo bash -
sudo yum install -y nodejs
sudo npm install -g bower

# copy the plugin zip and unzip it and fix the name
cd /usr/share/kibana/plugins
sudo aws s3 cp s3://<YOUR-BUCKET>/kibana-time-plugin-master.zip .
sudo unzip kibana-time-plugin-master.zip
sudo mv kibana-time-plugin-master kibana-time-plugin

# install the plugin
cd /usr/share/kibana/plugins/kibana-time-plugin
sudo sed -i -e 's/5.0.0/5.4.2/' package.json
sudo chown -R kibana:kibana *
sudo mkdir -p /home/kibana
sudo chown -R kibana:kibana /home/kibana
sudo -u kibana bower install


问:
Page view counter in mvc
I want to create function to update count for page views
I use ado.net i build update method to update count by 1 every page load and lookup by id

Problem :
We have large visitors it can reach to 3k online user per second and execute it by ajax call
Its make database high performance and table locked and site run out memory
Is there are any solution for it ?

答:
Rather than execute SQL on every page view, you should increment an in-memory int or long using Interlocked.Increment. Then on every (for example) 5,000 increments (checked using Mod) then you should hit the database and increase the pageview count by 5,000.

It does mean the page view count will be updated slower than currently, but it will massively reduce DB load.

Also consider using Redis to store the counts, rather than whatever your existing database is. Redis is awesome for this kind of use-case.

Title: Page view counter in mvc


问:
For jmeter post request, how can I generate input json from csv file?
I am trying to make a post rest call to my service. My sample input json file is,

{
  "$id": "1",
  "description": "sfdasd"
}

I have one csv file which contain a bunch of id and description, So is there a option where I can convert csv file to json objects and pass them to post call?

答:
CSV data can be converted to JSON via a POJO using Jackson. If a POJO is not already defined or required, you can always use the Java Collection classes to store parsed data and later convert it to JSON. http://www.novixys.com/blog/convert-csv-json-java/ is a good reference on how to convert csv to java.
You can check the following links too.
1. directly convert CSV file to JSON file using the Jackson library
2. Converting an CSV file to a JSON object in Java</p>


问:
clojure-api: Single main clj for multiple API handlers
The below is my app project.clj

```<code>(defproject clojure-my-app-api "0.1.0-SNAPSHOT"
      :description "FIXME: write description"
      :url "http://example.com/FIXME"
      :license {:name "Eclipse Public License"
                :url "http://www.eclipse.org/legal/epl-v10.html"}
      :ring {:handler clojure-my-app-api.core/app}
      :dependencies [[org.clojure/clojure "1.8.0"]
                     [metosin/compojure-api "1.1.10"]
                     [ring/ring-core "1.4.0"]
                     [ring/ring-jetty-adapter "1.4.0"]]
      :main clojure-my-app-api.core)
</code>```

and my app core.clj is

```<code>(ns clojure-my-app-api.core
  (:require [ring.adapter.jetty :as jetty])
  (:require [compojure.api.sweet :refer :all])
  (:require [ring.util.http-response :refer :all]))

(defapi app
  (GET "/hello" []
    :query-params [name :- String]
    (ok {:message (str "Dear " name ", Hello I am here ")})))

(jetty/run-jetty app {:port 3000})
</code>```

My doubt is, Is it mandatory to put (jetty/run-jetty app {:port 3000}) in every clj class if we have multiple classes for handling multiple API requests.

Can you please help me out is there any single main class mechanism for multiple clj class to handle different API path.

I have modified my code.

project.clj

```<code>(defproject clojure-dauble-business-api "0.1.0-SNAPSHOT"
  :description "FIXME: write description"
  :url "http://example.com/FIXME"
  :license {:name "Eclipse Public License"
            :url "http://www.eclipse.org/legal/epl-v10.html"}
  :ring {:handler {clojure-dauble-business-api.core/app
                  clojure-dauble-business-api.test/test1}}
  :repl-options {:init-ns clojure-dauble-business-api.user}
  :dependencies [[org.clojure/clojure "1.8.0"]
                 [metosin/compojure-api "1.1.10"]
                 [ring/ring-core "1.4.0"]
                 [ring/ring-jetty-adapter "1.4.0"]]
  :main clojure-dauble-business-api.user)
</code>```

user.clj

```<code>(ns clojure-dauble-business-api.user
  (:require [ring.adapter.jetty :as jetty])
  (:require [compojure.api.sweet :refer :all])
  (:require [ring.util.http-response :refer :all])
  (:require [clojure-dauble-business-api.core :as core])
  (:require [clojure-dauble-business-api.test :as test]))

(jetty/run-jetty (list core/app test/test) {:port 3000})
</code>```

core.clj

```<code>(ns clojure-dauble-business-api.core
  (:require [ring.adapter.jetty :as jetty])
  (:require [compojure.api.sweet :refer :all])
  (:require [ring.util.http-response :refer :all]))

(defapi app
  (GET "/hello" []
    :query-params [name :- String]
    (ok {:message (str "Dear " name ", Hello I am here ")})))
</code>```

test.clj

```<code>(ns clojure-dauble-business-api.test
  (:require [ring.adapter.jetty :as jetty])
  (:require [compojure.api.sweet :refer :all])
  (:require [ring.util.http-response :refer :all]))

(defapi test
  (GET "/ping" []
    :query-params [name :- String]
    (ok {:message (str "Dear " name ", Hello I am here ")})))
</code>```

Error while running http://localhost:3000/hello?name=acbd endpoint in Postman

```<code>2017-07-08 10:46:34.413:WARN:oejs.HttpChannel:qtp191004666-15: /hello?name=abcd
java.lang.ClassCastException: clojure.lang.PersistentList cannot be cast to clojure.lang.IFn
    at ring.adapter.jetty$proxy_handler$fn__1401.invoke(jetty.clj:24)
    at ring.adapter.jetty.proxy$org.eclipse.jetty.server.handler.AbstractHandler$ff19274a.handle(Unknown Source)
    at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:97)
    at org.eclipse.jetty.server.Server.handle(Server.java:497)
    at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:310)
    at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:257)
    at org.eclipse.jetty.io.AbstractConnection$2.run(AbstractConnection.java:540)
    at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:635)
    at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:555)
    at java.lang.Thread.run(Thread.java:745)
</code>```

答:
I am a newbie too, but hope this helps:

This is how I have implemented. There is one file named user.clj which has

(jetty/run-jetty app {:port 3000})

and other common function that you may specify in main and then in project.clj
 :repl-options {:init-ns user}

you can also use injections to load namespaces but I have never used them.

Body:
The below is my app project.clj

(defproject clojure-my-app-api "0.1.0-SNAPSHOT"
      :description "FIXME: write description"
      :url "http://example.com/FIXME"
      :license {:name "Eclipse Public License"
                :url "http://www.eclipse.org/legal/epl-v10.html"}
      :ring {:handler clojure-my-app-api.core/app}
      :dependencies [[org.clojure/clojure "1.8.0"]
                     [metosin/compojure-api "1.1.10"]
                     [ring/ring-core "1.4.0"]
                     [ring/ring-jetty-adapter "1.4.0"]]
      :main clojure-my-app-api.core)

and my app core.clj is

(ns clojure-my-app-api.core
  (:require [ring.adapter.jetty :as jetty])
  (:require [compojure.api.sweet :refer :all])
  (:require [ring.util.http-response :refer :all]))

(defapi app
  (GET "/hello" []
    :query-params [name :- String]
    (ok {:message (str "Dear " name ", Hello I am here ")})))

(jetty/run-jetty app {:port 3000})

My doubt is, Is it mandatory to put (jetty/run-jetty app {:port 3000}) in every clj class if we have multiple classes for handling multiple API requests.

Can you please help me out is there any single main class mechanism for multiple clj class to handle different API path.

I have modified my code.

project.clj

(defproject clojure-dauble-business-api "0.1.0-SNAPSHOT"
  :description "FIXME: write description"
  :url "http://example.com/FIXME"
  :license {:name "Eclipse Public License"
            :url "http://www.eclipse.org/legal/epl-v10.html"}
  :ring {:handler {clojure-dauble-business-api.core/app
                  clojure-dauble-business-api.test/test1}}
  :repl-options {:init-ns clojure-dauble-business-api.user}
  :dependencies [[org.clojure/clojure "1.8.0"]
                 [metosin/compojure-api "1.1.10"]
                 [ring/ring-core "1.4.0"]
                 [ring/ring-jetty-adapter "1.4.0"]]
  :main clojure-dauble-business-api.user)

user.clj

(ns clojure-dauble-business-api.user
  (:require [ring.adapter.jetty :as jetty])
  (:require [compojure.api.sweet :refer :all])
  (:require [ring.util.http-response :refer :all])
  (:require [clojure-dauble-business-api.core :as core])
  (:require [clojure-dauble-business-api.test :as test]))

(jetty/run-jetty (list core/app test/test) {:port 3000})

core.clj

(ns clojure-dauble-business-api.core
  (:require [ring.adapter.jetty :as jetty])
  (:require [compojure.api.sweet :refer :all])
  (:require [ring.util.http-response :refer :all]))

(defapi app
  (GET "/hello" []
    :query-params [name :- String]
    (ok {:message (str "Dear " name ", Hello I am here ")})))

test.clj

(ns clojure-dauble-business-api.test
  (:require [ring.adapter.jetty :as jetty])
  (:require [compojure.api.sweet :refer :all])
  (:require [ring.util.http-response :refer :all]))

(defapi test
  (GET "/ping" []
    :query-params [name :- String]
    (ok {:message (str "Dear " name ", Hello I am here ")})))

Error while running http://localhost:3000/hello?name=acbd endpoint in Postman

2017-07-08 10:46:34.413:WARN:oejs.HttpChannel:qtp191004666-15: /hello?name=abcd
java.lang.ClassCastException: clojure.lang.PersistentList cannot be cast to clojure.lang.IFn
    at ring.adapter.jetty$proxy_handler$fn__1401.invoke(jetty.clj:24)
    at ring.adapter.jetty.proxy$org.eclipse.jetty.server.handler.AbstractHandler$ff19274a.handle(Unknown Source)
    at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:97)
    at org.eclipse.jetty.server.Server.handle(Server.java:497)
    at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:310)
    at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:257)
    at org.eclipse.jetty.io.AbstractConnection$2.run(AbstractConnection.java:540)
    at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:635)
    at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:555)
    at java.lang.Thread.run(Thread.java:745)


问:
WPF Dynamic Cursor
I am creating a vector graphic editor in WPF. I am rendering the artwork using a D3DImage that has been customised using SharpDX so that I use it with Direct2D. When an item is selected, resize handles appear around the selected item. I want the cursor to change when the user hovers over these resize handles, but they are rendered in Direct2D and are not WPF elements. How do I accomplish this?</p>

答:
Well, if you’re doing your own rendering to D3DImage, you gotta do your own hit testing.

If your geometry’s relatively simple (boxes, circles, polylines, not too many of them), you can hit test these handles shapes in mouse move event handler. Either manually, or by using e.g. FillContainsPoint D2D APIs.

Or, if you aren’t doing something very color-sensitive like a desktop publishing, you can encode resize handles in the color of your shapes. Use a couple of least significant bits of the blue channel (human eyes are least sensitive to blue), read the color under the mouse, change cursor accordingly to the blue color value.

Or, you can switch to DXGI_FORMAT_R16G16B16A16_UNORM for your render target (looks like D2D supports that format), this way you can add much more per-pixel data to your image without any visible artifacts (use lower bytes of each of the 3 color channels). This however complicates rendering, you’ll need to do one more pass to convert the texture into A8R8G8B8 for the WPF.

P.S. I wonder why don’t you use WPF elements instead? 2D vector graphics there is rather advanced. You can easily create/manipulate/fill/outline these shapes programmatically (just place then on a canvas), this way WPF will handle all these hit tests, and rendering, and more.

Title: WPF Dynamic Cursor


问:
How to setup a live template in intellij for a new file extension
I have a new customized file type with new file extension and I want to setup some Live Templates for that file type, Does anyone know how to do that?</p>

答: In order for the live template to be visible in your customized file type you need to select "Other" when defining the applicable contexts.Please see below:


问:
retrieving data in Indian language from MySql database using php shows unusual character set
I am retrieving data in Indian language and I am getting output as ??????????????????????????

NOTE : - I used this 2 line in my php script

```<code>header('Content-type: text/plain; charset=utf-8');
mysqli_set_charset($conn,'utf-8');
</code>```

and also I used utf8_general_ci encoding in databse and table.

my php script is

```<code><?php

require 'init.php';

header('Content-type: text/plain; charset=utf-8');
mysqli_set_charset($conn,'utf-8');

$table = $_GET['table_name'];

$sql = "SELECT * FROM ".$table;

$response = array();

$result = mysqli_query($conn,$sql);

if(mysqli_num_rows($result)>0) {
        while($row = mysqli_fetch_array($result)) {
        array_push($response, array('id'=>$row['id'],'text'=>$row['text']));
    }
    echo json_encode($response);
} else {
    echo "error";
}

mysqli_close($conn);

?>
</code>```

You can check the link http://www.sharefb.com/statusApp/readStatus.php?table_name=gujrati_attitude

答:
See "question marks" in Trouble with utf8 characters; what I see is not what I stored

If you still have trouble, provide

SHOW CREATE TABLE

Sample of the text being inserted

SELECT HEX(...) of a sample of the bad data (? = 3F)

Body:
I am retrieving data in Indian language and I am getting output as ??????????????????????????

NOTE : - I used this 2 line in my php script

header('Content-type: text/plain; charset=utf-8');
mysqli_set_charset($conn,'utf-8');

and also I used utf8_general_ci encoding in databse and table.

my php script is

<?php

require 'init.php';

header('Content-type: text/plain; charset=utf-8');
mysqli_set_charset($conn,'utf-8');

$table = $_GET['table_name'];

$sql = "SELECT * FROM ".$table;

$response = array();

$result = mysqli_query($conn,$sql);

if(mysqli_num_rows($result)>0) {
        while($row = mysqli_fetch_array($result)) {
        array_push($response, array('id'=>$row['id'],'text'=>$row['text']));
    }
    echo json_encode($response);
} else {
    echo "error";
}

mysqli_close($conn);

?>

You can check the link http://www.sharefb.com/statusApp/readStatus.php?table_name=gujrati_attitude


问:
How to return multiple values within a group of rows.
I have tried to use Max(), subqueries, and joins, but my knowledge is limited enough that I am not sure how to organize them. I was willing to just use several nested select statements, knowing it could be resource intensive, but I can't get it to work.

I need to return any nulls, as well as the highest ConfigID for each Location.

```<code>TABLE
ID     Location     ConfigID
1      AA           NULL
2      AA           2
3      AA           1
4      BB           5
5      BB           4
6      BB           3
7      CC           NULL
8      CC           6
</code>```

I want to see the results:

```<code>ID     Location     ConfigID
1      AA           NULL
2      AA           2
4      BB           5
7      CC           NULL
8      CC           6
</code>```

I have tried:

```<code>select ID, Location, ConfigID
from Table
where ConfigID is null
      or configID = (select ConfigID
                     from table
                     where Location in (select distinct Location
                                        from Table
                                        order by ConfigID desc
                                        )
                     )
</code>```

SQL server didn't like that because I cannot have an order by in a subquery unless Top is used. Now that I am looking at it again, I don't think that the order by is even within the correct subquery. It was as close as I could get. I was hopeful when I saw Select Max from each subset, but that was a dead-end, I think. Also, I don't believe that a self-join will work because the data I would self-join on is all in one column.

答:
You would better have separate queries for NULLs and highest ConfigID and then UNION them, then ORDER BY ID:

```<code>WITH cte
AS
(
    SELECT ROW_NUMBER() OVER(PARTITION BY Location ORDER BY Location, ConfigId DESC) AS rn, *
    FROM [Table]
    WHERE ConfigID IS NOT NULL
    UNION ALL
    SELECT 1, ID, Location, ConfigID
    FROM [Table]
    WHERE ConfigID IS NULL
)
SELECT ID, Location, ConfigID FROM cte
WHERE rn = 1
ORDER BY ID
</code>```

Link to SQL Fiddle.

Body:
I have tried to use Max(), subqueries, and joins, but my knowledge is limited enough that I am not sure how to organize them. I was willing to just use several nested select statements, knowing it could be resource intensive, but I can't get it to work.

I need to return any nulls, as well as the highest ConfigID for each Location.

TABLE
ID     Location     ConfigID
1      AA           NULL
2      AA           2
3      AA           1
4      BB           5
5      BB           4
6      BB           3
7      CC           NULL
8      CC           6

I want to see the results:

ID     Location     ConfigID
1      AA           NULL
2      AA           2
4      BB           5
7      CC           NULL
8      CC           6

I have tried:

select ID, Location, ConfigID
from Table
where ConfigID is null
      or configID = (select ConfigID
                     from table
                     where Location in (select distinct Location
                                        from Table
                                        order by ConfigID desc
                                        )
                     )

SQL server didn't like that because I cannot have an order by in a subquery unless Top is used. Now that I am looking at it again, I don't think that the order by is even within the correct subquery. It was as close as I could get. I was hopeful when I saw Select Max from each subset, but that was a dead-end, I think. Also, I don't believe that a self-join will work because the data I would self-join on is all in one column.

Body:
You would better have separate queries for NULLs and highest ConfigID and then UNION them, then ORDER BY ID:

WITH cte
AS
(
    SELECT ROW_NUMBER() OVER(PARTITION BY Location ORDER BY Location, ConfigId DESC) AS rn, *
    FROM [Table]
    WHERE ConfigID IS NOT NULL
    UNION ALL
    SELECT 1, ID, Location, ConfigID
    FROM [Table]
    WHERE ConfigID IS NULL
)
SELECT ID, Location, ConfigID FROM cte
WHERE rn = 1
ORDER BY ID

Link to SQL Fiddle.


问:
How to stop a python script launching many subprocesses from terminal
I have a python script which launches a sequence of subprocesses in a loop:

```<code>for c in cmds:
  subprocess.call(c, shell=True)
</code>```

When the script is running in terminal, I try to stop it with Ctrl+C or Ctrl+D, however, it will continue to launch next subprocess. How can I terminate the whole python script at once?

答: What likely happens is that ctrl-C is intercepted by you sub-process (running on the same terminal) and never gets to your Python script. What you can do is to check the return value of subprocess.call to see whether the child process was killed by a signal and decide whether you want to stop submitting new processes.

Body:
I have a python script which launches a sequence of subprocesses in a loop:

for c in cmds:
  subprocess.call(c, shell=True)

When the script is running in terminal, I try to stop it with Ctrl+C or Ctrl+D, however, it will continue to launch next subprocess. How can I terminate the whole python script at once?


问:
How can I convert a date from the format "dd/mm/yyyy" to "yyyy/dd/mm"?
I have a Textbox in which the user is supposed to enter a date in the format dd/mm/yyyy, this date is stored as yyyy/mm/dd in the database.

So I want the user to enter the date in dd/mm/yyyy format and later I want to convert to yyyy/mm/dd so that I can query database.

How can I convert the user input date dd/mm/yyyy to yyyy/mm/dd?

答:
Here's the way to convert a DateTime to a string:

```<code>dateTime.ToString("dddd, dd MMMM yyyy");
</code>```

Here are the different format of ToString

But I think it is better to use a DateTimePicker, you're sure to have a date and user can use keyboard to input a date.

Body:
Here's the way to convert a DateTime to a string:

dateTime.ToString("dddd, dd MMMM yyyy");

Here are the different format of ToString

But I think it is better to use a DateTimePicker, you're sure to have a date and user can use keyboard to input a date.


问:
no implicit conversion of Symbol into Integer in view forms
I am working on configuring the apartment gem for my rails app to give users the functionality to create subdomains. I have a nested form and when attempting to access "accounts/new" I am getting the following error:

```<code>no implicit conversion of Symbol into Integer in view forms
</code>```

accounts/new.html.erb

```<code><div>
   </div>
    <h2>Create an Account</h2>

<%= form_for @account do |f| %>
    <%= f.fields_for :owner do |o| %>
      <%= form_for o, :email do %>
        <%= o.text_field :email, class: 'form-control' %>
      <% end %>
     <%= form_for o, :password do %>
        <%= o.password_field :password, class: 'form-control' %>
      <% end %>
     <%= form_for o, :password_confirmation do %>
        <%= o.password_field :password_confirmation, class: 'form-control' %>
     <% end %>
   <% end %>

    <%= form_for f, :subdomain do %>
      <div class="input-group">
      <%= f.text_field :subdomain, class: 'form-control' %>
        <span class="input-group-addon">.scrumteam.com</span>
      </div>
      <% end %>
     <%= f.submit class: 'btn btn-primary' %>
    <% end %>
  </div>
</div>
</code>```

accounts_controller.rb

```<code>private
      def account_params
        params.require(:account).permit(:subdomain, :owner_attributes => [:email, :password, :password_confirmation])
      end
</code>```

答: Not sure if this is your route problem, but form_for creates an actual form tag in html. You only need (and should have) 1, the fields_for allows you to switch the form helpers to a different object, but you don't need to call form_for again within it. If you're just trying to group your form fields, you can just add some divs and/or labels.

Body:
I am working on configuring the apartment gem for my rails app to give users the functionality to create subdomains. I have a nested form and when attempting to access "accounts/new" I am getting the following error:

no implicit conversion of Symbol into Integer in view forms

accounts/new.html.erb

Create an Account

<%= form_for @account do |f| %>
    <%= f.fields_for :owner do |o| %>
      <%= form_for o, :email do %>
        <%= o.text_field :email, class: 'form-control' %>
      <% end %>
     <%= form_for o, :password do %>
        <%= o.password_field :password, class: 'form-control' %>
      <% end %>
     <%= form_for o, :password_confirmation do %>
        <%= o.password_field :password_confirmation, class: 'form-control' %>
     <% end %>
   <% end %>

    <%= form_for f, :subdomain do %>

      <%= f.text_field :subdomain, class: 'form-control' %>
        .scrumteam.com

      <% end %>
     <%= f.submit class: 'btn btn-primary' %>
    <% end %>

accounts_controller.rb

private
      def account_params
        params.require(:account).permit(:subdomain, :owner_attributes => [:email, :password, :password_confirmation])
      end


答:
You can use std::stringstream for this:

```<code>#include <sstream>
#include <iostream>

int main(){
  std::stringstream ss;
  int a = 3;
  ss<<"Hello, world! "<<a<<std::endl;
  std::cout<<"Size was: "<<ss.str().size()<<std::endl;
  std::cout<<ss.str()<<std::endl;
}
</code>```

The above returns 16: 14 character for "Hello, world!", 1 character for the contents of the variable a, and one character from std::endl.

Title: Is there any way to know the size of what will be printed to standard output in C++?

Body:
You can use std::stringstream for this:

#include <sstream>
#include <iostream>

int main(){
  std::stringstream ss;
  int a = 3;
  ss<<"Hello, world! "<<a<<std::endl;
  std::cout<<"Size was: "<<ss.str().size()<<std::endl;
  std::cout<<ss.str()<<std::endl;
}

The above returns 16: 14 character for "Hello, world!", 1 character for the contents of the variable a, and one character from std::endl.


问:
DrvFs location of %UserProfile%
From within the Windows Subsystem for Linux, how can I get the DrvFs path that points to what would be %UserProfile% inside the Windows personality?  I've seen Access Windows Environment Variables from within Bash in WSL. It seems rather involved for getting one environment variable, and requires hard-coding something from within %UserProfile% anyway ($LXSS_ROOT).

答:
This seems to work:

```<code>win_userprofile="$(cmd.exe /c "<nul set /p=%UserProfile%" 2>/dev/null)"

win_userprofile_drive="${win_userprofile%%:*}:"
userprofile_mount="$(findmnt --noheadings --first-only --output TARGET "$win_userprofile_drive")"

win_userprofile_dir="${win_userprofile#*:}"

userprofile="${userprofile_mount}${win_userprofile_dir//\\//}"
</code>```

Thanks to Craig Loewen at Microsoft for getting me started.

Title: DrvFs location of %UserProfile%

Body:
This seems to work:

win_userprofile="$(cmd.exe /c "<nul set /p=%UserProfile%" 2>/dev/null)"

win_userprofile_drive="${win_userprofile%%:*}:"
userprofile_mount="$(findmnt --noheadings --first-only --output TARGET "$win_userprofile_drive")"

win_userprofile_dir="${win_userprofile#*:}"

userprofile="${userprofile_mount}${win_userprofile_dir//\\//}"

Thanks to Craig Loewen at Microsoft for getting me started.


问:
Mamp - Getting Gzip to work
How do you get gzip to work on a Wordpress site setup in MAMP?

I've got gulp creating the file /dist/css/main.css.gz and have added it to the header PHP file of my wordpress site.

I then lose all of my styling. I'm assuming this is because I haven't enabled it in my .htaccess? So I found the following code to add to my .htaccess:

```<code><IfModule mod_deflate.c>
# Compress HTML, CSS, JavaScript, Text, XML and fonts
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/rss+xml
AddOutputFilterByType DEFLATE application/vnd.ms-fontobject
AddOutputFilterByType DEFLATE application/x-font
AddOutputFilterByType DEFLATE application/x-font-opentype
AddOutputFilterByType DEFLATE application/x-font-otf
AddOutputFilterByType DEFLATE application/x-font-truetype
AddOutputFilterByType DEFLATE application/x-font-ttf
AddOutputFilterByType DEFLATE application/x-javascript
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE font/opentype
AddOutputFilterByType DEFLATE font/otf
AddOutputFilterByType DEFLATE font/ttf
AddOutputFilterByType DEFLATE image/svg+xml
AddOutputFilterByType DEFLATE image/x-icon
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/javascript
AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/xml

# Remove browser bugs (only needed for really old browsers)
BrowserMatch ^Mozilla/4 gzip-only-text/html
BrowserMatch ^Mozilla/4\.0[678] no-gzip
BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
Header append Vary User-Agent
</IfModule>
</code>```

And it still does not work.

答:
I'm not sure why you'd want to store your files as gzip archives, but this is not the way to do it. AddOutputFilterByType DEFLATE text/css will compress the file before sending it. To decompress an existing file, something like this will work (tested with 2.2):

```<code><Directory />
        AddOutputFilter INFLATE gz
        RemoveType .gz
        AddType text/css .css.gz
</Directory>
</code>```

Test output:

```<code>$ echo "body {color:black; background:white;}" > foo.css
$ gzip foo.css
$ curl http://localhost/foo.css.gz
body {color:black; background:white;}
$ curl -I http://localhost/foo.css.gz
HTTP/1.1 200 OK
Date: Fri, 07 Jul 2017 23:01:22 GMT
Server: Apache/2.2.15 (Scientific Linux)
Last-Modified: Fri, 07 Jul 2017 22:59:22 GMT
Content-Length: 38
Content-Type: text/css
$
</code>```

Of course, this interferes with your ability to serve actual gzip files, and you'll need to manually specify MIME types for each compressed file.

Also, if you're controlling the server you should not be using .htaccess files. They're slow and present a security risk. Put this in the server configuration!

Title: Mamp - Getting Gzip to work

Body:
How do you get gzip to work on a Wordpress site setup in MAMP?

I've got gulp creating the file /dist/css/main.css.gz and have added it to the header PHP file of my wordpress site.

I then lose all of my styling. I'm assuming this is because I haven't enabled it in my .htaccess? So I found the following code to add to my .htaccess:

<IfModule mod_deflate.c>
# Compress HTML, CSS, JavaScript, Text, XML and fonts
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/rss+xml
AddOutputFilterByType DEFLATE application/vnd.ms-fontobject
AddOutputFilterByType DEFLATE application/x-font
AddOutputFilterByType DEFLATE application/x-font-opentype
AddOutputFilterByType DEFLATE application/x-font-otf
AddOutputFilterByType DEFLATE application/x-font-truetype
AddOutputFilterByType DEFLATE application/x-font-ttf
AddOutputFilterByType DEFLATE application/x-javascript
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE font/opentype
AddOutputFilterByType DEFLATE font/otf
AddOutputFilterByType DEFLATE font/ttf
AddOutputFilterByType DEFLATE image/svg+xml
AddOutputFilterByType DEFLATE image/x-icon
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/javascript
AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/xml

# Remove browser bugs (only needed for really old browsers)
BrowserMatch ^Mozilla/4 gzip-only-text/html
BrowserMatch ^Mozilla/4\.0[678] no-gzip
BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
Header append Vary User-Agent
</IfModule>

And it still does not work.

Body:
I'm not sure why you'd want to store your files as gzip archives, but this is not the way to do it. AddOutputFilterByType DEFLATE text/css will compress the file before sending it. To decompress an existing file, something like this will work (tested with 2.2):

<Directory />
        AddOutputFilter INFLATE gz
        RemoveType .gz
        AddType text/css .css.gz
</Directory>

Test output:

$ echo "body {color:black; background:white;}" > foo.css
$ gzip foo.css
$ curl http://localhost/foo.css.gz
body {color:black; background:white;}
$ curl -I http://localhost/foo.css.gz
HTTP/1.1 200 OK
Date: Fri, 07 Jul 2017 23:01:22 GMT
Server: Apache/2.2.15 (Scientific Linux)
Last-Modified: Fri, 07 Jul 2017 22:59:22 GMT
Content-Length: 38
Content-Type: text/css
$

Of course, this interferes with your ability to serve actual gzip files, and you'll need to manually specify MIME types for each compressed file.

Also, if you're controlling the server you should not be using .htaccess files. They're slow and present a security risk. Put this in the server configuration!


问:
Java Selenium looping through website sendKeys combine strings together
I have a for loop that constantly loops back a website to fill out and submit a search box with the next string from a list.

For example, if the list contains [abcd, efgh, ijkl....], the first loop would send abcd, the second loop would send efgh and etc.

Currently the loop sends the first string correctly, but on every loop afterwards, the string sent is added to the previous string. So instead of efgh on the second loop, it is abcdefgh.

How do I clear the keys so that I can just send the individual string? Here's what I have right now:

```<code>    for(String value : List){
        driver.get(Link);
        Actions actions = new Actions(driver);
        WebElement input_field = driver.findElement(By.id("txtBoxSearch"));

        actions.moveToElement(input_field);
        actions.click();
        actions.sendKeys(value);
        actions.build().perform();

        WebElement submit_key = driver.findElement(By.xpath("//button[contains(@title, 'Search')]"));
        actions.moveToElement(submit_key);

        actions.click();
        actions.build().perform();
    }
</code>```

答:
You need to clear the content of textbox before write value to it</p>

```<code>for(String value : List){
    driver.get(Link);
    Actions actions = new Actions(driver);
    WebElement input_field = driver.findElement(By.id("txtBoxSearch"));
    input_field.clear();
    actions.moveToElement(input_field);
    actions.click();
    actions.sendKeys(value);
    actions.build().perform();
    WebElement submit_key = driver.findElement(By.xpath("//button[contains(@title, 'Search')]"));
    actions.moveToElement(submit_key);
    actions.click();
    actions.build().perform();
}
</code>```

Body:
I have a for loop that constantly loops back a website to fill out and submit a search box with the next string from a list.

For example, if the list contains [abcd, efgh, ijkl....], the first loop would send abcd, the second loop would send efgh and etc.

Currently the loop sends the first string correctly, but on every loop afterwards, the string sent is added to the previous string. So instead of efgh on the second loop, it is abcdefgh.

How do I clear the keys so that I can just send the individual string? Here's what I have right now:

    for(String value : List){
        driver.get(Link);
        Actions actions = new Actions(driver);
        WebElement input_field = driver.findElement(By.id("txtBoxSearch"));

        actions.moveToElement(input_field);
        actions.click();
        actions.sendKeys(value);
        actions.build().perform();

        WebElement submit_key = driver.findElement(By.xpath("//button[contains(@title, 'Search')]"));
        actions.moveToElement(submit_key);

        actions.click();
        actions.build().perform();
    }

Body:
You need to clear the content of textbox before write value to it

for(String value : List){
    driver.get(Link);
    Actions actions = new Actions(driver);
    WebElement input_field = driver.findElement(By.id("txtBoxSearch"));
    input_field.clear();
    actions.moveToElement(input_field);
    actions.click();
    actions.sendKeys(value);
    actions.build().perform();
    WebElement submit_key = driver.findElement(By.xpath("//button[contains(@title, 'Search')]"));
    actions.moveToElement(submit_key);
    actions.click();
    actions.build().perform();
}


问:
evaluating "()" in node.js causes wierd behaviour, but browser says syntax error (bug in node.js?)
When I evaluate the expression "()" in node.js (without the quotes), it corrupts the environment. The global object is trashed and nothing works. When i evaluate the same express in the browser console it reports a syntax error. From my research it appears the browser is correct. Is this a bug in the node.js expression parser? Can anyone explain what is happening under the hood?
Here is a screenshot</p>

答:
Imagine you're writing your own JavaScript REPL. You know JavaScript's grammar in and out, and you want to abort processing of an invalid input as soon as possible (but NOT before that). So, you decide to read character by character, build token by token and abort as soon as you encounter the impossible token (for a current state, state defined by input processed thus far).

So, you know if users enters (}, it's pretty safe to abort - there's no way something meaningful is going to come out of that!

Also, if user enters (2, you don't want to abort yet - there are a plenty of valid characters to follow, like ), *, ,, etc.

You also know what to expect after (). If it isn't =>... (lambda expression), than it's invalid token.

Now back to reality. REPL implementations in Node.js, Chrome, Firefox, etc. differ because they can. Some are "smarter" than other, and will abort sooner than others, but that's really up to them.

Node.js chose to have "less smart" REPL, as it won't abort reading your input, as soon as it can. In fact, if you entered something that can never form a valid expression, it will leave you hanging, reading junk until you explicitly abort with Ctrl+C.

Chrome's console is a little bit smarter. When you type (), you'll get:

```<code>> ()
Uncaught SyntaxError: Unexpected token )
</code>```

but, when you start typing a lambda ()=>, it will allow you to finish it in the next line:

```<code>> ()=>
2
</code>```

As a comfort note, you'll get the same error in Node.js REPL if you indicate you're done with entering of your expression, like this:

```<code>> eval("()")
SyntaxError: Unexpected token )
</code>```

Body:
Imagine you're writing your own JavaScript REPL. You know JavaScript's grammar in and out, and you want to abort processing of an invalid input as soon as possible (but NOT before that). So, you decide to read character by character, build token by token and abort as soon as you encounter the impossible token (for a current state, state defined by input processed thus far).

So, you know if users enters (}, it's pretty safe to abort - there's no way something meaningful is going to come out of that!

Also, if user enters (2, you don't want to abort yet - there are a plenty of valid characters to follow, like ), *, ,, etc.

You also know what to expect after (). If it isn't =>... (lambda expression), than it's invalid token.

Now back to reality. REPL implementations in Node.js, Chrome, Firefox, etc. differ because they can. Some are "smarter" than other, and will abort sooner than others, but that's really up to them.

Node.js chose to have "less smart" REPL, as it won't abort reading your input, as soon as it can. In fact, if you entered something that can never form a valid expression, it will leave you hanging, reading junk until you explicitly abort with Ctrl+C.

Chrome's console is a little bit smarter. When you type (), you'll get:

> ()
Uncaught SyntaxError: Unexpected token )

but, when you start typing a lambda ()=>, it will allow you to finish it in the next line:

> ()=>
2

As a comfort note, you'll get the same error in Node.js REPL if you indicate you're done with entering of your expression, like this:

> eval("()")
SyntaxError: Unexpected token )


答:
You are nesting multiple forms into each other which is not supported in HTML:

See this question for more details: Can you nest html forms?

These form_for lines look invalid in particular:

```<code><%= form_for o, :field_name do %>
</code>```

Here, o is a special FormBuilder object which should not be fed to form_for. Try this instead:

```<code><%= f.fields_for :owner do |o| %>
  <%= o.fields_for :email do %>
</code>```

Unlike form_for, it is possible to nest fields_for blocks.

Title: no implicit conversion of Symbol into Integer in view forms

Body:
You are nesting multiple forms into each other which is not supported in HTML:

See this question for more details: Can you nest html forms?

These form_for lines look invalid in particular:

<%= form_for o, :field_name do %>

Here, o is a special FormBuilder object which should not be fed to form_for. Try this instead:

<%= f.fields_for :owner do |o| %>
  <%= o.fields_for :email do %>

Unlike form_for, it is possible to nest fields_for blocks.