问:
I want to merge two query to have one result
This is my first Query that it give me sum of actual and estimated expenses related to salaries

```<code>SELECT
  d.y_                                   AS `salaries`
 , IFNULL(SUM(d.actual),0)               AS `Estimated`
 , IFNULL(SUM(d.estimated),0)            AS `Actual`
FROM (
SELECT estimated_type                       AS`y_`
    ,null                                       AS `Estimated`
    , sum(estimated_amount)                     AS `Actual`
FROM bacci.estimated_expenses_table it
WHERE it.estimated_year = '2017'
    AND it.estimated_type = 'management'
GROUP
    BY YEAR(it.estimated_year)
         union all
SELECT Type_expenses_table                      AS`y_`
    ,SUM(it.Amount_expenses_table)              AS `Estimated`
    , null                                      AS `Actual`
FROM bacci.expenses_table it
WHERE it.Date_expenses_table >= '2017-01-01'
        AND it.Date_expenses_table  < '2017-01-01' + INTERVAL 1 YEAR
        AND it.Type_expenses_table = 'management'
GROUP
     BY YEAR(it.Date_expenses_table)
         union all
SELECT estimated_type                           AS`y_`
    ,null                                       AS `Estimated`
    , sum(estimated_amount)                     AS `Actual`
FROM bacci.estimated_expenses_table it
WHERE it.estimated_year = '2017'
    AND it.estimated_type = 'staff salaries'
GROUP
     BY YEAR(it.estimated_year)
         union all
SELECT Type_expenses_table                      AS`y_`
    ,SUM(it.Amount_expenses_table)              AS `Estimated`
    , null                                      AS `Actual`
FROM bacci.expenses_table it
WHERE it.Date_expenses_table >= '2017-01-01'
        AND it.Date_expenses_table  < '2017-01-01' + INTERVAL 1 YEAR
        AND it.Type_expenses_table = 'staff salaries'
GROUP
     BY YEAR(it.Date_expenses_table)
) d
 GROUP
 BY d.y_

ORDER
 BY d.y_;
</code>```

The result:

My second Query that it give me sum of actual and estimated expenses related to equipments

```<code>SELECT
  d.y_                                   AS `Equipments`
 , IFNULL(SUM(d.actual),0)               AS `Estimated`
 , IFNULL(SUM(d.estimated),0)            AS `Actual`
FROM (
    select estimated_type                       AS`y_`
    ,null                                       AS `Estimated`
    , sum(estimated_amount)                     AS `Actual`
FROM bacci.estimated_expenses_table it
WHERE it.estimated_year = '2017'
    and it.estimated_type = 'vehicle rent'
GROUP
     BY YEAR(it.estimated_year)
         union all
SELECT Type_expenses_table                      AS`y_`
    ,SUM(it.Amount_expenses_table)              AS `Estimated`
    , null                                      AS `Actual`
FROM bacci.expenses_table it
WHERE it.Date_expenses_table >= '2017-01-01'
        AND it.Date_expenses_table  < '2017-01-01' + INTERVAL 1 YEAR
        and it.Type_expenses_table = 'vehicle rent'
GROUP
     BY YEAR(it.Date_expenses_table)
         union all
SELECT estimated_type                         AS`y_`
    ,null                                     AS `Estimated`
    , sum(estimated_amount)                   AS `Actual`
FROM bacci.estimated_expenses_table it
WHERE it.estimated_year = '2017'
    and it.estimated_type = 'vehicle fuel'
GROUP
     BY YEAR(it.estimated_year)
         union all
SELECT Type_expenses_table                      AS`y_`
    ,SUM(it.Amount_expenses_table)              AS `Estimated`
    , null                                      AS `Actual`
FROM bacci.expenses_table it
WHERE it.Date_expenses_table >= '2017-01-01'
        AND it.Date_expenses_table  < '2017-01-01' + INTERVAL 1 YEAR
        and it.Type_expenses_table = 'vehicle fuel'
GROUP
     BY YEAR(it.Date_expenses_table)
                  union all
SELECT estimated_type                         AS`y_`
    ,null                                     AS `Estimated`
    , sum(estimated_amount)                   AS `Actual`
FROM bacci.estimated_expenses_table it
WHERE it.estimated_year = '2017'
    and it.estimated_type = 'generator fuel'
GROUP
     BY YEAR(it.estimated_year)
         union all
SELECT Type_expenses_table                      AS`y_`
    ,SUM(it.Amount_expenses_table)              AS `Estimated`
    , null                                      AS `Actual`
FROM bacci.expenses_table it
WHERE it.Date_expenses_table >= '2017-01-01'
        AND it.Date_expenses_table  < '2017-01-01' + INTERVAL 1 YEAR
        and it.Type_expenses_table = 'generator fuel'
GROUP
     BY YEAR(it.Date_expenses_table)
) d
  GROUP
  BY d.y_

ORDER
  BY d.y_;
</code>```

The result:

I want to have Salaries under it management and staff salaries

than Equipments under it Vehicle Rent, Vehicle fuel and Generator Fuel etcetera

答:
If you have duplicate registries and dont want to see them, u can use UNION ALL. if u dont mind duplicate registries u can use UNION.
here is and example

SELECT [query_1]
UNION ALL
SELECT [query_2]
UNION ALL
SELECT [query_3]

Body:
This is my first Query that it give me sum of actual and estimated expenses related to salaries

SELECT
  d.y_                                   AS `salaries`
 , IFNULL(SUM(d.actual),0)               AS `Estimated`
 , IFNULL(SUM(d.estimated),0)            AS `Actual`
FROM (
SELECT estimated_type                       AS`y_`
    ,null                                       AS `Estimated`
    , sum(estimated_amount)                     AS `Actual`
FROM bacci.estimated_expenses_table it
WHERE it.estimated_year = '2017'
    AND it.estimated_type = 'management'
GROUP
    BY YEAR(it.estimated_year)
         union all
SELECT Type_expenses_table                      AS`y_`
    ,SUM(it.Amount_expenses_table)              AS `Estimated`
    , null                                      AS `Actual`
FROM bacci.expenses_table it
WHERE it.Date_expenses_table >= '2017-01-01'
        AND it.Date_expenses_table  < '2017-01-01' + INTERVAL 1 YEAR
        AND it.Type_expenses_table = 'management'
GROUP
     BY YEAR(it.Date_expenses_table)
         union all
SELECT estimated_type                           AS`y_`
    ,null                                       AS `Estimated`
    , sum(estimated_amount)                     AS `Actual`
FROM bacci.estimated_expenses_table it
WHERE it.estimated_year = '2017'
    AND it.estimated_type = 'staff salaries'
GROUP
     BY YEAR(it.estimated_year)
         union all
SELECT Type_expenses_table                      AS`y_`
    ,SUM(it.Amount_expenses_table)              AS `Estimated`
    , null                                      AS `Actual`
FROM bacci.expenses_table it
WHERE it.Date_expenses_table >= '2017-01-01'
        AND it.Date_expenses_table  < '2017-01-01' + INTERVAL 1 YEAR
        AND it.Type_expenses_table = 'staff salaries'
GROUP
     BY YEAR(it.Date_expenses_table)
) d
 GROUP
 BY d.y_

ORDER
 BY d.y_;

The result:

My second Query that it give me sum of actual and estimated expenses related to equipments

SELECT
  d.y_                                   AS `Equipments`
 , IFNULL(SUM(d.actual),0)               AS `Estimated`
 , IFNULL(SUM(d.estimated),0)            AS `Actual`
FROM (
    select estimated_type                       AS`y_`
    ,null                                       AS `Estimated`
    , sum(estimated_amount)                     AS `Actual`
FROM bacci.estimated_expenses_table it
WHERE it.estimated_year = '2017'
    and it.estimated_type = 'vehicle rent'
GROUP
     BY YEAR(it.estimated_year)
         union all
SELECT Type_expenses_table                      AS`y_`
    ,SUM(it.Amount_expenses_table)              AS `Estimated`
    , null                                      AS `Actual`
FROM bacci.expenses_table it
WHERE it.Date_expenses_table >= '2017-01-01'
        AND it.Date_expenses_table  < '2017-01-01' + INTERVAL 1 YEAR
        and it.Type_expenses_table = 'vehicle rent'
GROUP
     BY YEAR(it.Date_expenses_table)
         union all
SELECT estimated_type                         AS`y_`
    ,null                                     AS `Estimated`
    , sum(estimated_amount)                   AS `Actual`
FROM bacci.estimated_expenses_table it
WHERE it.estimated_year = '2017'
    and it.estimated_type = 'vehicle fuel'
GROUP
     BY YEAR(it.estimated_year)
         union all
SELECT Type_expenses_table                      AS`y_`
    ,SUM(it.Amount_expenses_table)              AS `Estimated`
    , null                                      AS `Actual`
FROM bacci.expenses_table it
WHERE it.Date_expenses_table >= '2017-01-01'
        AND it.Date_expenses_table  < '2017-01-01' + INTERVAL 1 YEAR
        and it.Type_expenses_table = 'vehicle fuel'
GROUP
     BY YEAR(it.Date_expenses_table)
                  union all
SELECT estimated_type                         AS`y_`
    ,null                                     AS `Estimated`
    , sum(estimated_amount)                   AS `Actual`
FROM bacci.estimated_expenses_table it
WHERE it.estimated_year = '2017'
    and it.estimated_type = 'generator fuel'
GROUP
     BY YEAR(it.estimated_year)
         union all
SELECT Type_expenses_table                      AS`y_`
    ,SUM(it.Amount_expenses_table)              AS `Estimated`
    , null                                      AS `Actual`
FROM bacci.expenses_table it
WHERE it.Date_expenses_table >= '2017-01-01'
        AND it.Date_expenses_table  < '2017-01-01' + INTERVAL 1 YEAR
        and it.Type_expenses_table = 'generator fuel'
GROUP
     BY YEAR(it.Date_expenses_table)
) d
  GROUP
  BY d.y_

ORDER
  BY d.y_;

The result:

I want to have Salaries under it management and staff salaries

than Equipments under it Vehicle Rent, Vehicle fuel and Generator Fuel etcetera


来源: stackexchange

问:
Extract data after a string one each appearance R
I have a data like this (named spectra):

```<code>#Milk spectra: 1234
##XYDATA=(X++(Y..Y))
649.025085449219
667.675231457819
686.325377466418
##XYDATA=(X++(Y..Y))
723.625669483618
742.275815492218
760.925961500818
##XYDATA=(X++(Y..Y))
872.826837552417
891.476983561017
910.127129569617
928.777275578216
</code>```

In this data, each time the string ##XYDATA=(X++(Y..Y)), that is the data for each different animal.
So, I want to have the code that can help extract this sample into 3 pieces of data.

```<code>Animal 1: 3 lines after 1st '  ##XYDATA=(X++(Y..Y))'
Animal 2: 3 lines after 2nd '  ##XYDATA=(X++(Y..Y))'
</code>```

And so on.

I tried this line of code but it only help to extract line 1 of all times the string '##XYDATA=(X++(Y..Y))' appeared together. Thus, it did not meet my expect to have three lines and to have a separate pieces of data after each appearance of the string.

```<code>bo<-data.frame(spectra$V1[which(spectra$V1 == '##XYDATA=(X++(Y..Y))')+1])
</code>```

答:
Okay I think you could do something along these lines. I'm sure this could be much better and more efficient but read it in as a character vector.
Then loop through to spread it out.  However this assumes there are always the same number of measures and you have a way to identify the character values.

```<code>c_data<- c("split", 1, 2, 3,
                   "split", 4, 5, 6)

y<- c_data == "split"

df_wide <- data.frame("animal"= character(), "v1" = numeric(), "v2" = numeric(), "v3" = numeric(),
                      stringsAsFactors = FALSE)
names(df_wide)<- c("animal", "v1", "v2", "v3")
x <- 0
for (i in 1:length(c_data)){

  if (y[i] == TRUE){
    x <- x +1
    df_wide[x,] <- rbind(c(c_data[i], c_data[i+1], c_data[i+2], c_data[i+3]))
  }
}
</code>```

