问:
How does __git_ps1 update the bash prompt?
I'm a Windows user with the Git Bash shell as my daily-driver. I'm curious how the __git_ps1 function updates the prompt every time you change a directory. It's really the only example of updating the bash prompt on the fly that I've seen. I want to leverage this behavior in my own function to add a display on my prompt if I have an RDP session open.

tldr: Any ideas on how the __git_ps1 function evaluates the bash prompt on the fly????

So here is my simple function to see if the RDP client is running

function __rdp_ps1() {
  local MATCH=
  if tasklist | grep --quiet mstsc; then
    MATCH="\e[41mRDP\e[0m"
  fi
  echo "$MATCH"
}
```

<p>So the idea is I want to display RDP with a red background, and I want my shell to evaluate this on the fly the same way <code>__git__ps1</code> is seemingly able to.</p>

<p>What I've investigated (without real success) so far</p>

<p><strong><code>/etc/profile.d/git-prompt.sh</code></strong></p>

<p>This block seems to create the PS1 my shell is using</p>

<pre class="lang-sh prettyprint-override"><code>    PS1='\[\033]0;$TITLEPREFIX:$PWD\007\]' # set window title
    PS1="$PS1"'\n'                 # new line
    PS1="$PS1"'\[\033[32m\]'       # change to green
    PS1="$PS1"'\u@\h '             # user@host<space>
    PS1="$PS1"'\[\033[35m\]'       # change to purple
    PS1="$PS1"'$MSYSTEM '          # show MSYSTEM
    PS1="$PS1"'\[\033[33m\]'       # change to brownish yellow
    PS1="$PS1"'\w'                 # current working directory
    if test -z "$WINELOADERNOEXEC"
    then
        GIT_EXEC_PATH="$(git --exec-path 2>/dev/null)"
        COMPLETION_PATH="${GIT_EXEC_PATH%/libexec/git-core}"
        COMPLETION_PATH="${COMPLETION_PATH%/lib/git-core}"
        COMPLETION_PATH="$COMPLETION_PATH/share/git/completion"
        if test -f "$COMPLETION_PATH/git-prompt.sh"
        then
            . "$COMPLETION_PATH/git-completion.bash"
            . "$COMPLETION_PATH/git-prompt.sh"
            PS1="$PS1"'\[\033[36m\]'  # change color to cyan
</code>```

# tried hamjamming PS1="$PS1 `__rdp_ps1`" here, it only works on login

            PS1="$PS1"'`__git_ps1`'   # bash function
        fi
    fi
    PS1="$PS1"'\[\033[0m\]'        # change color
    PS1="$PS1"'\n'                 # new line
    PS1="$PS1"'$ '                 # prompt: always $

```

<p>So I went to see where this file was being sourced to see if that could lead to the answer</p>

<p><strong><code>/etc/bash.bashrc</code></strong></p>

<p>Last line held the gold</p>

<pre class="lang-sh prettyprint-override"><code># Fixup git-bash in non login env
shopt -q login_shell || . /etc/profile.d/git-prompt.sh`
</code>```

So I evaluated shopt login_shell and it's always on, but I don't really know what that means because the comment leads me to believe that when login env is off, the prompt script will be evaluated

Any ideas???

答:
Your problem might be that you define your $PS1 with double quotes, which bash interprets when executing. Which means that __rdp_ps1 is ran when $PS1 is defined.

In your .bashrc, try replacing the definition with:

```<code>PS1='$PS1 `__rdp_ps1`' # Note the single quote.
</code>```

I have a similar feature on my PS1 (but to display the number of jobs in the background), here is the full version (available here: https://github.com/padawin/dotfiles/blob/master/.bashrc#L70):

```<code>function j(){
    jobs | wc -l | egrep -v ^0 | sed -r 's/^([0-9]+)/ (\1)/'
}

PROMPT_COMMAND=__prompt_command # Func to gen PS1 after CMDs

__prompt_command() {
    local EXIT="$?" # This needs to be first
    PS1="$(virtual_env_name)"

    local RCol='\[\e[0m\]'

    local Red='\e[0;31m'
    local Gre='\e[0;32m'
    local Blu='\e[1;34m'

    PS1+="${Gre}\u@\h$(j)${RCol}: ${Red}\w${Blu}$(__git_ps1)"
    if [ $EXIT != 0 ]; then
        PS1+="$Red \342\234\226 (${EXIT})"
    else
        PS1+="$Gre \342\234\224"
    fi
    PS1+="$RCol\n> "
}
</code>```

Which can be simplified as the following in .bashrc:

```<code>function j(){
    jobs | wc -l | egrep -v ^0 | sed -r 's/^([0-9]+)/ (\1)/'
}

PS1='\u$(j) > ' # Note the single quote here
</code>```

Which behaves as follow:

```<code>padawin > vim

[1]+  Stopped                 vim
padawin (1) > fg
vim
padawin >
</code>```

Body:
I'm a Windows user with the Git Bash shell as my daily-driver. I'm curious how the __git_ps1 function updates the prompt every time you change a directory. It's really the only example of updating the bash prompt on the fly that I've seen. I want to leverage this behavior in my own function to add a display on my prompt if I have an RDP session open.

tldr: Any ideas on how the __git_ps1 function evaluates the bash prompt on the fly????

So here is my simple function to see if the RDP client is running

function __rdp_ps1() {
  local MATCH=
  if tasklist | grep --quiet mstsc; then
    MATCH="\e[41mRDP\e[0m"
  fi
  echo "$MATCH"
}

So the idea is I want to display RDP with a red background, and I want my shell to evaluate this on the fly the same way __git__ps1 is seemingly able to.

What I've investigated (without real success) so far

/etc/profile.d/git-prompt.sh

This block seems to create the PS1 my shell is using

    PS1='\[\033]0;$TITLEPREFIX:$PWD\007\]' # set window title
    PS1="$PS1"'\n'                 # new line
    PS1="$PS1"'\[\033[32m\]'       # change to green
    PS1="$PS1"'\u@\h '             # user@host<space>
    PS1="$PS1"'\[\033[35m\]'       # change to purple
    PS1="$PS1"'$MSYSTEM '          # show MSYSTEM
    PS1="$PS1"'\[\033[33m\]'       # change to brownish yellow
    PS1="$PS1"'\w'                 # current working directory
    if test -z "$WINELOADERNOEXEC"
    then
        GIT_EXEC_PATH="$(git --exec-path 2>/dev/null)"
        COMPLETION_PATH="${GIT_EXEC_PATH%/libexec/git-core}"
        COMPLETION_PATH="${COMPLETION_PATH%/lib/git-core}"
        COMPLETION_PATH="$COMPLETION_PATH/share/git/completion"
        if test -f "$COMPLETION_PATH/git-prompt.sh"
        then
            . "$COMPLETION_PATH/git-completion.bash"
            . "$COMPLETION_PATH/git-prompt.sh"
            PS1="$PS1"'\[\033[36m\]'  # change color to cyan

# tried hamjamming PS1="$PS1 `__rdp_ps1`" here, it only works on login

            PS1="$PS1"'`__git_ps1`'   # bash function
        fi
    fi
    PS1="$PS1"'\[\033[0m\]'        # change color
    PS1="$PS1"'\n'                 # new line
    PS1="$PS1"'$ '                 # prompt: always $

So I went to see where this file was being sourced to see if that could lead to the answer

/etc/bash.bashrc

Last line held the gold

# Fixup git-bash in non login env
shopt -q login_shell || . /etc/profile.d/git-prompt.sh`

So I evaluated shopt login_shell and it's always on, but I don't really know what that means because the comment leads me to believe that when login env is off, the prompt script will be evaluated

Any ideas???

Body:
Your problem might be that you define your $PS1 with double quotes, which bash interprets when executing. Which means that __rdp_ps1 is ran when $PS1 is defined.

In your .bashrc, try replacing the definition with:

PS1='$PS1 `__rdp_ps1`' # Note the single quote.

