问:
How to persist the list which we made dynamically from dataFrame in scala spark
```<code> def getAnimalName(dataFrame: DataFrame): List[String] = {
    dataFrame.select("animal").
      filter(col("animal").isNotNull && col("animal").notEqual("")).
      rdd.map(r => r.getString(0)).distinct().collect.toList
  }
</code>```

I am basicaly Calling this function 2 times For getting the list for different purposes . I just want to know is there a way to retain the list in memory and we dont have to call the same function again and again to generate the list and only have to generate the list only one time in scala spark.

答:
Try something as below and you can also check the performance using time func.
Also find the code explanation inline

```<code>import org.apache.spark.rdd
import org.apache.spark.sql.functions._
import org.apache.spark.sql.{DataFrame, functions}

object HandleCachedDF {

  var cachedAnimalDF : rdd.RDD[String] = _
  def main(args: Array[String]): Unit = {
    val spark = Constant.getSparkSess
    val df = spark.read.json("src/main/resources/hugeTest.json") // Load your Dataframe
    val df1 = time[rdd.RDD[String]] {
      getAnimalName(df)
    }
    val resultList = df1.collect().toList
    val df2 = time{
      getAnimalName(df)
    }
    val resultList1 = df2.collect().toList
    println(resultList.equals(resultList1))
  }

  def getAnimalName(dataFrame: DataFrame): rdd.RDD[String] = {
    if (cachedAnimalDF == null) { // Check if this the first initialization of your dataframe
      cachedAnimalDF = dataFrame.select("animal").
        filter(functions.col("animal").isNotNull && col("animal").notEqual("")).
        rdd.map(r => r.getString(0)).distinct().cache() // Cache your dataframe
    }
    cachedAnimalDF // Return your cached dataframe
  }

  def time[R](block: => R): R = { // COmpute the time taken by function to execute
    val t0 = System.nanoTime()
    val result = block // call-by-name
    val t1 = System.nanoTime()
    println("Elapsed time: " + (t1 - t0) + "ns")
    result
  }

}

</code>```

Body:
 def getAnimalName(dataFrame: DataFrame): List[String] = {
    dataFrame.select("animal").
      filter(col("animal").isNotNull && col("animal").notEqual("")).
      rdd.map(r => r.getString(0)).distinct().collect.toList
  }

I am basicaly Calling this function 2 times For getting the list for different purposes . I just want to know is there a way to retain the list in memory and we dont have to call the same function again and again to generate the list and only have to generate the list only one time in scala spark.

Body:
Try something as below and you can also check the performance using time func.
Also find the code explanation inline

import org.apache.spark.rdd
import org.apache.spark.sql.functions._
import org.apache.spark.sql.{DataFrame, functions}

object HandleCachedDF {

  var cachedAnimalDF : rdd.RDD[String] = _
  def main(args: Array[String]): Unit = {
    val spark = Constant.getSparkSess
    val df = spark.read.json("src/main/resources/hugeTest.json") // Load your Dataframe
    val df1 = time[rdd.RDD[String]] {
      getAnimalName(df)
    }
    val resultList = df1.collect().toList
    val df2 = time{
      getAnimalName(df)
    }
    val resultList1 = df2.collect().toList
    println(resultList.equals(resultList1))
  }

  def getAnimalName(dataFrame: DataFrame): rdd.RDD[String] = {
    if (cachedAnimalDF == null) { // Check if this the first initialization of your dataframe
      cachedAnimalDF = dataFrame.select("animal").
        filter(functions.col("animal").isNotNull && col("animal").notEqual("")).
        rdd.map(r => r.getString(0)).distinct().cache() // Cache your dataframe
    }
    cachedAnimalDF // Return your cached dataframe
  }

  def time[R](block: => R): R = { // COmpute the time taken by function to execute
    val t0 = System.nanoTime()
    val result = block // call-by-name
    val t1 = System.nanoTime()
    println("Elapsed time: " + (t1 - t0) + "ns")
    result
  }

}


来源: stackexchange

问:
Not able figure out the error in Codewars Growth of a Population kata
I have just tried to attempt some challenges from Codewars. Unfortunately a test out of 106 is failing and I'm not able to find the error since I am new to Python and Codewars.

(see the image)

```<code>import math
def nb_year(p0, percent, aug, p):
    counter = 0
    nw_pop = p0

    while nw_pop <= p:
        nw_pop = math.floor(nw_pop)
        nw_pop = nw_pop + (nw_pop * (percent/100)) + aug
        counter += 1
    return int(counter)

print(nb_year(1500, 5, 100, 5000))
</code>```

51 should equal  50

答:
```<code>def nb_year(p0, percent, aug, p, count = 0):
    if p0 >= p:
        return count
    else:
        count += 1
        n = p0 + p0 * (percent / 100) + aug
        return nb_year(n, percent, aug, p, count)

print(nb_year(1500, 5, 100, 5000))
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have just tried to attempt some challenges from Codewars. Unfortunately a test out of 106 is failing and I'm not able to find the error since I am new to Python and Codewars.

(see the image)

import math
def nb_year(p0, percent, aug, p):
    counter = 0
    nw_pop = p0

    while nw_pop <= p:
        nw_pop = math.floor(nw_pop)
        nw_pop = nw_pop + (nw_pop * (percent/100)) + aug
        counter += 1
    return int(counter)

print(nb_year(1500, 5, 100, 5000))

51 should equal  50


问:
Selenium using Java - The path to the driver executable must be set by the webdriver.gecko.driver system property
I am trying to launch Mozilla but still I am getting this error:

Exception in thread "main" java.lang.IllegalStateException: The path to the driver executable must be set by the webdriver.gecko.driver system property; for more information, see https://github.com/mozilla/geckodriver. The latest version can be downloaded from https://github.com/mozilla/geckodriver/releases

I am using Selenium 3.0.01 Beta version and Mozilla 45. I have tried with Mozilla 47 too. but still the same thing.

答:
I use from selenium-java-3.141.59 in windows 10 and solved my problem with this code:

```<code>System.setProperty("webdriver.gecko.driver", "C:\\gecko\\geckodriver.exe");
System.setProperty("webdriver.firefox.bin","C:\\Program Files\\Mozilla Firefox\\firefox.exe");
WebDriver driver = new FirefoxDriver();
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I use from selenium-java-3.141.59 in windows 10 and solved my problem with this code:

System.setProperty("webdriver.gecko.driver", "C:\\gecko\\geckodriver.exe");
System.setProperty("webdriver.firefox.bin","C:\\Program Files\\Mozilla Firefox\\firefox.exe");
WebDriver driver = new FirefoxDriver();


问:
Test IF file exist, del this local file
This question is related to Test IF file exist, ELSE xcopy these two files.