yields

```<code>  animal v1 v2 v3
1  split  1  2  3
2  split  4  5  6
</code>```

If it is a one time thing, it may not be worth trying to write something nicer. If it is an ongoing thing then you may want to look at using an apply function that you could have to write a function for.

ContentLicense: CC BY-SA 3.0

Body:
I have a data like this (named spectra):

#Milk spectra: 1234
##XYDATA=(X++(Y..Y))
649.025085449219
667.675231457819
686.325377466418
##XYDATA=(X++(Y..Y))
723.625669483618
742.275815492218
760.925961500818
##XYDATA=(X++(Y..Y))
872.826837552417
891.476983561017
910.127129569617
928.777275578216

In this data, each time the string ##XYDATA=(X++(Y..Y)), that is the data for each different animal.
So, I want to have the code that can help extract this sample into 3 pieces of data.

Animal 1: 3 lines after 1st '  ##XYDATA=(X++(Y..Y))'
Animal 2: 3 lines after 2nd '  ##XYDATA=(X++(Y..Y))'

And so on.

I tried this line of code but it only help to extract line 1 of all times the string '##XYDATA=(X++(Y..Y))' appeared together. Thus, it did not meet my expect to have three lines and to have a separate pieces of data after each appearance of the string.

bo<-data.frame(spectra$V1[which(spectra$V1 == '##XYDATA=(X++(Y..Y))')+1])

Body:
Okay I think you could do something along these lines. I'm sure this could be much better and more efficient but read it in as a character vector.
Then loop through to spread it out.  However this assumes there are always the same number of measures and you have a way to identify the character values.

c_data<- c("split", 1, 2, 3,
                   "split", 4, 5, 6)

y<- c_data == "split"

df_wide <- data.frame("animal"= character(), "v1" = numeric(), "v2" = numeric(), "v3" = numeric(),
                      stringsAsFactors = FALSE)
names(df_wide)<- c("animal", "v1", "v2", "v3")
x <- 0
for (i in 1:length(c_data)){

  if (y[i] == TRUE){
    x <- x +1
    df_wide[x,] <- rbind(c(c_data[i], c_data[i+1], c_data[i+2], c_data[i+3]))
  }
}

yields

  animal v1 v2 v3
1  split  1  2  3
2  split  4  5  6

If it is a one time thing, it may not be worth trying to write something nicer. If it is an ongoing thing then you may want to look at using an apply function that you could have to write a function for.


问:
url pattern matching php
I have a url of the format /?var1 = val1&var2 = val2;

I want to check for the presence of just var2 = val2 in the url using php. How can that be done?

答:
do this</p>

```<code>if (isset($_GET['var2']))  // check if exist
{
  if ($_GET['var2'] == val2) // do something
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: url pattern matching php

Body:
do this

if (isset($_GET['var2']))  // check if exist
{
  if ($_GET['var2'] == val2) // do something
}


问:
VBA to open Excel or/and Word Files
I'm trying to setup a command button in a user form to allow the user to open either an Excel and/or a Word Document one at a time or both at the same time. But so far I'm able only to select and open Excel but not Word files with the following code:

```<code>Sub OpeningExcelFile()
    Dim Finfo As String
    Dim FilterIndex As Integer
    Dim Title As String
    Dim Filename As Variant
    Dim wb As Workbook

    'Setup the list of file filters
    Finfo = "Excel Files (*.xlsx),*xlsx," & _
            "Macro-Enable Worksheet (*.xlsm),*xlsm," & _
            "Word Files (*.docx),*.docx," & _
            "All Files (*.*),*.*"
             MultiSelect = True

    'Display *.* by default
    FilterIndex = 4

    'Set the dialog box caption
    Title = "Select a File to Open"

    'Get the Filename
    Filename = Application.GetOpenFilename(Finfo, _
        FilterIndex, Title)

    'Handle return info from dialog box
    If Filename = False Then
        MsgBox "No file was selected."
    Else
        MsgBox "You selected " & Filename

    End If

    On Error Resume Next

    Set wb = Workbooks.Open(Filename)
</code>```

Do you know what it is missing?

答:
You cannot open word files with Excel Application.

You need to have check like below to handle this.

```<code>Dim objWdApp As Object
Dim objWdDoc As Object
If InStr(1, Filename, ".docx", vbTextCompare) > 0 Then
    Set objWdApp = CreateObject("Word.Application")
    objWdApp.Visible = True
    Set objWdDoc = objWdApp.Documents.Open(Filename) '\\ Open Word Document
Else
    Set wb = Workbooks.Open(Filename) '\\ Open Excel Spreadsheet
End If
</code>```

Title: VBA to open Excel or/and Word Files

Body:
I'm trying to setup a command button in a user form to allow the user to open either an Excel and/or a Word Document one at a time or both at the same time. But so far I'm able only to select and open Excel but not Word files with the following code:

Sub OpeningExcelFile()
    Dim Finfo As String
    Dim FilterIndex As Integer
    Dim Title As String
    Dim Filename As Variant
    Dim wb As Workbook

    'Setup the list of file filters
    Finfo = "Excel Files (*.xlsx),*xlsx," & _
            "Macro-Enable Worksheet (*.xlsm),*xlsm," & _
            "Word Files (*.docx),*.docx," & _
            "All Files (*.*),*.*"
             MultiSelect = True

    'Display *.* by default
    FilterIndex = 4

    'Set the dialog box caption
    Title = "Select a File to Open"

    'Get the Filename
    Filename = Application.GetOpenFilename(Finfo, _
        FilterIndex, Title)

    'Handle return info from dialog box
    If Filename = False Then
        MsgBox "No file was selected."
    Else
        MsgBox "You selected " & Filename

    End If

    On Error Resume Next

    Set wb = Workbooks.Open(Filename)

Do you know what it is missing?

Body:
You cannot open word files with Excel Application.

You need to have check like below to handle this.

Dim objWdApp As Object
Dim objWdDoc As Object
If InStr(1, Filename, ".docx", vbTextCompare) > 0 Then
    Set objWdApp = CreateObject("Word.Application")
    objWdApp.Visible = True
    Set objWdDoc = objWdApp.Documents.Open(Filename) '\\ Open Word Document
Else
    Set wb = Workbooks.Open(Filename) '\\ Open Excel Spreadsheet
End If


问:
multiple validation for single field
I have 3 fields 'account_name','billable_option' and 'billable_option_yes'
'billable_option' is required if 'billable_option_yes' is not filled and 'billable_option_yes' is required if 'billable_option' is not filled

and I want to check both field is not required if 'account_name' value is 0
I want to combine the validation required_unless:account_name,0

```<code>if($account!=0){ } not working

$account=$request->account_name;
     if($account!=0){ //not working
                $this->validate($request,[
                'billable_option' => 'required_without:billable_option_yes',
                'billable_option_yes' =>'required_without:billable_option',
                ],$messages);
    }
   $messages=[
            'billable_option.required_without'=>'The Billable is Required',
            'billable_option_yes.required_without'=>'The Billable optoion is Required',
       ];
      $this->validate($request,[
        ...
       'billable'=>'required_unless:account_name,0', //fourth field working fine
        ..
      ],$messages);
</code>```

答:
Have you checked comparison used in if condition,

If your account_name field is string, then you can't compare like this:

```<code>if($account != 0)
{
    ....
}
</code>```

This will compare string $account with integer 0 so that condition will never true. So, you have to change like,

```<code>if($account != '0')
{
    ....
}
</code>```

Now, Another thing is you want no validation check up for billable_option and billable_option_yes if account is 0.

So, you can write validation method inside single if condition and no need to add further validation code after the end of if condition.

```<code>if($account != '0'){     // if $account is string variable
        $this->validate($request,[
            'billable_option' => 'required_without:billable_option_yes',
            'billable_option_yes' =>'required_without:billable_option',
            ],
        $messages = [
            'billable_option.required_without'=>'The Billable is Required',
            'billable_option_yes.required_without'=>'The Billable option is Required',
        ]);
}
</code>```

Hope you understand.

Title: multiple validation for single field

Body:
I have 3 fields 'account_name','billable_option' and 'billable_option_yes'
'billable_option' is required if 'billable_option_yes' is not filled and 'billable_option_yes' is required if 'billable_option' is not filled

and I want to check both field is not required if 'account_name' value is 0
I want to combine the validation required_unless:account_name,0

if($account!=0){ } not working

$account=$request->account_name;
     if($account!=0){ //not working
                $this->validate($request,[
                'billable_option' => 'required_without:billable_option_yes',
                'billable_option_yes' =>'required_without:billable_option',
                ],$messages);
    }
   $messages=[
            'billable_option.required_without'=>'The Billable is Required',
            'billable_option_yes.required_without'=>'The Billable optoion is Required',
       ];
      $this->validate($request,[
        ...
       'billable'=>'required_unless:account_name,0', //fourth field working fine
        ..
      ],$messages);

Body:
Have you checked comparison used in if condition,

If your account_name field is string, then you can't compare like this:

if($account != 0)
{
    ....
}

This will compare string $account with integer 0 so that condition will never true. So, you have to change like,

if($account != '0')
{
    ....
}

Now, Another thing is you want no validation check up for billable_option and billable_option_yes if account is 0.

So, you can write validation method inside single if condition and no need to add further validation code after the end of if condition.

if($account != '0'){     // if $account is string variable
        $this->validate($request,[
            'billable_option' => 'required_without:billable_option_yes',
            'billable_option_yes' =>'required_without:billable_option',
            ],
        $messages = [
            'billable_option.required_without'=>'The Billable is Required',
            'billable_option_yes.required_without'=>'The Billable option is Required',
        ]);
}

Hope you understand.


问:
error while trying to install cassandra-driver using python
I'm trying to install cassandra-driver using python(on windows) but it fails with following exception. could someone please help me on this,

I have also tried the manual installation process mentioned at following location & its same error,
http://datastax.github.io/python-driver/installation.html

Install Exception:

```<code>C:\Windows\System32>pip install cassandra-driver
Collecting cassandra-driver
  Using cached cassandra-driver-3.9.0.tar.gz
Requirement already satisfied: six>=1.6 in c:\python27\lib\site-packages (from c
assandra-driver)
Requirement already satisfied: futures in c:\python27\lib\site-packages (from ca
ssandra-driver)
Building wheels for collected packages: cassandra-driver
  Running setup.py bdist_wheel for cassandra-driver ... error
  Complete output from command c:\python27\python.exe -u -c "import setuptools,
tokenize;__file__='c:\\users\\user01\\appdata\\local\\temp\\pip-build-pa7rph\\
cassandra-driver\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.r
ead().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" bdi
st_wheel -d c:\users\user01\appdata\local\temp\tmpbqprncpip-wheel- --python-ta
g cp27:
  Unable to find pgen, not compiling formal grammar.
  warning: no files found matching '*.pyx' under directory 'Cython\Debugger\Test
s'
  warning: no files found matching '*.pxd' under directory 'Cython\Debugger\Test
s'
  warning: no files found matching '*.h' under directory 'Cython\Debugger\Tests'

  warning: no files found matching '*.pxd' under directory 'Cython\Utility'
  Traceback (most recent call last):
    File "<string>", line 1, in <module>
    File "c:\users\user01\appdata\local\temp\pip-build-pa7rph\cassandra-driver
\setup.py", line 433, in <module>
      run_setup(None)
    File "c:\users\user01\appdata\local\temp\pip-build-pa7rph\cassandra-driver
\setup.py", line 431, in run_setup
      **kw)
    File "c:\python27\lib\distutils\core.py", line 112, in setup
      _setup_distribution = dist = klass(attrs)
    File "c:\python27\lib\site-packages\setuptools\dist.py", line 318, in __init
__
      self.fetch_build_eggs(attrs['setup_requires'])
    File "c:\python27\lib\site-packages\setuptools\dist.py", line 373, in fetch_
build_eggs
      replace_conflicting=True,
    File "c:\python27\lib\site-packages\pkg_resources\__init__.py", line 851, in
 resolve
      dist = best[req.key] = env.best_match(req, ws, installer)
    File "c:\python27\lib\site-packages\pkg_resources\__init__.py", line 1123, i