I have a similar feature on my PS1 (but to display the number of jobs in the background), here is the full version (available here: https://github.com/padawin/dotfiles/blob/master/.bashrc#L70):

function j(){
    jobs | wc -l | egrep -v ^0 | sed -r 's/^([0-9]+)/ (\1)/'
}

PROMPT_COMMAND=__prompt_command # Func to gen PS1 after CMDs

__prompt_command() {
    local EXIT="$?" # This needs to be first
    PS1="$(virtual_env_name)"

    local RCol='\[\e[0m\]'

    local Red='\e[0;31m'
    local Gre='\e[0;32m'
    local Blu='\e[1;34m'

    PS1+="${Gre}\u@\h$(j)${RCol}: ${Red}\w${Blu}$(__git_ps1)"
    if [ $EXIT != 0 ]; then
        PS1+="$Red \342\234\226 (${EXIT})"
    else
        PS1+="$Gre \342\234\224"
    fi
    PS1+="$RCol\n> "
}

Which can be simplified as the following in .bashrc:

function j(){
    jobs | wc -l | egrep -v ^0 | sed -r 's/^([0-9]+)/ (\1)/'
}

PS1='\u$(j) > ' # Note the single quote here

Which behaves as follow:

padawin > vim

[1]+  Stopped                 vim
padawin (1) > fg
vim
padawin >


来源: stackexchange

问:
Post request with Cookies in Flutter
I'm trying to add Cookies to my request:

Here i get csrftoken with a GET request:

```<code> Future<String> getCsrftoken() async{
       var response = await http.get(Uri.encodeFull('http://test/accounts/login/'));
       var csrftoken = response.headers.remove('set-cookie').substring(10,74); //csrf
       64 chars
       return csrftoken;
    }
</code>```

Here i'm trying to perform the POST (application/x-www-form-urlencoded) request using the package  Dio.

```<code>getSessionId() async {
  var csrf = await getCsrftoken();
  var cj = new CookieJar();
  List<Cookie> cookies = [new Cookie("csrftoken", csrf)];
  cj.saveFromResponse(Uri.parse("http://test/accounts/login/"), cookies);
  List<Cookie> results = cj.loadForRequest(Uri.parse("http://test/accounts/login/"));
  var dio = new Dio(new Options(
      baseUrl: "http://test/accounts/login/",
      connectTimeout: 5000,
      receiveTimeout: 100000,
      // 5s
      headers: {
      },
      contentType: ContentType.JSON,
      // Transform the response data to a String encoded with UTF8.
      // The default value is [ResponseType.JSON].
      responseType: ResponseType.PLAIN
  ));

  Response<String> response;

  response = await dio.post("",
    data: {
      "username": "username",
      "password": "password",
      "csrfmiddlewaretoken" : getCsrftoken()
    },
    // Send data with "application/x-www-form-urlencoded" format
    options: new Options(
        contentType: ContentType.parse("application/x-www-form-urlencoded")),
  );
  print(response.statusCode);
}
</code>```

I get 403 status code, because i need to add as a cookie csrftoken.

How should I proceed?

答:
Check if the csrftoken needs to be passed in the header and the cookie or just one of them. It sometimes needs to be included as a header, which is shown in the example below, but the header name varies. To persist cookies, use a PersistCookieJar. Other options are persisted through BaseOptions (previously named Options).

Add to pubspec.yaml the latest versions of these plugins

```<code>  path_provider: ^1.1.0
  dio: ^2.1.6
  cookie_jar: ^1.0.0

</code>```

In a new class named webFunctions:

```<code>import 'dart:io';
import 'package:cookie_jar/cookie_jar.dart';
import 'package:dio/dio.dart';
import 'package:path_provider/path_provider.dart';

class webFunctions {
  final Dio _dio = Dio();
  PersistCookieJar persistentCookies;
  final String URL = "http://test/";

  Future<String> get _localPath async {
    final directory = await getApplicationDocumentsDirectory();
    return directory.path;
  }

  Future<Directory> get _localCoookieDirectory async {
    final path = await _localPath;
    final Directory dir = new Directory('$path/cookies');
    await dir.create();
    return dir;
  }

  Future<String> getCsrftoken() async{
    try {
      String csrfTokenValue;
      final Directory dir = await _localCoookieDirectory;
      final cookiePath = dir.path;
      persistentCookies = new PersistCookieJar(dir: '$cookiePath');
      persistentCookies.deleteAll(); //clearing any existing cookies for a fresh start
      _dio.interceptors.add(
          CookieManager(persistentCookies) //this sets up _dio to persist cookies throughout subsequent requests
      );
      _dio.options = new BaseOptions(
        baseUrl: URL,
        contentType: ContentType.json,
        responseType: ResponseType.plain,
        connectTimeout: 5000,
        receiveTimeout: 100000,
        headers: {
          HttpHeaders.userAgentHeader: "dio",
          "Connection": "keep-alive",
        },
      ); //BaseOptions will be persisted throughout subsequent requests made with _dio
      _dio.interceptors.add(
          InterceptorsWrapper(
              onResponse:(Response response) {
                List<Cookie> cookies = persistentCookies.loadForRequest(Uri.parse(URL));
                csrfTokenValue = cookies.firstWhere((c) => c.name == 'csrftoken', orElse: () => null)?.value;
                if (csrfTokenValue != null) {
                  _dio.options.headers['X-CSRF-TOKEN'] = csrfTokenValue; //setting the csrftoken from the response in the headers
                }
                return response;
              }
          )
      );
      await _dio.get("/accounts/login/");
      return csrfTokenValue;
    } catch (error, stacktrace) {
      print("Exception occured: $error stackTrace: $stacktrace");
      return null;
    }
  }

  getSessionId() async {
    try {
      final csrf = await getCsrftoken();
      FormData formData = new FormData.from({
        "username": "username",
        "password": 'A *passphrase* is stronger than a password.',
        "csrfmiddlewaretoken" : '$csrf'
      });
      Options optionData = new Options(
        contentType: ContentType.parse("application/x-www-form-urlencoded"),
      );
      Response response = await _dio.post("/accounts/login/", data: formData, options: optionData);
      print(response.statusCode);
    } on DioError catch(e) {
      if(e.response != null) {
        print( e.response.statusCode.toString() + " " + e.response.statusMessage);
        print(e.response.data);
        print(e.response.headers);
        print(e.response.request);
      } else{
        print(e.request);
        print(e.message);
      }
    }
    catch (error, stacktrace) {
      print("Exception occured: $error stackTrace: $stacktrace");
      return null;
    }
  }
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Post request with Cookies in Flutter

Body:
I'm trying to add Cookies to my request:

Here i get csrftoken with a GET request:

 Future<String> getCsrftoken() async{
       var response = await http.get(Uri.encodeFull('http://test/accounts/login/'));
       var csrftoken = response.headers.remove('set-cookie').substring(10,74); //csrf
       64 chars
       return csrftoken;
    }

Here i'm trying to perform the POST (application/x-www-form-urlencoded) request using the package  Dio.

getSessionId() async {
  var csrf = await getCsrftoken();
  var cj = new CookieJar();
  List<Cookie> cookies = [new Cookie("csrftoken", csrf)];
  cj.saveFromResponse(Uri.parse("http://test/accounts/login/"), cookies);
  List<Cookie> results = cj.loadForRequest(Uri.parse("http://test/accounts/login/"));
  var dio = new Dio(new Options(
      baseUrl: "http://test/accounts/login/",
      connectTimeout: 5000,
      receiveTimeout: 100000,
      // 5s
      headers: {
      },
      contentType: ContentType.JSON,
      // Transform the response data to a String encoded with UTF8.
      // The default value is [ResponseType.JSON].
      responseType: ResponseType.PLAIN
  ));

  Response<String> response;

  response = await dio.post("",
    data: {
      "username": "username",
      "password": "password",
      "csrfmiddlewaretoken" : getCsrftoken()
    },
    // Send data with "application/x-www-form-urlencoded" format
    options: new Options(
        contentType: ContentType.parse("application/x-www-form-urlencoded")),
  );
  print(response.statusCode);
}

I get 403 status code, because i need to add as a cookie csrftoken.

How should I proceed?

Body:
Check if the csrftoken needs to be passed in the header and the cookie or just one of them. It sometimes needs to be included as a header, which is shown in the example below, but the header name varies. To persist cookies, use a PersistCookieJar. Other options are persisted through BaseOptions (previously named Options).

Add to pubspec.yaml the latest versions of these plugins

  path_provider: ^1.1.0
  dio: ^2.1.6
  cookie_jar: ^1.0.0

In a new class named webFunctions:

import 'dart:io';
import 'package:cookie_jar/cookie_jar.dart';
import 'package:dio/dio.dart';
import 'package:path_provider/path_provider.dart';

class webFunctions {
  final Dio _dio = Dio();
  PersistCookieJar persistentCookies;
  final String URL = "http://test/";

  Future<String> get _localPath async {
    final directory = await getApplicationDocumentsDirectory();
    return directory.path;
  }

  Future<Directory> get _localCoookieDirectory async {
    final path = await _localPath;
    final Directory dir = new Directory('$path/cookies');
    await dir.create();
    return dir;
  }

  Future<String> getCsrftoken() async{
    try {
      String csrfTokenValue;
      final Directory dir = await _localCoookieDirectory;
      final cookiePath = dir.path;
      persistentCookies = new PersistCookieJar(dir: '$cookiePath');
      persistentCookies.deleteAll(); //clearing any existing cookies for a fresh start
      _dio.interceptors.add(
          CookieManager(persistentCookies) //this sets up _dio to persist cookies throughout subsequent requests
      );
      _dio.options = new BaseOptions(
        baseUrl: URL,
        contentType: ContentType.json,
        responseType: ResponseType.plain,
        connectTimeout: 5000,
        receiveTimeout: 100000,
        headers: {
          HttpHeaders.userAgentHeader: "dio",
          "Connection": "keep-alive",
        },
      ); //BaseOptions will be persisted throughout subsequent requests made with _dio
      _dio.interceptors.add(
          InterceptorsWrapper(
              onResponse:(Response response) {
                List<Cookie> cookies = persistentCookies.loadForRequest(Uri.parse(URL));
                csrfTokenValue = cookies.firstWhere((c) => c.name == 'csrftoken', orElse: () => null)?.value;
                if (csrfTokenValue != null) {
                  _dio.options.headers['X-CSRF-TOKEN'] = csrfTokenValue; //setting the csrftoken from the response in the headers
                }
                return response;
              }
          )
      );
      await _dio.get("/accounts/login/");
      return csrfTokenValue;
    } catch (error, stacktrace) {
      print("Exception occured: $error stackTrace: $stacktrace");
      return null;
    }
  }

  getSessionId() async {
    try {
      final csrf = await getCsrftoken();
      FormData formData = new FormData.from({
        "username": "username",
        "password": 'A *passphrase* is stronger than a password.',
        "csrfmiddlewaretoken" : '$csrf'
      });
      Options optionData = new Options(
        contentType: ContentType.parse("application/x-www-form-urlencoded"),
      );
      Response response = await _dio.post("/accounts/login/", data: formData, options: optionData);
      print(response.statusCode);
    } on DioError catch(e) {
      if(e.response != null) {
        print( e.response.statusCode.toString() + " " + e.response.statusMessage);
        print(e.response.data);
        print(e.response.headers);
        print(e.response.request);
      } else{
        print(e.request);
        print(e.message);
      }
    }
    catch (error, stacktrace) {
      print("Exception occured: $error stackTrace: $stacktrace");
      return null;
    }
  }
}


问:
Is there a quick way to close a thread before the main code continues?
I have a students working on a Simon Game for a final project at school and I have tried all day to solve her problem.
She is trying to create the game Simon. The program randomly selects a sequence of colours and highlights those colours by changing the colours of the 4 coloured buttons from the regular colour to white for a few seconds and then back.
Instead of highlighting one colour at a time white, the programming is making all colours appear white at the same time. So users don't know the sequence.

I have been looking up issues with running multiple threads and have tried using the .join() function. However, when that is used no colours turn white.

//highlights the colours that are currently in the array

```<code>
public void play() {

   //loop through the array and look at all the colours so far
   for(int i=0; i<round;i++){

             //red is the position in the array
             if(colours[i]==1){

                  Thread sleep=new Thread(new Runnable(){
                     @Override
                     public void run(){
                         //change the colour of the red button to white
                         redButton.setBackground(Color.WHITE);
                         redButton.setOpaque(true);

                            //wait
                            try {
                                Thread.currentThread().sleep(1000);
                                }
                             catch (InterruptedException e) {
                                e.printStackTrace();
                                }
                            //change the colour back
                        redButton.setBackground(Color.RED);
                         redButton.setOpaque(false);
                     }
                 });

                        sleep.start();

             }

             //yellow
             else if(colours[i]==2){
                 Thread sleep=new Thread(new Runnable(){
                     @Override
                     public void run(){
                         yellowButton.setBackground(Color.WHITE);
                         yellowButton.setOpaque(true);

                            try {
                                Thread.currentThread().sleep(1000);
                                }
                             catch (InterruptedException e) {
                                e.printStackTrace();
                                }
                         yellowButton.setBackground(Color.YELLOW);
                        yellowButton.setOpaque(false);
                     }
                 });
                 sleep.start();

             }
             //green
             else if(colours[i]==3){
                 Thread sleep=new Thread(new Runnable(){
                     @Override
                     public void run(){
                         greenButton.setBackground(Color.WHITE);
                         greenButton.setOpaque(true);

                            try {
                                Thread.currentThread().sleep(1000);
                                }
                             catch (InterruptedException e) {
                                e.printStackTrace();
                                }
                         greenButton.setBackground(Color.GREEN);
                        greenButton.setOpaque(false);

                     }
                 });
                 sleep.start();

             }
             //blue
             else if(colours[i]==4){
                 Thread sleep=new Thread(new Runnable(){
                     @Override
                     public void run(){
                         blueButton.setBackground(Color.WHITE);
                         blueButton.setOpaque(true);

                            try {
                                Thread.currentThread().sleep(1000);
                                }
                             catch (InterruptedException e) {
                                e.printStackTrace();
                                }
                         blueButton.setBackground(Color.CYAN);
                         blueButton.setOpaque(false);

                     }
                 });
                 sleep.start();

             }

   }

}

</code>```

答:
While you want to change the color of each button for 1 second, your main thread is too fast and finish within that second. Thats why it seems all lights change at same time.

Simple solution is to also to make the outer thread sleep for some time but that will not gurantee sequence of the threads. I would suggest to use java.util.concurrent.CountDownLatch to make the outer thread wait for inner thread to finish.

```<code>    for (int i = 0; i < round; i++) {
        CountDownLatch countDownLatch = new CountDownLatch(1);
        // red is the position in the array
        if (colours[i] == 1) {
            Thread sleep = new Thread(new Worker(redButton, Color.RED, countDownLatch))
            sleep.start();

        }

        // yellow
        else if (colours[i] == 2) {
            Thread sleep = new Thread(new Worker(yellowButton, Color.YELLOW, countDownLatch))
            sleep.start();

        }
        // green
        else if (colours[i] == 3) {
            Thread sleep = new Thread(new Worker(greenButton, Color.GREEN, countDownLatch))
            sleep.start();

        }
        // blue
        else if (colours[i] == 4) {
            Thread sleep = new Thread(new Worker(blueButton, Color.CYAN, countDownLatch))
            sleep.start();

        }
        countDownLatch.await();
    }
}

