问:
I not getting the correct value of my variable in command prompt using for loop
I have this batch file

```<code>SETLOCAL ENABLEDELAYEDEXPANSION
SET count=1
FOR /F "tokens=* USEBACKQ" %%F IN (`find "@  STATISTICS ON CLIENT_JE_AMT EY_ENT_DATE EY_EFF_DATE" "z_B10_VALIDATION.LOG"`) DO (
  SET var!count!=%%F
  SET /a count=!count!+1
)
ECHO %var1%
ECHO %var2%

for /f "tokens=1 delims=:" %%i in ("%var2%") do (
set stat_line_start=%%i
)
echo %stat_line_start%
set /a stat_line_end=!stat_line_start!+3

for /L %%j in (%stat_line_start%,1,%stat_line_end%) do (
echo %%j

set k=%%j

set cfirst=%k:~0,1%
set csec=%k:~1,1%
set cthird=%k:~2,1%

findstr /B "[%cfirst%-%cfirst%][%csec%-%csec%][%cthird%-%cthird%]:" "z_B10_VALIDATION.LOG">> z_STATS.txt
)
ENDLOCAL
</code>```

when i run this, I am getting the correct value for variable "k" but having error on "cfirst", "csec" and "cthird" variable.
sample result line :

```<code>set k=254
set cfirst=~0,1
</code>```

instead of

```<code>set cfirst=2
</code>```

I am new on this field and just starting to explore. Hope you can help me.
Thank you in advance.

答:
CMD expands variables when the command is parsed, not when it is run.

Because code blocks (i.e. chunks of code suurrounded by parentheses - like multi-line if statements and for loops) are considered a single command by the interepreter, any variables that you set inside of the block are set to the default value: nothing.

You can delay this expansion to runtime with the command setlocal enabledelayedexpansion (which you already included at the top of your code) and using the !variable! syntax instead of the %variable% syntax.

Body:
I have this batch file

SETLOCAL ENABLEDELAYEDEXPANSION
SET count=1
FOR /F "tokens=* USEBACKQ" %%F IN (`find "@  STATISTICS ON CLIENT_JE_AMT EY_ENT_DATE EY_EFF_DATE" "z_B10_VALIDATION.LOG"`) DO (
  SET var!count!=%%F
  SET /a count=!count!+1
)
ECHO %var1%
ECHO %var2%

for /f "tokens=1 delims=:" %%i in ("%var2%") do (
set stat_line_start=%%i
)
echo %stat_line_start%
set /a stat_line_end=!stat_line_start!+3

for /L %%j in (%stat_line_start%,1,%stat_line_end%) do (
echo %%j

set k=%%j

set cfirst=%k:~0,1%
set csec=%k:~1,1%
set cthird=%k:~2,1%

findstr /B "[%cfirst%-%cfirst%][%csec%-%csec%][%cthird%-%cthird%]:" "z_B10_VALIDATION.LOG">> z_STATS.txt
)
ENDLOCAL

when i run this, I am getting the correct value for variable "k" but having error on "cfirst", "csec" and "cthird" variable.
sample result line :

set k=254
set cfirst=~0,1

instead of

set cfirst=2

I am new on this field and just starting to explore. Hope you can help me.
Thank you in advance.


来源: stackexchange

问:
Construct DataFrame from scraped data using Scrapy
I have a problem with constructing csv type data file from scraped data. I have managed to scrape the data from the table but when it comes to writing it I can't do that for days. I am using items and trying to write it to pandas data frame. I am using items list.

```<code>import scrapy
from wiki.items import WikiItem
import pandas as pd

class Spider(scrapy.Spider):

name = "wiki"
start_urls = ['https://datatables.net/']

def parse(self, response):

    items = {'Name':[], 'Position':[], 'Office':[], 'Age':[],
        'Start_Date':[],'Salary':[]}

    trs = response.xpath('//table[@id="example"]//tr')
    name = WikiItem()
    pos = WikiItem()
    office = WikiItem()
    age = WikiItem()
    start_data = WikiItem()
    salary = WikiItem()

    name['name'] = trs.xpath('//td[1]//text()').extract()
    pos['position'] = trs.xpath('//td[2]//text()').extract()
    office['office'] = trs.xpath('//td[3]//text()').extract()
    age['age'] = trs.xpath('//td[4]//text()').extract()
    start_data['start_data'] = trs.xpath('//td[5]//text()').extract()
    salary['salary'] = trs.xpath('td[6]//text()').extract()

    items['Name'].append(name)
    items['Position'].append(pos)
    items['Office'].append(office)
    items['Age'].append(age)
    items['Start_Date'].append(start_data)
    items['Salary'].append(salary)

    x = pd.DataFrame(items, columns=['Name','Position','Office','Age',
        'Start_Date','Salary'])

    yield x.to_csv("r",sep=",")
</code>```

From this code what I get is like this ;

```<code>,Name,Position,Office,Age,Start_Date,Salary
0,"{'name': [u'Tiger Nixon',
      u'Garrett Winters',
      u'Ashton Cox',
      u'Cedric Kelly',
      u'Airi Satou',
      u'Brielle Williamson',
      u'Herrod Chandler',
</code>```

I am getting the names column but I get it 59 times.For instance I have the first row, 'Tiger Nixon' 59 times. I get 59 times position column also and so on. And the scraped data is not in good shape also. I am new to scrapy and open to any help or suggestions. Thanks in advance!

EDIT : My items.py is like this;

```<code>import scrapy

class WikiItem(scrapy.Item):

name = scrapy.Field()
position = scrapy.Field()
office = scrapy.Field()
age = scrapy.Field()
start_data = scrapy.Field()
salary = scrapy.Field()
</code>```

答:
Ok, I can't comment and I can't test your code because I don't have the definition of WikiItem. But let iterate over this response, ok?
Can you check what do you get with this code?</p>