n best_match
      return self.obtain(req, installer)
    File "c:\python27\lib\site-packages\pkg_resources\__init__.py", line 1135, i
n obtain
      return installer(requirement)
    File "c:\python27\lib\site-packages\setuptools\dist.py", line 441, in fetch_
build_egg
      return cmd.easy_install(req)
    File "c:\python27\lib\site-packages\setuptools\command\easy_install.py", lin
e 674, in easy_install
      return self.install_item(spec, dist.location, tmpdir, deps)
    File "c:\python27\lib\site-packages\setuptools\command\easy_install.py", lin
e 700, in install_item
      dists = self.install_eggs(spec, download, tmpdir)
    File "c:\python27\lib\site-packages\setuptools\command\easy_install.py", lin
e 881, in install_eggs
      return self.build_and_install(setup_script, setup_base)
    File "c:\python27\lib\site-packages\setuptools\command\easy_install.py", lin
e 1120, in build_and_install
      self.run_setup(setup_script, setup_base, args)
    File "c:\python27\lib\site-packages\setuptools\command\easy_install.py", lin
e 1108, in run_setup
      raise DistutilsError("Setup script exited with %s" % (v.args[0],))
  distutils.errors.DistutilsError: Setup script exited with error: INCLUDE envir
onment variable is empty

  ----------------------------------------
  Failed building wheel for cassandra-driver
  Running setup.py clean for cassandra-driver
  Complete output from command c:\python27\python.exe -u -c "import setuptools,
tokenize;__file__='c:\\users\\user01\\appdata\\local\\temp\\pip-build-pa7rph\\
cassandra-driver\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.r
ead().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" cle
an --all:
  Unable to find pgen, not compiling formal grammar.
  warning: no files found matching '*.pyx' under directory 'Cython\Debugger\Test
s'
  warning: no files found matching '*.pxd' under directory 'Cython\Debugger\Test
s'
  warning: no files found matching '*.h' under directory 'Cython\Debugger\Tests'

  warning: no files found matching '*.pxd' under directory 'Cython\Utility'
  Traceback (most recent call last):
    File "<string>", line 1, in <module>
    File "c:\users\user01\appdata\local\temp\pip-build-pa7rph\cassandra-driver
\setup.py", line 433, in <module>
      run_setup(None)
    File "c:\users\user01\appdata\local\temp\pip-build-pa7rph\cassandra-driver
\setup.py", line 431, in run_setup
      **kw)
    File "c:\python27\lib\distutils\core.py", line 112, in setup
      _setup_distribution = dist = klass(attrs)
    File "c:\python27\lib\site-packages\setuptools\dist.py", line 318, in __init
__
      self.fetch_build_eggs(attrs['setup_requires'])
    File "c:\python27\lib\site-packages\setuptools\dist.py", line 373, in fetch_
build_eggs
      replace_conflicting=True,
    File "c:\python27\lib\site-packages\pkg_resources\__init__.py", line 851, in
 resolve
      dist = best[req.key] = env.best_match(req, ws, installer)
    File "c:\python27\lib\site-packages\pkg_resources\__init__.py", line 1123, i
n best_match
      return self.obtain(req, installer)
    File "c:\python27\lib\site-packages\pkg_resources\__init__.py", line 1135, i
n obtain
      return installer(requirement)
    File "c:\python27\lib\site-packages\setuptools\dist.py", line 441, in fetch_
build_egg
      return cmd.easy_install(req)
    File "c:\python27\lib\site-packages\setuptools\command\easy_install.py", lin
e 674, in easy_install
      return self.install_item(spec, dist.location, tmpdir, deps)
    File "c:\python27\lib\site-packages\setuptools\command\easy_install.py", lin
e 700, in install_item
      dists = self.install_eggs(spec, download, tmpdir)
    File "c:\python27\lib\site-packages\setuptools\command\easy_install.py", lin
e 881, in install_eggs
      return self.build_and_install(setup_script, setup_base)
    File "c:\python27\lib\site-packages\setuptools\command\easy_install.py", lin
e 1120, in build_and_install
      self.run_setup(setup_script, setup_base, args)
    File "c:\python27\lib\site-packages\setuptools\command\easy_install.py", lin
e 1108, in run_setup
      raise DistutilsError("Setup script exited with %s" % (v.args[0],))
  distutils.errors.DistutilsError: Setup script exited with error: INCLUDE envir
onment variable is empty

  ----------------------------------------
  Failed cleaning build dir for cassandra-driver
Failed to build cassandra-driver
Installing collected packages: cassandra-driver
  Running setup.py install for cassandra-driver ... error
    Complete output from command c:\python27\python.exe -u -c "import setuptools
, tokenize;__file__='c:\\users\\user01\\appdata\\local\\temp\\pip-build-pa7rph
\\cassandra-driver\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f
.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" i
nstall --record c:\users\user01\appdata\local\temp\pip-inudnv-record\install-r
ecord.txt --single-version-externally-managed --compile:
    Unable to find pgen, not compiling formal grammar.
    warning: no files found matching '*.pyx' under directory 'Cython\Debugger\Te
sts'
    warning: no files found matching '*.pxd' under directory 'Cython\Debugger\Te
sts'
    warning: no files found matching '*.h' under directory 'Cython\Debugger\Test
s'
    warning: no files found matching '*.pxd' under directory 'Cython\Utility'
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "c:\users\user01\appdata\local\temp\pip-build-pa7rph\cassandra-driv
er\setup.py", line 433, in <module>
        run_setup(None)
      File "c:\users\user01\appdata\local\temp\pip-build-pa7rph\cassandra-driv
er\setup.py", line 431, in run_setup
        **kw)
      File "c:\python27\lib\distutils\core.py", line 112, in setup
        _setup_distribution = dist = klass(attrs)
      File "c:\python27\lib\site-packages\setuptools\dist.py", line 318, in __in
it__
        self.fetch_build_eggs(attrs['setup_requires'])
      File "c:\python27\lib\site-packages\setuptools\dist.py", line 373, in fetc
h_build_eggs
        replace_conflicting=True,
      File "c:\python27\lib\site-packages\pkg_resources\__init__.py", line 851,
in resolve
        dist = best[req.key] = env.best_match(req, ws, installer)
      File "c:\python27\lib\site-packages\pkg_resources\__init__.py", line 1123,
 in best_match
        return self.obtain(req, installer)
      File "c:\python27\lib\site-packages\pkg_resources\__init__.py", line 1135,
 in obtain
        return installer(requirement)
      File "c:\python27\lib\site-packages\setuptools\dist.py", line 441, in fetc
h_build_egg
        return cmd.easy_install(req)
      File "c:\python27\lib\site-packages\setuptools\command\easy_install.py", l
ine 674, in easy_install
        return self.install_item(spec, dist.location, tmpdir, deps)
      File "c:\python27\lib\site-packages\setuptools\command\easy_install.py", l
ine 700, in install_item
        dists = self.install_eggs(spec, download, tmpdir)
      File "c:\python27\lib\site-packages\setuptools\command\easy_install.py", l
ine 881, in install_eggs
        return self.build_and_install(setup_script, setup_base)
      File "c:\python27\lib\site-packages\setuptools\command\easy_install.py", l
ine 1120, in build_and_install
        self.run_setup(setup_script, setup_base, args)
      File "c:\python27\lib\site-packages\setuptools\command\easy_install.py", l
ine 1108, in run_setup
        raise DistutilsError("Setup script exited with %s" % (v.args[0],))
    distutils.errors.DistutilsError: Setup script exited with error: INCLUDE env
ironment variable is empty

    ----------------------------------------