class Worker implements Runnable {
    Button button;
    Color color;
    CountDownLatch countDownLatch;

    public Worker(Button button, Color color, CountDownLatch countDownLatch) {
        this.button = button;
        this.color = color;
        this.countDownLatch = countDownLatch;
    }

    @Override
    public void run() {
        button.setBackground(Color.WHITE);
        button.setOpaque(true);

        try {
            Thread.currentThread().sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        button.setBackground(color);
        button.setOpaque(false);
        countDownLatch.countDown();

    }
}
</code>```

As soon as the light changes color for 1 second you count down the latch using countDownLatch.countDown() you wait for count down to hit zero with  countDownLatch.await() in outer thread.

Body:
I have a students working on a Simon Game for a final project at school and I have tried all day to solve her problem.
She is trying to create the game Simon. The program randomly selects a sequence of colours and highlights those colours by changing the colours of the 4 coloured buttons from the regular colour to white for a few seconds and then back.
Instead of highlighting one colour at a time white, the programming is making all colours appear white at the same time. So users don't know the sequence.

I have been looking up issues with running multiple threads and have tried using the .join() function. However, when that is used no colours turn white.

//highlights the colours that are currently in the array

public void play() {

   //loop through the array and look at all the colours so far
   for(int i=0; i<round;i++){

             //red is the position in the array
             if(colours[i]==1){

                  Thread sleep=new Thread(new Runnable(){
                     @Override
                     public void run(){
                         //change the colour of the red button to white
                         redButton.setBackground(Color.WHITE);
                         redButton.setOpaque(true);

                            //wait
                            try {
                                Thread.currentThread().sleep(1000);
                                }
                             catch (InterruptedException e) {
                                e.printStackTrace();
                                }
                            //change the colour back
                        redButton.setBackground(Color.RED);
                         redButton.setOpaque(false);
                     }
                 });

                        sleep.start();

             }

             //yellow
             else if(colours[i]==2){
                 Thread sleep=new Thread(new Runnable(){
                     @Override
                     public void run(){
                         yellowButton.setBackground(Color.WHITE);
                         yellowButton.setOpaque(true);

                            try {
                                Thread.currentThread().sleep(1000);
                                }
                             catch (InterruptedException e) {
                                e.printStackTrace();
                                }
                         yellowButton.setBackground(Color.YELLOW);
                        yellowButton.setOpaque(false);
                     }
                 });
                 sleep.start();

             }
             //green
             else if(colours[i]==3){
                 Thread sleep=new Thread(new Runnable(){
                     @Override
                     public void run(){
                         greenButton.setBackground(Color.WHITE);
                         greenButton.setOpaque(true);

                            try {
                                Thread.currentThread().sleep(1000);
                                }
                             catch (InterruptedException e) {
                                e.printStackTrace();
                                }
                         greenButton.setBackground(Color.GREEN);
                        greenButton.setOpaque(false);

                     }
                 });
                 sleep.start();

             }
             //blue
             else if(colours[i]==4){
                 Thread sleep=new Thread(new Runnable(){
                     @Override
                     public void run(){
                         blueButton.setBackground(Color.WHITE);
                         blueButton.setOpaque(true);

                            try {
                                Thread.currentThread().sleep(1000);
                                }
                             catch (InterruptedException e) {
                                e.printStackTrace();
                                }
                         blueButton.setBackground(Color.CYAN);
                         blueButton.setOpaque(false);

                     }
                 });
                 sleep.start();

             }

   }

}

Body:
While you want to change the color of each button for 1 second, your main thread is too fast and finish within that second. Thats why it seems all lights change at same time.

Simple solution is to also to make the outer thread sleep for some time but that will not gurantee sequence of the threads. I would suggest to use java.util.concurrent.CountDownLatch to make the outer thread wait for inner thread to finish.

    for (int i = 0; i < round; i++) {
        CountDownLatch countDownLatch = new CountDownLatch(1);
        // red is the position in the array
        if (colours[i] == 1) {
            Thread sleep = new Thread(new Worker(redButton, Color.RED, countDownLatch))
            sleep.start();

        }

        // yellow
        else if (colours[i] == 2) {
            Thread sleep = new Thread(new Worker(yellowButton, Color.YELLOW, countDownLatch))
            sleep.start();

        }
        // green
        else if (colours[i] == 3) {
            Thread sleep = new Thread(new Worker(greenButton, Color.GREEN, countDownLatch))
            sleep.start();

        }
        // blue
        else if (colours[i] == 4) {
            Thread sleep = new Thread(new Worker(blueButton, Color.CYAN, countDownLatch))
            sleep.start();

        }
        countDownLatch.await();
    }
}

class Worker implements Runnable {
    Button button;
    Color color;
    CountDownLatch countDownLatch;

    public Worker(Button button, Color color, CountDownLatch countDownLatch) {
        this.button = button;
        this.color = color;
        this.countDownLatch = countDownLatch;
    }

    @Override
    public void run() {
        button.setBackground(Color.WHITE);
        button.setOpaque(true);

        try {
            Thread.currentThread().sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        button.setBackground(color);
        button.setOpaque(false);
        countDownLatch.countDown();

    }
}

As soon as the light changes color for 1 second you count down the latch using countDownLatch.countDown() you wait for count down to hit zero with  countDownLatch.await() in outer thread.


问:
Labelled images but don't know what those labels correspond to
I have a bunch of images (basically a resized subset of Celeba dataset). And I have a binary label for each of those images. The images are people's faces.

The problem is : I don't know to which characteristic correspond those labels.

Do you have any method to "backtest" features and labels ? I have no idea how to determine what those labels correspond to.

I have tried visualizing those images again and again trying to understand what were the similarities between the images without success.

I have tried SVM classifier and then plot the coefficients to determine where the classifier was targeted, without success.

Thank you for the help

答:
No.  From an information theory standpoint, there is no way to reconstruct an arbitrary, abstract concept from a set of observations.  This is equivalent to most research using the scientific method: you're trying to guess the classification rationale from a finite set of data.  A guess that does a reliable job of predicting observed behaviour is called a "theory".

Does that help frame the way you look at the problem you're facing?


问:
Execute specific code based on input type
I need a function that accepts all subclasses of a parent class, this function will check the type of the argument it received and then it will do some specific operation on it, something like this:

class Animal {
  String sound;
}

class Cat extends Animal {
  String sound = 'Meow';
}

class Dog extends Animal {
  final String sound = 'Roof';
  final String somePropertyOnlyDogHave = 'Best friend';
}

void foo<T extends Animal>(T animal) {
  print(T.runtimeType);
  switch(T) {
    case Cat:
      print(animal.sound);
      break;
    case Dog:
      print(animal.sound);
      print(animal.somePropertyOnlyDogHave);
      break;
    default:
      print('No match');
  }
}
```

The code above doesn't compile, because somePropertyOnlyDogHave is not defined on the parent class.

How can achieve this functionality without having to define somePropertyOnlyDogHave on the parent class?

答:
you can cast the animal to type dog inside the Dog case, like this:

```<code>    case Dog:
      Dog dog = animal;
      print(dog.sound);
      print(dog.somePropertyOnlyDogHave);
      break;
</code>```

Body:
I need a function that accepts all subclasses of a parent class, this function will check the type of the argument it received and then it will do some specific operation on it, something like this:

class Animal {
  String sound;
}

class Cat extends Animal {
  String sound = 'Meow';
}

class Dog extends Animal {
  final String sound = 'Roof';
  final String somePropertyOnlyDogHave = 'Best friend';
}

void foo<T extends Animal>(T animal) {
  print(T.runtimeType);
  switch(T) {
    case Cat:
      print(animal.sound);
      break;
    case Dog:
      print(animal.sound);
      print(animal.somePropertyOnlyDogHave);
      break;
    default:
      print('No match');
  }
}

The code above doesn't compile, because somePropertyOnlyDogHave is not defined on the parent class.

How can achieve this functionality without having to define somePropertyOnlyDogHave on the parent class?

Body:
you can cast the animal to type dog inside the Dog case, like this:

    case Dog:
      Dog dog = animal;
      print(dog.sound);
      print(dog.somePropertyOnlyDogHave);
      break;


答:
Instead of a switch/case, consider using if/else with is operator:

```<code>void foo<T extends Animal>(T animal) {
  print(T.runtimeType);
  if (animal is Cat) {
    print(animal.sound);
  } else if (animal is Dog) {
    print(animal.sound);
    print(animal.somePropertyOnlyDogHave);
  } else {
    print('No match');
  }
}
</code>```

Using this syntax, Dart infers animal as Dog within the scope of the if.

Title: Execute specific code based on input type

Body:
Instead of a switch/case, consider using if/else with is operator:

void foo<T extends Animal>(T animal) {
  print(T.runtimeType);
  if (animal is Cat) {
    print(animal.sound);
  } else if (animal is Dog) {
    print(animal.sound);
    print(animal.somePropertyOnlyDogHave);
  } else {
    print('No match');
  }
}

Using this syntax, Dart infers animal as Dog within the scope of the if.


问:
How to write a PHP regexp that matches an optional substring?
OK, so now I've got two problems.

I've got a list of filenames. Some of those filenames may contain a HTML hex color reference. Like #11AACC. Also I'm interested only in image files (extensions jpg, jpeg, png, gif and bmp). So I'd like a regexp that would match if the file extension is one of the above, plus, if there is a HTML color reference anywhere in the string, it would get captured too. If there are multiple references, I don't care which one gets captured (there should be only one), but one should get captured. More than one is OK too, I can just ignore the rest beyond the first. Oh, and also the whole thing should be case-insensitive, but that's the least of worries.

If necessary, I can restrict the position of the color reference. But then I'd prefer it to be right before the extension, because otherwise naming these files would be awkward.

I'm trying to do something like /(#[a-fA-F]{6})?\.(?:jpeg|jpg|png|gif|bmp)$/i or /(#[a-fA-F]{6})?.*\.(?:jpeg|jpg|png|gif|bmp)$/i, but it doesn't capture the color reference.

答:
Is it because your character class

```<code>[a-fA-F]
</code>```

which represents a hex digit is missing digits?

Try

```<code>[a-fA-F0-9]
</code>```

Since you are using the i modifier for case in-sensitiveness you can just use:

```<code>[a-f0-9]
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Is it because your character class

[a-fA-F]

which represents a hex digit is missing digits?

Try

[a-fA-F0-9]

Since you are using the i modifier for case in-sensitiveness you can just use:

[a-f0-9]


问:
Oracle - Joining a inline table or table on the fly
I have a problem where a validation Code is stored in my table along with other data. Unfortunately the description is stored in a table where  I dont have access to. I do know the values

Example

12, 14, and 22- Description for them is available in an excel. I have no permissions to create a table to store the data and I need to run them every day as a reporting work.

12- Missing Work

14 - Absent

22 - Incomplete

Question: how do I write a query where I can create a dummy table(inline? On the fly?) with the values in excel and join to my table so that results looks like this

Note:

I cant create a perm table - no permissions. Its a read only Db for me

I want to give 12,MissingWork, 14, Absent as part of my query

Any thoughts. I tried searching. I think I am not using the right terminology and hence not finding results.

答:
You can do that by joining a subquery that SELECTs each code description pair FROM dual and uses UNION ALL to combine their results into one set.

```<code>SELECT t1.date,
       t1.task,
       t1.code,
       x.description
       FROM table1 t1
            LEFT JOIN (SELECT 12 code,
                              'Missing Work' description
                              FROM dual
                       UNION ALL
                       SELECT 14 code,
                              'Absent' description
                              FROM dual
                       ...) x
                      ON x.code = t1.code;
</code>```

Body:
You can do that by joining a subquery that SELECTs each code description pair FROM dual and uses UNION ALL to combine their results into one set.

SELECT t1.date,
       t1.task,
       t1.code,
       x.description
       FROM table1 t1
            LEFT JOIN (SELECT 12 code,
                              'Missing Work' description
                              FROM dual
                       UNION ALL
                       SELECT 14 code,
                              'Absent' description
                              FROM dual
                       ...) x
                      ON x.code = t1.code;


答:
As you know those codes and descriptions, a simple option is to create a CTE; in the following example, it is called excel. Another CTE in this example represents your "real" table1 (I could have created it in my database, but CTE is good enough to show what to do).

```<code>SQL> with excel (code, description) as
  2    (select 12, 'Missing Work' from dual union all
  3     select 14, 'Absent'       from dual union all
  4     select 22, 'Incomplete'   from dual
  5    ),
  6    table1 (c_date, task, code) as
  7    (select date '2019-05-30', 'Homework', 12 from dual union all
  8     select date '2019-05-31', 'Labwork' , 14 from dual union all
  9     select date '2019-05-30', 'Other'   , 22 from dual
 10    )
 11  select t.c_date, t.task, t.code, e.description
 12  from table1 t join excel e on e.code = t.code;

C_DATE     TASK           CODE DESCRIPTION
---------- -------- ---------- ------------
05/30/2019 Homework         12 Missing Work
05/31/2019 Labwork          14 Absent
05/30/2019 Other            22 Incomplete

SQL>
</code>```

Title: Oracle - Joining a inline table or table on the fly

Body:
I have a problem where a validation Code is stored in my table along with other data. Unfortunately the description is stored in a table where  I dont have access to. I do know the values

Example

12, 14, and 22- Description for them is available in an excel. I have no permissions to create a table to store the data and I need to run them every day as a reporting work.

12- Missing Work

14 - Absent

22 - Incomplete

Question: how do I write a query where I can create a dummy table(inline? On the fly?) with the values in excel and join to my table so that results looks like this

Note:

I cant create a perm table - no permissions. Its a read only Db for me

I want to give 12,MissingWork, 14, Absent as part of my query

Any thoughts. I tried searching. I think I am not using the right terminology and hence not finding results.

Body:
As you know those codes and descriptions, a simple option is to create a CTE; in the following example, it is called excel. Another CTE in this example represents your "real" table1 (I could have created it in my database, but CTE is good enough to show what to do).

SQL> with excel (code, description) as
  2    (select 12, 'Missing Work' from dual union all
  3     select 14, 'Absent'       from dual union all
  4     select 22, 'Incomplete'   from dual
  5    ),
  6    table1 (c_date, task, code) as
  7    (select date '2019-05-30', 'Homework', 12 from dual union all
  8     select date '2019-05-31', 'Labwork' , 14 from dual union all
  9     select date '2019-05-30', 'Other'   , 22 from dual
 10    )
 11  select t.c_date, t.task, t.code, e.description
 12  from table1 t join excel e on e.code = t.code;

C_DATE     TASK           CODE DESCRIPTION
---------- -------- ---------- ------------
05/30/2019 Homework         12 Missing Work
05/31/2019 Labwork          14 Absent
05/30/2019 Other            22 Incomplete

SQL>


问:
XSLT Delete and Append Tags
In my XML below, <Subject> is a sub-tag of <Subjects>. Additionally, <Subject> has a few sub-tags. What I need to do is A) remove all the sub-tags of <Subject> (they're duplicates of other fields we're merging this doc with later) and B) make the xref number the value of <Subject> so that it becomes <Subject_xref></Subject_xref>.

I attempted this using

```<code><xsl:template match="Subject">
   <xsl:apply-templates select="*" mode="extra" />
</xsl:template>
</code>```

but it did not change <Subject> and instead changed <SubjectPhone> to <SubjectPhone_Mobile>. What am I doing wrong, and how can I fix it?

XML

```<code><?xml version="1.0" encoding="UTF-8"?>
<NORMDOC>
   <DOC>
      <DOCID>123456789</DOCID>
      <Subjects>
         <Subject stype="PER" xref="54815594140">
            <SubjectPhone type="Mobile">JANE</SubjectPhone>
         </Subject>
      </Subjects>
      <TXT>
         <S sid="123456789-SENT-075">For assistance contact <ENAMEX type="BANK" id="BAN-123456789-323">BANK OF FURY</ENAMEX> Law Enforcement Liaison at <IDEX type="PHONE" id="PHO-123456789-324">000-000-0000</IDEX> or <CYBEX type="EMAIL" id="EMA-123456789-325">email@bankoffury.com</CYBEX>.</S>
      </TXT>
   </DOC>
   <ENTINFO ID="ACC-123456789-013"
            TYPE="ACCOUNT"
            MENTION="MI checking account # 333222111000"/>
</NORMDOC>
</code>```

XSLT

```<code><xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:template match="/NORMDOC">
    <xsl:apply-templates select="DOC"/>
    <ENTINFOS>
        <xsl:apply-templates select="ENTINFO"/>
    </ENTINFOS>
</xsl:template>

<xsl:template match="TXT">
    <RAW_TXT>
        <xsl:value-of select="."/>
    </RAW_TXT>
    <xsl:copy>
        <xsl:apply-templates/>
    </xsl:copy>
</xsl:template>

<xsl:template match="S">
    <xsl:copy>
        <xsl:apply-templates select="*" mode="extra"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="*" mode="extra">
    <xsl:element name="{name()}_{@type}">
        <xsl:apply-templates/>
    </xsl:element>
</xsl:template>

<xsl:template match="ENTINFO">
    <xsl:copy>
        <xsl:for-each select="@*">
            <xsl:element name="ENTINFO_{translate(name(), '-', '_')}">
                <xsl:value-of select="." />
             </xsl:element>
        </xsl:for-each>
    </xsl:copy>
</xsl:template>

<xsl:template match="/">
  <NORMDOC>
    <xsl:apply-templates/>
  </NORMDOC>
</xsl:template>

<xsl:template match="@*|node()">
  <xsl:copy>
    <xsl:apply-templates/>
  </xsl:copy>
</xsl:template>

</xsl:stylesheet>
</code>```

Actual Output

```<code><NORMDOC>
   <DOC>
      <DOCID>123456789</DOCID>
      <Subjects>
         <Subject>
            <SubjectPhone>JANE</SubjectPhone>
         </Subject>
      </Subjects>
      <RAW_TXT>For assistance contact BANK OF FURY Law Enforcement Liaison at 000-000-0000 or email@bankoffury.com.</RAW_TXT>
      <TXT>
         <S>
            <ENAMEX_BANK>BANK OF FURY</ENAMEX_BANK>
            <IDEX_PHONE>000-000-0000</IDEX_PHONE>
            <CYBEX_EMAIL>email@bankoffury.com</CYBEX_EMAIL>
         </S>
      </TXT>
   </DOC>
   <ENTINFOS>
      <ENTINFO>
         <ENTINFO_ID>ACC-123456789-013</ENTINFO_ID>
         <ENTINFO_TYPE>ACCOUNT</ENTINFO_TYPE>
         <ENTINFO_MENTION>MI checking account # 333222111000</ENTINFO_MENTION>
      </ENTINFO>
   </ENTINFOS>
</NORMDOC>
</code>```

Goal

```<code><NORMDOC>
   <DOC>
      <DOCID>123456789</DOCID>
      <Subjects>
         <Subject_xref>54815594140</Subject_xref>
      </Subjects>
      <RAW_TXT>For assistance contact BANK OF FURY Law Enforcement Liaison at 000-000-0000 or email@bankoffury.com.</RAW_TXT>
      <TXT>
         <S>
            ...
         </S>
      </TXT>
   </DOC>
   <ENTINFOS>
      <ENTINFO>
         ...
      </ENTINFO>
   </ENTINFOS>
</NORMDOC>
</code>```

答:
Just add the following template to the set:

```<code><xsl:template match="Subject">
  <Subject_xref><xsl:value-of select="@xref"/></Subject_xref>
</xsl:template>
</code>```

This does also remove all children of <Subject> elements.

Title: XSLT Delete and Append Tags

Body:
In my XML below, <Subject> is a sub-tag of <Subjects>. Additionally, <Subject> has a few sub-tags. What I need to do is A) remove all the sub-tags of <Subject> (they're duplicates of other fields we're merging this doc with later) and B) make the xref number the value of <Subject> so that it becomes <Subject_xref></Subject_xref>.

I attempted this using

<xsl:template match="Subject">
   <xsl:apply-templates select="*" mode="extra" />
</xsl:template>

but it did not change <Subject> and instead changed <SubjectPhone> to <SubjectPhone_Mobile>. What am I doing wrong, and how can I fix it?

XML

<?xml version="1.0" encoding="UTF-8"?>
<NORMDOC>
   <DOC>
      <DOCID>123456789</DOCID>
      <Subjects>
         <Subject stype="PER" xref="54815594140">
            <SubjectPhone type="Mobile">JANE</SubjectPhone>
         </Subject>
      </Subjects>
      <TXT>
         <S sid="123456789-SENT-075">For assistance contact <ENAMEX type="BANK" id="BAN-123456789-323">BANK OF FURY</ENAMEX> Law Enforcement Liaison at <IDEX type="PHONE" id="PHO-123456789-324">000-000-0000</IDEX> or <CYBEX type="EMAIL" id="EMA-123456789-325">email@bankoffury.com</CYBEX>.</S>
      </TXT>
   </DOC>
   <ENTINFO ID="ACC-123456789-013"
            TYPE="ACCOUNT"
            MENTION="MI checking account # 333222111000"/>
</NORMDOC>

XSLT

<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:template match="/NORMDOC">
    <xsl:apply-templates select="DOC"/>
    <ENTINFOS>
        <xsl:apply-templates select="ENTINFO"/>
    </ENTINFOS>
</xsl:template>

<xsl:template match="TXT">
    <RAW_TXT>
        <xsl:value-of select="."/>
    </RAW_TXT>
    <xsl:copy>
        <xsl:apply-templates/>
    </xsl:copy>
</xsl:template>

<xsl:template match="S">
    <xsl:copy>
        <xsl:apply-templates select="*" mode="extra"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="*" mode="extra">
    <xsl:element name="{name()}_{@type}">
        <xsl:apply-templates/>
    </xsl:element>
</xsl:template>

<xsl:template match="ENTINFO">
    <xsl:copy>
        <xsl:for-each select="@*">
            <xsl:element name="ENTINFO_{translate(name(), '-', '_')}">
                <xsl:value-of select="." />
             </xsl:element>
        </xsl:for-each>
    </xsl:copy>
</xsl:template>

<xsl:template match="/">
  <NORMDOC>
    <xsl:apply-templates/>
  </NORMDOC>
</xsl:template>

<xsl:template match="@*|node()">
  <xsl:copy>
    <xsl:apply-templates/>
  </xsl:copy>
</xsl:template>

</xsl:stylesheet>

Actual Output

<NORMDOC>
   <DOC>
      <DOCID>123456789</DOCID>
      <Subjects>
         <Subject>
            <SubjectPhone>JANE</SubjectPhone>
         </Subject>
      </Subjects>
      <RAW_TXT>For assistance contact BANK OF FURY Law Enforcement Liaison at 000-000-0000 or email@bankoffury.com.</RAW_TXT>
      <TXT>
         <S>
            <ENAMEX_BANK>BANK OF FURY</ENAMEX_BANK>
            <IDEX_PHONE>000-000-0000</IDEX_PHONE>
            <CYBEX_EMAIL>email@bankoffury.com</CYBEX_EMAIL>
         </S>
      </TXT>
   </DOC>
   <ENTINFOS>
      <ENTINFO>
         <ENTINFO_ID>ACC-123456789-013</ENTINFO_ID>
         <ENTINFO_TYPE>ACCOUNT</ENTINFO_TYPE>
         <ENTINFO_MENTION>MI checking account # 333222111000</ENTINFO_MENTION>
      </ENTINFO>
   </ENTINFOS>
</NORMDOC>

Goal

<NORMDOC>
   <DOC>
      <DOCID>123456789</DOCID>
      <Subjects>
         <Subject_xref>54815594140</Subject_xref>
      </Subjects>
      <RAW_TXT>For assistance contact BANK OF FURY Law Enforcement Liaison at 000-000-0000 or email@bankoffury.com.</RAW_TXT>
      <TXT>
         <S>
            ...
         </S>
      </TXT>
   </DOC>
   <ENTINFOS>
      <ENTINFO>
         ...
      </ENTINFO>
   </ENTINFOS>
</NORMDOC>

Body:
Just add the following template to the set:

<xsl:template match="Subject">
  <Subject_xref><xsl:value-of select="@xref"/></Subject_xref>
</xsl:template>

This does also remove all children of <Subject> elements.


答:
Perhaps use a common table expression with a union:</p>

```<code>with descr (code, description) as (
    select 12, 'Missing Work' from dual union
    select 14, 'Absent' from dual union
    select 22, 'Incomplete' from dual
)
select table1.date, table1.task, table1.code, descr.description
from table1
left join descr on table1.code = descr.code
</code>```

Body:
Perhaps use a common table expression with a union:

with descr (code, description) as (
    select 12, 'Missing Work' from dual union
    select 14, 'Absent' from dual union
    select 22, 'Incomplete' from dual
)
select table1.date, table1.task, table1.code, descr.description
from table1
left join descr on table1.code = descr.code


问:
What technique I should use for this web UI feature? (HTML frame or table or others)
I am not quite experienced with web UI design, so I ask here for some opinions of the UI feature I am currently working on. Basically, I would like to know which techniques I should use for the following feature:

I would like to implement a page, the left side of the page occupy 1/3 width of the page, and contain text field, buttons and checkboxes. The right side of the page occupy 2/3 width of the page, it will show some dynamic content based on the left side user input. The right side of the page is mainly implemented by using javascript, jQuery and ajax.

Should I use HTML frame for left and right sides of the page or should I just use a table to divide the page to two parts? or what else? which is better?

答: Never ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever use frames. </p>


问:
Why doesn't my geocoding-based address verifier output to Google Sheets?
So I'm a mega-beginner (familiar with js from SoloLearn, some Google apps script knowledge from Udemy) trying my hand at setting up an "address verifier" for a dataset that my organization uses. We get address information from people who fill out our forms online and also have interns enter the same info from paper forms that are submitted. This leads to a mess of different address formats being entered into our central Google sheet column.

I'm basically trying to use the geocoder service to take the raw data from that address column (the one in "SpreadsheetApp.getActive"), run it through Google to match it to actual coordinates, then output the correct address using a standard format. I modeled this code from a Stack Exchange thread that I wish I had kept open to link here.

I've debugged this and it seems to "run" just fine, (without error messages), but it doesn't ultimately put out the new addresses. I tried to put a Log in there so that I could see if the geocoder was actually pulling anything into a results object, but I failed with that too. Please help me I am drowning.

```<code><!-- language: lang-js -->
function menuItem1() {
function addrVerify() {
var sheet = SpreadsheetApp.getActive()
var addrRange = sheet.getActiveRange()
var geocoder = new google.maps.Geocoder();
  geocoder.geocode({
    'Addresses': addrRange.value});
function(results, status) {
    if (status === google.maps.GeocoderStatus.OK && results.length > 0)
    {addrRange.value = results[0].formatted_address;;}
  else alert("Invalid address");
  };
 }
}
</code>```

I was able to put a button to run the function on my sheet's UI, so there's a start. Also, I now know how to do a code fence!

答:
Using the example in the above comment I put addresses in column one starting at line two and I used "Address" for column1 header and "Lat" for column2 Header and "Lng" for column3 header.

This code correctly filled in the lat and lng for each address in columns 2 and 3.

```<code>function addrVerify() {
  var ss = SpreadsheetApp.getActive()
  var dsh = ss.getActiveSheet();
  var rg = dsh.getRange(2,1,dsh.getLastRow()-1,3);
  var addrA= rg.getValues();

  for(var i=0;i<addrA.length;i++) {
    var resp=Maps.newGeocoder().geocode(addrA[i][0]);
    for(var j=0;j<resp.results.length;j++) {
      var result=resp.results[j];
      addrA[i][1]=result.geometry.location.lat;
      addrA[i][2]=result.geometry.location.lng;
      Logger.log('%s: %s, %s', result.formatted_address, result.geometry.location.lat,result.geometry.location.lng);
    }
  }
  rg.setValues(addrA);
}
</code>```

My spreadsheet looked like this:( only with real addresses)

Body:
So I'm a mega-beginner (familiar with js from SoloLearn, some Google apps script knowledge from Udemy) trying my hand at setting up an "address verifier" for a dataset that my organization uses. We get address information from people who fill out our forms online and also have interns enter the same info from paper forms that are submitted. This leads to a mess of different address formats being entered into our central Google sheet column.

I'm basically trying to use the geocoder service to take the raw data from that address column (the one in "SpreadsheetApp.getActive"), run it through Google to match it to actual coordinates, then output the correct address using a standard format. I modeled this code from a Stack Exchange thread that I wish I had kept open to link here.

I've debugged this and it seems to "run" just fine, (without error messages), but it doesn't ultimately put out the new addresses. I tried to put a Log in there so that I could see if the geocoder was actually pulling anything into a results object, but I failed with that too. Please help me I am drowning.

function menuItem1() {
function addrVerify() {
var sheet = SpreadsheetApp.getActive()
var addrRange = sheet.getActiveRange()
var geocoder = new google.maps.Geocoder();
  geocoder.geocode({
    'Addresses': addrRange.value});
function(results, status) {
    if (status === google.maps.GeocoderStatus.OK && results.length > 0)
    {addrRange.value = results[0].formatted_address;;}
  else alert("Invalid address");
  };
 }
}

I was able to put a button to run the function on my sheet's UI, so there's a start. Also, I now know how to do a code fence!

Body:
Using the example in the above comment I put addresses in column one starting at line two and I used "Address" for column1 header and "Lat" for column2 Header and "Lng" for column3 header.

This code correctly filled in the lat and lng for each address in columns 2 and 3.

function addrVerify() {
  var ss = SpreadsheetApp.getActive()
  var dsh = ss.getActiveSheet();
  var rg = dsh.getRange(2,1,dsh.getLastRow()-1,3);
  var addrA= rg.getValues();

  for(var i=0;i<addrA.length;i++) {
    var resp=Maps.newGeocoder().geocode(addrA[i][0]);
    for(var j=0;j<resp.results.length;j++) {
      var result=resp.results[j];
      addrA[i][1]=result.geometry.location.lat;
      addrA[i][2]=result.geometry.location.lng;
      Logger.log('%s: %s, %s', result.formatted_address, result.geometry.location.lat,result.geometry.location.lng);
    }
  }
  rg.setValues(addrA);
}

My spreadsheet looked like this:( only with real addresses)


答:
You can use something called Common Table Expressions (CTE)</p>

```<code>WITH Code_lookup AS (
  SELECT 12 Code, 'Missing Work' Description FROM DUAL UNION ALL
  SELECT 14, 'Absent' FROM DUAL UNION ALL
  SELECT 22, 'Incomplete' FROM DUAL)
SELECT <your columns list>
  FROM <your table>
  JOIN Code_lookup USING (Code)
</code>```

Body:
You can use something called Common Table Expressions (CTE)

WITH Code_lookup AS (
  SELECT 12 Code, 'Missing Work' Description FROM DUAL UNION ALL
  SELECT 14, 'Absent' FROM DUAL UNION ALL
  SELECT 22, 'Incomplete' FROM DUAL)
SELECT <your columns list>
  FROM <your table>
  JOIN Code_lookup USING (Code)


问:
How do I set SVG user units when the height/width values are React props?
Newbie here, and this is my first stackoverflow question, so apologies if this a poorly formed question.

I'm working in React and generating an SVG with user defined inputs. I'm trying to define user units as mm instead of the default px, but I can't seem to find the right syntax for using props as the height/width values AND setting the units at the same time. I currently have the width/height values set by props, and I can successfully define units if I give a fixed value (15mm, for example), but I'm not able to do both at the same time.

```<code>// app.js

...

state = {
   svgWidth: 200,
   svgHeight: 200,
};

handleChange = (e) => {
   const name = e.target.id;
   const value = parseFloat(e.target.value
   this.setState({ [name]: value });
};

...

<Inputs
   {...this.state}
   handleChange={this.handleChange}
/>

<SVG
  {...this.state}
/>

//inputs.js

...

<TextField
   id="svgWidth"
   value={props.svgWidth}
   onChange={handleChange}
/>

<TextField
   id="svgHeight"
   value={props.svgHeight}
   onChange={handleChange}
/>

// svg.js

...

<svg width={props.svgWidth} height={props.svgHeight}>
   ...
</svg>
</code>```

答:
As I suspected, my original question was just a lack of experience with the syntax. I was able to define units alongside props as the value by using template literals to concatenate the variable and the unit indicator.

```<code>// svg.js

...

<svg
   width={`${props.svgWidth}mm`}
   height={`${props.svgHeight}mm`}
>
   ...
</svg>
</code>```

However, in order link the svg user units to the "real world" units defined at the top level svg element, I had to define the svg viewBox to be the same dimensions.

```<code>// svg.js

...

<svg
   width={`${props.svgWidth}mm`}
   height={`${props.svgHeight}mm`}
   viewBox={`0 0 ${props.svgWidth} ${props.svgHeight}`}
>
   ...
</svg>
</code>```

Thanks for the assist, John.

Body:
Newbie here, and this is my first stackoverflow question, so apologies if this a poorly formed question.

I'm working in React and generating an SVG with user defined inputs. I'm trying to define user units as mm instead of the default px, but I can't seem to find the right syntax for using props as the height/width values AND setting the units at the same time. I currently have the width/height values set by props, and I can successfully define units if I give a fixed value (15mm, for example), but I'm not able to do both at the same time.

// app.js

...

state = {
   svgWidth: 200,
   svgHeight: 200,
};

handleChange = (e) => {
   const name = e.target.id;
   const value = parseFloat(e.target.value
   this.setState({ [name]: value });
};

...

<Inputs
   {...this.state}
   handleChange={this.handleChange}
/>

<SVG
  {...this.state}
/>

//inputs.js

...

<TextField
   id="svgWidth"
   value={props.svgWidth}
   onChange={handleChange}
/>

<TextField
   id="svgHeight"
   value={props.svgHeight}
   onChange={handleChange}
/>

// svg.js

...

<svg width={props.svgWidth} height={props.svgHeight}>
   ...
</svg>

Body:
As I suspected, my original question was just a lack of experience with the syntax. I was able to define units alongside props as the value by using template literals to concatenate the variable and the unit indicator.

// svg.js

...

<svg
   width={`${props.svgWidth}mm`}
   height={`${props.svgHeight}mm`}
>
   ...
</svg>

However, in order link the svg user units to the "real world" units defined at the top level svg element, I had to define the svg viewBox to be the same dimensions.

// svg.js

...

<svg
   width={`${props.svgWidth}mm`}
   height={`${props.svgHeight}mm`}
   viewBox={`0 0 ${props.svgWidth} ${props.svgHeight}`}
>
   ...
</svg>

Thanks for the assist, John.


问:
AMP with Ruby on Rails : Impossible to use a a Google Font
I am implementing AMP pages on my Rails app. However I can't get my font to work. It raises this error on the Google Search Console :

"CSS syntax error in the "amp-custom style" tag. Incorrect declaration."
Ligne 14:63 quot;Raleway", sans-serif}.banner{color:white;tex...

This is my application.amp.erb

```<code><!doctype html>
<html ⚡>
  <head>
    <meta charset="utf-8">
    <link rel="canonical" href="<%= url_for(format: :html, only_path: false) %>" >
    <link href="https://fonts.googleapis.com/css?family=Raleway:400,600&display=swap" rel="stylesheet">
    <meta name="viewport" content="width=device-width,minimum-scale=1,initial-scale=1">
    <style amp-boilerplate>body{-webkit-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-moz-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-ms-animation:-amp-start 8s steps(1,end) 0s 1 normal both;animation:-amp-start 8s steps(1,end) 0s 1 normal both}@-webkit-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-moz-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-ms-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-o-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}</style><noscript><style amp-boilerplate>body{-webkit-animation:none;-moz-animation:none;-ms-animation:none;animation:none}</style></noscript>
    <script async src="https://cdn.ampproject.org/v0.js"></script>
    <script async custom-element="amp-iframe" src="https://cdn.ampproject.org/v0/amp-iframe-0.1.js"></script>
    <script async custom-element="amp-youtube" src="https://cdn.ampproject.org/v0/amp-youtube-0.1.js"></script>
    <script async custom-element="amp-form" src="https://cdn.ampproject.org/v0/amp-form-0.1.js"></script>
    <script async custom-element="amp-font" src="https://cdn.ampproject.org/v0/amp-font-0.1.js"></script>
    <% if Rails.application.assets && Rails.application.assets['amp/application'] %>
      <style amp-custom>
        <%= Rails.application.assets['amp/application'].to_s.html_safe %>
      </style>
    <% else %>
    <style amp-custom><%= File.read "#{Rails.root}/public#{stylesheet_path('amp/application', host: nil)}" %>
    </style>
    <% end %>
  </head>
  <body>
    <amp-font
      layout="nodisplay"
      timeout="3000"
      font-family="Raleway">
    </amp-font>
    <div class="amp">
      <%= render "shared/navbar" %>
      <%= yield %>
    </div>
  </body>
</html>`
</code>```

And the beginning of my application.scss that I import for my AMP views which triggers the error on the Google Console :

```<code>body {
  font-family: "Raleway", sans-serif;
}
</code>```

I tried everything, @font-face included, but nothing worked.

However, according to the official documentation (https://amp.dev/documentation/guides-and-tutorials/develop/style_and_layout/custom_fonts) the link syntax should work with Google Fonts which is obviously a white-listed font provider allowed by AMP.

答:
Try to import your font directly into your css file:

```<code>@import url('https://fonts.googleapis.com/css?family=Raleway&display=swap');
</code>```

then you can create a class for this font or use it directly in body style:

```<code>.raleway {
    font-family: "Raleway", sans-serif; /* for set this font on every element you want by using this class
}
/* or in body style: */
body {
    font-family: "Raleway", sans-serif;
}
</code>```

Greetz Toxi

Body:
I am implementing AMP pages on my Rails app. However I can't get my font to work. It raises this error on the Google Search Console :

"CSS syntax error in the "amp-custom style" tag. Incorrect declaration."
Ligne 14:63 quot;Raleway", sans-serif}.banner{color:white;tex...

This is my application.amp.erb

<!doctype html>

    <meta charset="utf-8">
    <link rel="canonical" href="<%= url_for(format: :html, only_path: false) %>" >
    <link href="https://fonts.googleapis.com/css?family=Raleway:400,600&display=swap" rel="stylesheet">
    <meta name="viewport" content="width=device-width,minimum-scale=1,initial-scale=1">

    <% if Rails.application.assets && Rails.application.assets['amp/application'] %>

    <% else %>

    <% end %>

    <amp-font
      layout="nodisplay"
      timeout="3000"
      font-family="Raleway">
    </amp-font>

      <%= render "shared/navbar" %>
      <%= yield %>

`

And the beginning of my application.scss that I import for my AMP views which triggers the error on the Google Console :

body {
  font-family: "Raleway", sans-serif;
}

I tried everything, @font-face included, but nothing worked.

However, according to the official documentation (https://amp.dev/documentation/guides-and-tutorials/develop/style_and_layout/custom_fonts) the link syntax should work with Google Fonts which is obviously a white-listed font provider allowed by AMP.

Body:
Try to import your font directly into your css file:

@import url('https://fonts.googleapis.com/css?family=Raleway&display=swap');

then you can create a class for this font or use it directly in body style:

.raleway {
    font-family: "Raleway", sans-serif; /* for set this font on every element you want by using this class
}
/* or in body style: */
body {
    font-family: "Raleway", sans-serif;
}

Greetz Toxi


问:
How do I make a border-left display outside the list marker in IE8?
I have an ordered list that I want to put a border on the left.

```<code><ol class="steps">
  <li>item 1</li>
  <li>item 2</li>
  <li>item 3</li>
<ol>

.steps {border-left: 5px double #7ab800;}
</code>```

In Firefox and Safari, the border displays outside the numbers for the
. However, IE8 displays the border inside the numbers, right next to the text for each
.

I tried changing <display> to inline-block but that removes the numbering. I tried changing list-style-position to inside but that changes the indentation of the list without moving the position of the border. There are no floats involved. There is a
 wrapping the
 but it is not styled in any way.

I'm stumped. How can I get IE8 to display the border the same as Firefox and Safari?

答: Try putting a div tag around your list and apply your class to the div instead.</p>

Body:
I have an ordered list that I want to put a border on the left.

item 1

item 2

item 3

.steps {border-left: 5px double #7ab800;}

In Firefox and Safari, the border displays outside the numbers for the
. However, IE8 displays the border inside the numbers, right next to the text for each
.

I tried changing <display> to inline-block but that removes the numbering. I tried changing list-style-position to inside but that changes the indentation of the list without moving the position of the border. There are no floats involved. There is a
 wrapping the
 but it is not styled in any way.

I'm stumped. How can I get IE8 to display the border the same as Firefox and Safari?


问:
Extraction of Data using tbodyclass and Beautifulsoup
Extraction with tbody class using BeautifulSoup and Python 3.

Im trying to extract the table (summary) on top of it. Im using BeautifulSoup for extraction. However I get the following error while using tclass to extract the table containing name,age,info etc

I am aware I can use the previous table{class :datatable} to extract the table .However I want to try extracting using tbody class

How do i extract the table with tbodyclass and what error am i making?
Im bit new to web scraping and any  detailed help would be appreciated

Here is the code

```<code>import numpy as np
import pandas as pd
from bs4 import BeautifulSoup
import requests

urls=['https://www.reuters.com/finance/stocks/company- officers/GOOG.O',
      'https://www.reuters.com/finance/stocks/company- officers/AMZN',
      'https://www.reuters.com/finance/stocks/company- officers/AAPL']

for item in urls:
   response=requests.get(item)
   data=response.content
   soup=BeautifulSoup(data,'html.parser')
   required_data=soup.find_all(class_='moduleBody')
   real_data=required_data.find_all(tbodyclass_='dataSmall')
   print(real_data)
</code>```

Here is the Error

```<code>Traceback (most recent call last):
 File "C:\Users\XXXX\Desktop\scrape.py", line 15, in <module>
real_data=required_data.find_all(tbodyclass_='dataSmall')
 File "C:\Users\XXXX\AppData\Local\Programs\Python\Python37\lib\site-
 packages\bs4\element.py", line 1620, in __getattr__
"ResultSet object has no attribute '%s'. You're probably treating a list of items like a single item. Did you call find_all() when you meant to call find()?" % key
AttributeError: ResultSet object has no attribute 'find_all'. You're
probably treating a list of items like a single item. Did you call
find_all() when you meant to call find()?
</code>```

答:
To target only be tbody you need to select only the first match for that tbody class. So you can use select_one.

```<code>table = soup.select_one('table:has(.dataSmall)')
</code>```

gets you the table without the table tags and you can still loop trs and tds within to write out table. I show using pandas though to handle below.

Looks like you can use pandas

```<code>import pandas as pd

urls=['https://www.reuters.com/finance/stocks/company- officers/GOOG.O',
      'https://www.reuters.com/finance/stocks/company- officers/AMZN',
      'https://www.reuters.com/finance/stocks/company- officers/AAPL']
for url in urls:
    table = pd.read_html(url)[0]
    print(table)
</code>```

Combining using pandas and the tbody class but pulling in parent table tag

```<code>import requests
import pandas as pd

urls=['https://www.reuters.com/finance/stocks/company- officers/GOOG.O',
      'https://www.reuters.com/finance/stocks/company- officers/AMZN',
      'https://www.reuters.com/finance/stocks/company- officers/AAPL']
with requests.Session() as s:
    for url in urls:
        r = s.get(url)
        soup = bs(r.content, 'lxml')
        table = soup.select_one('table:has(.dataSmall)')
        print(pd.read_html(str(table)))
</code>```

Ignoring table tag (but adding later for pandas to parse) - you don't have to and can loop tr and td within rather than handover to pandas.

```<code>import pandas as pd

urls=['https://www.reuters.com/finance/stocks/company- officers/GOOG.O',
      'https://www.reuters.com/finance/stocks/company- officers/AMZN',
      'https://www.reuters.com/finance/stocks/company- officers/AAPL']
with requests.Session() as s:
    for url in urls:
        r = s.get(url)
        soup = bs(r.content, 'lxml')
        table = soup.select_one('.dataSmall')
        print(pd.read_html('<table>' + str(table) + '</table>'))
</code>```

Body:
Extraction with tbody class using BeautifulSoup and Python 3.

Im trying to extract the table (summary) on top of it. Im using BeautifulSoup for extraction. However I get the following error while using tclass to extract the table containing name,age,info etc

I am aware I can use the previous table{class :datatable} to extract the table .However I want to try extracting using tbody class

How do i extract the table with tbodyclass and what error am i making?
Im bit new to web scraping and any  detailed help would be appreciated

Here is the code

import numpy as np
import pandas as pd
from bs4 import BeautifulSoup
import requests

urls=['https://www.reuters.com/finance/stocks/company- officers/GOOG.O',
      'https://www.reuters.com/finance/stocks/company- officers/AMZN',
      'https://www.reuters.com/finance/stocks/company- officers/AAPL']

for item in urls:
   response=requests.get(item)
   data=response.content
   soup=BeautifulSoup(data,'html.parser')
   required_data=soup.find_all(class_='moduleBody')
   real_data=required_data.find_all(tbodyclass_='dataSmall')
   print(real_data)

Here is the Error

Traceback (most recent call last):
 File "C:\Users\XXXX\Desktop\scrape.py", line 15, in <module>
real_data=required_data.find_all(tbodyclass_='dataSmall')
 File "C:\Users\XXXX\AppData\Local\Programs\Python\Python37\lib\site-
 packages\bs4\element.py", line 1620, in __getattr__
"ResultSet object has no attribute '%s'. You're probably treating a list of items like a single item. Did you call find_all() when you meant to call find()?" % key
AttributeError: ResultSet object has no attribute 'find_all'. You're
probably treating a list of items like a single item. Did you call
find_all() when you meant to call find()?

Body:
To target only be tbody you need to select only the first match for that tbody class. So you can use select_one.

table = soup.select_one('table:has(.dataSmall)')

gets you the table without the table tags and you can still loop trs and tds within to write out table. I show using pandas though to handle below.

Looks like you can use pandas

import pandas as pd

urls=['https://www.reuters.com/finance/stocks/company- officers/GOOG.O',
      'https://www.reuters.com/finance/stocks/company- officers/AMZN',
      'https://www.reuters.com/finance/stocks/company- officers/AAPL']
for url in urls:
    table = pd.read_html(url)[0]
    print(table)

Combining using pandas and the tbody class but pulling in parent table tag

import requests
import pandas as pd

urls=['https://www.reuters.com/finance/stocks/company- officers/GOOG.O',
      'https://www.reuters.com/finance/stocks/company- officers/AMZN',
      'https://www.reuters.com/finance/stocks/company- officers/AAPL']
with requests.Session() as s:
    for url in urls:
        r = s.get(url)
        soup = bs(r.content, 'lxml')
        table = soup.select_one('table:has(.dataSmall)')
        print(pd.read_html(str(table)))

Ignoring table tag (but adding later for pandas to parse) - you don't have to and can loop tr and td within rather than handover to pandas.

import pandas as pd

urls=['https://www.reuters.com/finance/stocks/company- officers/GOOG.O',
      'https://www.reuters.com/finance/stocks/company- officers/AMZN',
      'https://www.reuters.com/finance/stocks/company- officers/AAPL']
with requests.Session() as s:
    for url in urls:
        r = s.get(url)
        soup = bs(r.content, 'lxml')
        table = soup.select_one('.dataSmall')
        print(pd.read_html('<table>' + str(table) + '</table>'))


问:
Searching multiple columns for multiple values showing records that match all values only MySQL
I am having an issue on how to structure a statement so it will return the records that match multiple values within multiple columns even though the value may not be located in other columns...yeah I know it sounds confusing let me explain.

Let's say I am looking for 2 values ("this" and "that"). Let's also say that I am looking in 4 different columns for these values. Here are 2 scenario statements I have come up with but neither work correctly and I will explain each one.

Using the AND operator

```<code>SELECT * FROM table
WHERE (column1 LIKE '%this%'
    AND column2 LIKE '%this%'
    AND column3 LIKE '%this%'
    AND column4 LIKE '%this%'
    AND column1 LIKE '%that%'
    AND column2 LIKE '%that%'
    AND column3 LIKE '%that%'
    AND column4 LIKE '%that%')
</code>```

If I use the AND operator for my statement then each value has to be within each column or the statement will return no records. So let's say it finds "this" in column2 and finds "that" in column1. Even though it found these values in those 2 columns this will still return no records because these values were not found in column3 and column 4

Using the OR operator

```<code>SELECT * FROM table
WHERE (column1 LIKE '%this%'
    OR column2 LIKE '%this%'
    OR column3 LIKE '%this%'
    OR column4 LIKE '%this%'
    OR column1 LIKE '%that%'
    OR column2 LIKE '%that%'
    OR column3 LIKE '%that%'
    OR column4 LIKE '%that%')
</code>```

If I use the OR operator then it will return all the records that contain any of the values in any of the columns even though the record may only contain one of these values and not both.

What I am trying to accomplish with my statement is to only return the records that contain both "this" AND "that" in any of the columns even though other columns may not contain those values.

Hope this makes sense.

答:
Use a combination of AND and OR.

```<code>SELECT * FROM table
WHERE (column1 LIKE '%this%'
    OR column2 LIKE '%this%'
    OR column3 LIKE '%this%'
    OR column4 LIKE '%this%')
AND (column1 LIKE '%that%'
    OR column2 LIKE '%that%'
    OR column3 LIKE '%that%'
    OR column4 LIKE '%that%')
</code>```

Body:
I am having an issue on how to structure a statement so it will return the records that match multiple values within multiple columns even though the value may not be located in other columns...yeah I know it sounds confusing let me explain.

Let's say I am looking for 2 values ("this" and "that"). Let's also say that I am looking in 4 different columns for these values. Here are 2 scenario statements I have come up with but neither work correctly and I will explain each one.

Using the AND operator

SELECT * FROM table
WHERE (column1 LIKE '%this%'
    AND column2 LIKE '%this%'
    AND column3 LIKE '%this%'
    AND column4 LIKE '%this%'
    AND column1 LIKE '%that%'
    AND column2 LIKE '%that%'
    AND column3 LIKE '%that%'
    AND column4 LIKE '%that%')

If I use the AND operator for my statement then each value has to be within each column or the statement will return no records. So let's say it finds "this" in column2 and finds "that" in column1. Even though it found these values in those 2 columns this will still return no records because these values were not found in column3 and column 4

Using the OR operator

SELECT * FROM table
WHERE (column1 LIKE '%this%'
    OR column2 LIKE '%this%'
    OR column3 LIKE '%this%'
    OR column4 LIKE '%this%'
    OR column1 LIKE '%that%'
    OR column2 LIKE '%that%'
    OR column3 LIKE '%that%'
    OR column4 LIKE '%that%')

If I use the OR operator then it will return all the records that contain any of the values in any of the columns even though the record may only contain one of these values and not both.

What I am trying to accomplish with my statement is to only return the records that contain both "this" AND "that" in any of the columns even though other columns may not contain those values.

Hope this makes sense.

Body:
Use a combination of AND and OR.

SELECT * FROM table
WHERE (column1 LIKE '%this%'
    OR column2 LIKE '%this%'
    OR column3 LIKE '%this%'
    OR column4 LIKE '%this%')
AND (column1 LIKE '%that%'
    OR column2 LIKE '%that%'
    OR column3 LIKE '%that%'
    OR column4 LIKE '%that%')


问:
Debugging greasemonkey-like scripts
I'm writing javascript code that is read in as a string and executed via eval() by a firefox extension. Firebug does "see" my script so I am not able to use breakpoints, see objects, etc.

I am currently using Firefox's error console which I'm starting to find limiting. What are my other options? Ideally, I would be able to use Firebug or something similar to it. How do people generally debug Greasemonkey scripts?

I've tried using Lint and other validators, but my script uses a lot of objects and functions provided by the extension environment, making of a lot of the errors reported irrelevant. Also, the output tends to be too nitpicky (focusing of spacing issues, etc).

答:
I've created an interactive console for debugging Greasemonkey scripts. It requires Google Gears, but it includes a persistent history of commands that were typed.

UPDATE: Here's a link to a blog post describing using GreasyThug to debug a GM script. It's got a step by step procedure to replicate an error and devise a solution.

OwnerDisplayName: thaiyoshi

ContentLicense: CC BY-SA 2.5

Title: Debugging greasemonkey-like scripts

LastEditorDisplayName: Daniel X Moore


问:
Outer sum of coordinates
I have two arrays:

# A
[[0 3]
 [2 3]
 [3 1]]

# B
[[2  0]
 [0 -1]
 [0  1]
 [1  0]]
```

<p>The result should be the outer sum coordinate-wise:</p>

```[[2 3],[0 2],[0 4],[1 3]], # [0 3] + each element of B
[[4 3],[2 2],[2 4],[3 3]],
[[5 1],[3 0],[3 2],[4 1]]
```

<p>I managed to solve it with loops, however, the vectorized implementation is needed to work with large matrices. I have approached this with outer sum, but without any success.</p>

```for i in A:
    for j in B:
        print(i+j)
```

答:
Simply extend a to 3D keeping the last axis aligned with the last one from b and add them up. This would leverage broadcasting for a vectorized solution. To do the extension to higher dimensions, we can use np.newaxis/None.

Hence, simply do -

```<code>a[:,None,:] + b[:, :]
</code>```

Skipping the redundant last axes specified with :'s, we would be left with -

```<code>a[:,None] + b
</code>```

Schematically put -

```<code>a[:,None,:] :   m x 1 x n
b[:,:]      :       k x n
output      :   m x k x n
</code>```

For large arrays, we can also leverage numexpr that makes uses of multi-cores. To do so, we need to port the earlier listed broadcasting method with few modifications, like so -

```<code>import numexpr as ne

ne.evaluate('a3D+b',{'a3D':a[:,None]})
</code>```

Timings -

```<code>In [17]: np.random.seed(0)
    ...: a = np.random.rand(1000,3)
    ...: b = np.random.rand(1000,3)

In [18]: %timeit a[:,None] + b
11 ms ± 92.7 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

In [19]: %timeit ne.evaluate('a3D+b',{'a3D':a[:,None]})
4.1 ms ± 95.1 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
</code>```

Title: Outer sum of coordinates

Body:
I have two arrays:

# A
[[0 3]
 [2 3]
 [3 1]]

# B
[[2  0]
 [0 -1]
 [0  1]
 [1  0]]

The result should be the outer sum coordinate-wise:

[[2 3],[0 2],[0 4],[1 3]], # [0 3] + each element of B
[[4 3],[2 2],[2 4],[3 3]],
[[5 1],[3 0],[3 2],[4 1]]

I managed to solve it with loops, however, the vectorized implementation is needed to work with large matrices. I have approached this with outer sum, but without any success.

for i in A:
    for j in B:
        print(i+j)

Body:
Simply extend a to 3D keeping the last axis aligned with the last one from b and add them up. This would leverage broadcasting for a vectorized solution. To do the extension to higher dimensions, we can use np.newaxis/None.

Hence, simply do -

a[:,None,:] + b[:, :]

Skipping the redundant last axes specified with :'s, we would be left with -

a[:,None] + b

Schematically put -

a[:,None,:] :   m x 1 x n
b[:,:]      :       k x n
output      :   m x k x n

For large arrays, we can also leverage numexpr that makes uses of multi-cores. To do so, we need to port the earlier listed broadcasting method with few modifications, like so -

import numexpr as ne

ne.evaluate('a3D+b',{'a3D':a[:,None]})

Timings -

In [17]: np.random.seed(0)
    ...: a = np.random.rand(1000,3)
    ...: b = np.random.rand(1000,3)

In [18]: %timeit a[:,None] + b
11 ms ± 92.7 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

In [19]: %timeit ne.evaluate('a3D+b',{'a3D':a[:,None]})
4.1 ms ± 95.1 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)


问:
Not found constructor AndroidDriver with Appium in eclipse
Code with errors:

```<code>package TestCase;

import java.net.MalformedURLException;
import java.net.URI;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import com.gargoylesoftware.htmlunit.javascript.host.URL;
import io.appium.java_client.AppiumDriver;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.remote.MobileCapabilityType;
import io.appium.java_client.remote.MobilePlatform;

public class TestWebBrowser {
    //AppiumDriver driver = new IOSDriver();
    public static AndroidDriver driver;

    public static void main(String[] args) throws MalformedURLException {
        DesiredCapabilities capabilities = new DesiredCapabilities();
        driver = new AndroidDriver(new URL("http://127.0.0.1:4723/wd/hub"), capabilities);
    }
}
</code>```

The message error is:

The constructor URL(string) is undefined

The constructor AndroidDriver(URL, DesiredCapabilities) is undefined

AndroidDriver is a raw type

I have tried with different versions of java-client and still the problem persists

答:
You need to use an existen constructor like this:

https://appium.github.io/java-client/io/appium/java_client/android/AndroidDriver.html

You need use java.net.URL and not com.gargoylesoftware.htmlunit.javascript.host.URL

Body:
Code with errors:

package TestCase;

import java.net.MalformedURLException;
import java.net.URI;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import com.gargoylesoftware.htmlunit.javascript.host.URL;
import io.appium.java_client.AppiumDriver;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.remote.MobileCapabilityType;
import io.appium.java_client.remote.MobilePlatform;

public class TestWebBrowser {
    //AppiumDriver driver = new IOSDriver();
    public static AndroidDriver driver;

    public static void main(String[] args) throws MalformedURLException {
        DesiredCapabilities capabilities = new DesiredCapabilities();
        driver = new AndroidDriver(new URL("http://127.0.0.1:4723/wd/hub"), capabilities);
    }
}

The message error is:

The constructor URL(string) is undefined

The constructor AndroidDriver(URL, DesiredCapabilities) is undefined

AndroidDriver is a raw type

I have tried with different versions of java-client and still the problem persists


问:
How to get target's version by Ruby (or Xcodeproj)
How to get target's version(The version of you APP) in Ruby or Xcodeproj?

I have tried sdk_version in AbstractTarget with Xcodeproj, But it returns nil.

If Xcodeproj doesn't support it. How to get the version by Ruby?

答:
I did this in Ruby using the plist gem, like this:

```<code>require 'plist'
info = Plist.parse_xml('path/to/Info.plist')
puts info["CFBundleShortVersionString"]
puts info["CFBundleVersion"]
</code>```

I hope it helps.

Body:
I did this in Ruby using the plist gem, like this:

require 'plist'
info = Plist.parse_xml('path/to/Info.plist')
puts info["CFBundleShortVersionString"]
puts info["CFBundleVersion"]

I hope it helps.


问:
pip install Error: setup script specifies an absolute path
I suffer a strange behaviour of pip.
Calling

```<code>pip install git+https://github.com/username/repo
</code>```

generally works, but on some packages it fails in an abnormal way

```<code>Downloading/unpacking git+git://github.com/artscoop/django-inplaceedit
  Cloning git://github.com/artscoop/django-inplaceedit to /tmp/pip-rl1_7G-build
  Running setup.py egg_info for package from git+git://github.com/artscoop/django-inplaceedit

Installing collected packages: django-inplaceedit
  Running setup.py install for django-inplaceedit

    error: Error: setup script specifies an absolute path:

        /tmp/pip-rl1_7G-build/AUTHORS.rst

    setup() arguments must *always* be /-separated paths relative to the
    setup.py directory, *never* absolute paths.

    Complete output from command /home/steve/virtualenv/project/bin/python -c "import setuptools;__file__='/tmp/pip-rl1_7G-build/setup.py';exec(compile(open(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-vVDBRe-record/install-record.txt --single-version-externally-managed --install-headers /home/steve/virtualenv/project/include/site/python2.7:
    running install

running build

running build_py

creating build

creating build/lib.linux-x86_64-2.7

creating build/lib.linux-x86_64-2.7/inplaceeditform

copying inplaceeditform/urls.py -> build/lib.linux-x86_64-2.7/inplaceeditform

copying inplaceeditform/views.py -> build/lib.linux-x86_64-2.7/inplaceeditform

copying inplaceeditform/perms.py -> build/lib.linux-x86_64-2.7/inplaceeditform

copying inplaceeditform/__init__.py -> build/lib.linux-x86_64-2.7/inplaceeditform

copying inplaceeditform/fields.py -> build/lib.linux-x86_64-2.7/inplaceeditform

copying inplaceeditform/adaptors.py -> build/lib.linux-x86_64-2.7/inplaceeditform

copying inplaceeditform/commons.py -> build/lib.linux-x86_64-2.7/inplaceeditform

copying inplaceeditform/tag_utils.py -> build/lib.linux-x86_64-2.7/inplaceeditform

creating build/lib.linux-x86_64-2.7/inplaceeditform/templatetags

copying inplaceeditform/templatetags/__init__.py -> build/lib.linux-x86_64-2.7/inplaceeditform/templatetags

copying inplaceeditform/templatetags/inplace_edit.py -> build/lib.linux-x86_64-2.7/inplaceeditform/templatetags

running egg_info

creating django_inplaceedit.egg-info

writing django_inplaceedit.egg-info/PKG-INFO

writing top-level names to django_inplaceedit.egg-info/top_level.txt

writing dependency_links to django_inplaceedit.egg-info/dependency_links.txt

writing manifest file 'django_inplaceedit.egg-info/SOURCES.txt'

warning: manifest_maker: standard file '-c' not found

reading manifest template 'MANIFEST.in'

writing manifest file 'django_inplaceedit.egg-info/SOURCES.txt'

error: Error: setup script specifies an absolute path:

    /tmp/pip-rl1_7G-build/AUTHORS.rst

setup() arguments must *always* be /-separated paths relative to the

setup.py directory, *never* absolute paths.

----------------------------------------
Command /home/steve/virtualenv/project/bin/python -c "import setuptools;__file__='/tmp/pip-rl1_7G-build/setup.py';exec(compile(open(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-vVDBRe-record/install-record.txt --single-version-externally-managed --install-headers /home/steve/virtualenv/project/include/site/python2.7 failed with error code 1 in /tmp/pip-rl1_7G-build
Storing complete log in /home/steve/.pip/pip.log
</code>```

setuptools-git is obviously installed, and I found zero information on this bug, though I've been struck by this a dozen times.
I can't find why it complains of having absolute paths since it's the one generating them.

答:
In my case, the solution to this problem was that my MANIFEST.ini file contained the static path (it wasn't being created on accident, nuking the old egg didn't help):

wrong:

```<code>recursive-include resources /*.*
</code>```

right:

```<code>recursive-include resources *.*
</code>```

Body:
I suffer a strange behaviour of pip.
Calling

pip install git+https://github.com/username/repo

generally works, but on some packages it fails in an abnormal way

Downloading/unpacking git+git://github.com/artscoop/django-inplaceedit
  Cloning git://github.com/artscoop/django-inplaceedit to /tmp/pip-rl1_7G-build
  Running setup.py egg_info for package from git+git://github.com/artscoop/django-inplaceedit

Installing collected packages: django-inplaceedit
  Running setup.py install for django-inplaceedit

    error: Error: setup script specifies an absolute path:

        /tmp/pip-rl1_7G-build/AUTHORS.rst

    setup() arguments must *always* be /-separated paths relative to the
    setup.py directory, *never* absolute paths.

    Complete output from command /home/steve/virtualenv/project/bin/python -c "import setuptools;__file__='/tmp/pip-rl1_7G-build/setup.py';exec(compile(open(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-vVDBRe-record/install-record.txt --single-version-externally-managed --install-headers /home/steve/virtualenv/project/include/site/python2.7:
    running install

running build

running build_py

creating build

creating build/lib.linux-x86_64-2.7

creating build/lib.linux-x86_64-2.7/inplaceeditform

copying inplaceeditform/urls.py -> build/lib.linux-x86_64-2.7/inplaceeditform

copying inplaceeditform/views.py -> build/lib.linux-x86_64-2.7/inplaceeditform

copying inplaceeditform/perms.py -> build/lib.linux-x86_64-2.7/inplaceeditform

copying inplaceeditform/__init__.py -> build/lib.linux-x86_64-2.7/inplaceeditform

copying inplaceeditform/fields.py -> build/lib.linux-x86_64-2.7/inplaceeditform

copying inplaceeditform/adaptors.py -> build/lib.linux-x86_64-2.7/inplaceeditform

copying inplaceeditform/commons.py -> build/lib.linux-x86_64-2.7/inplaceeditform

copying inplaceeditform/tag_utils.py -> build/lib.linux-x86_64-2.7/inplaceeditform

creating build/lib.linux-x86_64-2.7/inplaceeditform/templatetags

copying inplaceeditform/templatetags/__init__.py -> build/lib.linux-x86_64-2.7/inplaceeditform/templatetags

copying inplaceeditform/templatetags/inplace_edit.py -> build/lib.linux-x86_64-2.7/inplaceeditform/templatetags

running egg_info

creating django_inplaceedit.egg-info

writing django_inplaceedit.egg-info/PKG-INFO

writing top-level names to django_inplaceedit.egg-info/top_level.txt

writing dependency_links to django_inplaceedit.egg-info/dependency_links.txt

writing manifest file 'django_inplaceedit.egg-info/SOURCES.txt'

warning: manifest_maker: standard file '-c' not found

reading manifest template 'MANIFEST.in'

writing manifest file 'django_inplaceedit.egg-info/SOURCES.txt'

error: Error: setup script specifies an absolute path:

    /tmp/pip-rl1_7G-build/AUTHORS.rst

setup() arguments must *always* be /-separated paths relative to the

setup.py directory, *never* absolute paths.

----------------------------------------
Command /home/steve/virtualenv/project/bin/python -c "import setuptools;__file__='/tmp/pip-rl1_7G-build/setup.py';exec(compile(open(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-vVDBRe-record/install-record.txt --single-version-externally-managed --install-headers /home/steve/virtualenv/project/include/site/python2.7 failed with error code 1 in /tmp/pip-rl1_7G-build
Storing complete log in /home/steve/.pip/pip.log

setuptools-git is obviously installed, and I found zero information on this bug, though I've been struck by this a dozen times.
I can't find why it complains of having absolute paths since it's the one generating them.

Body:
In my case, the solution to this problem was that my MANIFEST.ini file contained the static path (it wasn't being created on accident, nuking the old egg didn't help):

wrong:

recursive-include resources /*.*

right:

recursive-include resources *.*