```<code>class Spider(scrapy.Spider):

    name = "wiki"
    start_urls = ['https://datatables.net/']

    def parse(self, response):

        trs = response.xpath('//table[@id="example"]//tr')

        if trs:
            items = []
            for tr in trs:
                print tr.xpath('td[2]//text()').extract()
                item = {
                    "Name": tr.xpath('td[1]//text()').extract(),
                    "Position": tr.xpath('td[2]//text()').extract(),
                    "Office": tr.xpath('td[3]//text()').extract(),
                    "Age": tr.xpath('td[4]//text()').extract(),
                    "Start_Date": tr.xpath('td[5]//text()').extract(),
                    "Salary": tr.xpath('td[6]//text()').extract()
                }
                items.append(item)

            x = pd.DataFrame(items, columns=['Name','Position','Office','Age',
                'Start_Date','Salary'])

            yield x.to_csv("r",sep=",")
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a problem with constructing csv type data file from scraped data. I have managed to scrape the data from the table but when it comes to writing it I can't do that for days. I am using items and trying to write it to pandas data frame. I am using items list.

import scrapy
from wiki.items import WikiItem
import pandas as pd

class Spider(scrapy.Spider):

name = "wiki"
start_urls = ['https://datatables.net/']

def parse(self, response):

    items = {'Name':[], 'Position':[], 'Office':[], 'Age':[],
        'Start_Date':[],'Salary':[]}

    trs = response.xpath('//table[@id="example"]//tr')
    name = WikiItem()
    pos = WikiItem()
    office = WikiItem()
    age = WikiItem()
    start_data = WikiItem()
    salary = WikiItem()

    name['name'] = trs.xpath('//td[1]//text()').extract()
    pos['position'] = trs.xpath('//td[2]//text()').extract()
    office['office'] = trs.xpath('//td[3]//text()').extract()
    age['age'] = trs.xpath('//td[4]//text()').extract()
    start_data['start_data'] = trs.xpath('//td[5]//text()').extract()
    salary['salary'] = trs.xpath('td[6]//text()').extract()

    items['Name'].append(name)
    items['Position'].append(pos)
    items['Office'].append(office)
    items['Age'].append(age)
    items['Start_Date'].append(start_data)
    items['Salary'].append(salary)

    x = pd.DataFrame(items, columns=['Name','Position','Office','Age',
        'Start_Date','Salary'])

    yield x.to_csv("r",sep=",")

From this code what I get is like this ;

,Name,Position,Office,Age,Start_Date,Salary
0,"{'name': [u'Tiger Nixon',
      u'Garrett Winters',
      u'Ashton Cox',
      u'Cedric Kelly',
      u'Airi Satou',
      u'Brielle Williamson',
      u'Herrod Chandler',

I am getting the names column but I get it 59 times.For instance I have the first row, 'Tiger Nixon' 59 times. I get 59 times position column also and so on. And the scraped data is not in good shape also. I am new to scrapy and open to any help or suggestions. Thanks in advance!

EDIT : My items.py is like this;

import scrapy

class WikiItem(scrapy.Item):

name = scrapy.Field()
position = scrapy.Field()
office = scrapy.Field()
age = scrapy.Field()
start_data = scrapy.Field()
salary = scrapy.Field()

Body:
Ok, I can't comment and I can't test your code because I don't have the definition of WikiItem. But let iterate over this response, ok?
Can you check what do you get with this code?

class Spider(scrapy.Spider):

    name = "wiki"
    start_urls = ['https://datatables.net/']

    def parse(self, response):

        trs = response.xpath('//table[@id="example"]//tr')

        if trs:
            items = []
            for tr in trs:
                print tr.xpath('td[2]//text()').extract()
                item = {
                    "Name": tr.xpath('td[1]//text()').extract(),
                    "Position": tr.xpath('td[2]//text()').extract(),
                    "Office": tr.xpath('td[3]//text()').extract(),
                    "Age": tr.xpath('td[4]//text()').extract(),
                    "Start_Date": tr.xpath('td[5]//text()').extract(),
                    "Salary": tr.xpath('td[6]//text()').extract()
                }
                items.append(item)

            x = pd.DataFrame(items, columns=['Name','Position','Office','Age',
                'Start_Date','Salary'])

            yield x.to_csv("r",sep=",")


问:
Phonegap BUILD plugin for chromecast mirroring (iOS&Android)
I'm stucked to find a Phonegap BUILD (yes, it really needs to be compatible with this service) plugin that works properly.

I've tried a lot of plugins, but none of them seems to work. I really liked the ConnectSDK aproach, but phonegap build got an error at building, the error reported is:

(iOs)

'Error - The following 3rd-party plugin is causing the build to fail
  and may need to be updated to a newer version:
  cordova-plugin-connectsdk'

(Android)

'Oh geez. Your build failed. Click the "Log" button above to view the
  compile log. If you need help diagnosing the issue, you can post to
  the support forum with your App ID (please do a search first).'

I found an old issue in their Github reporting a similar but not equal case, and seems that they don't support the phonegap build service..

"However, you won't be able to build using PhoneGap Build since it
  requires a binary plugin, the closed-source Google Cast SDK plugin.
  Currently PhoneGap Build does not support binary plugins."
  at: https://github.com/ConnectSDK/Connect-SDK-Cordova-Plugin/issues/1

Does anyone already used a plugin that fit in this purpose ? (it could be separated plugin for each platform).

All kinds of help are welcome, thanks in advance.

答:
If you click the Log button next to a PhoneGap Build build, then search for "error", you may see what the exact error is. In my experience though, it's usually a compilation code issue that you'd have to fix manually - defeating the purpose of PG Build.

If the Google Cast SDK plugin isn't supported on PhoneGap Build, there's not much you can do, short of contacting Adobe.  Sounds like this is not ideal for you, but your best course of action is to build your project using the Cordova CLI. It'll take more effort than Build, but it's not too bad. Create a local "project", add the Cast and other plugins, and build for iOS/Android.


问:
Codechef KCHAR wrong answer
Recently I was solving the following problem on codechef:

Alice has quarreled with Chef recently. So Chef gives a problem to Alice.
  Initially you are given an empty string and are allowed following two operations.

Operation-1: Every 'a' becomes 'c' and every 'c' becomes 'a'. For example, "acc" becomes "caa".

  Operation-2: String is reversed. For Example, "acc" becomes "cca".

Chef gives following generating equation SN = SN-1 + "a" + Operation-1(Operation-2(SN-1))

where S0 = "" (empty string).

Alice easily finds out next few sequences as:

S1 = "a"

  S2 = "aac"

  S3 = "aacaacc"

Now Chef asks to find Kth character of SLOC, where LOC = 102017. You need to help Alice find the answer.

1 ≤ T ≤ 100

  1 ≤ K ≤ 1018

I have tried to solve the problem using following code:

```<code>scanf("%lld",&t);
while(t--)
{
    scanf("%lld",&k);
    count=0;
    while(1)
    {
        lg=(double)log(k)/log(2);
        av=pow(2,lg);
        if(av!=k)
        {
            diff=k-av;
            k=av-diff;
            count++;
        }
        else
        {
            if(count%2==0)
            {
                printf("a\n");
            }
            else
            {
                printf("c\n");
            }
            break;
        }
    }

}
</code>```

What is wrong in the solution?

I have tried out various inputs and I get correct answer but the I am getting WA when I submit. Can anyone provide some test cases where the solution is failing.

答:
While @PaulHankin explained what's wrong with you solution

Here is my accepted solution written in C++14

#include <bits/stdc++.h>
#define LL long long
using namespace std;

LL k;
int T;
string f(int N, LL K){
    LL len = (1LL<<N)-1;
    LL pLen = (1LL<<(N-1)) - 1;
    if(K == len/2 + 1LL) return "a";
    if(K == len - pLen/2) return "c";
    return f(N-1, K < len/2+1LL? K : K-len/2-1LL);
}

int main() {
    cin >> T;
    while(T--){
        cin >> k;
        cout << f(60, k) << endl;
    }
    return 0;
}
```

My solution is based on the following key observations:

S_n = S_(n-1) + "a" + REPLACE(S_(n-1), mid_point, "c")

K <= 10^18 implies n <= 60, which length is long enough to cover all Ks

Based on 1, for each n, there is two special position which you know the answer of S_n:

3a. Len(S_n)/2 + 1 (which is mid point and it must be "a")

3b. Len(S_n) - Len(S_(n-1))/2 (which is the 3/4 quartile point and it must be "c")

Then the algorithm is simple: Just see if K is the special position of current S_n, if yes we have found the answer; Otherwise the answer is equal to searching relative position K' in S_(n-1)

Title: Codechef KCHAR wrong answer

Body:
Recently I was solving the following problem on codechef:

Alice has quarreled with Chef recently. So Chef gives a problem to Alice.
  Initially you are given an empty string and are allowed following two operations.

Operation-1: Every 'a' becomes 'c' and every 'c' becomes 'a'. For example, "acc" becomes "caa".

  Operation-2: String is reversed. For Example, "acc" becomes "cca".

Chef gives following generating equation SN = SN-1 + "a" + Operation-1(Operation-2(SN-1))

where S0 = "" (empty string).

Alice easily finds out next few sequences as:

S1 = "a"

  S2 = "aac"

  S3 = "aacaacc"

Now Chef asks to find Kth character of SLOC, where LOC = 102017. You need to help Alice find the answer.

1 ≤ T ≤ 100

  1 ≤ K ≤ 1018

I have tried to solve the problem using following code:

scanf("%lld",&t);
while(t--)
{
    scanf("%lld",&k);
    count=0;
    while(1)
    {
        lg=(double)log(k)/log(2);
        av=pow(2,lg);
        if(av!=k)
        {
            diff=k-av;
            k=av-diff;
            count++;
        }
        else
        {
            if(count%2==0)
            {
                printf("a\n");
            }
            else
            {
                printf("c\n");
            }
            break;
        }
    }

}

What is wrong in the solution?

I have tried out various inputs and I get correct answer but the I am getting WA when I submit. Can anyone provide some test cases where the solution is failing.

Body:
While @PaulHankin explained what's wrong with you solution

Here is my accepted solution written in C++14

#include <bits/stdc++.h>
#define LL long long
using namespace std;

LL k;
int T;
string f(int N, LL K){
    LL len = (1LL<<N)-1;
    LL pLen = (1LL<<(N-1)) - 1;
    if(K == len/2 + 1LL) return "a";
    if(K == len - pLen/2) return "c";
    return f(N-1, K < len/2+1LL? K : K-len/2-1LL);
}

int main() {
    cin >> T;
    while(T--){
        cin >> k;
        cout << f(60, k) << endl;
    }
    return 0;
}

My solution is based on the following key observations:

S_n = S_(n-1) + "a" + REPLACE(S_(n-1), mid_point, "c")

K <= 10^18 implies n <= 60, which length is long enough to cover all Ks

Based on 1, for each n, there is two special position which you know the answer of S_n:

3a. Len(S_n)/2 + 1 (which is mid point and it must be "a")

3b. Len(S_n) - Len(S_(n-1))/2 (which is the 3/4 quartile point and it must be "c")

Then the algorithm is simple: Just see if K is the special position of current S_n, if yes we have found the answer; Otherwise the answer is equal to searching relative position K' in S_(n-1)


问:
Stanford POS tagger with nltk in arabic text
I am trying to use Stanford POS Tagger in NLTK 3.2.4 on arabic text using Python 3.6, I found a code source but I did not understand most of it because I am totally new to Stanford POS Tagger.

Code Source :

```<code>import os
java_path = "C:\\Program Files (x86)\\Java\\jdk1.8.0_112\\bin\\java.exe"
os.environ['JAVAHOME'] = java_path

from nltk.tag.stanford import StanfordPOSTagger as POS_Tag
home = 'E:\\Asmaa\\TP python\\'
_path_to_model = home + 'stanford-arabic-corenlp-2017-06-09-models.jar'
_path_to_jar = home + 'stanford-postagger.jar'
POS_Tag.java_options='-mx4096m'
st = POS_Tag(model_filename=_path_to_model, path_to_jar=_path_to_jar)
sentence = '.شرب القط الحليب اللذيذ'
st.tag(sentence.split())
</code>```

The error I get :

```<code>Exception in thread "main" java.lang.RuntimeException: 'file' parameter must be specified
    at edu.stanford.nlp.tagger.maxent.TaggerConfig.<init>(TaggerConfig.java:87)
    at edu.stanford.nlp.tagger.maxent.MaxentTagger.main(MaxentTagger.java:273)
Traceback (most recent call last):
  File "<input>", line 8, in <module>
  File "F:\Python36\lib\site-packages\nltk\tag\stanford.py", line 76, in tag
    return sum(self.tag_sents([tokens]), [])
  File "F:\Python36\lib\site-packages\nltk\tag\stanford.py", line 99, in tag_sents
    stdout=PIPE, stderr=PIPE)
  File "F:\Python36\lib\site-packages\nltk\internals.py", line 136, in java
    raise OSError('Java command failed : ' + str(cmd))
OSError: Java command failed : ['C:\\Program Files (x86)\\Java\\jdk1.8.0_112\\bin\\java.exe', '-mx1000m', '-cp', 'E:\\Asmaa\\TP python\\stanford-postagger.jar', 'edu.stanford.nlp.tagger.maxent.MaxentTagger', '-model', 'E:\\Asmaa\\TP python\\stanford-arabic-corenlp-2017-06-09-models.jar', '-textFile', 'C:\\Users\\2017\\AppData\\Local\\Temp\\tmpqajz7z6c', '-tokenize', 'false', '-outputFormatOptions', 'keepEmptySentences', '-encoding', 'utf8']
</code>```