Command "c:\python27\python.exe -u -c "import setuptools, tokenize;__file__='c:\
\users\\user01\\appdata\\local\\temp\\pip-build-pa7rph\\cassandra-driver\\setu
p.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n',
'\n');f.close();exec(compile(code, __file__, 'exec'))" install --record c:\users
\user01\appdata\local\temp\pip-inudnv-record\install-record.txt --single-versi
on-externally-managed --compile" failed with error code 1 in c:\users\user01\a
ppdata\local\temp\pip-build-pa7rph\cassandra-driver\
</code>```

答:
I installed cqlsh client on remote using following command,</p>

```<code>sudo apt-get install build-essential python-dev python-pip libev4 libev-dev
sudo apt-get install cython3
sudo pip install cassandra-driver
sudo pip install cassandra-driver --install-option="--no-cython"
sudo pip install cqlsh; (Or cqlsh==5.0.3)
export CQLSH_NO_BUNDLED=TRUE
cqlsh 192.168.0.330  --cqlversion="3.4.2"
</code>```

Body:
I'm trying to install cassandra-driver using python(on windows) but it fails with following exception. could someone please help me on this,

I have also tried the manual installation process mentioned at following location & its same error,
http://datastax.github.io/python-driver/installation.html

Install Exception:

C:\Windows\System32>pip install cassandra-driver
Collecting cassandra-driver
  Using cached cassandra-driver-3.9.0.tar.gz
Requirement already satisfied: six>=1.6 in c:\python27\lib\site-packages (from c
assandra-driver)
Requirement already satisfied: futures in c:\python27\lib\site-packages (from ca
ssandra-driver)
Building wheels for collected packages: cassandra-driver
  Running setup.py bdist_wheel for cassandra-driver ... error
  Complete output from command c:\python27\python.exe -u -c "import setuptools,
tokenize;__file__='c:\\users\\user01\\appdata\\local\\temp\\pip-build-pa7rph\\
cassandra-driver\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.r
ead().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" bdi
st_wheel -d c:\users\user01\appdata\local\temp\tmpbqprncpip-wheel- --python-ta
g cp27:
  Unable to find pgen, not compiling formal grammar.
  warning: no files found matching '*.pyx' under directory 'Cython\Debugger\Test
s'
  warning: no files found matching '*.pxd' under directory 'Cython\Debugger\Test
s'
  warning: no files found matching '*.h' under directory 'Cython\Debugger\Tests'

  warning: no files found matching '*.pxd' under directory 'Cython\Utility'
  Traceback (most recent call last):
    File "<string>", line 1, in <module>
    File "c:\users\user01\appdata\local\temp\pip-build-pa7rph\cassandra-driver
\setup.py", line 433, in <module>
      run_setup(None)
    File "c:\users\user01\appdata\local\temp\pip-build-pa7rph\cassandra-driver
\setup.py", line 431, in run_setup
      **kw)
    File "c:\python27\lib\distutils\core.py", line 112, in setup
      _setup_distribution = dist = klass(attrs)
    File "c:\python27\lib\site-packages\setuptools\dist.py", line 318, in __init
__
      self.fetch_build_eggs(attrs['setup_requires'])
    File "c:\python27\lib\site-packages\setuptools\dist.py", line 373, in fetch_
build_eggs
      replace_conflicting=True,
    File "c:\python27\lib\site-packages\pkg_resources\__init__.py", line 851, in
 resolve
      dist = best[req.key] = env.best_match(req, ws, installer)
    File "c:\python27\lib\site-packages\pkg_resources\__init__.py", line 1123, i
n best_match
      return self.obtain(req, installer)
    File "c:\python27\lib\site-packages\pkg_resources\__init__.py", line 1135, i
n obtain
      return installer(requirement)
    File "c:\python27\lib\site-packages\setuptools\dist.py", line 441, in fetch_
build_egg
      return cmd.easy_install(req)
    File "c:\python27\lib\site-packages\setuptools\command\easy_install.py", lin
e 674, in easy_install
      return self.install_item(spec, dist.location, tmpdir, deps)
    File "c:\python27\lib\site-packages\setuptools\command\easy_install.py", lin
e 700, in install_item
      dists = self.install_eggs(spec, download, tmpdir)
    File "c:\python27\lib\site-packages\setuptools\command\easy_install.py", lin
e 881, in install_eggs
      return self.build_and_install(setup_script, setup_base)
    File "c:\python27\lib\site-packages\setuptools\command\easy_install.py", lin
e 1120, in build_and_install
      self.run_setup(setup_script, setup_base, args)
    File "c:\python27\lib\site-packages\setuptools\command\easy_install.py", lin
e 1108, in run_setup
      raise DistutilsError("Setup script exited with %s" % (v.args[0],))
  distutils.errors.DistutilsError: Setup script exited with error: INCLUDE envir
onment variable is empty

  ----------------------------------------
  Failed building wheel for cassandra-driver
  Running setup.py clean for cassandra-driver
  Complete output from command c:\python27\python.exe -u -c "import setuptools,
tokenize;__file__='c:\\users\\user01\\appdata\\local\\temp\\pip-build-pa7rph\\
cassandra-driver\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.r
ead().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" cle
an --all:
  Unable to find pgen, not compiling formal grammar.
  warning: no files found matching '*.pyx' under directory 'Cython\Debugger\Test
s'
  warning: no files found matching '*.pxd' under directory 'Cython\Debugger\Test
s'
  warning: no files found matching '*.h' under directory 'Cython\Debugger\Tests'

  warning: no files found matching '*.pxd' under directory 'Cython\Utility'
  Traceback (most recent call last):
    File "<string>", line 1, in <module>
    File "c:\users\user01\appdata\local\temp\pip-build-pa7rph\cassandra-driver
\setup.py", line 433, in <module>
      run_setup(None)
    File "c:\users\user01\appdata\local\temp\pip-build-pa7rph\cassandra-driver
\setup.py", line 431, in run_setup
      **kw)
    File "c:\python27\lib\distutils\core.py", line 112, in setup
      _setup_distribution = dist = klass(attrs)
    File "c:\python27\lib\site-packages\setuptools\dist.py", line 318, in __init
__
      self.fetch_build_eggs(attrs['setup_requires'])
    File "c:\python27\lib\site-packages\setuptools\dist.py", line 373, in fetch_
build_eggs
      replace_conflicting=True,
    File "c:\python27\lib\site-packages\pkg_resources\__init__.py", line 851, in
 resolve
      dist = best[req.key] = env.best_match(req, ws, installer)
    File "c:\python27\lib\site-packages\pkg_resources\__init__.py", line 1123, i
n best_match
      return self.obtain(req, installer)
    File "c:\python27\lib\site-packages\pkg_resources\__init__.py", line 1135, i
n obtain
      return installer(requirement)
    File "c:\python27\lib\site-packages\setuptools\dist.py", line 441, in fetch_
build_egg
      return cmd.easy_install(req)
    File "c:\python27\lib\site-packages\setuptools\command\easy_install.py", lin
e 674, in easy_install
      return self.install_item(spec, dist.location, tmpdir, deps)
    File "c:\python27\lib\site-packages\setuptools\command\easy_install.py", lin
e 700, in install_item
      dists = self.install_eggs(spec, download, tmpdir)
    File "c:\python27\lib\site-packages\setuptools\command\easy_install.py", lin
e 881, in install_eggs
      return self.build_and_install(setup_script, setup_base)
    File "c:\python27\lib\site-packages\setuptools\command\easy_install.py", lin
e 1120, in build_and_install
      self.run_setup(setup_script, setup_base, args)
    File "c:\python27\lib\site-packages\setuptools\command\easy_install.py", lin
e 1108, in run_setup
      raise DistutilsError("Setup script exited with %s" % (v.args[0],))
  distutils.errors.DistutilsError: Setup script exited with error: INCLUDE envir
onment variable is empty

  ----------------------------------------
  Failed cleaning build dir for cassandra-driver
Failed to build cassandra-driver
Installing collected packages: cassandra-driver
  Running setup.py install for cassandra-driver ... error
    Complete output from command c:\python27\python.exe -u -c "import setuptools
, tokenize;__file__='c:\\users\\user01\\appdata\\local\\temp\\pip-build-pa7rph
\\cassandra-driver\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f
.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" i
nstall --record c:\users\user01\appdata\local\temp\pip-inudnv-record\install-r
ecord.txt --single-version-externally-managed --compile:
    Unable to find pgen, not compiling formal grammar.
    warning: no files found matching '*.pyx' under directory 'Cython\Debugger\Te
sts'
    warning: no files found matching '*.pxd' under directory 'Cython\Debugger\Te
sts'
    warning: no files found matching '*.h' under directory 'Cython\Debugger\Test
s'
    warning: no files found matching '*.pxd' under directory 'Cython\Utility'
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "c:\users\user01\appdata\local\temp\pip-build-pa7rph\cassandra-driv
er\setup.py", line 433, in <module>
        run_setup(None)
      File "c:\users\user01\appdata\local\temp\pip-build-pa7rph\cassandra-driv
er\setup.py", line 431, in run_setup
        **kw)
      File "c:\python27\lib\distutils\core.py", line 112, in setup
        _setup_distribution = dist = klass(attrs)
      File "c:\python27\lib\site-packages\setuptools\dist.py", line 318, in __in
it__
        self.fetch_build_eggs(attrs['setup_requires'])
      File "c:\python27\lib\site-packages\setuptools\dist.py", line 373, in fetc
h_build_eggs
        replace_conflicting=True,
      File "c:\python27\lib\site-packages\pkg_resources\__init__.py", line 851,
in resolve
        dist = best[req.key] = env.best_match(req, ws, installer)
      File "c:\python27\lib\site-packages\pkg_resources\__init__.py", line 1123,
 in best_match
        return self.obtain(req, installer)
      File "c:\python27\lib\site-packages\pkg_resources\__init__.py", line 1135,
 in obtain
        return installer(requirement)
      File "c:\python27\lib\site-packages\setuptools\dist.py", line 441, in fetc
h_build_egg
        return cmd.easy_install(req)
      File "c:\python27\lib\site-packages\setuptools\command\easy_install.py", l
ine 674, in easy_install
        return self.install_item(spec, dist.location, tmpdir, deps)
      File "c:\python27\lib\site-packages\setuptools\command\easy_install.py", l
ine 700, in install_item
        dists = self.install_eggs(spec, download, tmpdir)
      File "c:\python27\lib\site-packages\setuptools\command\easy_install.py", l
ine 881, in install_eggs
        return self.build_and_install(setup_script, setup_base)
      File "c:\python27\lib\site-packages\setuptools\command\easy_install.py", l
ine 1120, in build_and_install
        self.run_setup(setup_script, setup_base, args)
      File "c:\python27\lib\site-packages\setuptools\command\easy_install.py", l
ine 1108, in run_setup
        raise DistutilsError("Setup script exited with %s" % (v.args[0],))
    distutils.errors.DistutilsError: Setup script exited with error: INCLUDE env
ironment variable is empty

    ----------------------------------------
Command "c:\python27\python.exe -u -c "import setuptools, tokenize;__file__='c:\
\users\\user01\\appdata\\local\\temp\\pip-build-pa7rph\\cassandra-driver\\setu
p.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n',
'\n');f.close();exec(compile(code, __file__, 'exec'))" install --record c:\users
\user01\appdata\local\temp\pip-inudnv-record\install-record.txt --single-versi
on-externally-managed --compile" failed with error code 1 in c:\users\user01\a
ppdata\local\temp\pip-build-pa7rph\cassandra-driver\

Body:
I installed cqlsh client on remote using following command,

sudo apt-get install build-essential python-dev python-pip libev4 libev-dev
sudo apt-get install cython3
sudo pip install cassandra-driver
sudo pip install cassandra-driver --install-option="--no-cython"
sudo pip install cqlsh; (Or cqlsh==5.0.3)
export CQLSH_NO_BUNDLED=TRUE
cqlsh 192.168.0.330  --cqlversion="3.4.2"


问:
Tensorflow GPU version CNN CuDNN error on Windows 10
I'm trying to do CIFAR-100 training with Python Tensorflow CNN, but the error CUDA_ERROR_OUT_OF_MEMORY, CUDA_STATUS_NOT_INITIALIZED and CUDA_STATUS_BAD_PARAM keep bothering me, I'm using Anaconda virtual environment which Tensorflow depends on my machine, Python version is Anaconda Python 3.5 virtual environment, Tensorflow version is 1.1.0, here's my code:
tf_cifar_learning.py:

```<code># Set working directory

import os
dir_model = "c:/tf_model_cifar100"

# Modules needed

import numpy as np
import tensorflow as tf
import pandas as pd
from mlxtend.preprocessing import one_hot

# Load CIFAR Data
from batch import next_batch
from read import unpickle
import time
gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.995)

# Prepare test data

testdata = unpickle('test')[b'data']
testdata1 = testdata.astype('float')
del testdata
testdata = testdata1[0:5000, :]
testlabel = unpickle('test')[b'coarse_labels'][0:5000]
testlabel = one_hot(testlabel, 100)
for i in range(testdata.shape[0]):
    for j in range(3072):
        testdata[i][j] = float(testdata[i][j]) / 255.0
    if(i % 1000 == 0):
        print("%d of 5000 test datasets processed" % i)

# Parameters
learning_rate = 0.001
training_iters = 1000000
batch_size = 10 # 128
display_step = 2

# Network Parameters
n_input = 1024*3 # CIFAR data input (img shape: 32*32)
n_classes = 100 # CIFAR total classes
dropout = 0.75 # Dropout, probability to keep units

# tf Graph input
x = tf.placeholder(tf.float32, [None, n_input])
y = tf.placeholder(tf.float32, [None, n_classes])
keep_prob = tf.placeholder(tf.float32) #dropout (keep probability)

# Create some wrappers for simplicity
def conv2d(x, W, b, strides=1):
    # Conv2D wrapper, with bias and relu activation
    x = tf.nn.conv2d(x, W, strides=[1, strides, strides, 1], padding='SAME')
    x = tf.nn.bias_add(x, b)
    o = tf.nn.relu(x)
    return o

def maxpool2d(x, k=2):
    # MaxPool2D wrapper
    o = tf.nn.max_pool(x, ksize=[1, k, k, 1], strides=[1, k, k, 1], padding='SAME')
    return o

# Create model
def conv_net(x, weights, biases, dropout):
        # Reshape input picture
    x = tf.reshape(x, shape=[-1, 32, 32, 3])
    # Convolution Layer
    conv1 = conv2d(x, weights['wc1'], biases['bc1'])
    # Max Pooling (down-sampling)
    conv1 = maxpool2d(conv1, k=2)

    # Convolution Layer
    conv2 = conv2d(conv1, weights['wc2'], biases['bc2'])
    # Max Pooling (down-sampling)
    conv2 = maxpool2d(conv2, k=2)

    # Fully connected layer
    # Reshape conv2 output to fit fully connected layer input
    fc1 = tf.reshape(conv2, [-1, weights['wd1'].get_shape().as_list()[0]])
    fc1 = tf.add(tf.matmul(fc1, weights['wd1']), biases['bd1'])
    fc1 = tf.nn.relu(fc1)
    # Apply Dropout
    fc1 = tf.nn.dropout(fc1, dropout)

    # Output, class prediction
    out = tf.add(tf.matmul(fc1, weights['out']), biases['out'])
    return out

# Store layers weight & bias
weights = {
    # 5x5 conv, 1 input, 32 outputs
    'wc1': tf.Variable(tf.random_normal([5, 5, 3, 32])),
    # 5x5 conv, 32 inputs, 64 outputs
    'wc2': tf.Variable(tf.random_normal([5, 5, 32, 64])),
    # fully connected, 8*8*64 inputs, 1024 outputs
    'wd1': tf.Variable(tf.random_normal([8*8*64, 1024])),
    # 1024 inputs, 100 outputs (class prediction)
    'out': tf.Variable(tf.random_normal([1024, n_classes]))
}

biases = {
    'bc1': tf.Variable(tf.random_normal([32])),
    'bc2': tf.Variable(tf.random_normal([64])),
    'bd1': tf.Variable(tf.random_normal([1024])),
    'out': tf.Variable(tf.random_normal([n_classes]))
}

# Construct model
pred = conv_net(x, weights, biases, keep_prob)

# Define loss and optimizer
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=pred, labels=y))
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)

# Evaluate model
correct_pred = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))
accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))

# Initializing the variables
init = tf.global_variables_initializer()