Background: On occasion I choose to run aGallery-dl.bat in a given folder (just one in each of 100's of folders). It first deletes Folder.jpg then renames Folder2.jpg to Folder.jpg. This has the effect of a red X being replaced by a yellow ! when viewing the folder with parent folder selected in File Explorer. Secondly, it calls gallery-dl.exe. I use going from red X to yellow ! to let me know I've run aGallery-dl.bat at least once. If aGallery-dl.bat completes successfully, it finally deletes the Folder.jpg (currently yellow !), and now the representative contents of the folder (usually DeviantArt .jpg's) are visible. All is well.

```<code>rem @echo off
del .\Folder.jpg
ren .\Folder2.jpg Folder.jpg
FOR /F %%i IN ('cd') DO set FOLDER=%%~nxi
"C:\Program Files (x86)\gallery-dl\gallery-dl.exe" -d "U:\11Web\gallery-dl" --download-archive ".\aGDB.sqlite3" "https://www.deviantart.com/"%FOLDER%"/gallery/all"
del .\Folder.jpg
</code>```

Problem: Restating, Gallery-dl.bat is in each of 100's of folders. On occasion, I run one of these from within it's local folder. Line 5, if the call to the web site is successful, gallery-dl.exe creates zzzGDB.sqlite3 within the local folder.

In the previous code, when aGallery-dl.bat completed, it would just delete the Folder.jpg. This assumes the call to the web page was successful. On rare occasion, the call to the web page will fail for any number of reasons, though at close (due to that final del .\Folder.jpg), it will still delete folder.jpg.

If zzzGDB.sqlite3 was not created/not present, I need the Folder.jpg (yellow !) to remain.

So, in the below code (line 6, now blank), I've lopped off the final del .\Folder.jpg and am trying to plug-in the provided code beginning at line 7, inserting a test for zzzGDB.sqlite. If found, del .\Folder.jpg. If not found, no action is taken against folder.jpg (it remains).

(The rem statement at the very bottom is just acting as a placeholder for my own knowledge.)

```<code>rem @echo off
del .\Folder.jpg
ren .\Folder2.jpg Folder.jpg
FOR /F %%i IN ('cd') DO set FOLDER=%%~nxi
"C:\Program Files (x86)\gallery-dl\gallery-dl.exe" -d "U:\11Web\gallery-dl" --download-archive ".\zzzGDB.sqlite3" "https://www.deviantart.com/"%FOLDER%"/gallery/all"

setlocal EnableExtensions DisableDelayedExpansion
for /D %%I in ("U:\11Web\gallery-dl\deviantart\*") do (
    if exist "%%I\zzzGDB.sqlite3" (
        del "%%I\Folder.jpg"
    )
rem
)
endlocal
</code>```

Note: Currently, the modified code goes back through every single folder within U:\11Web\gallery-dl\deviantart\*. This action should be reserved only to the local folder. I'm guessing the below is the issue.

```<code>for /D %%I in ("U:\11Web\gallery-dl\deviantart\*")
</code>```

I don't know how to remove it and still implement everything after do?

```<code>do (
if exist ".\zzzGDB.sqlite3" (
    del ".\Folder.jpg"
)
rem
)
</code>```

答:
I suggest to use following lines for aGallery-dl.bat.

```<code>@echo off
setlocal EnableExtensions DisableDelayedExpansion
pushd "%~dp0" || exit /B
move /Y "Folder2.jpg" "Folder.jpg"
for %%I in (.) do set "FOLDER=%%~nxI"
"%ProgramFiles(x86)%\gallery-dl\gallery-dl.exe" -d "U:\11Web\gallery-dl" --download-archive "%~dp0zzzGDB.sqlite3" "https://www.deviantart.com/%FOLDER%/gallery/all"
if not errorlevel 1 if exist "zzzGDB.sqlite3" del "Folder.jpg"
popd
endlocal
</code>```

The first two lines define the execution environment for the batch file.

The third line with command PUSHD pushes the current directory path on stack and sets the directory of the executed batch file as current directory. This works even on batch file being stored on a network resource accessed using a UNC path, except there is a network problem on execution of that command line.

The command exit /B is executed in case of an error to immediately exit processing of the batch file on batch file directory could not be set as current directory. The Windows command processor runs implicitly the command ENDLOCAL in this case.

See Single line with multiple commands using Windows batch file for an explanation of operator || which results in conditionally executing exit /B only if pushd exited with a non-zero exit code indicating an error.

The fourth command line with MOVE does not really move the data of file Folder2.jpg to file with name Folder.jpg. In real it just updates the file system in this case as done also by the two commands del .\Folder.jpg and ren .\Folder2.jpg Folder.jpg in your batch file. This is just a very little bit faster method to replace one file by another file with the advantage that Folder.jpg must not exist at all for success without displaying an error message as done by command DEL on file Folder.jpg not existing.

The FOR command line determines the name of the current folder without path and assigns it to environment variable FOLDER. This is a much faster and safer solution then using the command line:

```<code>FOR /F %%i IN ('cd') DO set FOLDER=%%~nxi
</code>```

The command line above results in starting in background one more command process with %ComSpec% /c and the command line between ' appended as additional arguments. So there is executed in background with Windows installed to C:\Windows:

```<code>C:\Windows\System32\cmd.exe /c cd
</code>```

The started cmd.exe executes internal command cd which outputs the full qualified folder name of current directory to handle STDOUT of background command process. This output is captured by cmd.exe processing the batch file and is processed by for after started cmd.exe closed itself after finishing execution of command CD.

The command FOR would split up the folder path into substrings (tokens) using normal space and horizontal tab as string delimiters, would look next if the first space/tab delimited string starts with a semicolon in which case the captured line would be ignored for further processing, and would assign otherwise just the first space/tab delimited string to loop variable i. So if the full qualified folder name of current directory would contain a space, this command line would fail to determine the folder name of current directory without path.

There is the dynamic variable CD of which value can be referenced with %CD%. The value is the full qualified folder name of current directory not ending with a backslash, except the root directory of a drive is the current directory. That would be identical to %~dp0 for batch file aGallery-dl.bat with the difference that %~dp0 expands to full qualified name of batch file folder always with a backslash at end.

However, neither dynamic variable CD nor %~dp0 nor execution of command CD in a separate command process in background are really useful to get name of current directory (= batch file directory) without path. The best method is using:

```<code>for %%I in (.) do set "FOLDER=%%~nxI"
</code>```

This simple FOR does nothing else than getting name of current folder without path with a very fast executed file system query and assigning it to environment variable FOLDER.

Note: for %%I in ("%~dp0.") do set "FOLDER=%%~nxI" could be also used to get folder name without path of folder containing currently executed batch file if the current directory would not be the batch file directory.

The sixth command line executes gallery-dl.exe with various parameters (arguments).

Please note that "https://www.deviantart.com/"%FOLDER%"/gallery/all" is in real an invalid argument string. It is not valid to have " inside a URL. The character " is never valid inside an argument string which references a file or folder. This syntax error is detected and automatically fixed which is the reason why the command line in your batch file works at all. The correct argument string is "https://www.deviantart.com/%FOLDER%/gallery/all" with one " at beginning and one " at end and no double quote inside the argument string enclosed in double quotes.

There is standard for console applications to exit with value 0 on success and a greater value like 1 on an error. I don't know if this is true also for gallery-dl.exe, but I assume that with the command line:

```<code>if not errorlevel 1 if exist "zzzGDB.sqlite3" del "Folder.jpg"
</code>```

if not errorlevel 1 checks if exit code of gallery-dl.exe assigned to dynamic variable errorlevel is NOT greater or equal 1 which means less than 1 which means equal 0 (on executable never exiting with a negative value which is not recommended to do by a program on any operating system) which means no error occurred during execution of gallery-dl.exe. Please read the documentation of gallery-dl.exe regarding to exit codes of this program or find it out with several executions in a command prompt window and using echo Exit code is: %errorlevel% after each execution of gallery-dl.exe with success or an error (like a wrong URL).

That condition should be already enough. But there is used one more condition to check for existence of the file zzzGDB.sqlite3 in current directory only before deleting the file Folder.jpg in the current directory which is the batch file directory.

Please read issue 2 in this answer for the reason writing in batch file

```<code>if not errorlevel 1 if exist "zzzGDB.sqlite3" del "Folder.jpg"
</code>```

instead of

```<code>if not errorlevel 1 (
    if exist "zzzGDB.sqlite3" (
        del "Folder.jpg"
    )
)
</code>```

The code above works also, but requires more CPU cycles for being processed by Windows command processor than the single line with two IF commands and one DEL command on one command line.

The last but one line pops the full qualified folder name of initial current directory from stack and sets it again as current directory and the last line restores initial execution environment on starting the batch file.

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

call /?... explains %~dp0 ... drive and path of argument 0 ... full batch file path.

del /?

echo /?

endlocal /?

exit /?

for /?

move /?

popd /?

pushd /?

set /?

setlocal /?

Title: Test IF file exist, del this local file

Body:
This question is related to Test IF file exist, ELSE xcopy these two files.

Background: On occasion I choose to run aGallery-dl.bat in a given folder (just one in each of 100's of folders). It first deletes Folder.jpg then renames Folder2.jpg to Folder.jpg. This has the effect of a red X being replaced by a yellow ! when viewing the folder with parent folder selected in File Explorer. Secondly, it calls gallery-dl.exe. I use going from red X to yellow ! to let me know I've run aGallery-dl.bat at least once. If aGallery-dl.bat completes successfully, it finally deletes the Folder.jpg (currently yellow !), and now the representative contents of the folder (usually DeviantArt .jpg's) are visible. All is well.

rem @echo off
del .\Folder.jpg
ren .\Folder2.jpg Folder.jpg
FOR /F %%i IN ('cd') DO set FOLDER=%%~nxi
"C:\Program Files (x86)\gallery-dl\gallery-dl.exe" -d "U:\11Web\gallery-dl" --download-archive ".\aGDB.sqlite3" "https://www.deviantart.com/"%FOLDER%"/gallery/all"
del .\Folder.jpg

Problem: Restating, Gallery-dl.bat is in each of 100's of folders. On occasion, I run one of these from within it's local folder. Line 5, if the call to the web site is successful, gallery-dl.exe creates zzzGDB.sqlite3 within the local folder.

In the previous code, when aGallery-dl.bat completed, it would just delete the Folder.jpg. This assumes the call to the web page was successful. On rare occasion, the call to the web page will fail for any number of reasons, though at close (due to that final del .\Folder.jpg), it will still delete folder.jpg.

If zzzGDB.sqlite3 was not created/not present, I need the Folder.jpg (yellow !) to remain.

So, in the below code (line 6, now blank), I've lopped off the final del .\Folder.jpg and am trying to plug-in the provided code beginning at line 7, inserting a test for zzzGDB.sqlite. If found, del .\Folder.jpg. If not found, no action is taken against folder.jpg (it remains).

(The rem statement at the very bottom is just acting as a placeholder for my own knowledge.)

rem @echo off
del .\Folder.jpg
ren .\Folder2.jpg Folder.jpg
FOR /F %%i IN ('cd') DO set FOLDER=%%~nxi
"C:\Program Files (x86)\gallery-dl\gallery-dl.exe" -d "U:\11Web\gallery-dl" --download-archive ".\zzzGDB.sqlite3" "https://www.deviantart.com/"%FOLDER%"/gallery/all"

setlocal EnableExtensions DisableDelayedExpansion
for /D %%I in ("U:\11Web\gallery-dl\deviantart\*") do (
    if exist "%%I\zzzGDB.sqlite3" (
        del "%%I\Folder.jpg"
    )
rem
)
endlocal

Note: Currently, the modified code goes back through every single folder within U:\11Web\gallery-dl\deviantart\*. This action should be reserved only to the local folder. I'm guessing the below is the issue.

for /D %%I in ("U:\11Web\gallery-dl\deviantart\*")

I don't know how to remove it and still implement everything after do?

do (
if exist ".\zzzGDB.sqlite3" (
    del ".\Folder.jpg"
)
rem
)

Body:
I suggest to use following lines for aGallery-dl.bat.

@echo off
setlocal EnableExtensions DisableDelayedExpansion
pushd "%~dp0" || exit /B
move /Y "Folder2.jpg" "Folder.jpg"
for %%I in (.) do set "FOLDER=%%~nxI"
"%ProgramFiles(x86)%\gallery-dl\gallery-dl.exe" -d "U:\11Web\gallery-dl" --download-archive "%~dp0zzzGDB.sqlite3" "https://www.deviantart.com/%FOLDER%/gallery/all"
if not errorlevel 1 if exist "zzzGDB.sqlite3" del "Folder.jpg"
popd
endlocal

The first two lines define the execution environment for the batch file.

The third line with command PUSHD pushes the current directory path on stack and sets the directory of the executed batch file as current directory. This works even on batch file being stored on a network resource accessed using a UNC path, except there is a network problem on execution of that command line.

The command exit /B is executed in case of an error to immediately exit processing of the batch file on batch file directory could not be set as current directory. The Windows command processor runs implicitly the command ENDLOCAL in this case.

See Single line with multiple commands using Windows batch file for an explanation of operator || which results in conditionally executing exit /B only if pushd exited with a non-zero exit code indicating an error.

The fourth command line with MOVE does not really move the data of file Folder2.jpg to file with name Folder.jpg. In real it just updates the file system in this case as done also by the two commands del .\Folder.jpg and ren .\Folder2.jpg Folder.jpg in your batch file. This is just a very little bit faster method to replace one file by another file with the advantage that Folder.jpg must not exist at all for success without displaying an error message as done by command DEL on file Folder.jpg not existing.

The FOR command line determines the name of the current folder without path and assigns it to environment variable FOLDER. This is a much faster and safer solution then using the command line:

FOR /F %%i IN ('cd') DO set FOLDER=%%~nxi

The command line above results in starting in background one more command process with %ComSpec% /c and the command line between ' appended as additional arguments. So there is executed in background with Windows installed to C:\Windows:

C:\Windows\System32\cmd.exe /c cd

The started cmd.exe executes internal command cd which outputs the full qualified folder name of current directory to handle STDOUT of background command process. This output is captured by cmd.exe processing the batch file and is processed by for after started cmd.exe closed itself after finishing execution of command CD.

The command FOR would split up the folder path into substrings (tokens) using normal space and horizontal tab as string delimiters, would look next if the first space/tab delimited string starts with a semicolon in which case the captured line would be ignored for further processing, and would assign otherwise just the first space/tab delimited string to loop variable i. So if the full qualified folder name of current directory would contain a space, this command line would fail to determine the folder name of current directory without path.

There is the dynamic variable CD of which value can be referenced with %CD%. The value is the full qualified folder name of current directory not ending with a backslash, except the root directory of a drive is the current directory. That would be identical to %~dp0 for batch file aGallery-dl.bat with the difference that %~dp0 expands to full qualified name of batch file folder always with a backslash at end.

However, neither dynamic variable CD nor %~dp0 nor execution of command CD in a separate command process in background are really useful to get name of current directory (= batch file directory) without path. The best method is using:

for %%I in (.) do set "FOLDER=%%~nxI"

This simple FOR does nothing else than getting name of current folder without path with a very fast executed file system query and assigning it to environment variable FOLDER.

Note: for %%I in ("%~dp0.") do set "FOLDER=%%~nxI" could be also used to get folder name without path of folder containing currently executed batch file if the current directory would not be the batch file directory.

The sixth command line executes gallery-dl.exe with various parameters (arguments).

Please note that "https://www.deviantart.com/"%FOLDER%"/gallery/all" is in real an invalid argument string. It is not valid to have " inside a URL. The character " is never valid inside an argument string which references a file or folder. This syntax error is detected and automatically fixed which is the reason why the command line in your batch file works at all. The correct argument string is "https://www.deviantart.com/%FOLDER%/gallery/all" with one " at beginning and one " at end and no double quote inside the argument string enclosed in double quotes.

There is standard for console applications to exit with value 0 on success and a greater value like 1 on an error. I don't know if this is true also for gallery-dl.exe, but I assume that with the command line:

if not errorlevel 1 if exist "zzzGDB.sqlite3" del "Folder.jpg"

if not errorlevel 1 checks if exit code of gallery-dl.exe assigned to dynamic variable errorlevel is NOT greater or equal 1 which means less than 1 which means equal 0 (on executable never exiting with a negative value which is not recommended to do by a program on any operating system) which means no error occurred during execution of gallery-dl.exe. Please read the documentation of gallery-dl.exe regarding to exit codes of this program or find it out with several executions in a command prompt window and using echo Exit code is: %errorlevel% after each execution of gallery-dl.exe with success or an error (like a wrong URL).

That condition should be already enough. But there is used one more condition to check for existence of the file zzzGDB.sqlite3 in current directory only before deleting the file Folder.jpg in the current directory which is the batch file directory.

Please read issue 2 in this answer for the reason writing in batch file

if not errorlevel 1 if exist "zzzGDB.sqlite3" del "Folder.jpg"

instead of

if not errorlevel 1 (
    if exist "zzzGDB.sqlite3" (
        del "Folder.jpg"
    )
)

The code above works also, but requires more CPU cycles for being processed by Windows command processor than the single line with two IF commands and one DEL command on one command line.

The last but one line pops the full qualified folder name of initial current directory from stack and sets it again as current directory and the last line restores initial execution environment on starting the batch file.

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

call /?... explains %~dp0 ... drive and path of argument 0 ... full batch file path.

del /?

echo /?

endlocal /?

exit /?

for /?

move /?

popd /?

pushd /?

set /?

setlocal /?


问:
How to download specific Google Drive folder using Python?
I'm trying to download specific folders from Google Drive.

I tried this example
http://www.mwclearning.com/?p=1608 but its download all the files from G-Drive.

EX: If I have two folders in Google Drive say..

A folder having -> 1 , 2 Files

B folder having -> 3, 4, 5 Files

If I want to download folder A then only 1 , 2 files should get downloaded..

Any suggestion or help could be very helpful.

Thanks in advance.

答:
Please do download the 'client_id.json' file as specified in the tutorial link for downloading follow steps 5-7

In the last line of the code change the "folder_id" to the id of the folder you want to download from drive by right clicking on the folder and enabling share link. The id will be the part of URL after "id=" and also changing the "savepath" to the path where you want to save the downloaded folder to be on your system.

```<code>from __future__ import print_function

from googleapiclient import discovery
from httplib2 import Http
from oauth2client import file, client, tools
import os, io
from apiclient.http import MediaFileUpload, MediaIoBaseDownload

SCOPES = 'https://www.googleapis.com/auth/drive'
store = file.Storage('storage.json')
creds = store.get()
if not creds or creds.invalid:
    flow = client.flow_from_clientsecrets('client_id.json', SCOPES)
    creds = tools.run_flow(flow, store)
DRIVE = discovery.build('drive', 'v3', http=creds.authorize(Http()))

def retaining_folder_structure(query,filepath):
    results = DRIVE.files().list(fields="nextPageToken, files(id, name, kind, mimeType)",q=query).execute()
    items = results.get('files', [])
    for item in items:
        #print(item['name'])
        if item['mimeType']=='application/vnd.google-apps.folder':
            fold=item['name']
            path=filepath+'/'+fold
            if os.path.isdir(path):
                retaining_folder_structure("'%s' in parents"%(item['id']),path)
            else:
                os.mkdir(path)
                retaining_folder_structure("'%s' in parents"%(item['id']),path)
        else:
            request = DRIVE.files().get_media(fileId=item['id'])
            fh = io.BytesIO()
            downloader = MediaIoBaseDownload(fh, request)
            done = False
            while done is False:
                status, done = downloader.next_chunk()
                print("Download %d%%." % int(status.progress() * 100))
            path=filepath+'/'+item['name']
            #print(path)
            with io.open(path,'wb') as f:
                fh.seek(0)
                f.write(fh.read())

retaining_floder_structure("'folder_id' in parents",'savepath')
</code>```

Body:
Please do download the 'client_id.json' file as specified in the tutorial link for downloading follow steps 5-7

In the last line of the code change the "folder_id" to the id of the folder you want to download from drive by right clicking on the folder and enabling share link. The id will be the part of URL after "id=" and also changing the "savepath" to the path where you want to save the downloaded folder to be on your system.

from __future__ import print_function

from googleapiclient import discovery
from httplib2 import Http
from oauth2client import file, client, tools
import os, io
from apiclient.http import MediaFileUpload, MediaIoBaseDownload

SCOPES = 'https://www.googleapis.com/auth/drive'
store = file.Storage('storage.json')
creds = store.get()
if not creds or creds.invalid:
    flow = client.flow_from_clientsecrets('client_id.json', SCOPES)
    creds = tools.run_flow(flow, store)
DRIVE = discovery.build('drive', 'v3', http=creds.authorize(Http()))

def retaining_folder_structure(query,filepath):
    results = DRIVE.files().list(fields="nextPageToken, files(id, name, kind, mimeType)",q=query).execute()
    items = results.get('files', [])
    for item in items:
        #print(item['name'])
        if item['mimeType']=='application/vnd.google-apps.folder':
            fold=item['name']
            path=filepath+'/'+fold
            if os.path.isdir(path):
                retaining_folder_structure("'%s' in parents"%(item['id']),path)
            else:
                os.mkdir(path)
                retaining_folder_structure("'%s' in parents"%(item['id']),path)
        else:
            request = DRIVE.files().get_media(fileId=item['id'])
            fh = io.BytesIO()
            downloader = MediaIoBaseDownload(fh, request)
            done = False
            while done is False:
                status, done = downloader.next_chunk()
                print("Download %d%%." % int(status.progress() * 100))
            path=filepath+'/'+item['name']
            #print(path)
            with io.open(path,'wb') as f:
                fh.seek(0)
                f.write(fh.read())

retaining_floder_structure("'folder_id' in parents",'savepath')


问:
Statement-Level Read Consistency in various SQL/NoSQL DBs
Recently I was thinking about query consistency in various SQL and NoSQL databases. What happens, when I have a (long running) query and rows are inserted or updated while the query is running? A simple theoretic example:

Let’s assume the following query takes a long time:

```<code>SELECT SUM(salary) FROM emp;
</code>```

And while this query is running, another transaction does:

```<code>UPDATE emp SET salary = salary * 1.05 WHERE salary > 10000;
COMMIT;
</code>```

When the SUM query has read half of the updated employees before the update, and the other half after the update, I would get an inconsistent nonsense result. Does this phenomenon have a name? By definition, it is not really a phantom read, because just one query is involved.

How do various DBs handle this situation? I am especially interested in SQL Server, MongoDB, RavenDB and Azure Table Storage.

Oracle for example guarantees statement-level read consistency, which says that the data returned by a single query is committed and consistent for a single point in time.

UPDATE: SQL Server seems to only prevent this kind of problem when READ_COMMITTED_SNAPSHOT is set to ON.

答:
I believe the term you're looking for is "Dirty Read"

I can answer this one for SQL server.
You get 5 options for transaction isolation level, where the default is READ COMMITTED.

Only READ UNCOMMITTED allows dirty reads. You'll have to specifically enable that using SET TRANSACTION LEVEL READ UNCOMMITTED.

READ UNCOMMITTED is equivalent to NOLOCK, but syntactically nicer (opinion) as it doesn't need to be repeated for each table in your query.

Possible isolation levels are as below. I've linked the docs for more detail, if future readers find the link stale please edit.
https://learn.microsoft.com/en-us/sql/t-sql/statements/set-transaction-isolation-level-transact-sql

READ UNCOMMITTED

READ COMMITTED

REPEATABLE READ

SNAPSHOT

SERIALIZABLE

Body:
Recently I was thinking about query consistency in various SQL and NoSQL databases. What happens, when I have a (long running) query and rows are inserted or updated while the query is running? A simple theoretic example:

Let’s assume the following query takes a long time:

SELECT SUM(salary) FROM emp;

And while this query is running, another transaction does:

UPDATE emp SET salary = salary * 1.05 WHERE salary > 10000;
COMMIT;

When the SUM query has read half of the updated employees before the update, and the other half after the update, I would get an inconsistent nonsense result. Does this phenomenon have a name? By definition, it is not really a phantom read, because just one query is involved.

How do various DBs handle this situation? I am especially interested in SQL Server, MongoDB, RavenDB and Azure Table Storage.

Oracle for example guarantees statement-level read consistency, which says that the data returned by a single query is committed and consistent for a single point in time.

UPDATE: SQL Server seems to only prevent this kind of problem when READ_COMMITTED_SNAPSHOT is set to ON.


问:
Host...not allowed error in ODBC connection, while connecting to an online MySQL database
I have downloaded MySQL ODBC Connector 5.1. Now am trying to setup the DSN. But am getting the error:

Connection Failed : [HY000] [MySQL] [ODBC 5.1 Driver]Host '117.x.x.x' is not allowed to connect to this MySQL server

My server url is server.myweb.com - this name am entering in the TCP/IP Server and Port =3306.

I have also entered the userid and password , which is the one which i enter when i open www.myweb.com/cpanel

Is this a version problem? Should the version of MySQL on my server also be 5.1, i.e. the one of the ODBC?

Please help.

答: It is not a version or ODBC problem. This error says there is no user with specified host name. Read more information in MySQL reference - http://dev.mysql.com/doc/refman/5.1/en/grant.html#grant-accounts-passwords</p>


问:
Typescript infer that field is truthy(cannot be undefined), without user-defined type guards
```<code>type Item = {
    left?: { photoSrc: string };
};

type ItemRequired = {
    left: { photoSrc: string };
};

const item: Item = {} as any;

if (item.left) {
    const itemRequired: ItemRequired = item; // fails. Typescript still says left may be undefined
    // I'd like Typescript to know that field left is truthy
}
</code>```

I know about user-defined type guards. E.g.

```<code>function isFish(pet: Fish | Bird): pet is Fish {
  return (pet as Fish).swim !== undefined;
}
</code>```

My questions:

Why is Typescript unable to infer that left cannot be undefined?

Does that mean I need to create a type guard function for every variation of a type I need to check? Isn't there a simpler way? E.g. I expect when inside the scope of an if check that proves that left field cannot be undefined, I expect Typescript to know that.

This seems like a very common case, but I couldn't find the answer, please excuse me if there is one.

答:
At the moment, Typescript does not infer types from the conditional flow of statements.

```<code>const item: Item = {} as any;
if (item.left) {
    const itemRequired: ItemRequired = item;
}
</code>```

As a result, the above code block does not actually narrow the item type from Item to ItemRequired. Hence, to the compiler, you are trying to assign two incompatible types - one where left is mandatory and other where it is optional.

An alternative, as you mentioned, you can write a type guard or simply, you can do the following.

```<code>const itemRequired: ItemRequired = item as ItemRequired;
</code>```

However, writing type guards is always recommended.

Body:
type Item = {
    left?: { photoSrc: string };
};

type ItemRequired = {
    left: { photoSrc: string };
};

const item: Item = {} as any;

if (item.left) {
    const itemRequired: ItemRequired = item; // fails. Typescript still says left may be undefined
    // I'd like Typescript to know that field left is truthy
}

I know about user-defined type guards. E.g.

function isFish(pet: Fish | Bird): pet is Fish {
  return (pet as Fish).swim !== undefined;
}

My questions:

Why is Typescript unable to infer that left cannot be undefined?

Does that mean I need to create a type guard function for every variation of a type I need to check? Isn't there a simpler way? E.g. I expect when inside the scope of an if check that proves that left field cannot be undefined, I expect Typescript to know that.

This seems like a very common case, but I couldn't find the answer, please excuse me if there is one.

Body:
At the moment, Typescript does not infer types from the conditional flow of statements.

const item: Item = {} as any;
if (item.left) {
    const itemRequired: ItemRequired = item;
}

As a result, the above code block does not actually narrow the item type from Item to ItemRequired. Hence, to the compiler, you are trying to assign two incompatible types - one where left is mandatory and other where it is optional.

An alternative, as you mentioned, you can write a type guard or simply, you can do the following.

const itemRequired: ItemRequired = item as ItemRequired;

However, writing type guards is always recommended.


问:
How do I make 2 lists correspond to each other?
I have 2 lists here:

```<code>list1 = [happy, sad, grumpy, mad]
list2 = [2, 5, 6, 9]
</code>```

I want to make it so that the numbers are assigned to the emotions? (happy is equal to 2, sad is equal to 5, etc). Ideally, I want to make it so you can compare items from list1, for example:

```<code>if happy > sad:
    print ("you are happy")
</code>```

I want to make this code as efficient as possible, so I do not want to separately assign each variable from list1 a number.

答:
If you don't want to use a dictionary, you can use exec function.

```<code>list1 = ['happy', 'sad', 'grumpy', 'mad']
list2 = [2, 5, 6, 9]

for L,i in zip(list1,list2):
  exec('{}={}'.format(L,i))

if happy > sad:
  print ("you are happy")
</code>```

Notice here that you must use strings to name the variables (you can't have a list of unassigned variables).

Body:
I have 2 lists here:

list1 = [happy, sad, grumpy, mad]
list2 = [2, 5, 6, 9]

I want to make it so that the numbers are assigned to the emotions? (happy is equal to 2, sad is equal to 5, etc). Ideally, I want to make it so you can compare items from list1, for example:

if happy > sad:
    print ("you are happy")

I want to make this code as efficient as possible, so I do not want to separately assign each variable from list1 a number.

Body:
If you don't want to use a dictionary, you can use exec function.

list1 = ['happy', 'sad', 'grumpy', 'mad']
list2 = [2, 5, 6, 9]

for L,i in zip(list1,list2):
  exec('{}={}'.format(L,i))

if happy > sad:
  print ("you are happy")

Notice here that you must use strings to name the variables (you can't have a list of unassigned variables).


问:
Why my YouTube video downloader only downloads some videos and for other videos it shows keyerror like URL and cipher?
I am trying to make a YouTube video downloader using Python pytube3 but it doesn't download all the videos. Some videos download very easily but some videos won't download and instead of download it shows error:</p>

```<code>Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\tarun\PycharmProjects\YTDownloader\venv\lib\site-packages\pytube\extract.py", line 297, in apply_descrambler
    for format_item in formats
  File "C:\Users\tarun\PycharmProjects\YTDownloader\venv\lib\site-packages\pytube\extract.py", line 297, in <listcomp>
    for format_item in formats
KeyError: 'url'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\tarun\AppData\Local\Programs\Python\Python37-32\lib\tkinter\__init__.py", line 1705, in __call__
    return self.func(*args)
  File "C:/Users/tarun/PycharmProjects/YTDownloader/YTD.py", line 15, in video_download
    my_video = YouTube(input_user)
  File "C:\Users\tarun\PycharmProjects\YTDownloader\venv\lib\site-packages\pytube\__main__.py", line 92, in __init__
    self.descramble()
  File "C:\Users\tarun\PycharmProjects\YTDownloader\venv\lib\site-packages\pytube\__main__.py", line 132, in descramble
    apply_descrambler(self.player_config_args, fmt)
  File "C:\Users\tarun\PycharmProjects\YTDownloader\venv\lib\site-packages\pytube\extract.py", line 301, in apply_descrambler
    parse_qs(formats[i]["cipher"]) for i, data in enumerate(formats)
  File "C:\Users\tarun\PycharmProjects\YTDownloader\venv\lib\site-packages\pytube\extract.py", line 301, in <listcomp>
    parse_qs(formats[i]["cipher"]) for i, data in enumerate(formats)
KeyError: 'cipher'
</code>```

答:
This is an error in the file extract.py from pytube.

Go to the location where the package was installed. If you don't know where, run the command

```<code>pip show pytube3
</code>```

And it'll give you something like this:

We can see Location: c:\users\tiago\anaconda3\lib\site-packages.

Go to that location, open the folder pytube and the file extract.py

In the file, line no. 306 or 301, you will find parse_qs(formats[i]["cipher"]). If yes, then change "cipher" to "signatureCipher" (make sure 'C' is capital).

So, you'll initially have

```<code> cipher_url = [
                 parse_qs(formats[i]["cipher"]) for i, data in enumerate(formats)
             ]
</code>```

but it should be

```<code> cipher_url = [
                 parse_qs(formats[i]["signatureCipher"]) for i, data in enumerate(formats)
             ]
</code>```

Run the following script to see it working

```<code> # -*- coding: utf-8 -*-
 """
 Created on Mon Jun 15 12:21:49 2020

 @author: tiago
 """
 from pytube import YouTube

 video_url = "https://youtu.be/gp5tziO5lXg" # YouTube video URL
 youtube = YouTube(video_url)
 video = youtube.streams.first()
 video.download("C:/Users/tiago/Desktop/videos/") # Path where to store the video
</code>```

You'll then see the video downloaded in that folder

Body:
I am trying to make a YouTube video downloader using Python pytube3 but it doesn't download all the videos. Some videos download very easily but some videos won't download and instead of download it shows error:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\tarun\PycharmProjects\YTDownloader\venv\lib\site-packages\pytube\extract.py", line 297, in apply_descrambler
    for format_item in formats
  File "C:\Users\tarun\PycharmProjects\YTDownloader\venv\lib\site-packages\pytube\extract.py", line 297, in <listcomp>
    for format_item in formats
KeyError: 'url'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\tarun\AppData\Local\Programs\Python\Python37-32\lib\tkinter\__init__.py", line 1705, in __call__
    return self.func(*args)
  File "C:/Users/tarun/PycharmProjects/YTDownloader/YTD.py", line 15, in video_download
    my_video = YouTube(input_user)
  File "C:\Users\tarun\PycharmProjects\YTDownloader\venv\lib\site-packages\pytube\__main__.py", line 92, in __init__
    self.descramble()
  File "C:\Users\tarun\PycharmProjects\YTDownloader\venv\lib\site-packages\pytube\__main__.py", line 132, in descramble
    apply_descrambler(self.player_config_args, fmt)
  File "C:\Users\tarun\PycharmProjects\YTDownloader\venv\lib\site-packages\pytube\extract.py", line 301, in apply_descrambler
    parse_qs(formats[i]["cipher"]) for i, data in enumerate(formats)
  File "C:\Users\tarun\PycharmProjects\YTDownloader\venv\lib\site-packages\pytube\extract.py", line 301, in <listcomp>
    parse_qs(formats[i]["cipher"]) for i, data in enumerate(formats)
KeyError: 'cipher'

Body:
This is an error in the file extract.py from pytube.

Go to the location where the package was installed. If you don't know where, run the command

pip show pytube3

And it'll give you something like this:

We can see Location: c:\users\tiago\anaconda3\lib\site-packages.

Go to that location, open the folder pytube and the file extract.py

In the file, line no. 306 or 301, you will find parse_qs(formats[i]["cipher"]). If yes, then change "cipher" to "signatureCipher" (make sure 'C' is capital).

So, you'll initially have

 cipher_url = [
                 parse_qs(formats[i]["cipher"]) for i, data in enumerate(formats)
             ]

but it should be

 cipher_url = [
                 parse_qs(formats[i]["signatureCipher"]) for i, data in enumerate(formats)
             ]

Run the following script to see it working

 # -*- coding: utf-8 -*-
 """
 Created on Mon Jun 15 12:21:49 2020

 @author: tiago
 """
 from pytube import YouTube

 video_url = "https://youtu.be/gp5tziO5lXg" # YouTube video URL
 youtube = YouTube(video_url)
 video = youtube.streams.first()
 video.download("C:/Users/tiago/Desktop/videos/") # Path where to store the video

You'll then see the video downloaded in that folder


问:
Laravel, Using a cPanel shared hosting if possible?
I have a shared hosting with bluehost.com... can I just put my project on that.. like upload public files to public_html and others to root directory and backup MySQL DB and upload it to my shared hosting then edit my .env file... will this actually work with Laravel?

I searched most online resources and it requires ssh access to deploy, but the way I explained should not require that right?

I mean this way you don't have to go throw terminal access right?

I used to do that with WordPress when I want to set everything locally then upload it and edit URLs from the dashboard and stuff...

答:
Yes it would work.
But you have to ensure one thing that, in your cpanel your domain point to the /public folder of laravel project.
Normally cPanel points the http requests to public_html folder, but laravel start from its public folder. You can achieve this by two way.

By pointing your server to straight to public folder

Copying the index.php to the public_html, in that case you have to edit index.php to run the laravel project properly. And I don't recommend this step. Step 1 is lot more easier.


问:
The setup for this installation of visual studio is not complete, really?
I have been using Vs 2017 for several months on dev machine. This fine morning says setup incomplete. Am I missing something?

答: I was using Vs 2019 professional 16.6 and happened to me this issue one morning. I modified the installation  by adding Azure Development tools even though I was not using it. This fixed the issue.</p>


问:
Add shared libraries references to enterprise applications whith Jython in Websphere application server
I would like to programmatically add the shared libraries to my deployed applications in websphere application server (WAS).

I heard that it is possible using jython scripting.

How can I achieve this?

Can someone give some pratical example?

答:
You can do this with the following script:

```<code># Map shared library
AdminApp.edit('ApplicationName', ['-MapSharedLibForMod', [['.*', '.*', 'SharedLibName']]])

# Save configuration
AdminConfig.save()

# Synchronize nodes (if you don't have standalone server but network deployment)
Sync1 = AdminControl.completeObjectName('type=NodeSync,node=*,*')
AdminControl.invoke(Sync1, 'sync')
</code>```

I am using this method and it works.

Body:
You can do this with the following script:

# Map shared library
AdminApp.edit('ApplicationName', ['-MapSharedLibForMod', [['.*', '.*', 'SharedLibName']]])

# Save configuration
AdminConfig.save()

# Synchronize nodes (if you don't have standalone server but network deployment)
Sync1 = AdminControl.completeObjectName('type=NodeSync,node=*,*')
AdminControl.invoke(Sync1, 'sync')

I am using this method and it works.


问:
Is using a class which sole purpose is to group 2 (very much related) objects together considered a good idea?
I can't find any information on this anywhere and was wondering whether such a use of a class is considered bad practise or not.

Let me explain. I have a class ToDecimalConverter which converts an integer from any base to decimal. However, I now need to add the functionality to also convert fractions. As such, I abstracted the integer conversion into a separate class and created a new class with the purpose of converting fractions. (Code isn't finished so I just added some comments to explain)

```<code>public class ToDecimalConverter {
    private IntegerToDecimalConverter integerConverter;
    private DoubleToDecimalConverter doubleConverter;

    public double convert(String number, int baseNumber) {
        this.integerConverter = new IntegerToDecimalConverter();
        this.doubleConverter = new DoubleToDecimalConverter();

        number = this.removeZerosAtBeginningOfNumber(number);

        // split the number into integer and fraction so they can be used below:

        int decimalInt = this.integerConverter.convert(integerNumber, baseNumber);
        double decimalDouble = this.doubleConverter.convert(fractioNumber, baseNumber);

        // add them together and return them
    }
}

</code>```

Now, except for the methods that remove the zero's from the start of a number and the method that splits the number into integer and fraction (both of which can easily be abstracted into their own class), the ToDecimalConverter class does nothing but group the integer and fraction converters together.

When searching online, I don't see a lot of classes being used like this. Should this be avoided or not? and if so, what are alternatives?

This meant as a more general question, the above is just to explain what I mean.

Edit: Or should I see it as a sort of mini GoF Facade pattern?

答:
Not going into the specifics of what your class is doing, there indeed value in grouping several or many function/classes together to from a single unified API.

This is called the Facade design pattern.

The intent is that instead of relying on your client to have to know of the various classes/objects you use internally to achieve a feature and to have to look all over the place inside your implementation code is that you put in place a single entry point for given feature/set of feature. It is much better for discoverability & documentation.

Also this way, you ensure to only provide the public API that is only one or a few classes that make the facade while the implementation remains hidden and can change at any time.

Body:
I can't find any information on this anywhere and was wondering whether such a use of a class is considered bad practise or not.

Let me explain. I have a class ToDecimalConverter which converts an integer from any base to decimal. However, I now need to add the functionality to also convert fractions. As such, I abstracted the integer conversion into a separate class and created a new class with the purpose of converting fractions. (Code isn't finished so I just added some comments to explain)

public class ToDecimalConverter {
    private IntegerToDecimalConverter integerConverter;
    private DoubleToDecimalConverter doubleConverter;

    public double convert(String number, int baseNumber) {
        this.integerConverter = new IntegerToDecimalConverter();
        this.doubleConverter = new DoubleToDecimalConverter();

        number = this.removeZerosAtBeginningOfNumber(number);

        // split the number into integer and fraction so they can be used below:

        int decimalInt = this.integerConverter.convert(integerNumber, baseNumber);
        double decimalDouble = this.doubleConverter.convert(fractioNumber, baseNumber);

        // add them together and return them
    }
}

Now, except for the methods that remove the zero's from the start of a number and the method that splits the number into integer and fraction (both of which can easily be abstracted into their own class), the ToDecimalConverter class does nothing but group the integer and fraction converters together.

When searching online, I don't see a lot of classes being used like this. Should this be avoided or not? and if so, what are alternatives?

This meant as a more general question, the above is just to explain what I mean.

Edit: Or should I see it as a sort of mini GoF Facade pattern?


问:
Why does numpy.corrcoef() returns nan?
Trying to build a regression model, but got a problem I can't solve.
Have googled and read everything about it but nothing works. Have this dataframe:

```<code><class 'pandas.core.frame.DataFrame'>
RangeIndex: 334195 entries, 0 to 334194
Data columns (total 12 columns):
type         334195 non-null int64
zipcode      334195 non-null int64
sqft         334195 non-null float64
lotsize      334195 non-null float64
beds         334195 non-null float64
baths        334195 non-null float64
year         334195 non-null float64
s_num        334195 non-null int64
s_rate       334195 non-null float64
s_dist       334195 non-null float64
crimes       334195 non-null float64
target       334195 non-null float64
dtypes: float64(9), int64(3)
</code>```

Trying to do this:

data = pd.read_csv('data_prep_sale')
df = pd.DataFrame(data)

x = df.drop(['target'],axis=1)
y = pd.Series(df['target'])

trimmed_feature_names = []
for i in range(x.shape[1]):
    correlation = np.corrcoef(x.iloc[:,i],y)[0,1]
    if abs(correlation) > 0.5:
        feature_name = x.columns[i]
        print(feature_name, correlation)
        trimmed_feature_names.append(feature_name)```
</div>
</div>
</p>

<p>and keep getting this matrix for all the x:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>array([[ 1., nan],
       [nan, nan]])</code>```

This is a data sample:

type zipcode sqft lotsize beds baths year s_num s_rate s_dist crimes target
4 28387 2900.0 0.0 4.0 3.5 2019.0 8 5.20 5.54 6.0 144.137931
4 99216 1947.0 5828.0 3.0 3.0 2019.0 3 4.00 1.33 3.1 159.219312
3 90049 3000.0 8626.0 3.0 2.0 1967.0 3 6.67 1.96 4.4 965.000000
1 75205 6457.0 8220.0 5.0 8.0 2006.0 4 9.25 0.75 4.6 370.915286```

Link to the complete data file

Please, help me! Need any ideas!

答:
According to the uploaded file, there are some inf values in the target column... like the ones at row: 43, 283, 372, ...etc. So, to fix this issue you have to remove all inf rows. Also, there is a better way to find the correlation between target and other features. Both are shown in the following code:

```<code>import numpy as np
import pandas as pd

data = pd.read_csv('data_prep_sale.csv')
df = pd.DataFrame(data)

# remove any (inf, -inf, nan) values
df = df.replace([np.inf, -np.inf], np.nan).dropna()

# find the correlation between target other features
print(df.corr()["target"])
</code>```

As you can see from the output of the correlation, all values are way lower than 0.5.

Title: Why does numpy.corrcoef() returns nan?

Body:
Trying to build a regression model, but got a problem I can't solve.
Have googled and read everything about it but nothing works. Have this dataframe:

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 334195 entries, 0 to 334194
Data columns (total 12 columns):
type         334195 non-null int64
zipcode      334195 non-null int64
sqft         334195 non-null float64
lotsize      334195 non-null float64
beds         334195 non-null float64
baths        334195 non-null float64
year         334195 non-null float64
s_num        334195 non-null int64
s_rate       334195 non-null float64
s_dist       334195 non-null float64
crimes       334195 non-null float64
target       334195 non-null float64
dtypes: float64(9), int64(3)

Trying to do this:

data = pd.read_csv('data_prep_sale')
df = pd.DataFrame(data)

x = df.drop(['target'],axis=1)
y = pd.Series(df['target'])

trimmed_feature_names = []
for i in range(x.shape[1]):
    correlation = np.corrcoef(x.iloc[:,i],y)[0,1]
    if abs(correlation) > 0.5:
        feature_name = x.columns[i]
        print(feature_name, correlation)
        trimmed_feature_names.append(feature_name)

and keep getting this matrix for all the x:

array([[ 1., nan],
       [nan, nan]])

This is a data sample:

type zipcode sqft lotsize beds baths year s_num s_rate s_dist crimes target
4 28387 2900.0 0.0 4.0 3.5 2019.0 8 5.20 5.54 6.0 144.137931
4 99216 1947.0 5828.0 3.0 3.0 2019.0 3 4.00 1.33 3.1 159.219312
3 90049 3000.0 8626.0 3.0 2.0 1967.0 3 6.67 1.96 4.4 965.000000
1 75205 6457.0 8220.0 5.0 8.0 2006.0 4 9.25 0.75 4.6 370.915286

Link to the complete data file

Please, help me! Need any ideas!

Body:
According to the uploaded file, there are some inf values in the target column... like the ones at row: 43, 283, 372, ...etc. So, to fix this issue you have to remove all inf rows. Also, there is a better way to find the correlation between target and other features. Both are shown in the following code:

import numpy as np
import pandas as pd

data = pd.read_csv('data_prep_sale.csv')
df = pd.DataFrame(data)

# remove any (inf, -inf, nan) values
df = df.replace([np.inf, -np.inf], np.nan).dropna()

# find the correlation between target other features
print(df.corr()["target"])

As you can see from the output of the correlation, all values are way lower than 0.5.


问:
NiFi - New attribute to create a new one with a previous attribute + harcoded text
I'm trying to add a new "attributeX" to create an URL (using UpdateAttribute). This URL will be like this:
Part 1: harcoded value (eg.: "www.google.com/")
Part 2: evaluate attribute 1; if empty, use attribute 2: if not, use attribute 1.
Part 3: harcoded value (eg.: "/tests/")
Part 4: attribute3

Attributes 1,2 and 3 are present in the flow file from previous processors.
So, my goal is to get an url like this:
www.google.com/attribute1 OR attribute2/tests/attribute3

BUT; this "attributeX" needs a condition: if attribute3 is empty, I need to set the value as "empty": if NOT empty, I need to create that URL.

I was trying with regex expression but I couldn't get this done. My "isEmpty" and "ifElse" evaluations fails when I'm trying to set the the "ifElse" with harcoded values+attributes.

Any help is much appreciated, thanks in advance!

EDIT: I didn't specify any of my tests because I did a lot of attempts and couldn't get the expected attribute.
I'm trying to do something like this:

```<code>${attributeA:isEmpty():ifElse(${literal("")},hardcodedText+${attributeB}+${attributeA})}
</code>```

The expression works fine until the argument after the comma; if I use only 1 attribute/variable it works fine; but if I try with more than 1 attribute it's not recognized as as valid expression.

答:
@NahuelGonzalez You should share your expression language progress so we can see what you are doing.   It should be possible to do all the if/else logic in a single NiFi Expression Language string.  Sometimes the issue could be a simple (, :, or ' missing or misplaced.

However, I would maybe do this a different way.   Create your different combined attributes upstream from the isEmpty logic.  Then you can use the specific urls you need in the function response.

You can also use a RouteOnAttribute to split flow into to different updateAttributes that create different urls.   Then bring the flow back together for all the urls.

Body:
I'm trying to add a new "attributeX" to create an URL (using UpdateAttribute). This URL will be like this:
Part 1: harcoded value (eg.: "www.google.com/")
Part 2: evaluate attribute 1; if empty, use attribute 2: if not, use attribute 1.
Part 3: harcoded value (eg.: "/tests/")
Part 4: attribute3

Attributes 1,2 and 3 are present in the flow file from previous processors.
So, my goal is to get an url like this:
www.google.com/attribute1 OR attribute2/tests/attribute3

BUT; this "attributeX" needs a condition: if attribute3 is empty, I need to set the value as "empty": if NOT empty, I need to create that URL.

I was trying with regex expression but I couldn't get this done. My "isEmpty" and "ifElse" evaluations fails when I'm trying to set the the "ifElse" with harcoded values+attributes.

Any help is much appreciated, thanks in advance!

EDIT: I didn't specify any of my tests because I did a lot of attempts and couldn't get the expected attribute.
I'm trying to do something like this:

${attributeA:isEmpty():ifElse(${literal("")},hardcodedText+${attributeB}+${attributeA})}

The expression works fine until the argument after the comma; if I use only 1 attribute/variable it works fine; but if I try with more than 1 attribute it's not recognized as as valid expression.


问:
How To Install and Run wkhtmltopdf on Mac OsX 10.7.3 for use in a PHP Application
I've written a PHP/MySQL application that utilizes wkhtmltopdf to generate reports from data entered into the database.  The client asked that I also install it to run as a standalone on a Mac that he has.  Currently have the PHP/MySQL portion running without difficulty using XAMMP, but am having incredible difficulty getting wkhtmltopdf even installed on the system.

I have zero experience with Macs, and despite five hours of Googling and trying different approaches, I cannot even copy the most recent wkhtmltopdf .i386 into the /usr folder.  Oddly, the laptop doesn't have a /usr/local/bin folder.

Unless I've missed it, I can't find simple instructions on how to get this thing working and would greatly appreciate any help that could be offered.

答:
You will need to run the command in the terminal before the PDF creation:

```<code>brew cask install wkhtmltopdf
</code>```

When I create the PDF, I get this log in the server:

```<code>2020-05-31 17:20:10.657  INFO 11168 --- [io-8080-exec-10] c.g.jhonnymertz.wkhtmltopdf.wrapper.Pdf  : Initialized with {xvfbConfig=null, wkhtmltopdfCommand='/usr/local/bin/wkhtmltopdf'}
2020-05-31 17:20:20.166  INFO 11168 --- [io-8080-exec-10] c.g.jhonnymertz.wkhtmltopdf.wrapper.Pdf  : PDF successfully generated with: /usr/local/bin/wkhtmltopdf -B 0 -L 0 -R 0 -T 0 --page-width 148 --page-height 212 /var/folders/0c/_vpt6xnj71ng91nm9kk5jw3w0000gn/T/java-wkhtmltopdf-wrapper6721963b-6a8c-4260-9ac6-a545920d1ab117331429448032181725.html -
</code>```

Body:
You will need to run the command in the terminal before the PDF creation:

brew cask install wkhtmltopdf

When I create the PDF, I get this log in the server:

2020-05-31 17:20:10.657  INFO 11168 --- [io-8080-exec-10] c.g.jhonnymertz.wkhtmltopdf.wrapper.Pdf  : Initialized with {xvfbConfig=null, wkhtmltopdfCommand='/usr/local/bin/wkhtmltopdf'}
2020-05-31 17:20:20.166  INFO 11168 --- [io-8080-exec-10] c.g.jhonnymertz.wkhtmltopdf.wrapper.Pdf  : PDF successfully generated with: /usr/local/bin/wkhtmltopdf -B 0 -L 0 -R 0 -T 0 --page-width 148 --page-height 212 /var/folders/0c/_vpt6xnj71ng91nm9kk5jw3w0000gn/T/java-wkhtmltopdf-wrapper6721963b-6a8c-4260-9ac6-a545920d1ab117331429448032181725.html -


问:
Store tokens in browser cookies with Flask jwt extended
I know how to create tokens with this library, and also how to put tokens in reponse body:

access_token = create_access_token(identity = token_identity)
refresh_token = create_refresh_token(identity = token_identity)
set_access_cookies({"login": True}, access_token)
set_refresh_cookies({"login": True}, refresh_token)
```

<p>However, when using it with my flask application, nothing is stored in my browser cookies.
Do I need to do something more than use the set_access_cookies or set_refresh_cookies in order to store tokens in cookies? </p>

<p>One example of code:</p>

<pre class="lang-py prettyprint-override"><code>import logging
from flask import Blueprint, render_template, redirect, url_for, request, current_app as app, jsonify
from flask_login import login_user, logout_user, login_required
from werkzeug.security import generate_password_hash, check_password_hash
from .models import User
from . import db, login_manager, login_serializer, jwt
from flask_jwt_extended import (create_access_token,
create_refresh_token, jwt_required, jwt_refresh_token_required, get_jwt_identity, get_raw_jwt, set_access_cookies,
set_refresh_cookies, unset_jwt_cookies)

def set_response_cookies(token_identity, resp=None, token_types=["access", "refresh"]):
    """
    Helper function to set cookies
    """
    logging.warning("Setting cookies")
    token_types.sort()
    if token_types == ["access", "refresh"]:
        access_token = create_access_token(identity = token_identity)
        refresh_token = create_refresh_token(identity = token_identity)
        if not resp:
            resp = jsonify({"access_token": access_token, "refresh_token": refresh_token})
        set_access_cookies(resp, access_token)
        set_refresh_cookies(resp, refresh_token)
        return resp
    elif token_types == ["access"]:
        access_token = create_access_token(identity = token_identity)
        if not resp:
            resp = jsonify({"access_token": access_token})
        set_access_cookies(resp, access_token)
        return resp
    elif token_types == ["refresh"]:
        refresh_token = create_refresh_token(identity = token_identity)
        if not resp:
            resp = jsonify({"refresh_token": refresh_token})
        set_refresh_cookies(resp, refresh_token)
        return resp
    else:
        raise ValueError("Wrong Call to this function")

@auth.route('/signup', methods=['POST'])
def signup_post():
    email = request.form.get('email')
    name = request.form.get('name')
    password = request.form.get('password')

    user = User.objects(email=email)
    if user:  # Email already exist.
        return redirect(url_for('auth.signup')), 409
    logging.warning("User not existing")
    new_user = User(email=email, name=name, password=generate_password_hash(password, method='sha256'))
    new_user.save()
    set_response_cookies(email, ["access", "refresh"])
    return redirect(url_for('auth.login')), 200
</code>```

答:
You can make use of set_cookie()

Store token in cookie:

```<code>from flask import make_response

@app.route('/')
def index():
    response = make_response(render_template(...))
    response.set_cookie('access_token', 'YOUR_ACCESS_TOKEN')
    response.set_cookie('refresh_token', 'YOUR_REFRESH_TOKEN')
    return response
</code>```

To Retrieve the token from cookie:

```<code>from flask import request

@app.route('/')
def index():
    access_token = request.cookies.get('access_token')
</code>```

In this way you can store the token in a cookie and retrive the token from the cookie.

Body:
I know how to create tokens with this library, and also how to put tokens in reponse body:

access_token = create_access_token(identity = token_identity)
refresh_token = create_refresh_token(identity = token_identity)
set_access_cookies({"login": True}, access_token)
set_refresh_cookies({"login": True}, refresh_token)

However, when using it with my flask application, nothing is stored in my browser cookies.
Do I need to do something more than use the set_access_cookies or set_refresh_cookies in order to store tokens in cookies?

One example of code:

import logging
from flask import Blueprint, render_template, redirect, url_for, request, current_app as app, jsonify
from flask_login import login_user, logout_user, login_required
from werkzeug.security import generate_password_hash, check_password_hash
from .models import User
from . import db, login_manager, login_serializer, jwt
from flask_jwt_extended import (create_access_token,
create_refresh_token, jwt_required, jwt_refresh_token_required, get_jwt_identity, get_raw_jwt, set_access_cookies,
set_refresh_cookies, unset_jwt_cookies)

def set_response_cookies(token_identity, resp=None, token_types=["access", "refresh"]):
    """
    Helper function to set cookies
    """
    logging.warning("Setting cookies")
    token_types.sort()
    if token_types == ["access", "refresh"]:
        access_token = create_access_token(identity = token_identity)
        refresh_token = create_refresh_token(identity = token_identity)
        if not resp:
            resp = jsonify({"access_token": access_token, "refresh_token": refresh_token})
        set_access_cookies(resp, access_token)
        set_refresh_cookies(resp, refresh_token)
        return resp
    elif token_types == ["access"]:
        access_token = create_access_token(identity = token_identity)
        if not resp:
            resp = jsonify({"access_token": access_token})
        set_access_cookies(resp, access_token)
        return resp
    elif token_types == ["refresh"]:
        refresh_token = create_refresh_token(identity = token_identity)
        if not resp:
            resp = jsonify({"refresh_token": refresh_token})
        set_refresh_cookies(resp, refresh_token)
        return resp
    else:
        raise ValueError("Wrong Call to this function")

@auth.route('/signup', methods=['POST'])
def signup_post():
    email = request.form.get('email')
    name = request.form.get('name')
    password = request.form.get('password')

    user = User.objects(email=email)
    if user:  # Email already exist.
        return redirect(url_for('auth.signup')), 409
    logging.warning("User not existing")
    new_user = User(email=email, name=name, password=generate_password_hash(password, method='sha256'))
    new_user.save()
    set_response_cookies(email, ["access", "refresh"])
    return redirect(url_for('auth.login')), 200

Body:
You can make use of set_cookie()

Store token in cookie:

from flask import make_response

@app.route('/')
def index():
    response = make_response(render_template(...))
    response.set_cookie('access_token', 'YOUR_ACCESS_TOKEN')
    response.set_cookie('refresh_token', 'YOUR_REFRESH_TOKEN')
    return response

To Retrieve the token from cookie:

from flask import request

@app.route('/')
def index():
    access_token = request.cookies.get('access_token')

In this way you can store the token in a cookie and retrive the token from the cookie.


问:
Selecting rows with groupby, summing columns and creating new column with the sum for all groupby elements
I have this dataframe:

```<code>nome       code  tipo   score
Alexandre   AAA  Frads  4000
Alexandre   AAA  Memb   10000
Alexandre   AAA  Memb   20000
Bruno       BBB  Dans   10000
Bruno       BBB  Grap   4000
</code>```

Values available in this Google Sheets

I need to create a new column summing the rows with same nome and code where tipo = 'Memb', in a way that it looks like this:

I tried groupby with transform('sum') however it is getting me the wrong result.

```<code>df['score'].loc[df['tipo'] == "Memb"]=df[['nome','code','score']].groupby(['nome','code'])['score'].transform('sum')
</code>```

What am I missing?

答:
```<code>import numpy as np

df['Memb_sum']=df.groupby(['nome','code','tipo'])['score'].transform('sum')

df['Memb_sum']=np.where(df['tipo'] != 'Memb', 0, df['Memb_sum'])

df['Memb_sum']=df.groupby(['nome','code'])['Memb_sum'].transform('max')
</code>```

You can perform group by first and later filter out values.

Output:

```<code>        nome code   tipo  score  Memb_sum
0  Alexandre  AAA  Frads   4000     30000
1  Alexandre  AAA   Memb  10000     30000
2  Alexandre  AAA   Memb  20000     30000
3      Bruno  BBB   Dans  10000         0
4      Bruno  BBB   Grap   4000         0
</code>```

Body:
I have this dataframe:

nome       code  tipo   score
Alexandre   AAA  Frads  4000
Alexandre   AAA  Memb   10000
Alexandre   AAA  Memb   20000
Bruno       BBB  Dans   10000
Bruno       BBB  Grap   4000

Values available in this Google Sheets

I need to create a new column summing the rows with same nome and code where tipo = 'Memb', in a way that it looks like this:

I tried groupby with transform('sum') however it is getting me the wrong result.

df['score'].loc[df['tipo'] == "Memb"]=df[['nome','code','score']].groupby(['nome','code'])['score'].transform('sum')

What am I missing?

Body:
import numpy as np

df['Memb_sum']=df.groupby(['nome','code','tipo'])['score'].transform('sum')

df['Memb_sum']=np.where(df['tipo'] != 'Memb', 0, df['Memb_sum'])

df['Memb_sum']=df.groupby(['nome','code'])['Memb_sum'].transform('max')

You can perform group by first and later filter out values.

Output:

        nome code   tipo  score  Memb_sum
0  Alexandre  AAA  Frads   4000     30000
1  Alexandre  AAA   Memb  10000     30000
2  Alexandre  AAA   Memb  20000     30000
3      Bruno  BBB   Dans  10000         0
4      Bruno  BBB   Grap   4000         0


问:
Python regex: find and replace commas between quotation marks
I have a string,

```<code>line = '12/08/2013,3,"9,25",42:51,"3,08","12,9","13,9",159,170,"3,19",437,'
</code>```

and I would like to find and replace the commas, between quotation marks, with ":".
Looking for a results

```<code>line = '12/08/2013,3,9:25,42:51,3:08,12:9,13:9,159,170,3:19,437,'
</code>```

So far I have been able to match this pattern with,

```<code>import re
re.findall('(\"\d),(.+?\")', line)
</code>```

however, I guess I should be using

```<code>re.compile(...something..., line)
re.sub(':', line)
</code>```

Does anyone know how to do this?
thanks, labjunky

答:
There is also a generic regex solution to replace any kind of fixed (and non-fixed, too) pattern in between double (or single) quotes: match the double- or single quoted substrings with the corresponding pattern, and use a callable as the replacement argumet to re.sub where you may manipulate the match:

Replacing commas in between double quotes with colons and remove the double quotes (the current OP scenario):

re.sub(r'"([^"]*)"', lambda x: x.group(1).replace(',', ':'), line) (demo)
# => 12/08/2013,3,9:25,42:51,3:08,12:9,13:9,159,170,3:19,437,

Replacing  commas in between double quotes with colons and keep the double quotes:

re.sub(r'"[^"]*"', lambda x: x.group(0).replace(',', ':'), line) (demo)
# => 12/08/2013,3,"9:25",42:51,"3:08","12:9","13:9",159,170,"3:19",437,

Replacing  commas in between double and single quotes with colons and keep the single/double quotes:

re.sub(r''''[^']*'|"[^"]*"''', lambda x: x.group(0).replace(',', ':'), '''0,1,"2,3",'4,5',''') (demo)
# => 0,1,"2:3",'4:5',

Also, if you need to handle escaped single and double quotes, consider using r"'[^\\']*(?:\\.[^\\']*)*'" (for single quoted substrings), r'"[^\\"]*(?:\\.[^\\"]*)*"' (for double quoted substrings) or for both - r''''[^\\']*(?:\\.[^\\']*)*'|"[^\\"]*(?:\\.[^\\"]*)*"''' instead of the patterns above.

Body:
I have a string,

line = '12/08/2013,3,"9,25",42:51,"3,08","12,9","13,9",159,170,"3,19",437,'

and I would like to find and replace the commas, between quotation marks, with ":".
Looking for a results

line = '12/08/2013,3,9:25,42:51,3:08,12:9,13:9,159,170,3:19,437,'

So far I have been able to match this pattern with,

import re
re.findall('(\"\d),(.+?\")', line)

however, I guess I should be using

re.compile(...something..., line)
re.sub(':', line)

Does anyone know how to do this?
thanks, labjunky


问:
React - iterating through an array and Events
Suppose I have an array of cars that I use to set an inital state:

```<code>const [ carState, setCarstate ] = useState({
    cars: [
      {model: 'Ferarri', yearOfFabrication: 2001},
      {model: 'Toyota', yearOfFabrication: 2005},
      {model: 'Tesla', yearOfFabrication: 2017},
      {model: 'Ford Mustang', yearOfFabrication: 2003}
    ]
});
</code>```

Can someone please explain why the below code is not showing any cars?

```<code>{carState.cars.map(car => {<Car model={car.model} age={car.yearOfFabrication}/>})}
</code>```

and this one it's working?

```<code>{carState.cars.map(car => <Car model={car.model} age={car.yearOfFabrication}/>)}
</code>```

The only difference between those two piece of code is, that the first encapsulates the return in a block of code. So perhaps this is not a React question but rather an ES6 arrow functions question?

Also, consider the below component which is passing a method reference through props:

```<code><Input handler={() => changeCarNameHandler}/>
</code>```

This doesn't work as expected, as it should call the changeCarNameHandler method upon a change event, here's the component code:

```<code>const input = props => {
    return(
        <input onChange={props.handler}></input>
    )
}
</code>```

However, this is working

```<code><Input handler={(event) => changeCarNameHandler(event)}/>
</code>```

Can someone please clarify this? If you can also provide some resources where I can read more about this, that would be appreciated.

答:
```<code>{carState.cars.map(car => {<Car model={car.model} age={car.yearOfFabrication}/>})}
</code>```

If you're adding curly braces after arrow ( => ) then you have to explicitly add a return statement for rendering your Car component
so it looks-

```<code>{carState.cars.map(car => { return (<Car model={car.model} age={car.yearOfFabrication}/>)}
)}
</code>```

and

```<code>{carState.cars.map(car => <Car model={car.model} age={car.yearOfFabrication}/>)}
</code>```

Above code works without return because it doesn't have curly braces after arrow( => ) so a single line code without a curly brace implicitly refers to a return statement in javascript

Body:
Suppose I have an array of cars that I use to set an inital state:

const [ carState, setCarstate ] = useState({
    cars: [
      {model: 'Ferarri', yearOfFabrication: 2001},
      {model: 'Toyota', yearOfFabrication: 2005},
      {model: 'Tesla', yearOfFabrication: 2017},
      {model: 'Ford Mustang', yearOfFabrication: 2003}
    ]
});

Can someone please explain why the below code is not showing any cars?

{carState.cars.map(car => {<Car model={car.model} age={car.yearOfFabrication}/>})}

and this one it's working?

{carState.cars.map(car => <Car model={car.model} age={car.yearOfFabrication}/>)}

The only difference between those two piece of code is, that the first encapsulates the return in a block of code. So perhaps this is not a React question but rather an ES6 arrow functions question?

Also, consider the below component which is passing a method reference through props:

<Input handler={() => changeCarNameHandler}/>

This doesn't work as expected, as it should call the changeCarNameHandler method upon a change event, here's the component code:

const input = props => {
    return(
        <input onChange={props.handler}></input>
    )
}

However, this is working

<Input handler={(event) => changeCarNameHandler(event)}/>

Can someone please clarify this? If you can also provide some resources where I can read more about this, that would be appreciated.

Body:
{carState.cars.map(car => {<Car model={car.model} age={car.yearOfFabrication}/>})}

If you're adding curly braces after arrow ( => ) then you have to explicitly add a return statement for rendering your Car component
so it looks-

{carState.cars.map(car => { return (<Car model={car.model} age={car.yearOfFabrication}/>)}
)}

and

{carState.cars.map(car => <Car model={car.model} age={car.yearOfFabrication}/>)}

Above code works without return because it doesn't have curly braces after arrow( => ) so a single line code without a curly brace implicitly refers to a return statement in javascript


问:
Creating a json with dynamic values
In my code i need to call a web service with a json file as argument.

this.myWebService.call({"UserId" : "1"});

the above line is my webservice call.Here the UserId 's value is dynamic For eg.the userId is 1 or userId is 2 or 3 , etc...How do i pass this ID dynamically with a value I get from my program.

Please help.

答:
if it would have php then i would have done

```<code><script type="text/javascript">

var userId = <?php echo $user_id ?>;

this.webService.call("UserId": userId});

</script>
</code>```

Hope this helps!!!

Title: Creating a json with dynamic values

Body:
if it would have php then i would have done

<script type="text/javascript">

var userId = <?php echo $user_id ?>;

this.webService.call("UserId": userId});

</script>

Hope this helps!!!


问:
Set specified factor level as reference in GT regression?
I am using gtsummary package to generate tables from logistic regressions.

I would like to, for example, use the stage level "T3" in the trial data as the reference level, instead of the default "T1". How can I do that within this example code?

I aim to do this for both univariate and multiple variable logistic regression, so I am presuming the answer shall work on both scenarios.

```<code>library(gtsummary)
library(dplyr)

trial %>%
  dplyr::select(age, trt, marker, stage, response, death, ttdeath) %>%
  tbl_uvregression(
    method = glm,
    y = death,
    method.args = list(family = binomial),
    exponentiate = TRUE,
    pvalue_fun = function(x) style_pvalue(x, digits = 2)) %>%
  # overrides the default that shows p-values for each level
  add_global_p() %>%
  # adjusts global p-values for multiple testing (default method: FDR)
  add_q() %>%
  # bold p-values under a given threshold (default 0.05)
  bold_p() %>%
  # now bold q-values under the threshold of 0.10
  bold_p(t = 0.10, q = TRUE) %>%
  bold_labels() %>% as_gt()
</code>```

Sincerely,
nelly

答:
I managed to solve my own problem by using the forcats function "fct_relevel" to set the desired level for a categorical variable as the reference. </p>

```<code>trial$stage <- forcats::fct_relevel(trial$stage, "T3")
</code>```

Body:
I am using gtsummary package to generate tables from logistic regressions.

I would like to, for example, use the stage level "T3" in the trial data as the reference level, instead of the default "T1". How can I do that within this example code?

I aim to do this for both univariate and multiple variable logistic regression, so I am presuming the answer shall work on both scenarios.

library(gtsummary)
library(dplyr)

trial %>%
  dplyr::select(age, trt, marker, stage, response, death, ttdeath) %>%
  tbl_uvregression(
    method = glm,
    y = death,
    method.args = list(family = binomial),
    exponentiate = TRUE,
    pvalue_fun = function(x) style_pvalue(x, digits = 2)) %>%
  # overrides the default that shows p-values for each level
  add_global_p() %>%
  # adjusts global p-values for multiple testing (default method: FDR)
  add_q() %>%
  # bold p-values under a given threshold (default 0.05)
  bold_p() %>%
  # now bold q-values under the threshold of 0.10
  bold_p(t = 0.10, q = TRUE) %>%
  bold_labels() %>% as_gt()

Sincerely,
nelly

Body:
I managed to solve my own problem by using the forcats function "fct_relevel" to set the desired level for a categorical variable as the reference.

trial$stage <- forcats::fct_relevel(trial$stage, "T3")


问:
android set button background programmatically
I would like to know how to set the button color programatically?
I have coded the following but fails:

```<code>Button11.setBackgroundColor(R.color.red);
</code>```

Thanks!!

答:
Using setBackgroundColor() affects the style.
So, declare a new style of the same properties with respect to the previous button, with a a different color.

```<code><?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="@color/green"/>
<corners android:radius="10dp"/>
</shape>
</code>```

Now, use OnClick method.

```<code>location.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            location.setBackgroundResource(R.drawable.green);

        }
    });
</code>```

this changes the button but looks similar to changing the background.

Body:
I would like to know how to set the button color programatically?
I have coded the following but fails:

Button11.setBackgroundColor(R.color.red);

Thanks!!

Body:
Using setBackgroundColor() affects the style.
So, declare a new style of the same properties with respect to the previous button, with a a different color.

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="@color/green"/>
<corners android:radius="10dp"/>
</shape>

Now, use OnClick method.

location.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            location.setBackgroundResource(R.drawable.green);

        }
    });

this changes the button but looks similar to changing the background.


问:
Create pdf file from multiple models in rails app
In my rails app the user inputs a lot of data in different models. The user should have the possibility to create a pdf file from all the data he inputted in the different models. Which ruby gem does provide this functionality and how can it be used? I already looked into Prawn but couldn‘t figure out, if it provides the functionality to create one pdf with data from different models.</p>

答:
here sort tutorial how to use prawn pdf to print related models

for example I have parent model and it has many cars (related model)

```<code>class Parent < ActiveRecord::Base
  has_many :cars, dependent: :destroy
  accepts_nested_attributes_for :cars, allow_destroy: :true
end
</code>```

inside my controller I defined as follow

```<code>class ParentsController < ApplicationController

  def show
      @parent = Parent.find(params[:id])

      respond_to do |format|
        format.html
        format.pdf do
            # here you call prawn pdf class (see below)
            pdf = ParentPdf.new(@parent)
            send_data pdf.render, filename: 'family.pdf',
                                  type: 'application/pdf',
                                  disposition: 'inline'
          end
        end
      end
    end
  end
end
</code>```

you can create folder and file as follow app/pdf/parent_pdf.rb and it inherit from Prawn::Document class

```<code>class ParentPdf < Prawn::Document

  def initialize(parent)
    # init margin and size
    super(top_margin: 5, left_margin: 5, page_size: 'A4', page_layout: :landscape, print_scaling: :none)

    # pass argument to variable
    @parent = parent
    # here is you access related models like you access from your controller
    @cars = @parent.cars
    # you print the model
    print_header
    # and print related model
    print_detail
  end

  def print_header
    bounding_box([420, 510], width: 350, height: 90) do
      text "name: #{@parent.name}", size: 11
    end
  end

  def print_detail
    font 'Helvetica'
    font_size 9
    @cars.each do |car|
      text "car: #{car.name}", size: 11
    end
  end

end
</code>```

and last is the command to print the pdf through hyper link

```<code><%= link_to 'print pdf', parent_path(parent, format: "pdf"), :class => 'btn btn-sm btn-secondary' %>
</code>```

Body:
here sort tutorial how to use prawn pdf to print related models

for example I have parent model and it has many cars (related model)

class Parent < ActiveRecord::Base
  has_many :cars, dependent: :destroy
  accepts_nested_attributes_for :cars, allow_destroy: :true
end

inside my controller I defined as follow

class ParentsController < ApplicationController

  def show
      @parent = Parent.find(params[:id])

      respond_to do |format|
        format.html
        format.pdf do
            # here you call prawn pdf class (see below)
            pdf = ParentPdf.new(@parent)
            send_data pdf.render, filename: 'family.pdf',
                                  type: 'application/pdf',
                                  disposition: 'inline'
          end
        end
      end
    end
  end
end

you can create folder and file as follow app/pdf/parent_pdf.rb and it inherit from Prawn::Document class

class ParentPdf < Prawn::Document

  def initialize(parent)
    # init margin and size
    super(top_margin: 5, left_margin: 5, page_size: 'A4', page_layout: :landscape, print_scaling: :none)

    # pass argument to variable
    @parent = parent
    # here is you access related models like you access from your controller
    @cars = @parent.cars
    # you print the model
    print_header
    # and print related model
    print_detail
  end

  def print_header
    bounding_box([420, 510], width: 350, height: 90) do
      text "name: #{@parent.name}", size: 11
    end
  end

  def print_detail
    font 'Helvetica'
    font_size 9
    @cars.each do |car|
      text "car: #{car.name}", size: 11
    end
  end

end

and last is the command to print the pdf through hyper link

<%= link_to 'print pdf', parent_path(parent, format: "pdf"), :class => 'btn btn-sm btn-secondary' %>


问:
Using a custom field default image in menu via functions.php
I have a problem in custom field in menu, i want to show default image if image is not selected

NOTE: I want to know the funtions.php method not inside php page files.

Here is my code.

```<code>            if ($image) {
                $item->title .= '<div class="thumb wrapme "><img src="' . $image['url'] . '" alt="' . $image['alt'] . '" /></div>';
            }else{
                $item->title .= 'This Should show up in relevent menu not in all';
            }
</code>```

Else not working properly

It shows to all menu items which is wrong.

答:
Does it work with isset()?

Or do you need this inside a function.php override?

```<code>if (isset($image)) {
    $item->title .= '<div class="thumb wrapme "><img src="' . $image['url'] . '" alt="' . $image['alt'] . '" /></div>';
} else {
    $item->title .= '<div class="thumb wrapme "><img src="wp-content/folder/default-image-url.jpg" alt="Deafult image description" /></div>';
}
</code>```

EDIT:

maybe:

```<code>if (isset($image['url'] && isset($image['alt'])) {
    $item->title .= '<div class="thumb wrapme "><img src="' . $image['url'] . '" alt="' . $image['alt'] . '" /></div>';
} else {
    $item->title .= '<div class="thumb wrapme "><img src="wp-content/folder/default-image-url.jpg" alt="Deafult image description" /></div>';
}
</code>```

What happens?

EDIT:

Then just set the title instead of appending maybe.

```<code>if (isset($image['url'] && isset($image['alt'])) {
    $item->title = '<div class="thumb wrapme "><img src="' . $image['url'] . '" alt="' . $image['alt'] . '" /></div>';
} else {
    $item->title = '<div class="thumb wrapme "><img src="wp-content/folder/default-image-url.jpg" alt="Deafult image description" /></div>';
}
</code>```

Body:
I have a problem in custom field in menu, i want to show default image if image is not selected

NOTE: I want to know the funtions.php method not inside php page files.

Here is my code.

            if ($image) {
                $item->title .= '

';
            }else{
                $item->title .= 'This Should show up in relevent menu not in all';
            }

Else not working properly

It shows to all menu items which is wrong.

Body:
Does it work with isset()?

Or do you need this inside a function.php override?

if (isset($image)) {
    $item->title .= '<div class="thumb wrapme "><img src="' . $image['url'] . '" alt="' . $image['alt'] . '" /></div>';
} else {
    $item->title .= '<div class="thumb wrapme "><img src="wp-content/folder/default-image-url.jpg" alt="Deafult image description" /></div>';
}

EDIT:

maybe:

if (isset($image['url'] && isset($image['alt'])) {
    $item->title .= '<div class="thumb wrapme "><img src="' . $image['url'] . '" alt="' . $image['alt'] . '" /></div>';
} else {
    $item->title .= '<div class="thumb wrapme "><img src="wp-content/folder/default-image-url.jpg" alt="Deafult image description" /></div>';
}

What happens?

EDIT:

Then just set the title instead of appending maybe.

if (isset($image['url'] && isset($image['alt'])) {
    $item->title = '<div class="thumb wrapme "><img src="' . $image['url'] . '" alt="' . $image['alt'] . '" /></div>';
} else {
    $item->title = '<div class="thumb wrapme "><img src="wp-content/folder/default-image-url.jpg" alt="Deafult image description" /></div>';
}


问:
Hide Soft Keyboard using adb
I want to hide soft keyboard using adb shell command. Is there any specific command available to do so or in any ways can I get the current focus window object over adb on which I can hide the keyboard if showing?</p>

答:
@Matthias Miro answer is 4.5 years old and it did not work for me with Android 9.
Instead I found the following solution in a GitHub issue thread which worked:

Install Null Keyboard

Select it via ADB: adb shell ime set com.wparam.nullkeyboard/.NullKeyboard

to get your original keyboard back:

List all available keyboards: adb shell ime list -s -a

Select the one via: adb shell ime set [keyboard line from previous command]

Title: Hide Soft Keyboard using adb


问:
Function for converting numeric value into word
Is there any function in progress for converting a numeric value into word or there is another way of doing it?
For ex- 1234 -> one thousand two hundred thirty four.</p>

答: Not built in, no. You will probably have to write your own.</p>


答:
Naturally functions without a return statement return undefined by default.

This changes with arrow functions, which can potentially have an implicit return.

In the case that your arrow function has a single expression as the function body, that expression will be executed, and the resulting value will be implicitly returned when the function is called.

const simple = () => 'code'
simple()    // returns 'code'
```

<p>For an arrow function to have an implicit return, an expression is required. But sometimes we need to use statements (if-else etc).</p>

<blockquote>
  <p>In a programming language, an expression returns or is replaceable with a value. A statement will execute some code without a resulting value.</p>
</blockquote>

<p>For arrow functions to contain statements the function body must be surrounded by {curlies}. And as soon as you have curly braces surrounding your function body, returns are no longer implicit -- for either statements or expressions.</p>

<pre class="lang-js prettyprint-override"><code>const simple = () => { return 'code' }
simple()     // returns 'code'

const broken = () => { 'code' }
broken()       // returns undefined
</code>```

Title: React - iterating through an array and Events

Body:
Naturally functions without a return statement return undefined by default.

This changes with arrow functions, which can potentially have an implicit return.

In the case that your arrow function has a single expression as the function body, that expression will be executed, and the resulting value will be implicitly returned when the function is called.

const simple = () => 'code'
simple()    // returns 'code'

For an arrow function to have an implicit return, an expression is required. But sometimes we need to use statements (if-else etc).

In a programming language, an expression returns or is replaceable with a value. A statement will execute some code without a resulting value.

For arrow functions to contain statements the function body must be surrounded by {curlies}. And as soon as you have curly braces surrounding your function body, returns are no longer implicit -- for either statements or expressions.

const simple = () => { return 'code' }
simple()     // returns 'code'

const broken = () => { 'code' }
broken()       // returns undefined