So what goes wrong ?

答:
First upgrade your nltk, then on the terminal or command-prompt:

```<code>wget http://nlp.stanford.edu/software/stanford-corenlp-full-2016-10-31.zip
unzip stanford-corenlp-full-2016-10-31.zip && cd stanford-corenlp-full-2016-10-31

wget http://nlp.stanford.edu/software/stanford-arabic-corenlp-2016-10-31-models.jar
wget https://raw.githubusercontent.com/stanfordnlp/CoreNLP/master/src/edu/stanford/nlp/pipeline/StanfordCoreNLP-arabic.properties

java -Xmx4g -cp "*" edu.stanford.nlp.pipeline.StanfordCoreNLPServer \
-serverProperties StanfordCoreNLP-arabic.properties \
-preload tokenize,ssplit,pos,parse \
-status_port 9005  -port 9005 -timeout 15000
</code>```

In Python:

```<code>>>> from nltk.tag.stanford import CoreNLPPOSTagger
>>> from nltk.tokenize.stanford import CoreNLPTokenizer
>>> sttok = CoreNLPTokenizer('http://localhost:9005')
>>> stpos = CoreNLPPOSTagger('http://localhost:9005')
>>> text = u'انا حامل'
>>> stpos.tag(sttok.tokenize(text))
[('انا', 'DET'), ('حامل', 'NC')]
</code>```

Body:
I am trying to use Stanford POS Tagger in NLTK 3.2.4 on arabic text using Python 3.6, I found a code source but I did not understand most of it because I am totally new to Stanford POS Tagger.

Code Source :

import os
java_path = "C:\\Program Files (x86)\\Java\\jdk1.8.0_112\\bin\\java.exe"
os.environ['JAVAHOME'] = java_path

from nltk.tag.stanford import StanfordPOSTagger as POS_Tag
home = 'E:\\Asmaa\\TP python\\'
_path_to_model = home + 'stanford-arabic-corenlp-2017-06-09-models.jar'
_path_to_jar = home + 'stanford-postagger.jar'
POS_Tag.java_options='-mx4096m'
st = POS_Tag(model_filename=_path_to_model, path_to_jar=_path_to_jar)
sentence = '.شرب القط الحليب اللذيذ'
st.tag(sentence.split())

The error I get :

Exception in thread "main" java.lang.RuntimeException: 'file' parameter must be specified
    at edu.stanford.nlp.tagger.maxent.TaggerConfig.<init>(TaggerConfig.java:87)
    at edu.stanford.nlp.tagger.maxent.MaxentTagger.main(MaxentTagger.java:273)
Traceback (most recent call last):
  File "<input>", line 8, in <module>
  File "F:\Python36\lib\site-packages\nltk\tag\stanford.py", line 76, in tag
    return sum(self.tag_sents([tokens]), [])
  File "F:\Python36\lib\site-packages\nltk\tag\stanford.py", line 99, in tag_sents
    stdout=PIPE, stderr=PIPE)
  File "F:\Python36\lib\site-packages\nltk\internals.py", line 136, in java
    raise OSError('Java command failed : ' + str(cmd))
OSError: Java command failed : ['C:\\Program Files (x86)\\Java\\jdk1.8.0_112\\bin\\java.exe', '-mx1000m', '-cp', 'E:\\Asmaa\\TP python\\stanford-postagger.jar', 'edu.stanford.nlp.tagger.maxent.MaxentTagger', '-model', 'E:\\Asmaa\\TP python\\stanford-arabic-corenlp-2017-06-09-models.jar', '-textFile', 'C:\\Users\\2017\\AppData\\Local\\Temp\\tmpqajz7z6c', '-tokenize', 'false', '-outputFormatOptions', 'keepEmptySentences', '-encoding', 'utf8']

So what goes wrong ?

Body:
First upgrade your nltk, then on the terminal or command-prompt:

wget http://nlp.stanford.edu/software/stanford-corenlp-full-2016-10-31.zip
unzip stanford-corenlp-full-2016-10-31.zip && cd stanford-corenlp-full-2016-10-31

wget http://nlp.stanford.edu/software/stanford-arabic-corenlp-2016-10-31-models.jar
wget https://raw.githubusercontent.com/stanfordnlp/CoreNLP/master/src/edu/stanford/nlp/pipeline/StanfordCoreNLP-arabic.properties

java -Xmx4g -cp "*" edu.stanford.nlp.pipeline.StanfordCoreNLPServer \
-serverProperties StanfordCoreNLP-arabic.properties \
-preload tokenize,ssplit,pos,parse \
-status_port 9005  -port 9005 -timeout 15000

In Python:

>>> from nltk.tag.stanford import CoreNLPPOSTagger
>>> from nltk.tokenize.stanford import CoreNLPTokenizer
>>> sttok = CoreNLPTokenizer('http://localhost:9005')
>>> stpos = CoreNLPPOSTagger('http://localhost:9005')
>>> text = u'انا حامل'
>>> stpos.tag(sttok.tokenize(text))
[('انا', 'DET'), ('حامل', 'NC')]


问:
C++ syntax of 2D vector
Can someone explain below c++ syntax with example ?

```<code>vector <vector <int> > s(n,vector <int> ());
</code>```

especially this part inside the constructor:

```<code>vector <int> ()
</code>```

答:
First of all, vector of vectors is not exactly a "2D vector". The "rows" of vector<vector<>> are completely independent both in terms of memory layout and semantically. There are better options, e.g. Boost.Multi_array.

Then we have vector <int> (). Depending on context this could mean both temorary object initialization or a function declaration. The example in question actually does not provide enough context:

```<code>vector <vector <int> > s(n,vector <int> ());
</code>```

If n happens to be a type name, then this line is a function declaration. Of course n is probably an int, but it would be better to explicitly state that you want a default-constructed vector<int> as a second argument:

```<code>vector <vector <int> > s(n,vector <int> {});
</code>```

Here vector <int> {} unambiguously means "a default-constructed temporary object of type vector<int>", and you pass it to the vector<vector<int>> constructor as a value to initialize your rows with.

This brings us to another observation: std::vector value-initializes its elements by default, which means that the same result can be achieved like that:

```<code>vector <vector <int> > s(n);
</code>```

Finally, the presence of vector<int>() in the original statement kind of hints that it might have been intended to set up the "width" of the 2D vector:

```<code>vector <vector <int> > s(n,vector <int> (m));
</code>```

but m got lost somewhere along the lines :)

Title: C++ syntax of 2D vector

Body:
Can someone explain below c++ syntax with example ?

vector <vector <int> > s(n,vector <int> ());

especially this part inside the constructor:

vector <int> ()

Body:
First of all, vector of vectors is not exactly a "2D vector". The "rows" of vector<vector<>> are completely independent both in terms of memory layout and semantically. There are better options, e.g. Boost.Multi_array.

Then we have vector <int> (). Depending on context this could mean both temorary object initialization or a function declaration. The example in question actually does not provide enough context:

vector <vector <int> > s(n,vector <int> ());

If n happens to be a type name, then this line is a function declaration. Of course n is probably an int, but it would be better to explicitly state that you want a default-constructed vector<int> as a second argument:

vector <vector <int> > s(n,vector <int> {});

Here vector <int> {} unambiguously means "a default-constructed temporary object of type vector<int>", and you pass it to the vector<vector<int>> constructor as a value to initialize your rows with.

This brings us to another observation: std::vector value-initializes its elements by default, which means that the same result can be achieved like that:

vector <vector <int> > s(n);

Finally, the presence of vector<int>() in the original statement kind of hints that it might have been intended to set up the "width" of the 2D vector:

vector <vector <int> > s(n,vector <int> (m));

but m got lost somewhere along the lines :)


问:
Google Analytics non-interaction implementations (ni=1 vs nonInteraction:true)
I have a question regarding two seemingly different ways to implement sending an event in google analytics as a non-interaction hit type.

(1) Protocol docs:
 https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters#ni

In query param:

```<code>&ni=1

/collect?v=1&t=event&ni=1
</code>```

(2) Analytics dev guide:
https://developers.google.com/analytics/devguides/collection/analyticsjs/events

```<code>ga('send', 'event', 'Videos', 'play', 'Fall Campaign', {
  nonInteraction: true
});
</code>```

which I inferred allows me to do this:

```<code>ga('send', {
  hitType: 'event'
  eventCategory: 'myCategory',
  eventAction: 'myAction',
  eventLabel: 'myLabel',
  nonIteraction: true
});
</code>```

However, when I look at the network traffic in the chrome browser dev console I do not see the "ni=1" url parameter. Here is a list of the parameters that are present (values excluded):

v:
_v:
a:
t:
_s:
cd:
dl:
dp:
ul:
de:
dt:
sd:
sr:
vp:
je:
ec:
ea:
an:
av:
aid:
aiid:
_u:
jid:
gjid:
cid:
tid:
_gid:
z:

What is the difference betweeen these two implementations, and are the end results the same?

答:
I have both a server-side and JavaScript implementation of Google Analytics event tracking and in my experience they are treated exactly the same.

In my server-side implementation I send a payload directly to the /collect location with query parameters exactly as you posted (including &ni=1).

In JavaScript, I'm using the same syntax as you with {'nonInteraction': true} as my fieldsObject. Seemingly the only difference is I put nonInteraction in quotes (but I wouldn't think that would be enough to prevent it- worth a try).

I can see the ni=1 show up in my console when I use the Google Analytics debugger (here is part of the log):

And here it is in the Network tab itself:

I would double check that your t parameter is in fact event and double check that you're inspecting the correct one (maybe there is a chance you're looking at a different event)?

I'd also try installing the Google Analytics Debugger Chrome extension (even temporarily) for a more visual representation of each payload in the console.