# Launch the graph
with tf.Session(config=tf.ConfigProto(gpu_options=gpu_options)) as sess:
    sess.run(init)
    step = 1
    # Time measuring
    t1 = time.time()
    # Keep training until reach max iterations
    while step * batch_size < training_iters:
        # Prepare training batch
        batch_x, batch_y = next_batch(batch_size)
        batch_x1 = np.zeros([batch_size, 3072], dtype="float32")
        for i in range(batch_size):
            for j in range(3072):
                batch_x1[i][j] = batch_x[i][j] / 255.0
            #if(i % 200 == 0):
                #print("%d of %d training batch images processed" % (i, batch_size))
        # Run optimization op (backprop)
        sess.run(optimizer, feed_dict={x: batch_x1, y: batch_y, keep_prob: dropout})
        if step % display_step == 0:
            # Calculate batch loss and accuracy
            loss, acc = sess.run([cost, accuracy], feed_dict={x: batch_x1, y: batch_y, keep_prob: 1.})
            # Calculate accuracy for all test samples
            acc = accuracy.eval({x: testdata, y: testlabel, keep_prob: 1.})
            # Time measuring
            t2 = time.time()
            tmp = t2-t1
            sec = tmp % 60
            m = int(tmp / 60)
            print("Iter# %8d"%(step*batch_size) + \
                  ", Minibatch Loss= %16.10f"%(loss) + \
                  ", Testing Accuracy= %8.6f"%(acc) + \
                  ", Training currently elapsed " + \
                  "{:d} mins {:f} secs".format(m, sec))
        step += 1
    print("Optimization Finished!")
    # Save the model after learning
    model_saver = tf.train.Saver()
    model_saver.save(sess, dir_model + "/CIFAR-100_cnn_model.chkp")
</code>```

batch.py:

```<code>def next_batch(batch_size, onehot=True):
    class a:
        try:
            temp = current_batch
        except NameError:
            current_batch = 0
    import numpy as np
    from read import unpickle
    import tensorflow as tf
    #from mlxtend.preprocessing import one_hot
    dict_data = unpickle('train')
    label = np.array(dict_data[b'fine_labels'][a.current_batch:a.current_batch+batch_size])
    a1 = dict_data[b'data']
    a2 = a1[a.current_batch:a.current_batch+batch_size, :]
    a.current_batch += batch_size
    a2 = np.reshape(a2, (batch_size, 3072))
    with tf.device('/cpu:0'):
        if(onehot==True):
            label = tf.Session().run(tf.one_hot(label, 100))
    return a2,label
</code>```

read.py:

```<code>def unpickle(file):
    import pickle
    with open(file, 'rb') as a:
        dict = pickle.load(a, encoding='bytes')
        return dict
</code>```

Windows CMD python tf_cifar_learning.py output:

```<code>(tensorflow) C:\Users\Administrator\learn_tensorflow\cifar-100-python>python tf_cifar_learning.py
0 of 5000 test datasets processed
1000 of 5000 test datasets processed
2000 of 5000 test datasets processed
3000 of 5000 test datasets processed
4000 of 5000 test datasets processed
2017-05-02 17:48:46.635855: W c:\tf_jenkins\home\workspace\release-win\device\gpu\os\windows\tensorflow\core\platform\cpu_feature_guard.cc:45] The     TensorFlow library wasn't compiled to use SSE instructions, but these are available on your machine and could speed up CPU computations.
2017-05-02 17:48:46.635975: W c:\tf_jenkins\home\workspace\release-win\device\gpu\os\windows\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE2 instructions, but these are available on your machine and could speed up CPU computations.
2017-05-02 17:48:46.637256: W c:\tf_jenkins\home\workspace\release-win\device\gpu\os\windows\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE3 instructions, but these are available on your machine and could speed up CPU computations.
2017-05-02 17:48:46.638434: W c:\tf_jenkins\home\workspace\release-win\device\gpu\os\windows\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.1 instructions, but these are available on your machine and could speed up CPU computations.
2017-05-02 17:48:46.638939: W c:\tf_jenkins\home\workspace\release-win\device\gpu\os\windows\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.2 instructions, but these are available on your machine and could speed up CPU computations.
2017-05-02 17:48:46.639456: W c:\tf_jenkins\home\workspace\release-win\device\gpu\os\windows\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX instructions, but these are available on your machine and could speed up CPU computations.
2017-05-02 17:48:46.641753: W c:\tf_jenkins\home\workspace\release-win\device\gpu\os\windows\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX2 instructions, but these are available on your machine and could speed up CPU computations.
2017-05-02 17:48:46.641909: W c:\tf_jenkins\home\workspace\release-win\device\gpu\os\windows\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use FMA instructions, but these are available on your machine and could speed up CPU computations.
2017-05-02 17:48:46.994154: I c:\tf_jenkins\home\workspace\release-win\device\gpu\os\windows\tensorflow\core\common_runtime\gpu\gpu_device.cc:887] Found device 0 with properties:
name: GeForce GT 730
major: 3 minor: 5 memoryClockRate (GHz) 0.9015
pciBusID 0000:01:00.0
Total memory: 2.00GiB
Free memory: 1.66GiB
2017-05-02 17:48:46.994318: I c:\tf_jenkins\home\workspace\release-win\device\gpu\os\windows\tensorflow\core\common_runtime\gpu\gpu_device.cc:908] DMA: 0
2017-05-02 17:48:46.997080: I c:\tf_jenkins\home\workspace\release-win\device\gpu\os\windows\tensorflow\core\common_runtime\gpu\gpu_device.cc:918] 0:   Y
2017-05-02 17:48:46.997985: I c:\tf_jenkins\home\workspace\release-win\device\gpu\os\windows\tensorflow\core\common_runtime\gpu\gpu_device.cc:977] Creating TensorFlow device (/gpu:0) -> (device: 0, name: GeForce GT 730, pci bus id: 0000:01:00.0)
2017-05-02 17:48:46.999359: E c:\tf_jenkins\home\workspace\release-win\device\gpu\os\windows\tensorflow\stream_executor\cuda\cuda_driver.cc:893] failed to allocate 1.99G (2136745984 bytes) from device: CUDA_ERROR_OUT_OF_MEMORY
2017-05-02 17:48:46.999434: E c:\tf_jenkins\home\workspace\release-win\device\gpu\os\windows\tensorflow\stream_executor\cuda\cuda_driver.cc:893] failed to allocate 1.79G (1923071488 bytes) from device: CUDA_ERROR_OUT_OF_MEMORY
2017-05-02 17:48:47.766766: I c:\tf_jenkins\home\workspace\release-win\device\gpu\os\windows\tensorflow\core\common_runtime\gpu\gpu_device.cc:977] Creating TensorFlow device (/gpu:0) -> (device: 0, name: GeForce GT 730, pci bus id: 0000:01:00.0)
2017-05-02 17:48:48.334298: E c:\tf_jenkins\home\workspace\release-win\device\gpu\os\windows\tensorflow\stream_executor\cuda\cuda_dnn.cc:359] could not create cudnn handle: CUDNN_STATUS_NOT_INITIALIZED
2017-05-02 17:48:48.334466: E c:\tf_jenkins\home\workspace\release-win\device\gpu\os\windows\tensorflow\stream_executor\cuda\cuda_dnn.cc:366] error retrieving driver version: Unimplemented: kernel reported driver version not implemented on Windows
2017-05-02 17:48:48.343454: E c:\tf_jenkins\home\workspace\release-win\device\gpu\os\windows\tensorflow\stream_executor\cuda\cuda_dnn.cc:326] could not destroy cudnn handle: CUDNN_STATUS_BAD_PARAM
2017-05-02 17:48:48.343558: F c:\tf_jenkins\home\workspace\release-win\device\gpu\os\windows\tensorflow\core\kernels\conv_ops.cc:659] Check failed: stream->parent()->GetConvolveAlgorithms(&algorithms)