Google Analytics does not treat those two methods you posted differently, so the ni parameter should be in there if the event you're sending is in fact written as you posted. Maybe someone else can glean some additional ideas from what you posted, but to me it seems everything is properly implemented.

Body:
I have a question regarding two seemingly different ways to implement sending an event in google analytics as a non-interaction hit type.

(1) Protocol docs:
 https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters#ni

In query param:

&ni=1

/collect?v=1&t=event&ni=1

(2) Analytics dev guide:
https://developers.google.com/analytics/devguides/collection/analyticsjs/events

ga('send', 'event', 'Videos', 'play', 'Fall Campaign', {
  nonInteraction: true
});

which I inferred allows me to do this:

ga('send', {
  hitType: 'event'
  eventCategory: 'myCategory',
  eventAction: 'myAction',
  eventLabel: 'myLabel',
  nonIteraction: true
});

However, when I look at the network traffic in the chrome browser dev console I do not see the "ni=1" url parameter. Here is a list of the parameters that are present (values excluded):

v:
_v:
a:
t:
_s:
cd:
dl:
dp:
ul:
de:
dt:
sd:
sr:
vp:
je:
ec:
ea:
an:
av:
aid:
aiid:
_u:
jid:
gjid:
cid:
tid:
_gid:
z:

What is the difference betweeen these two implementations, and are the end results the same?


问:
How to find a float in a string - Python?
I want to find the first float that appears in a string using Python 3.

I looked at other similar questions but I couldn't understand them and when I tried to implement them they didn't work for my case.

An example string would be

I would like 1.5 cookies please

答:
If you expect whitespace separated decimal floats, using str methods and removing -+.:

```<code>s = 'I would like 1.5 cookies please'
results = [t for t in s.split()
           if t.lstrip('+-').replace('.', '', 1).isdigit()]
print(results[0])  #1.5
</code>```

lstrip is used to remove the sign only on the lefthand side of the text, and the third argument to replace is used to replace only one dot in the text. The exact implementation depends on the how you expect floats to be formatted (support whitespace between sign, etc).

Body:
If you expect whitespace separated decimal floats, using str methods and removing -+.:

s = 'I would like 1.5 cookies please'
results = [t for t in s.split()
           if t.lstrip('+-').replace('.', '', 1).isdigit()]
print(results[0])  #1.5

lstrip is used to remove the sign only on the lefthand side of the text, and the third argument to replace is used to replace only one dot in the text. The exact implementation depends on the how you expect floats to be formatted (support whitespace between sign, etc).


问:
Why 'YYModel' lead project crash on iOS8?
My YYModel is managed by cocoapods. I use YYModel to convert json to model.There is my code where use YYModel:

```<code>for (NSDictionary *dic in labelArray) {
       CQMenuButtonModel *model = [[CQMenuButtonModel alloc]init];
       [model yy_modelSetWithDictionary:dic];
       [modelsArray addObject:model];
    }
</code>```

It crashed at [model yy_modelSetWithDictionary:dic];,and the console showed:'-[CQMenuButtonModel yy_modelSetWithDictionary:]: unrecognized selector sent to instance 0x18b47d20'

However, it work fine on iOS9 and iOS10.

At first I think maybe the newest YYModel doesn't fit iOS8, so I change the YYModel's version to 0.9, However,it's crash on iOS8 too.

What confused me most is that why it crash on iOS8 but work fine on iOS9 and iOS10,What's more,I really don't understand why console show me :unrecognized selector sent to instance 0x18b47d20

答: I replaced YYModel with JSONModel at last then it work fine.</p>

Body:
My YYModel is managed by cocoapods. I use YYModel to convert json to model.There is my code where use YYModel:

for (NSDictionary *dic in labelArray) {
       CQMenuButtonModel *model = [[CQMenuButtonModel alloc]init];
       [model yy_modelSetWithDictionary:dic];
       [modelsArray addObject:model];
    }

It crashed at [model yy_modelSetWithDictionary:dic];,and the console showed:'-[CQMenuButtonModel yy_modelSetWithDictionary:]: unrecognized selector sent to instance 0x18b47d20'

However, it work fine on iOS9 and iOS10.

At first I think maybe the newest YYModel doesn't fit iOS8, so I change the YYModel's version to 0.9, However,it's crash on iOS8 too.

What confused me most is that why it crash on iOS8 but work fine on iOS9 and iOS10,What's more,I really don't understand why console show me :unrecognized selector sent to instance 0x18b47d20


问:
Read data from remote hive on spark over JDBC returns empty result
I need to execute hive queries on remote hive server from spark, but for some reasons i receive only column names(without data).
Data available in table, i checked it via HUE and java jdbc connection.

Here is my code example:

```<code>val test = spark.read
    .option("url", "jdbc:hive2://remote.hive.server:10000/work_base")
    .option("user", "user")
    .option("password", "password")
    .option("dbtable", "some_table_with_data")
    .option("driver", "org.apache.hive.jdbc.HiveDriver")
    .format("jdbc")
    .load()
test.show()
</code>```

Output:

```<code>+-------+
|dst.col|
+-------+
+-------+
</code>```

I know that data vailable on this table.

Scala version: 2.11
Spark version: 2.1.0, i also tried 2.1.1
Hive version: CDH 5.7 Hive 1.1.1, on HDP i have same story
Hive JDBC version: 1.1.1 i also tried later versions

But this problem available on Hive with later versions, too.
Could you help me with this issue, because i didn't find anything in mail group answers and StackOverflow.
Maybe you know how i can execute hive queries from spark to remote servers?

答:
You should add this into your options:</p>

```<code> .option("fetchsize", "10")
</code>```

Body:
I need to execute hive queries on remote hive server from spark, but for some reasons i receive only column names(without data).
Data available in table, i checked it via HUE and java jdbc connection.

Here is my code example:

val test = spark.read
    .option("url", "jdbc:hive2://remote.hive.server:10000/work_base")
    .option("user", "user")
    .option("password", "password")
    .option("dbtable", "some_table_with_data")
    .option("driver", "org.apache.hive.jdbc.HiveDriver")
    .format("jdbc")
    .load()
test.show()

Output:

+-------+
|dst.col|
+-------+
+-------+

I know that data vailable on this table.

Scala version: 2.11
Spark version: 2.1.0, i also tried 2.1.1
Hive version: CDH 5.7 Hive 1.1.1, on HDP i have same story
Hive JDBC version: 1.1.1 i also tried later versions

But this problem available on Hive with later versions, too.
Could you help me with this issue, because i didn't find anything in mail group answers and StackOverflow.
Maybe you know how i can execute hive queries from spark to remote servers?

Body:
You should add this into your options:

 .option("fetchsize", "10")


问:
Using Laravel Excel
I'm trying to use Laravel excel https://github.com/Maatwebsite/Laravel-Excel

I have a simple question, how do I put the rows loaded in, into my database, and also how do I display them in a table in my view. The CSV file i'm loading only has one column, with the heading "Email".

Below is my simple code

Controller:

public
function importCSV() {
  $excel = \App::make('excel');
  $excel - > load('kad.csv', function($reader) {

    $reader - > takeColumns(1);

  }) - > get();

  return view('index', compact('excel'));

}```
</div>
</div>
</p>

<p>View:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>@extends('layouts.master') @section('content')
<table class="table table-striped">
  @foreach($excel as $ex)
  <tr>
    <td>
      {{$ex->Email}}
    </td>
  </tr>
  @endforeach

</table>

@endsection</code>```

My view simply displays blank. What is the right way to go about this?
Kind regards

答:
Store the result from get() to a variable and pass it to your view.

```<code>public function importCSV() {
    $excel = \App::make('excel');
    $data = $excel->load('kad.csv', function($reader) {

        $reader->takeColumns(1);

    })->get();

    return view('index', compact('data'));
}
</code>```

Then use $data in your blade.

```<code> @foreach($data as $row)
</code>```

Title: Using Laravel Excel

Body:
I'm trying to use Laravel excel https://github.com/Maatwebsite/Laravel-Excel

I have a simple question, how do I put the rows loaded in, into my database, and also how do I display them in a table in my view. The CSV file i'm loading only has one column, with the heading "Email".

Below is my simple code

Controller:

public
function importCSV() {
  $excel = \App::make('excel');
  $excel - > load('kad.csv', function($reader) {

    $reader - > takeColumns(1);

  }) - > get();

  return view('index', compact('excel'));

}

View:

@extends('layouts.master') @section('content')

  @foreach($excel as $ex)

      {{$ex->Email}}

  @endforeach

@endsection

My view simply displays blank. What is the right way to go about this?
Kind regards

Body:
Store the result from get() to a variable and pass it to your view.

public function importCSV() {
    $excel = \App::make('excel');
    $data = $excel->load('kad.csv', function($reader) {

        $reader->takeColumns(1);

    })->get();

    return view('index', compact('data'));
}

Then use $data in your blade.

 @foreach($data as $row)


问:
WSO2 ESB (or EI) Best practice for managing environment specific variables
In some of my application I have to manage environment specific attributes / variables like:
- folder path
- rest api urls
- credentials
- ...

At the moment I'm manually setting variables in the configuration registry of each server. This is quite heavy when you've to deploy a new server because you've to recreate everything manually (I haven't find a way to initialize the repository from an xml file for instance)

I've seen different approaches like
- writing different version of the endpoints, sequences,... and create different car for distribution on each environment
- Using local registry with different entries
- Using governance registry (I've no experience with this)

What is according to you the best approach for this?
Thanks for helping

答:
You can find the best practices guide for WSO2 Enterprise Integrator (ESB, DSS, BPS and MB) at [1]. It also explains how to manage environment specific variables. </p>

<p>[1] https://docs.wso2.com/display/EI611/WSO2+Enterprise+Integrator+Best+Practices</p>

Body:
You can find the best practices guide for WSO2 Enterprise Integrator (ESB, DSS, BPS and MB) at [1]. It also explains how to manage environment specific variables.

[1] https://docs.wso2.com/display/EI611/WSO2+Enterprise+Integrator+Best+Practices


问:
In the top of NavigationView has shadow,How can I remove it?

I am sorry about that my English is horrible，thanks for your help！

This code is my fragments layout.

```<code><android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:openDrawer="end">
    <com.wk.reservation.view.PullListView
        android:id="@id/listView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view_right"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="end"
        app:itemBackground="@android:color/white">

        <include layout="@layout/nav_right_header_main" />

    </android.support.design.widget.NavigationView>
</android.support.v4.widget.DrawerLayout>`
</code>```

答:
Maybe it's already too late to answer this but for the version

```<code>'com.android.support:design:25.3.1'
</code>```

you can try adding

```<code>app:insetForeground="@android:color/transparent"
</code>```

So navigation view would look like this

```<code><android.support.design.widget.NavigationView
                android:id="@+id/nav_view"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:layout_gravity="start"
                android:layout_marginTop="?attr/actionBarSize"
                android:background="@color/colorPrimary"
                app:elevation="0dp"
                app:insetForeground="@android:color/transparent"
                app:itemIconTint="@color/white"
                app:itemTextColor="@color/white"
                app:menu="@menu/main_drawer">
</code>```

Body:
I am sorry about that my English is horrible，thanks for your help！

This code is my fragments layout.

<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:openDrawer="end">
    <com.wk.reservation.view.PullListView
        android:id="@id/listView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view_right"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="end"
        app:itemBackground="@android:color/white">

        <include layout="@layout/nav_right_header_main" />

    </android.support.design.widget.NavigationView>
</android.support.v4.widget.DrawerLayout>`

Body:
Maybe it's already too late to answer this but for the version

'com.android.support:design:25.3.1'

you can try adding

app:insetForeground="@android:color/transparent"

So navigation view would look like this

<android.support.design.widget.NavigationView
                android:id="@+id/nav_view"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:layout_gravity="start"
                android:layout_marginTop="?attr/actionBarSize"
                android:background="@color/colorPrimary"
                app:elevation="0dp"
                app:insetForeground="@android:color/transparent"
                app:itemIconTint="@color/white"
                app:itemTextColor="@color/white"
                app:menu="@menu/main_drawer">


问:
MySQL reordering list table
In MySQL workbench I have a list table of the following format:

```<code>ID  | type | order | time
----|------|-------|----------
id1 |  1   |  1    | 2017-1-1
id1 |  2   |  2    | 2017-1-2
id1 |  1   |  3    | 2017-1-4
id1 |  2   |  4    | 2017-1-5
id2 |  1   |  1    | 2017-1-1
id2 |  2   |  2    | 2017-1-9
id3 |  1   |  1    | 2017-1-1
id3 |  2   |  2    | 2017-1-2
id3 |  1   |  3    | 2017-1-9
id3 |  2   |  4    | 2017-1-11
id3 |  1   |  5    | 2017-1-13
id3 |  2   |  6    | 2017-1-18
</code>```

I would like to reorder the table to give the following output:

```<code>ID  |  time(1)  | time(2)
----|-----------|-----------
id1 | 2017-1-1  | 2017-1-2
id1 | 2017-1-4  | 2017-1-5
id2 | 2017-1-1  | 2017-1-9
id3 | 2017-1-1  | 2017-1-2
id3 | 2017-1-9  | 2017-1-11
id3 | 2017-1-13 | 2017-1-18
</code>```

I have a solution for the above but it seems to take ages when fetching the results on a half million entries table. I was wondering if anybody could offer a solution to the above problem that I could try.

Thanks for your help,Luca

Title: MySQL reordering list table

Body:
In MySQL workbench I have a list table of the following format:

ID  | type | order | time
----|------|-------|----------
id1 |  1   |  1    | 2017-1-1
id1 |  2   |  2    | 2017-1-2
id1 |  1   |  3    | 2017-1-4
id1 |  2   |  4    | 2017-1-5
id2 |  1   |  1    | 2017-1-1
id2 |  2   |  2    | 2017-1-9
id3 |  1   |  1    | 2017-1-1
id3 |  2   |  2    | 2017-1-2
id3 |  1   |  3    | 2017-1-9
id3 |  2   |  4    | 2017-1-11
id3 |  1   |  5    | 2017-1-13
id3 |  2   |  6    | 2017-1-18

I would like to reorder the table to give the following output:

ID  |  time(1)  | time(2)
----|-----------|-----------
id1 | 2017-1-1  | 2017-1-2
id1 | 2017-1-4  | 2017-1-5
id2 | 2017-1-1  | 2017-1-9
id3 | 2017-1-1  | 2017-1-2
id3 | 2017-1-9  | 2017-1-11
id3 | 2017-1-13 | 2017-1-18

I have a solution for the above but it seems to take ages when fetching the results on a half million entries table. I was wondering if anybody could offer a solution to the above problem that I could try.

Thanks for your help,Luca

Body:
select t1.ID, t1.time as 'time(1)', t2.time as 'time(2)'
from Table1 t1 join Table1 t2
on t1.ID=t2.ID and t1.type=1 and t2.type=2
and t1.order=t2.order-1 and t2.order%2=0;

|  ID |   time(1) |   time(2) |
|-----|-----------|-----------|
| id1 |  2017-1-1 |  2017-1-2 |
| id1 |  2017-1-4 |  2017-1-5 |
| id2 |  2017-1-1 |  2017-1-9 |
| id3 |  2017-1-1 |  2017-1-2 |
| id3 |  2017-1-9 | 2017-1-11 |
| id3 | 2017-1-13 | 2017-1-18 |


问:
find records in sequelize seeds
I've been trying to write some seeds for my project, but I've ran into a bit of a snag.

I've got a many-to-many relation with my users and roles table. So, when I'm seeding the database I need to add a record with correct ids into my join table. In order to do that I need to find user by email and role by name and get the ids and that's the problem. I can't find any good documentation on the sequelize site. I'm using the sequelize-cli for the seeding and migrating things. I get as a parameter a queryInterface, but I can't find any example or mention what this thing can actually do. Just some simple examples just got me through the migrating (somehow) and what I was able to find on google.

I've resolved this by using a "dirty trick" I'd say...

```<code>// user_seeds.js
up: function (queryInterface, Sequelize) {
  return queryInterface.bulkInsert(table, [{
    id: 1,
    name: 'John doe',
    email: 'john@doe.com',
    created_at,
    updated_at
}], {});

// roles_seeds.js
up: function (queryInterface, Sequelize) {
  return queryInterface.bulkInsert(table, [{
    id: 1,
    name: 'admin',
    created_at,
    updated_at
  }, {
    id: 2,
    name: 'user',
    created_at,
    updated_at
}]);

//user_roles_seeds.js
up: function (queryInterface, Sequelize) {
    return queryInterface.bulkInsert(table, [{
    employee_id: 1,
    role_id: 1
  }]);
},
</code>```

Don't like this solution since it may be troublesome in the future should I'd want to run the seeds again and forget about how this works. There should be a way for me to query the database using this queryInterface. I was wondering if one of you had ran into this issue and solved it, if so, please share.

答:
Yes you can use the queryInterface to query database.</p>

```<code>  async up(queryInterface, Sequelize) {
    const user = await queryInterface.rawSelect('User', {
      where: {
        name: 'John doe',
      },
    }, ['id']);

    if(!user) {
       // do bulkInsert stuff.
    }
  },
</code>```

Title: find records in sequelize seeds

Body:
I've been trying to write some seeds for my project, but I've ran into a bit of a snag.

I've got a many-to-many relation with my users and roles table. So, when I'm seeding the database I need to add a record with correct ids into my join table. In order to do that I need to find user by email and role by name and get the ids and that's the problem. I can't find any good documentation on the sequelize site. I'm using the sequelize-cli for the seeding and migrating things. I get as a parameter a queryInterface, but I can't find any example or mention what this thing can actually do. Just some simple examples just got me through the migrating (somehow) and what I was able to find on google.

I've resolved this by using a "dirty trick" I'd say...

// user_seeds.js
up: function (queryInterface, Sequelize) {
  return queryInterface.bulkInsert(table, [{
    id: 1,
    name: 'John doe',
    email: 'john@doe.com',
    created_at,
    updated_at
}], {});

// roles_seeds.js
up: function (queryInterface, Sequelize) {
  return queryInterface.bulkInsert(table, [{
    id: 1,
    name: 'admin',
    created_at,
    updated_at
  }, {
    id: 2,
    name: 'user',
    created_at,
    updated_at
}]);

//user_roles_seeds.js
up: function (queryInterface, Sequelize) {
    return queryInterface.bulkInsert(table, [{
    employee_id: 1,
    role_id: 1
  }]);
},

Don't like this solution since it may be troublesome in the future should I'd want to run the seeds again and forget about how this works. There should be a way for me to query the database using this queryInterface. I was wondering if one of you had ran into this issue and solved it, if so, please share.

Body:
Yes you can use the queryInterface to query database.

  async up(queryInterface, Sequelize) {
    const user = await queryInterface.rawSelect('User', {
      where: {
        name: 'John doe',
      },
    }, ['id']);

    if(!user) {
       // do bulkInsert stuff.
    }
  },


问:
How can I use connection pool in aiomysql
I just don't know what to do to reuse aiomysql connection pool by reading the aiohttp examples or by google.
Here is my code

```<code>import aiomysql
import asyncio

async def select(loop, sql):
    pool = await aiomysql.create_pool(host='127.0.0.1', port=3306,
                                      user='root', password='123456',
                                      db='test', loop=loop)
    async with pool.acquire() as conn:
        async with conn.cursor() as cur:
            await cur.execute(sql)
            r = await cur.fetchone()
            print(r)

async def insert(loop, sql):
    pool = await aiomysql.create_pool(host='127.0.0.1', port=3306,
                                      user='root', password='123456',
                                      db='test', loop=loop)
    async with pool.acquire() as conn:
        async with conn.cursor() as cur:
            await cur.execute(sql)
            await conn.commit()

async def main(loop):
    c1 = select(loop=loop, sql='select * from minifw')
    c2 = insert(loop=loop, sql="insert into minifw (name) values ('hello')")
    tasks = [
        asyncio.ensure_future(c1),
        asyncio.ensure_future(c2)
    ]
    return await asyncio.gather(*tasks)

if __name__ == '__main__':
    cur_loop = asyncio.get_event_loop()
    cur_loop.run_until_complete(main(cur_loop))
</code>```

If i run this code, the create_pool will be executed twice.So I want to know how to change this code to reuse aiomysql connecton pool.

Thanks!

答:
You can define pool in main func, like this:</p>

```<code>import aiomysql
import asyncio

async def select(loop, sql, pool):
    async with pool.acquire() as conn:
        async with conn.cursor() as cur:
            await cur.execute(sql)
            r = await cur.fetchone()
            print(r)

async def insert(loop, sql, pool):
    async with pool.acquire() as conn:
        async with conn.cursor() as cur:
            await cur.execute(sql)
            await conn.commit()

async def main(loop):
    pool = await aiomysql.create_pool(
        host='127.0.0.1',
        port=3306,
        user='root',
        password='123456',
        db='test',
        loop=loop)
    c1 = select(loop=loop, sql='select * from minifw limit 1', pool=pool)
    c2 = insert(loop=loop, sql="insert into minifw (name) values ('hello')", pool=pool)

    tasks = [asyncio.ensure_future(c1), asyncio.ensure_future(c2)]
    return await asyncio.gather(*tasks)

if __name__ == '__main__':
    cur_loop = asyncio.get_event_loop()
    cur_loop.run_until_complete(main(cur_loop))
</code>```

Body:
I just don't know what to do to reuse aiomysql connection pool by reading the aiohttp examples or by google.
Here is my code

import aiomysql
import asyncio

async def select(loop, sql):
    pool = await aiomysql.create_pool(host='127.0.0.1', port=3306,
                                      user='root', password='123456',
                                      db='test', loop=loop)
    async with pool.acquire() as conn:
        async with conn.cursor() as cur:
            await cur.execute(sql)
            r = await cur.fetchone()
            print(r)

async def insert(loop, sql):
    pool = await aiomysql.create_pool(host='127.0.0.1', port=3306,
                                      user='root', password='123456',
                                      db='test', loop=loop)
    async with pool.acquire() as conn:
        async with conn.cursor() as cur:
            await cur.execute(sql)
            await conn.commit()

async def main(loop):
    c1 = select(loop=loop, sql='select * from minifw')
    c2 = insert(loop=loop, sql="insert into minifw (name) values ('hello')")
    tasks = [
        asyncio.ensure_future(c1),
        asyncio.ensure_future(c2)
    ]
    return await asyncio.gather(*tasks)

if __name__ == '__main__':
    cur_loop = asyncio.get_event_loop()
    cur_loop.run_until_complete(main(cur_loop))

If i run this code, the create_pool will be executed twice.So I want to know how to change this code to reuse aiomysql connecton pool.

Thanks!

Body:
You can define pool in main func, like this:

import aiomysql
import asyncio

async def select(loop, sql, pool):
    async with pool.acquire() as conn:
        async with conn.cursor() as cur:
            await cur.execute(sql)
            r = await cur.fetchone()
            print(r)

async def insert(loop, sql, pool):
    async with pool.acquire() as conn:
        async with conn.cursor() as cur:
            await cur.execute(sql)
            await conn.commit()

async def main(loop):
    pool = await aiomysql.create_pool(
        host='127.0.0.1',
        port=3306,
        user='root',
        password='123456',
        db='test',
        loop=loop)
    c1 = select(loop=loop, sql='select * from minifw limit 1', pool=pool)
    c2 = insert(loop=loop, sql="insert into minifw (name) values ('hello')", pool=pool)

    tasks = [asyncio.ensure_future(c1), asyncio.ensure_future(c2)]
    return await asyncio.gather(*tasks)

if __name__ == '__main__':
    cur_loop = asyncio.get_event_loop()
    cur_loop.run_until_complete(main(cur_loop))


问:
Lock a Text File in Perl

Possible Duplicate:

  How do I lock a file in Perl?

Does anyone know how to lock a text file in Perl so only one thing can write to it until it is unlocked? I need something other than setting the read/write attributes. Thanks.

答: Take a look at flock.</p>

ContentLicense: CC BY-SA 2.5

Title: Lock a Text File in Perl

Body: Take a look at flock.


问:
Efficient alternative way than using multiple if statements to check keys in a dictionary
I have around 45 if statements that checks the dictionary  to see if it has that key.

```<code>    private List<MessageName> createMsgObject(Dictionary<string, string> infoHash, Dictionary<string, Int16> msgDescritionAndID)
    {
            MessageName msgName = null;
            List<MessageName> msgNameList = new List<MessageName>();
            var msgObjOuter = new MessageName();

            if (infoHash.ContainsKey("redis_version"))
            {
                msgName = new MessageName();
                msgName.MessageID = msgDescritionAndID["redis_version"];
                msgName.DiagnosticCnt = 0;
                msgName.DiagnosticStr = infoHash["redis_version"];
                msgNameList.Add(msgName);
            }
           if (infoHash.ContainsKey("uptime_in_seconds"))
           {
            msgName = new MessageName();
            msgName.MessageID = msgDescritionAndID["uptime_in_seconds"];
            msgName.DiagnosticCnt = Convert.ToInt32(infoHash["uptime_in_seconds"]);
            msgName.DiagnosticStr = "";
            msgNameList.Add(msgName);
          }
          //... 40 more if statements
         return msgNameList;
   }
</code>```

This really hasn't had a hit on performance but I was wondering if there was a more efficient way to check all the keys in that dictionary and if it does insert it's property in to a MessageName object and insert that object into a list. I don't know if switch statements would help in performance.

答:
Switch statements do help in performance, compared to multiple ifs, as discussed here.

However I have a suggestion, if there are multiple occasions in your 40+ statements where you assign the same properties to the same variables, you could try something like:

```<code>List<string> toCheckStrings1 = new List<string> { "redis_version", "something similar", };      //you can put all the strings here first
</code>```

Then with a foreach loop you can reduce the number of if statements

```<code>foreach (var match in toCheckStrings1.Intersect(infoHash.Keys))    //intersect() will give you a list of matched keys
{
    msgNameList.Add(new MessageName
    {
        MessageID = msgDescritionAndID[match],
        DiagnosticCnt = 0,
        DiagnosticStr = infoHash[match]
    });
}
</code>```

And since you assign different properties for some variables (e.g. DiagnosticCnt for "uptime_in_seconds"), you can group those differently:

```<code>List<string> toCheckStrings2 = new List<string> { "uptime_in_seconds", "others", "etc" };
foreach (var match in toCheckStrings2.Intersect(infoHash.Keys))
{
    msgNameList.Add(new MessageName
    {
        MessageID = msgDescritionAndID[match],
        DiagnosticCnt = Convert.ToInt32(infoHash["match"]),
        DiagnosticStr = ""
    });
}
</code>```

And so on for other cases. Even though it may be several foreach loops, hopefully it would be much less than 45 if statements.

EDIT

As pointed out in the comments, the time complexity of my suggestion above would be somewhere around O(N) while for your code it would be a bunch of O(1) which is basically O(1). As such, if time is a concern (if you have huge datasets), it would be wiser to just stick with if statements, or switch.

Body:
I have around 45 if statements that checks the dictionary  to see if it has that key.

    private List<MessageName> createMsgObject(Dictionary<string, string> infoHash, Dictionary<string, Int16> msgDescritionAndID)
    {
            MessageName msgName = null;
            List<MessageName> msgNameList = new List<MessageName>();
            var msgObjOuter = new MessageName();

            if (infoHash.ContainsKey("redis_version"))
            {
                msgName = new MessageName();
                msgName.MessageID = msgDescritionAndID["redis_version"];
                msgName.DiagnosticCnt = 0;
                msgName.DiagnosticStr = infoHash["redis_version"];
                msgNameList.Add(msgName);
            }
           if (infoHash.ContainsKey("uptime_in_seconds"))
           {
            msgName = new MessageName();
            msgName.MessageID = msgDescritionAndID["uptime_in_seconds"];
            msgName.DiagnosticCnt = Convert.ToInt32(infoHash["uptime_in_seconds"]);
            msgName.DiagnosticStr = "";
            msgNameList.Add(msgName);
          }
          //... 40 more if statements
         return msgNameList;
   }

This really hasn't had a hit on performance but I was wondering if there was a more efficient way to check all the keys in that dictionary and if it does insert it's property in to a MessageName object and insert that object into a list. I don't know if switch statements would help in performance.

Body:
Switch statements do help in performance, compared to multiple ifs, as discussed here.

However I have a suggestion, if there are multiple occasions in your 40+ statements where you assign the same properties to the same variables, you could try something like:

List<string> toCheckStrings1 = new List<string> { "redis_version", "something similar", };      //you can put all the strings here first

Then with a foreach loop you can reduce the number of if statements

foreach (var match in toCheckStrings1.Intersect(infoHash.Keys))    //intersect() will give you a list of matched keys
{
    msgNameList.Add(new MessageName
    {
        MessageID = msgDescritionAndID[match],
        DiagnosticCnt = 0,
        DiagnosticStr = infoHash[match]
    });
}

And since you assign different properties for some variables (e.g. DiagnosticCnt for "uptime_in_seconds"), you can group those differently:

List<string> toCheckStrings2 = new List<string> { "uptime_in_seconds", "others", "etc" };
foreach (var match in toCheckStrings2.Intersect(infoHash.Keys))
{
    msgNameList.Add(new MessageName
    {
        MessageID = msgDescritionAndID[match],
        DiagnosticCnt = Convert.ToInt32(infoHash["match"]),
        DiagnosticStr = ""
    });
}

And so on for other cases. Even though it may be several foreach loops, hopefully it would be much less than 45 if statements.

EDIT

As pointed out in the comments, the time complexity of my suggestion above would be somewhere around O(N) while for your code it would be a bunch of O(1) which is basically O(1). As such, if time is a concern (if you have huge datasets), it would be wiser to just stick with if statements, or switch.


问:
Hide Tab in Tablayout Android
Unfortunately the other question wasn't answered about how to hide a Tab in android.support.design.widget.TabLayout.
The others questions are made with TabHost, I don't want to change my code.

I would like to hide the tab "Three".

Fragment:

```<code>viewPager = (ViewPager) rootView.findViewById(R.id.search_viewPager);
viewPager.addOnPageChangeListener(viewPagerListener);
viewPager.setAdapter(adapter);
tabLayout = (TabLayout) rootView.findViewById(R.id.search_tabs);
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
tabLayout.setupWithViewPager(viewPager);
</code>```

Layout:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/white"
android:orientation="vertical">

    <android.support.design.widget.TabLayout
    android:id="@+id/search_tabs"
    style="@style/TabLayoutStyle"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/white"
    android:elevation="1dp" />

    <android.support.v4.view.ViewPager
    android:id="@+id/search_viewPager"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true" />

</LinearLayout>
</code>```

答:
```<code> //To hide the first tab
 ((ViewGroup) tabLayout.getChildAt(0)).getChildAt(0).setVisibility(View.GONE);
 //Set the next  tab as selected tab
 TabLayout.Tab tab = tabLayout.getTabAt(1);
 tab.select();
</code>```

Title: Hide Tab in Tablayout Android

Body:
Unfortunately the other question wasn't answered about how to hide a Tab in android.support.design.widget.TabLayout.
The others questions are made with TabHost, I don't want to change my code.

I would like to hide the tab "Three".

Fragment:

viewPager = (ViewPager) rootView.findViewById(R.id.search_viewPager);
viewPager.addOnPageChangeListener(viewPagerListener);
viewPager.setAdapter(adapter);
tabLayout = (TabLayout) rootView.findViewById(R.id.search_tabs);
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
tabLayout.setupWithViewPager(viewPager);

Layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/white"
android:orientation="vertical">

    <android.support.design.widget.TabLayout
    android:id="@+id/search_tabs"
    style="@style/TabLayoutStyle"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/white"
    android:elevation="1dp" />

    <android.support.v4.view.ViewPager
    android:id="@+id/search_viewPager"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true" />

</LinearLayout>


问:
Clean cache work on iOS 7 and iOS 8,however,on iOS 9 and iOS 10,it didn't work
The code I use to clean cache is:

```<code>-(void)removeCache
{
    NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:cachePath];

for (NSString *p in files)
{
    NSError *error;
    NSString *path = [cachePath stringByAppendingPathComponent:p];
    if([[NSFileManager defaultManager] fileExistsAtPath:path])
    {
        [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
    }
}
}
</code>```

It work fine on both iOS 7 and iOS 8,but on iOS 9 and iOS 10,it didn't work.I add a breakpoint in this method,it stoped there,so,the method had been called but it didn't clean caches on iOS 9 and iOS 10.

I am really very curious about why it work fine on iOS 7 and iOS 8,but,didn't work on iOS 9 and iOS 10.

答: There is a three part named EGOImageView in my project,and it will cache images,so the right way to clean cache is use EGOImage's own clean method.</p>

Body:
The code I use to clean cache is:

-(void)removeCache
{
    NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:cachePath];

for (NSString *p in files)
{
    NSError *error;
    NSString *path = [cachePath stringByAppendingPathComponent:p];
    if([[NSFileManager defaultManager] fileExistsAtPath:path])
    {
        [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
    }
}
}

It work fine on both iOS 7 and iOS 8,but on iOS 9 and iOS 10,it didn't work.I add a breakpoint in this method,it stoped there,so,the method had been called but it didn't clean caches on iOS 9 and iOS 10.

I am really very curious about why it work fine on iOS 7 and iOS 8,but,didn't work on iOS 9 and iOS 10.


问:
Asynchronously iterate through an array and then return the array?
I am trying to iterate through an array asynchronously and then want to push the values from a called function to a new array.

I have the following code but not sure how to approach this...

```<code>let companies = [];
_.forEach(notProcessed, function(company) {
    companies.push(processThem(company));
});
return companies;
</code>```

Of course when printing / returning companies, I will receive an empty array.

Thanks ahead time, any help is appreciated!

答:
One way of doing it:

```<code>var notProcessed = ['a', 'b', 'c'];

function processThem(company) {
  // Example long process
  return new Promise((resolve) => {
    setTimeout(() => resolve(company), 500);
  });
}

function processArrayAsync(notProcessed) {
  var companies = [];
  var promise = Promise.resolve();
  for(let next of notProcessed) {
    promise = promise
      .then(() => processThem(next))
      .then(company => companies.push(company));
  }

  return promise.then(() => companies);
}

processArrayAsync(notProcessed).then(console.log);
</code>```

And there is a better way using new in es6 async functions

```<code>var notProcessed = ['a', 'b', 'c'];

async function processThem(company) {
  // Example long process
  return new Promise((resolve) => {
    setTimeout(() => resolve(company), 500);
  });
}

async function processArrayAsync(notProcessed) {
  var companies = [];
  for(let next of notProcessed) {
    let res = await processThem(next);
    companies.push(res);
  }
  return companies;
}

processArrayAsync(notProcessed).then(console.log);
</code>```

I really like this second way of handling async operations :)

Body:
I am trying to iterate through an array asynchronously and then want to push the values from a called function to a new array.

I have the following code but not sure how to approach this...

let companies = [];
_.forEach(notProcessed, function(company) {
    companies.push(processThem(company));
});
return companies;

Of course when printing / returning companies, I will receive an empty array.

Thanks ahead time, any help is appreciated!

Body:
One way of doing it:

var notProcessed = ['a', 'b', 'c'];

function processThem(company) {
  // Example long process
  return new Promise((resolve) => {
    setTimeout(() => resolve(company), 500);
  });
}

function processArrayAsync(notProcessed) {
  var companies = [];
  var promise = Promise.resolve();
  for(let next of notProcessed) {
    promise = promise
      .then(() => processThem(next))
      .then(company => companies.push(company));
  }

  return promise.then(() => companies);
}

processArrayAsync(notProcessed).then(console.log);

And there is a better way using new in es6 async functions

var notProcessed = ['a', 'b', 'c'];

async function processThem(company) {
  // Example long process
  return new Promise((resolve) => {
    setTimeout(() => resolve(company), 500);
  });
}

async function processArrayAsync(notProcessed) {
  var companies = [];
  for(let next of notProcessed) {
    let res = await processThem(next);
    companies.push(res);
  }
  return companies;
}

processArrayAsync(notProcessed).then(console.log);

I really like this second way of handling async operations :)


问:
What the typical viewport size on a 1024x768 screen?
I am designing a web application, and I wish to know the largest size (x and y) that I can design for.

As of January 2008, about half of users are using 1024x278 screens, and probably less than 10% are using smaller screens. (Phone and palmtop users are an exception here.) So we are designing for minimum screen size of 1024x768.

However, that's the screen size, and when we are laying out our content we need to know the viewport size. There is evidence that most users have the browser maximized, but one still must subtract out space for OS decorations and browser chrome. People customize their chrome, so there is no single "right" answer; I am going for a reasonable bound that will accommodate the majority of users.

I see plenty of designers who say that they use a width of 960 pixels because it has many factors and can be divided up evenly -- but before deciding on this I want to know the maximum size that I can get away with, then I might choose to use somewhat less. I have seen max widths of 960, 974 or even 990 quoted... my own experiments seem to show a width of 1000 works OK.

Heights are even more difficult to come by: I find I can fit a vertical viewport height of 595 pixels works on the browsers that I've tried, with typical default OS and chrome settings. But I haven't tried very many, and I would rather see a more authoritative source. Surely someone else has done this research and done it better than me.

So my real question is this: What is the largest viewport size I can design for and expect it to fit without scrollbars for 80-90% of all users?

答: I'm currently on a Acer netbook at 1024x600 screen resolution. Remember that we are a growing market segment! (or at least, try not to make your vertical real-estate assume 768 as a minimum screen height)</p>

OwnerDisplayName: mcherm

OwnerDisplayName: Jimmy


问:
CMake Configuration Issue when using Qt Creator
I am trying to set up a build environment in qt creator using cmake, but no matter what I try I cannot get it to progress. It fails with issue; "Configuration Issue". When expanding the details in the General Messages section it looks like its failing to compile a test c program.

I can't see anything wrong with my qt creator configuration; which I had to set up in the past manually to use qmake for a qt app. This worked as desired. Here is that configuration.

This is the error in full as displayed in general messages;

```<code>Running Windows Runtime device detection.
No winrtrunner.exe found.
Running "C:\Program Files\CMake\bin\cmake.exe -E server "--pipe=\\.\pipe\{8454d5f3-9c7b-42c8-8f39-a6bfbbbdd562}" --experimental" in
C:\Users\Andrew\AppData\Local\Temp\QtCreator-l9Mfi9\qtc-cmake-XXUaBP1D.
The C compiler identification is MSVC 19.0.24215.1
The CXX compiler identification is MSVC 19.0.24215.1
Check for working C compiler: C:/Program Files (x86)/Microsoft Visual Studio 14.0/VC/BIN/x86_amd64/cl.exe
Check for working C compiler: C:/Program Files (x86)/Microsoft Visual Studio 14.0/VC/BIN/x86_amd64/cl.exe -- broken
CMake Error at C:/Program Files/CMake/share/cmake-3.7/Modules/CMakeTestCCompiler.cmake:51 (message):
  The C compiler "C:/Program Files (x86)/Microsoft Visual Studio
  14.0/VC/BIN/x86_amd64/cl.exe" is not able to compile a simple test program.

  It fails with the following output:

   Change Dir: C:/Users/Andrew/AppData/Local/Temp/QtCreator-l9Mfi9/qtc-cmake-XXUaBP1D/CMakeFiles/CMakeTmp

  Run Build Command:"nmake" "/NOLOGO" "cmTC_2c22c\fast"

    "C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\nmake.exe" -f
  CMakeFiles\cmTC_2c22c.dir\build.make /nologo -L
  CMakeFiles\cmTC_2c22c.dir\build

  Building C object CMakeFiles/cmTC_2c22c.dir/testCCompiler.c.obj

            C:\PROGRA~2\MICROS~1.0\VC\BIN\X86_AM~1\cl.exe
  @C:\Users\Andrew\AppData\Local\Temp\nm7672.tmp

  testCCompiler.c

  Linking C executable cmTC_2c22c.exe

"C:\Program Files\CMake\bin\cmake.exe" -E vs_link_exe
  --intdir=CMakeFiles\cmTC_2c22c.dir --manifests --
  C:\PROGRA~2\MICROS~1.0\VC\bin\X86_AM~1\link.exe /nologo
  @CMakeFiles\cmTC_2c22c.dir\objects1.rsp
  @C:\Users\Andrew\AppData\Local\Temp\nm76B2.tmp

  MT failed to run.

  NMAKE : fatal error U1077: '"C:\Program Files\CMake\bin\cmake.exe"' :
  return code '0xffffffff'

  Stop.

  NMAKE : fatal error U1077: '"C:\Program Files (x86)\Microsoft Visual Studio
  14.0\VC\BIN\nmake.exe"' : return code '0x2'

  Stop.

  CMake will not be able to correctly generate this project.
Call Stack (most recent call first):
  CMakeLists.txt:3 (project)

Configuring incomplete, errors occurred!
See also "C:/Users/Andrew/AppData/Local/Temp/QtCreator-l9Mfi9/qtc-cmake-XXUaBP1D/CMakeFiles/CMakeOutput.log".
See also "C:/Users/Andrew/AppData/Local/Temp/QtCreator-l9Mfi9/qtc-cmake-XXUaBP1D/CMakeFiles/CMakeError.log".
</code>```

The content of the actual CMake file doesn't seem to matter, so I'm heavily leaning on something not being correctly configured.

I've tried messing with the toolchain to no avail. Any ideas?

答:
I figured it out in the end.

This is the process I went through. Initially I assumed I had some how not configured the compiler toolchain correctly, so to rule that out I switched to the MinGW GNU toolchain gcc/gdb.

The issue persisted, so that left only two real possibility. CMake was broken or the CMake Generator wasn't correctly configured. Ignoring the first for sanity reasons that left the generator.

I tried switching through a few of the provided options, obviously I didn't have any of them installed. But finally one gave me a reasonable error, that Qt Creator couldn't find it. (I switched to ninja from nmake).

I installed it, and added it to the OS PATH environment variable; so Qt Creator could find it. (Windows 10: Control Panel > System > Advanced system settings (sidebar) > Environment Variables + Set Path > OK)

(Linux: add export PATH="${PATH}": to something like your bashrc). Probably wouldn't be an issue on Linux unless you installed the program from source.

Anyway, that was frustrating. Setting up a new development environment sucks.

Body:
I am trying to set up a build environment in qt creator using cmake, but no matter what I try I cannot get it to progress. It fails with issue; "Configuration Issue". When expanding the details in the General Messages section it looks like its failing to compile a test c program.

I can't see anything wrong with my qt creator configuration; which I had to set up in the past manually to use qmake for a qt app. This worked as desired. Here is that configuration.

This is the error in full as displayed in general messages;

Running Windows Runtime device detection.
No winrtrunner.exe found.
Running "C:\Program Files\CMake\bin\cmake.exe -E server "--pipe=\\.\pipe\{8454d5f3-9c7b-42c8-8f39-a6bfbbbdd562}" --experimental" in
C:\Users\Andrew\AppData\Local\Temp\QtCreator-l9Mfi9\qtc-cmake-XXUaBP1D.
The C compiler identification is MSVC 19.0.24215.1
The CXX compiler identification is MSVC 19.0.24215.1
Check for working C compiler: C:/Program Files (x86)/Microsoft Visual Studio 14.0/VC/BIN/x86_amd64/cl.exe
Check for working C compiler: C:/Program Files (x86)/Microsoft Visual Studio 14.0/VC/BIN/x86_amd64/cl.exe -- broken
CMake Error at C:/Program Files/CMake/share/cmake-3.7/Modules/CMakeTestCCompiler.cmake:51 (message):
  The C compiler "C:/Program Files (x86)/Microsoft Visual Studio
  14.0/VC/BIN/x86_amd64/cl.exe" is not able to compile a simple test program.

  It fails with the following output:

   Change Dir: C:/Users/Andrew/AppData/Local/Temp/QtCreator-l9Mfi9/qtc-cmake-XXUaBP1D/CMakeFiles/CMakeTmp

  Run Build Command:"nmake" "/NOLOGO" "cmTC_2c22c\fast"

    "C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\nmake.exe" -f
  CMakeFiles\cmTC_2c22c.dir\build.make /nologo -L
  CMakeFiles\cmTC_2c22c.dir\build

  Building C object CMakeFiles/cmTC_2c22c.dir/testCCompiler.c.obj

            C:\PROGRA~2\MICROS~1.0\VC\BIN\X86_AM~1\cl.exe
  @C:\Users\Andrew\AppData\Local\Temp\nm7672.tmp

  testCCompiler.c

  Linking C executable cmTC_2c22c.exe

"C:\Program Files\CMake\bin\cmake.exe" -E vs_link_exe
  --intdir=CMakeFiles\cmTC_2c22c.dir --manifests --
  C:\PROGRA~2\MICROS~1.0\VC\bin\X86_AM~1\link.exe /nologo
  @CMakeFiles\cmTC_2c22c.dir\objects1.rsp
  @C:\Users\Andrew\AppData\Local\Temp\nm76B2.tmp

  MT failed to run.

  NMAKE : fatal error U1077: '"C:\Program Files\CMake\bin\cmake.exe"' :
  return code '0xffffffff'

  Stop.

  NMAKE : fatal error U1077: '"C:\Program Files (x86)\Microsoft Visual Studio
  14.0\VC\BIN\nmake.exe"' : return code '0x2'

  Stop.

  CMake will not be able to correctly generate this project.
Call Stack (most recent call first):
  CMakeLists.txt:3 (project)

Configuring incomplete, errors occurred!
See also "C:/Users/Andrew/AppData/Local/Temp/QtCreator-l9Mfi9/qtc-cmake-XXUaBP1D/CMakeFiles/CMakeOutput.log".
See also "C:/Users/Andrew/AppData/Local/Temp/QtCreator-l9Mfi9/qtc-cmake-XXUaBP1D/CMakeFiles/CMakeError.log".

The content of the actual CMake file doesn't seem to matter, so I'm heavily leaning on something not being correctly configured.

I've tried messing with the toolchain to no avail. Any ideas?


问:
Laravel 4 - Blade Templating - How to properly Link to Route?
I want to create a resourceful link with Laravel.
Normally I just use the {{ link_to_route('Yadayadayada.route', 'LinkName', $params }}

But in this case I am using a Template with this layout:

```<code><a href="index.html">
     <i class="icon-dashboard"></i>
     <span class="menu-text"> Dashboard </span>
</a>
</code>```

That means that inside the anchor tag, is as well a -Tag and a -Tag.
Is it possible to use the {{ link_to_route }}-Method, without having to change the layout of the Template?

答:
Use URL::route() to get just a link:</p>

```<code><a href="{{ URL::route('user/profile/', $params) }}">
     <i class="icon-dashboard"></i>
     <span class="menu-text"> Dashboard </span>
</a>
</code>```

Body:
I want to create a resourceful link with Laravel.
Normally I just use the {{ link_to_route('Yadayadayada.route', 'LinkName', $params }}

But in this case I am using a Template with this layout:

      Dashboard

That means that inside the anchor tag, is as well a -Tag and a -Tag.
Is it possible to use the {{ link_to_route }}-Method, without having to change the layout of the Template?

Body:
Use URL::route() to get just a link:

<a href="{{ URL::route('user/profile/', $params) }}">
     <i class="icon-dashboard"></i>
     <span class="menu-text"> Dashboard </span>
</a>


问:
Java Exception Handling and streams
Before closing the stream and after reaching the end of stream marker, a program tries to read the stream again.
__error
__checked exception
__compile error
__no exception</p>

答:
Use the following code :

```<code>try{
   // your code
} catch ( Exception e ) {
throws RuntimeException(e);
}
</code>```

I hope this works

Title: Java Exception Handling and streams

Body:
Use the following code :

try{
   // your code
} catch ( Exception e ) {
throws RuntimeException(e);
}

I hope this works