(tensorflow) C:\Users\Administrator\learn_tensorflow\cifar-100-python>
</code>```

than Windows 10 says that Python has stopped working and immediately killed it, can someone please tell me what the problem is and tell me (or maybe give me an example) how to fix it?

答: Try to set per_process_gpu_memory_fraction=0.995 to a small data like 0.7 or 0.6

Body:
I'm trying to do CIFAR-100 training with Python Tensorflow CNN, but the error CUDA_ERROR_OUT_OF_MEMORY, CUDA_STATUS_NOT_INITIALIZED and CUDA_STATUS_BAD_PARAM keep bothering me, I'm using Anaconda virtual environment which Tensorflow depends on my machine, Python version is Anaconda Python 3.5 virtual environment, Tensorflow version is 1.1.0, here's my code:
tf_cifar_learning.py:

# Set working directory

import os
dir_model = "c:/tf_model_cifar100"

# Modules needed

import numpy as np
import tensorflow as tf
import pandas as pd
from mlxtend.preprocessing import one_hot

# Load CIFAR Data
from batch import next_batch
from read import unpickle
import time
gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.995)

# Prepare test data

testdata = unpickle('test')[b'data']
testdata1 = testdata.astype('float')
del testdata
testdata = testdata1[0:5000, :]
testlabel = unpickle('test')[b'coarse_labels'][0:5000]
testlabel = one_hot(testlabel, 100)
for i in range(testdata.shape[0]):
    for j in range(3072):
        testdata[i][j] = float(testdata[i][j]) / 255.0
    if(i % 1000 == 0):
        print("%d of 5000 test datasets processed" % i)

# Parameters
learning_rate = 0.001
training_iters = 1000000
batch_size = 10 # 128
display_step = 2

# Network Parameters
n_input = 1024*3 # CIFAR data input (img shape: 32*32)
n_classes = 100 # CIFAR total classes
dropout = 0.75 # Dropout, probability to keep units

# tf Graph input
x = tf.placeholder(tf.float32, [None, n_input])
y = tf.placeholder(tf.float32, [None, n_classes])
keep_prob = tf.placeholder(tf.float32) #dropout (keep probability)

# Create some wrappers for simplicity
def conv2d(x, W, b, strides=1):
    # Conv2D wrapper, with bias and relu activation
    x = tf.nn.conv2d(x, W, strides=[1, strides, strides, 1], padding='SAME')
    x = tf.nn.bias_add(x, b)
    o = tf.nn.relu(x)
    return o

def maxpool2d(x, k=2):
    # MaxPool2D wrapper
    o = tf.nn.max_pool(x, ksize=[1, k, k, 1], strides=[1, k, k, 1], padding='SAME')
    return o

# Create model
def conv_net(x, weights, biases, dropout):
        # Reshape input picture
    x = tf.reshape(x, shape=[-1, 32, 32, 3])
    # Convolution Layer
    conv1 = conv2d(x, weights['wc1'], biases['bc1'])
    # Max Pooling (down-sampling)
    conv1 = maxpool2d(conv1, k=2)

    # Convolution Layer
    conv2 = conv2d(conv1, weights['wc2'], biases['bc2'])
    # Max Pooling (down-sampling)
    conv2 = maxpool2d(conv2, k=2)

    # Fully connected layer
    # Reshape conv2 output to fit fully connected layer input
    fc1 = tf.reshape(conv2, [-1, weights['wd1'].get_shape().as_list()[0]])
    fc1 = tf.add(tf.matmul(fc1, weights['wd1']), biases['bd1'])
    fc1 = tf.nn.relu(fc1)
    # Apply Dropout
    fc1 = tf.nn.dropout(fc1, dropout)

    # Output, class prediction
    out = tf.add(tf.matmul(fc1, weights['out']), biases['out'])
    return out

# Store layers weight & bias
weights = {
    # 5x5 conv, 1 input, 32 outputs
    'wc1': tf.Variable(tf.random_normal([5, 5, 3, 32])),
    # 5x5 conv, 32 inputs, 64 outputs
    'wc2': tf.Variable(tf.random_normal([5, 5, 32, 64])),
    # fully connected, 8*8*64 inputs, 1024 outputs
    'wd1': tf.Variable(tf.random_normal([8*8*64, 1024])),
    # 1024 inputs, 100 outputs (class prediction)
    'out': tf.Variable(tf.random_normal([1024, n_classes]))
}

biases = {
    'bc1': tf.Variable(tf.random_normal([32])),
    'bc2': tf.Variable(tf.random_normal([64])),
    'bd1': tf.Variable(tf.random_normal([1024])),
    'out': tf.Variable(tf.random_normal([n_classes]))
}

# Construct model
pred = conv_net(x, weights, biases, keep_prob)

# Define loss and optimizer
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=pred, labels=y))
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)

# Evaluate model
correct_pred = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))
accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))

# Initializing the variables
init = tf.global_variables_initializer()

# Launch the graph
with tf.Session(config=tf.ConfigProto(gpu_options=gpu_options)) as sess:
    sess.run(init)
    step = 1
    # Time measuring
    t1 = time.time()
    # Keep training until reach max iterations
    while step * batch_size < training_iters:
        # Prepare training batch
        batch_x, batch_y = next_batch(batch_size)
        batch_x1 = np.zeros([batch_size, 3072], dtype="float32")
        for i in range(batch_size):
            for j in range(3072):
                batch_x1[i][j] = batch_x[i][j] / 255.0
            #if(i % 200 == 0):
                #print("%d of %d training batch images processed" % (i, batch_size))
        # Run optimization op (backprop)
        sess.run(optimizer, feed_dict={x: batch_x1, y: batch_y, keep_prob: dropout})
        if step % display_step == 0:
            # Calculate batch loss and accuracy
            loss, acc = sess.run([cost, accuracy], feed_dict={x: batch_x1, y: batch_y, keep_prob: 1.})
            # Calculate accuracy for all test samples
            acc = accuracy.eval({x: testdata, y: testlabel, keep_prob: 1.})
            # Time measuring
            t2 = time.time()
            tmp = t2-t1
            sec = tmp % 60
            m = int(tmp / 60)
            print("Iter# %8d"%(step*batch_size) + \
                  ", Minibatch Loss= %16.10f"%(loss) + \
                  ", Testing Accuracy= %8.6f"%(acc) + \
                  ", Training currently elapsed " + \
                  "{:d} mins {:f} secs".format(m, sec))
        step += 1
    print("Optimization Finished!")
    # Save the model after learning
    model_saver = tf.train.Saver()
    model_saver.save(sess, dir_model + "/CIFAR-100_cnn_model.chkp")

batch.py:

def next_batch(batch_size, onehot=True):
    class a:
        try:
            temp = current_batch
        except NameError:
            current_batch = 0
    import numpy as np
    from read import unpickle
    import tensorflow as tf
    #from mlxtend.preprocessing import one_hot
    dict_data = unpickle('train')
    label = np.array(dict_data[b'fine_labels'][a.current_batch:a.current_batch+batch_size])
    a1 = dict_data[b'data']
    a2 = a1[a.current_batch:a.current_batch+batch_size, :]
    a.current_batch += batch_size
    a2 = np.reshape(a2, (batch_size, 3072))
    with tf.device('/cpu:0'):
        if(onehot==True):
            label = tf.Session().run(tf.one_hot(label, 100))
    return a2,label

read.py:

def unpickle(file):
    import pickle
    with open(file, 'rb') as a:
        dict = pickle.load(a, encoding='bytes')
        return dict

Windows CMD python tf_cifar_learning.py output:

(tensorflow) C:\Users\Administrator\learn_tensorflow\cifar-100-python>python tf_cifar_learning.py
0 of 5000 test datasets processed
1000 of 5000 test datasets processed
2000 of 5000 test datasets processed
3000 of 5000 test datasets processed
4000 of 5000 test datasets processed
2017-05-02 17:48:46.635855: W c:\tf_jenkins\home\workspace\release-win\device\gpu\os\windows\tensorflow\core\platform\cpu_feature_guard.cc:45] The     TensorFlow library wasn't compiled to use SSE instructions, but these are available on your machine and could speed up CPU computations.
2017-05-02 17:48:46.635975: W c:\tf_jenkins\home\workspace\release-win\device\gpu\os\windows\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE2 instructions, but these are available on your machine and could speed up CPU computations.
2017-05-02 17:48:46.637256: W c:\tf_jenkins\home\workspace\release-win\device\gpu\os\windows\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE3 instructions, but these are available on your machine and could speed up CPU computations.
2017-05-02 17:48:46.638434: W c:\tf_jenkins\home\workspace\release-win\device\gpu\os\windows\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.1 instructions, but these are available on your machine and could speed up CPU computations.
2017-05-02 17:48:46.638939: W c:\tf_jenkins\home\workspace\release-win\device\gpu\os\windows\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.2 instructions, but these are available on your machine and could speed up CPU computations.
2017-05-02 17:48:46.639456: W c:\tf_jenkins\home\workspace\release-win\device\gpu\os\windows\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX instructions, but these are available on your machine and could speed up CPU computations.
2017-05-02 17:48:46.641753: W c:\tf_jenkins\home\workspace\release-win\device\gpu\os\windows\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX2 instructions, but these are available on your machine and could speed up CPU computations.
2017-05-02 17:48:46.641909: W c:\tf_jenkins\home\workspace\release-win\device\gpu\os\windows\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use FMA instructions, but these are available on your machine and could speed up CPU computations.
2017-05-02 17:48:46.994154: I c:\tf_jenkins\home\workspace\release-win\device\gpu\os\windows\tensorflow\core\common_runtime\gpu\gpu_device.cc:887] Found device 0 with properties:
name: GeForce GT 730
major: 3 minor: 5 memoryClockRate (GHz) 0.9015
pciBusID 0000:01:00.0
Total memory: 2.00GiB
Free memory: 1.66GiB
2017-05-02 17:48:46.994318: I c:\tf_jenkins\home\workspace\release-win\device\gpu\os\windows\tensorflow\core\common_runtime\gpu\gpu_device.cc:908] DMA: 0
2017-05-02 17:48:46.997080: I c:\tf_jenkins\home\workspace\release-win\device\gpu\os\windows\tensorflow\core\common_runtime\gpu\gpu_device.cc:918] 0:   Y
2017-05-02 17:48:46.997985: I c:\tf_jenkins\home\workspace\release-win\device\gpu\os\windows\tensorflow\core\common_runtime\gpu\gpu_device.cc:977] Creating TensorFlow device (/gpu:0) -> (device: 0, name: GeForce GT 730, pci bus id: 0000:01:00.0)
2017-05-02 17:48:46.999359: E c:\tf_jenkins\home\workspace\release-win\device\gpu\os\windows\tensorflow\stream_executor\cuda\cuda_driver.cc:893] failed to allocate 1.99G (2136745984 bytes) from device: CUDA_ERROR_OUT_OF_MEMORY
2017-05-02 17:48:46.999434: E c:\tf_jenkins\home\workspace\release-win\device\gpu\os\windows\tensorflow\stream_executor\cuda\cuda_driver.cc:893] failed to allocate 1.79G (1923071488 bytes) from device: CUDA_ERROR_OUT_OF_MEMORY
2017-05-02 17:48:47.766766: I c:\tf_jenkins\home\workspace\release-win\device\gpu\os\windows\tensorflow\core\common_runtime\gpu\gpu_device.cc:977] Creating TensorFlow device (/gpu:0) -> (device: 0, name: GeForce GT 730, pci bus id: 0000:01:00.0)
2017-05-02 17:48:48.334298: E c:\tf_jenkins\home\workspace\release-win\device\gpu\os\windows\tensorflow\stream_executor\cuda\cuda_dnn.cc:359] could not create cudnn handle: CUDNN_STATUS_NOT_INITIALIZED
2017-05-02 17:48:48.334466: E c:\tf_jenkins\home\workspace\release-win\device\gpu\os\windows\tensorflow\stream_executor\cuda\cuda_dnn.cc:366] error retrieving driver version: Unimplemented: kernel reported driver version not implemented on Windows
2017-05-02 17:48:48.343454: E c:\tf_jenkins\home\workspace\release-win\device\gpu\os\windows\tensorflow\stream_executor\cuda\cuda_dnn.cc:326] could not destroy cudnn handle: CUDNN_STATUS_BAD_PARAM
2017-05-02 17:48:48.343558: F c:\tf_jenkins\home\workspace\release-win\device\gpu\os\windows\tensorflow\core\kernels\conv_ops.cc:659] Check failed: stream->parent()->GetConvolveAlgorithms(&algorithms)

(tensorflow) C:\Users\Administrator\learn_tensorflow\cifar-100-python>

than Windows 10 says that Python has stopped working and immediately killed it, can someone please tell me what the problem is and tell me (or maybe give me an example) how to fix it?


问:
Swift - How to dismiss all of view controllers to go back to root
I want a my app can go to a first view controller when every time users want it.

So I want to create a function to dismiss all the view controllers, regardless of whether it is pushed in navigation controllers or presented modally or opened anything methods.

I tried various ways, but I failed to dismiss all the view controllers certainly.
Is there an easy way?

答:
Pops all the view controllers on the stack except the root view controller and updates the display.

```<code>func popToRootViewController(animated: Bool)
</code>```

But if you want to go to specific controller just use the below function.

```<code>func popToViewController(UIViewController, animated: Bool)
</code>```

Pops view controllers until the specified view controller is at the top of the navigation stack.

Body:
Pops all the view controllers on the stack except the root view controller and updates the display.

func popToRootViewController(animated: Bool)

But if you want to go to specific controller just use the below function.

func popToViewController(UIViewController, animated: Bool)

Pops view controllers until the specified view controller is at the top of the navigation stack.


问:
ankh svn does not show in source control in visual studio 2012
I installed TortoiseSVN and AnkhSVN and restarted my PC. However, I can't find subversion link in File -> Open and AnkhSvn does not show up in source control in Tools -> Options -> Source control.
I have tried uninstalling and reinstalling TortoiseSVN and AnkhSVN as well as Visual Studio 2012 with no success.

Can someone please help me with the integration of the SVN and Visual Studio 2012 Professional?

答:
I had the same issue; the root cause is that registry is not correctly written during installation. Visual Studio Source Control Plug-In Selection drop-down list links to the registry directly.
My regedit had been disabled by system admin, so that the installing was failed (but you would not get any error message).
Re-installing AnkhSVN after enabling read/write permission of registry and the issue gets solved.</p>


问:
how to handle alerts in android using appium
How do I handle alerts in an Android web application using Appium server (1.0.1) and the Android SDK?

The below code is not working on android:

```<code>driver.switchTo().accept().alert();
</code>```

Error message:

```<code>> -modal window does not get closed
</code>```

答:
 Please use the below code, Add some wait before clicking on OK Button.
    After that pass the xpath of you OK Button.

```<code>synchronized (driver)
{
driver.wait(2000);
}
driver.context(NATIVE_APP);
driver.findElementByXPath{("//android.widget.Button[@resourceid=
‘android:id/button1’]").click();
</code>```

Body:
How do I handle alerts in an Android web application using Appium server (1.0.1) and the Android SDK?

The below code is not working on android:

driver.switchTo().accept().alert();

Error message:

> -modal window does not get closed

Body:
 Please use the below code, Add some wait before clicking on OK Button.
    After that pass the xpath of you OK Button.

synchronized (driver)
{
driver.wait(2000);
}
driver.context(NATIVE_APP);
driver.findElementByXPath{("//android.widget.Button[@resourceid=
‘android:id/button1’]").click();


问:
tensorflow, How to index the true value of a tensor?
I have a 1-d tensor like:

```<code>[false, false, true, false, true, false]
</code>```

How to find the index of all the true value?

My solution is:

Turn it to 1 and 0 value

Use argmax API to find one index and then set the one to false/0.

Use argmax again to find the next true/1 value

But this solution is not that good.

答:
Is this what you're looking for?
[k for k, value in enumerate(tensor) if value]

Body:
I have a 1-d tensor like:

[false, false, true, false, true, false]

How to find the index of all the true value?

My solution is:

Turn it to 1 and 0 value

Use argmax API to find one index and then set the one to false/0.

Use argmax again to find the next true/1 value

But this solution is not that good.


问:
How to store the drop down values selected in a session and update in the database while clicking on the submit button

I want to choose the values from each dropdown and update in the database once I click on the "submit" button. Can anyone please tell me how to store these values in a session array and use while the button is clicked?

答: I'm not sure if I understand you well. But on drop you can save value to localStorage (https://developer.mozilla.org/pl/docs/Web/API/Window/localStorage) or cookies (https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie) and on button click you can read values from localStorage/cookies


问:
How can i get Client Webpage cookie information through javascript
I want to get the browser cookies information like email or name.

pls help me

答:
Have a look at this..

http://www.yourhtmlsource.com/javascript/cookies.html


问:
Laravel remove directory
When I try to delete a directory in Laravel 5.1 like this:

```<code>use Storage;

public function deleteUser(Request $request)
{
    $user = User::find($request->id);
    Storage::deleteDirectory('/files/'.$user->id);
    $user->delete();
    $user->websites()->delete();
    return redirect('/')->with('status','Customer removed');
}
</code>```

The directory isn't going away. But the user is successfully removed.

Here is the documentation:

https://laravel.com/docs/5.2/filesystem#deleting-files

Why is this not working?

答:
I was stuck with the Storage:deleteDirectory command too. Later I found out it could be easily done with the following command:

use Illuminate\Support\Facades\File;    File::deleteDirectory('/Users/zawad/web/storage/app/sleepdata/DirectoryToBeDeleted');

The argument is the absolute path to the directory which is to be deleted. You can find the root of the path by running the pwd command in the terminal.

Title: Laravel remove directory

Body:
When I try to delete a directory in Laravel 5.1 like this:

use Storage;

public function deleteUser(Request $request)
{
    $user = User::find($request->id);
    Storage::deleteDirectory('/files/'.$user->id);
    $user->delete();
    $user->websites()->delete();
    return redirect('/')->with('status','Customer removed');
}

The directory isn't going away. But the user is successfully removed.

Here is the documentation:

https://laravel.com/docs/5.2/filesystem#deleting-files

Why is this not working?


问:
Select column and values where values are greater than 0 in mysql
I have two tables.

```<code>Name: `table1`
name    d1      d2      d3      d4      d5
Tapan   2       0       3       8       0
</code>```

```<code>another table : `table2`
name    c1      c2      c3      c4      c5      c6
Tapan   12      14      0       0       17      0
</code>```

In both tables there are 50+ columns.
How to get a report like:

```<code>name    - Tapan
d1      - 2
d3      - 3
d4      - 8
c1      - 12
c2      - 14
c5      - 17
total   - 56
</code>```

I failed to create the sql query for the report where value>0 and name = 'Tapan'

```<code>SELECT a.*, b.*
FROM table1 a
INNER JOIN table2 b
ON a.name = b.name
</code>```

See the SQL Fiddle

I need to get the report  where column value is greater than 0

答:
It would be better if you redesigned your tables to be like this:

table1:

```<code>Name    Dnum    Dval
Tapan   1       2
Tapan   2       0
Tapan   3       3
Tapan   4       8
Tapan   5       0
</code>```

table2:

```<code>Name    Cnum    Cval
Tapan   1       12
Tapan   2       14
Tapan   3       0
Tapan   4       0
Tapan   5       17
Tapan   6       0
</code>```

Then you can query like this:

```<code>SELECT CONCAT('d', Dnum) AS name, Dval AS Tapan
FROM table1
WHERE Name = 'Tapan' AND Dval > 0
UNION ALL
SELECT CONCAT('c', Cnum) AS name, Cval AS Tapan
FROM table2
WHERE Name = 'Tapan' AND Cval > 0
</code>```

You could also combine both tables like:

```<code>Name    Prefix  Num    Val
Tapan   d       1       2
Tapan   d       2       0
Tapan   d       3       3
Tapan   d       4       8
Tapan   d       5       0
Tapan   c       1       12
Tapan   c       2       14
Tapan   c       3       0
Tapan   c       4       0
Tapan   c       5       17
Tapan   c       6       0
</code>```

Then the query is:

```<code>SELECT CONCAT(prefix, num) AS name, val AS Tapan
FROM yourTable
WHERE name = 'Tapan' AND val > 0
</code>```

Body:
I have two tables.

Name: `table1`
name    d1      d2      d3      d4      d5
Tapan   2       0       3       8       0

another table : `table2`
name    c1      c2      c3      c4      c5      c6
Tapan   12      14      0       0       17      0

In both tables there are 50+ columns.
How to get a report like:

name    - Tapan
d1      - 2
d3      - 3
d4      - 8
c1      - 12
c2      - 14
c5      - 17
total   - 56

I failed to create the sql query for the report where value>0 and name = 'Tapan'

SELECT a.*, b.*
FROM table1 a
INNER JOIN table2 b
ON a.name = b.name

See the SQL Fiddle

I need to get the report  where column value is greater than 0

Body:
It would be better if you redesigned your tables to be like this:

table1:

Name    Dnum    Dval
Tapan   1       2
Tapan   2       0
Tapan   3       3
Tapan   4       8
Tapan   5       0

table2:

Name    Cnum    Cval
Tapan   1       12
Tapan   2       14
Tapan   3       0
Tapan   4       0
Tapan   5       17
Tapan   6       0

Then you can query like this:

SELECT CONCAT('d', Dnum) AS name, Dval AS Tapan
FROM table1
WHERE Name = 'Tapan' AND Dval > 0
UNION ALL
SELECT CONCAT('c', Cnum) AS name, Cval AS Tapan
FROM table2
WHERE Name = 'Tapan' AND Cval > 0

You could also combine both tables like:

Name    Prefix  Num    Val
Tapan   d       1       2
Tapan   d       2       0
Tapan   d       3       3
Tapan   d       4       8
Tapan   d       5       0
Tapan   c       1       12
Tapan   c       2       14
Tapan   c       3       0
Tapan   c       4       0
Tapan   c       5       17
Tapan   c       6       0

Then the query is:

SELECT CONCAT(prefix, num) AS name, val AS Tapan
FROM yourTable
WHERE name = 'Tapan' AND val > 0


问:
How to hide and show a layout on scrolling down a scroll view in Android?
I have a particular layout which consist a scroll view and an image which is at bottom of the activity. My question is that when I start scrolling up that image will not visible and when the scroll reach to top it is visible again.

I attached my image link so that you get the idea what I want.

答:
Here is something that you should try out </p>

```<code>ScrollView sv = (ScrollView)findViewById(R.id.scrl);
sv.scrollTo(0, sv.getTop());
</code>```

<p>and when it gets to top show the visibility of the image view as visible and in else part make it gone...  </p>

Body:
Here is something that you should try out

ScrollView sv = (ScrollView)findViewById(R.id.scrl);
sv.scrollTo(0, sv.getTop());

and when it gets to top show the visibility of the image view as visible and in else part make it gone...


问:
Update property object in array state reactJS
I have an array Object in my state named object
so I have, in my state object in parent component something like:

```<code>object:[{id:1, name:"name"},{id:2, name:"name2"}];
</code>```

And I have a select box in child component for every object in array and select is printed with this.props.object.map passed by props like:

```<code>var elements = this.state.object.map(function(element, k){
        return (

        <Components object={this.state.object} element={element} setPropertyElement={this.setPropertyElement} />

        )
      }, this);
</code>```

In child component I have select with change function like:

```<code><select className="form-control" ref="name" defaultValue="j" onChange={this.change}>
   <option value="j">j</option>
   <option value="x">x</option>
</select>
</code>```

So in this case I see in my page 2 elements with related select for change name.
I have my function change.

```<code>change(event){
   this.props.setPropertyElement(this.props.element, event.target.value);
}
</code>```

In my parent element so I have a function setPropertyElement:

```<code>setPropertyElement(element, value){

      element.name = value;
  }
</code>```

My question is:
My operations are correct or I'm modifing in wrong way state object?
In this case How Can I change correctly value of property object in array?

答:
Try this:</p>

```<code>let editableComparatorIndexes = [...this.state.ids];
   editableComparatorIndexes[i] = 1;
   this.setState({editableComparatorIndexes});
</code>```

Body:
I have an array Object in my state named object
so I have, in my state object in parent component something like:

object:[{id:1, name:"name"},{id:2, name:"name2"}];

And I have a select box in child component for every object in array and select is printed with this.props.object.map passed by props like:

var elements = this.state.object.map(function(element, k){
        return (

        <Components object={this.state.object} element={element} setPropertyElement={this.setPropertyElement} />

        )
      }, this);

In child component I have select with change function like:

<select className="form-control" ref="name" defaultValue="j" onChange={this.change}>
   <option value="j">j</option>
   <option value="x">x</option>
</select>

So in this case I see in my page 2 elements with related select for change name.
I have my function change.

change(event){
   this.props.setPropertyElement(this.props.element, event.target.value);
}

In my parent element so I have a function setPropertyElement:

setPropertyElement(element, value){

      element.name = value;
  }

My question is:
My operations are correct or I'm modifing in wrong way state object?
In this case How Can I change correctly value of property object in array?

Body:
Try this:

let editableComparatorIndexes = [...this.state.ids];
   editableComparatorIndexes[i] = 1;
   this.setState({editableComparatorIndexes});


问:
Parsing Wikipedia .bz2 dump
I have downloaded the compressed Wikipedia corpus in .bz2 form. Is there a way to search through that bulk of data for a keyword without having to use an API? I need to upload the whole database on a server and search through it for data mining purposes.</p>

答:
Clearly, bzcat/bzgrep is the closest thing to "not using an API".

But at some point, you will want to think about search APIs for faster searching.

Title: Parsing Wikipedia .bz2 dump


问:
how to Autofill my data in java program
Hello people,
             I just learned java & it's basics. I really new to programming. I'm really ambitious to create my first project.  My Application kind of used for  ** grocery store** type. Please Understand.(I couldn't explain it)
Details:

It's just kind of Seller ledger book

It has all types of products prices & their other important details & which is updatable

It's design kind of Ms-Excel where default columns are generated

when a item is typed in respective column  in the product name. The application retrieves that particular item & it fills in the details. ( main feature)

I'm sorry for very vague details.Well my take is

Java Swings for GU-Interface

I think I need database for my application

I clearly don't have enough knowledge but trying to implement this project only way I can motivate my self to learn. Internet is my only resource. Please Help me.. in anyway.. Thank you.

答:
Considering you are new to programming, I would suggest create a CSV file and put details in there. When you start your program you can read the details from there. The format of File could be like:

```<code>ProductId,ProductName,Price,Description
P1,Soap,10,Cleaning
P2,Shampoo,50,Hair Wash
.....
</code>```

and so on.
You will easily find ways to read a CSV file as in this link.
Here

Title: how to Autofill my data in java program

Body:
Considering you are new to programming, I would suggest create a CSV file and put details in there. When you start your program you can read the details from there. The format of File could be like:

ProductId,ProductName,Price,Description
P1,Soap,10,Cleaning
P2,Shampoo,50,Hair Wash
.....

and so on.
You will easily find ways to read a CSV file as in this link.
Here


问:
javascript execution order
I am starting to learn Javascript and jQuery.
I wanted to make a simple slide show with jQuery which displays list unordered list items one by one.

My code is here: on jsfiddle

I thought that I'd make the slideshow by iterating over list items in a for loop and display them with fadeIn and fadeOut effects like below:

```<code>for(var i = 0; i < 3; i++)
{
    $('#slider li:nth-child('+ i +')')
        .fadeIn()
        .delay(1000)
        .fadeOut();
}
</code>```

But it only shows the last item in the list.

I read that I need to close the value of i variable in a separate function because of the Javascript scope that it sees the value of i is being increased to 2 in the loop. So, I made a separate function which closes the value of i and called the function. But it was still same, displaying the last item of the list.

So, I just wanted to try without the loop by making two separate effects on list items like below:

```<code>$('#slider li:first-child')
    .fadeIn()
    .delay(1000)
    .fadeOut();
$('#slider li:nth-child(2)')
    .fadeIn()
    .delay(1000)
    .fadeOut();
</code>```

But it doesn't display the list items sequentially like written above. When you run the code, it seems like the first item is shown really fast and the last item is displayed as intended.

I have written it like a C or Java code, thinking that it would execute from top to bottom. But it seems like Javascript is different and I didn't understand a key concept of Javascript.

So, my question is why it is not displaying the list items in order and only displaying the last item, and what should I need to know to make it work as intented.

Thank you.

答:
Since the reasons why yours didn't work have already been covered, instead I've set up a new fiddle for you with the following working slideshow code and commented explanation:</p>

```<code>$('#slider li').hide();

// Method 3
var slideIt = function ( which ) {
    $('#slider li:nth-child('+ which +')')
        .fadeIn(300)
        .delay(1000)
        .fadeOut(300, function() { // after animation complete
            which++; // increment which child
            which = (which > $('#slider li').length) ?
                    1 : // if last child loop back to beginning
                    which;
            slideIt( which ); // call again with new child
        });
};

slideIt( 1 ); // start the process
</code>```

Title: javascript execution order

Body:
I am starting to learn Javascript and jQuery.
I wanted to make a simple slide show with jQuery which displays list unordered list items one by one.

My code is here: on jsfiddle

I thought that I'd make the slideshow by iterating over list items in a for loop and display them with fadeIn and fadeOut effects like below:

for(var i = 0; i < 3; i++)
{
    $('#slider li:nth-child('+ i +')')
        .fadeIn()
        .delay(1000)
        .fadeOut();
}

But it only shows the last item in the list.

I read that I need to close the value of i variable in a separate function because of the Javascript scope that it sees the value of i is being increased to 2 in the loop. So, I made a separate function which closes the value of i and called the function. But it was still same, displaying the last item of the list.

So, I just wanted to try without the loop by making two separate effects on list items like below:

$('#slider li:first-child')
    .fadeIn()
    .delay(1000)
    .fadeOut();
$('#slider li:nth-child(2)')
    .fadeIn()
    .delay(1000)
    .fadeOut();

But it doesn't display the list items sequentially like written above. When you run the code, it seems like the first item is shown really fast and the last item is displayed as intended.

I have written it like a C or Java code, thinking that it would execute from top to bottom. But it seems like Javascript is different and I didn't understand a key concept of Javascript.

So, my question is why it is not displaying the list items in order and only displaying the last item, and what should I need to know to make it work as intented.

Thank you.

Body:
Since the reasons why yours didn't work have already been covered, instead I've set up a new fiddle for you with the following working slideshow code and commented explanation:

$('#slider li').hide();

// Method 3
var slideIt = function ( which ) {
    $('#slider li:nth-child('+ which +')')
        .fadeIn(300)
        .delay(1000)
        .fadeOut(300, function() { // after animation complete
            which++; // increment which child
            which = (which > $('#slider li').length) ?
                    1 : // if last child loop back to beginning
                    which;
            slideIt( which ); // call again with new child
        });
};

slideIt( 1 ); // start the process


问:
guess = raw_input() when i press enter button what will the value of the guess variable?
guess = raw_input(): if I press enter button here what will be the value inside the guess variable and is it printable?

Executable code in shell IDE:

```<code>>>> guess = raw_input()

>>> print guess
</code>```

答:
If you press enter then guess=''.

You can print guess which will turn out to be blank.

Body:
guess = raw_input(): if I press enter button here what will be the value inside the guess variable and is it printable?

Executable code in shell IDE:

>>> guess = raw_input()

>>> print guess


问:
Haskell: Using List Comprehension and reducing x by 1 each list to make x amount of lists
I'm new to using Haskell I've been spending hours trying to build a simple function where entering a function will turn out like this:

```<code>makeList 5 == [[1],[1,2],[1,2,3],[1,2,3,4],[1,2,3,4,5]]
makeList 2 == [[1],[1,2]]
</code>```

No amount of research can really help me figure out how I should iterate my functions 'x' so that I have multiple lists building based on the number I choose, I'm close but that's where I'm stumped, my current code is essentially set up where I can do this if I were to enter makeList 3:

```<code>makeList 3 = [ [ x | x <- xs ] | xs <- [[1..x-2],[1..x-1],[1..x]] ]
</code>```

prints out:

```<code>[[1],[1,2],[1,2,3]]
</code>```

答:
Or you can use explicit recursion.</p>

```<code>makeList :: Int -> [[Int]]
makeList cap = go 1 where
  go num | num < cap = [1..num]:go (num+1)
         | otherwise = [1..num]:[]
</code>```

Body:
I'm new to using Haskell I've been spending hours trying to build a simple function where entering a function will turn out like this:

makeList 5 == [[1],[1,2],[1,2,3],[1,2,3,4],[1,2,3,4,5]]
makeList 2 == [[1],[1,2]]

No amount of research can really help me figure out how I should iterate my functions 'x' so that I have multiple lists building based on the number I choose, I'm close but that's where I'm stumped, my current code is essentially set up where I can do this if I were to enter makeList 3:

makeList 3 = [ [ x | x <- xs ] | xs <- [[1..x-2],[1..x-1],[1..x]] ]

prints out:

[[1],[1,2],[1,2,3]]

Body:
Or you can use explicit recursion.

makeList :: Int -> [[Int]]
makeList cap = go 1 where
  go num | num < cap = [1..num]:go (num+1)
         | otherwise = [1..num]:[]


问:
How to export language file content to CSV in CodeIgniter?
CodeIgniter has the language class by default. I want to export all the language file into CSV format. Is there any PHP script available to parse and export the file content?
Sample file content:

```<code><?php
$lang['Mymenu'] = "Mymenu";
$lang['AdminUser'] = "AdminUser";
</code>```

The language files can also be placed inside the folders like

```<code>application/language/english
application/language/spanish ...etc
</code>```

答:
Got a solution from the gist
https://gist.github.com/timneutkens/19e58a00ff8af4663c6502a1d89990a4

Thanks for that but the solution not applicable for recursive language directories.

Here I am posting the modified version:

```<code><?php
/**
 * PHP version 5.4
 * @category Export
 * @package  Language
 * @author   Tim Neutkens <tim@weprovide.com>
 * @license  MIT <https://opensource.org/licenses/MIT>
 * @link     <weprovide.com>
 */

define('ENVIRONMENT', 'production');
/**
 * Placeholder for base_url function
 *
 * @param string $path path part of url
 *
 * @return string
 */
function base_url($path = '')
{
    return '/'.$path;
}

/**
 * Placeholder for base_url function
 *
 * @param string $path path part of url
 *
 * @return string
 */
function site_url($path = '')
{
    return '/'.$path;
}

/**
 * Export csv to file location
 *
 * @param array $data csv data
 * @param string $location location to put file
 *
 * @return string
 */
function export_csv($data = [], $location = '',$file_name)
{
   // $file_name = 'export-lang-'.time().'.csv';
    $file_name = $file_name.'.csv';
    $file_path = $location.'/'.$file_name;
    $file      = @fopen($file_path, 'w');

    fprintf($file, chr(0xEF).chr(0xBB).chr(0xBF));

    foreach ($data as $key => $value) {
        fputcsv($file, [$key, $value]);
    }

    fclose($file);

    return $file_path;
}

/**
 * Load language
 *
 * @param string $path path to language directory.
 *
 * @return array
 */
function load_language($path = '')
{
    // Loop through translations
    /*$files = glob($path.'/*.php');
    foreach ($files as $filename) {
        include_once $filename;
    }*/

    $di = new RecursiveDirectoryIterator($path);
    foreach (new RecursiveIteratorIterator($di) as $filename => $file) {
    if(!is_dir($filename))
      include_once $filename; //echo $filename . ' - ' . $file->getSize() . ' bytes <br/>';
    }

    return $lang;
}

$lang_array = array('arabic','chinese','english','french','german','italian','japanese','korean','polish','portuguese','russian','spanish','turkish','vietnam'); // List of language folders
$i=1;
$file_arr = array();
$lang1 = $lang2 = $lang3 = $lang4 = $lang5 = $lang6 = $lang7 = $lang8 = $lang9 = $lang10 = $lang11 = $lang12 = $lang13 = $lang14 = '' ;
foreach ($lang_array as $language) {

    ${"lang" . $i} =  load_language('application/language/'.$language);
    export_csv( ${"lang" . $i} , '/xampp/htdocs/CodeIginiter/language',$language);
    // Lang gets filled by the above includes
    $i++;
}
</code>```

Place the file in the root directory of CodeIgniter and execute. CSV files will get downloaded which can easily export to excel and used for language translators.

Body:
CodeIgniter has the language class by default. I want to export all the language file into CSV format. Is there any PHP script available to parse and export the file content?
Sample file content:

<?php
$lang['Mymenu'] = "Mymenu";
$lang['AdminUser'] = "AdminUser";

The language files can also be placed inside the folders like

application/language/english
application/language/spanish ...etc

Body:
Got a solution from the gist
https://gist.github.com/timneutkens/19e58a00ff8af4663c6502a1d89990a4

Thanks for that but the solution not applicable for recursive language directories.

Here I am posting the modified version:

<?php
/**
 * PHP version 5.4
 * @category Export
 * @package  Language
 * @author   Tim Neutkens <tim@weprovide.com>
 * @license  MIT <https://opensource.org/licenses/MIT>
 * @link     <weprovide.com>
 */

define('ENVIRONMENT', 'production');
/**
 * Placeholder for base_url function
 *
 * @param string $path path part of url
 *
 * @return string
 */
function base_url($path = '')
{
    return '/'.$path;
}

/**
 * Placeholder for base_url function
 *
 * @param string $path path part of url
 *
 * @return string
 */
function site_url($path = '')
{
    return '/'.$path;
}

/**
 * Export csv to file location
 *
 * @param array $data csv data
 * @param string $location location to put file
 *
 * @return string
 */
function export_csv($data = [], $location = '',$file_name)
{
   // $file_name = 'export-lang-'.time().'.csv';
    $file_name = $file_name.'.csv';
    $file_path = $location.'/'.$file_name;
    $file      = @fopen($file_path, 'w');

    fprintf($file, chr(0xEF).chr(0xBB).chr(0xBF));

    foreach ($data as $key => $value) {
        fputcsv($file, [$key, $value]);
    }

    fclose($file);

    return $file_path;
}

/**
 * Load language
 *
 * @param string $path path to language directory.
 *
 * @return array
 */
function load_language($path = '')
{
    // Loop through translations
    /*$files = glob($path.'/*.php');
    foreach ($files as $filename) {
        include_once $filename;
    }*/

    $di = new RecursiveDirectoryIterator($path);
    foreach (new RecursiveIteratorIterator($di) as $filename => $file) {
    if(!is_dir($filename))
      include_once $filename; //echo $filename . ' - ' . $file->getSize() . ' bytes <br/>';
    }

    return $lang;
}

$lang_array = array('arabic','chinese','english','french','german','italian','japanese','korean','polish','portuguese','russian','spanish','turkish','vietnam'); // List of language folders
$i=1;
$file_arr = array();
$lang1 = $lang2 = $lang3 = $lang4 = $lang5 = $lang6 = $lang7 = $lang8 = $lang9 = $lang10 = $lang11 = $lang12 = $lang13 = $lang14 = '' ;
foreach ($lang_array as $language) {

    ${"lang" . $i} =  load_language('application/language/'.$language);
    export_csv( ${"lang" . $i} , '/xampp/htdocs/CodeIginiter/language',$language);
    // Lang gets filled by the above includes
    $i++;
}

Place the file in the root directory of CodeIgniter and execute. CSV files will get downloaded which can easily export to excel and used for language translators.


问:
Appending text to div using JS
i have a div and i want to use JS to append text to the div. Currently in my code , the text appears but not on the div.

Why is it not appending onto the div panel ?

$('.panel').append(
  '
 ' +
  '
 item.name
' +
  '
'
);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
  <div class="col-md-8">
    <div class="panel" id="panel">
    </div>
  </div>
</div></code>```

答:
```<code>$('.panel').append(
  '<div class="container" style=" width:30%"> ' +
  '<p class="name">'+item.name+'</p>' +
  '</div>'
);
</code>```

Title: Appending text to div using JS