问:
How to detect hold and fastforward event in react native TVEventHandler
I am new to React Native. I want to know how can implement press and hold event for seek.
I am able to get fastForward and press right events in React native layer by using below code.

```<code>_enableTVEventHandler() {
    this._tvEventHandler = new TVEventHandler();
    this._tvEventHandler.enable(this, function(cmp, evt) {
      if (evt && evt.eventType === 'right') {
        cmp.setState({board: cmp.state.board.move(2)});
      } else if(evt && evt.eventType === 'up') {
        cmp.setState({board: cmp.state.board.move(1)});
      } else if(evt && evt.eventType === 'left') {
        cmp.setState({board: cmp.state.board.move(0)});
      } else if(evt && evt.eventType === 'down') {
        cmp.setState({board: cmp.state.board.move(3)});
      } else if(evt && evt.eventType === 'playPause') {
        cmp.restartGame();
      }
    });
  }
</code>```

Not able to get the hold fastforward or hold and right event to detect seek event. I am not sure it if its possible in RN layer. If not then how can i do the same in Android layer.

Thanks in advance

答:
you could try something like this where eventKeyAction is an integer value that represents button press(down/up).where "key up" is 1, "key down" is 0.
so you could use that to serve your purpose

```<code>const [isfastForwarding, setisfastForwarding] = useState(false);

 const _enableTVEventHandler = () => {
    _tvEventHandler = new TVEventHandler();
    _tvEventHandler.enable(this, (cmp, { eventType, eventKeyAction }) => {
      // eventKeyAction is an integer value representing button press(key down) and release(key up). "key up" is 1, "key down" is 0.
      if (eventType === "fastForward" && eventKeyAction === 0) {
        setisfastForwarding(true);
      }
      if (eventType === "fastForward" && eventKeyAction === 1) {
        setisfastForwarding(false);
      }
    });
  };
</code>```

you can also add some delay if you wish to

Body:
I am new to React Native. I want to know how can implement press and hold event for seek.
I am able to get fastForward and press right events in React native layer by using below code.

_enableTVEventHandler() {
    this._tvEventHandler = new TVEventHandler();
    this._tvEventHandler.enable(this, function(cmp, evt) {
      if (evt && evt.eventType === 'right') {
        cmp.setState({board: cmp.state.board.move(2)});
      } else if(evt && evt.eventType === 'up') {
        cmp.setState({board: cmp.state.board.move(1)});
      } else if(evt && evt.eventType === 'left') {
        cmp.setState({board: cmp.state.board.move(0)});
      } else if(evt && evt.eventType === 'down') {
        cmp.setState({board: cmp.state.board.move(3)});
      } else if(evt && evt.eventType === 'playPause') {
        cmp.restartGame();
      }
    });
  }

Not able to get the hold fastforward or hold and right event to detect seek event. I am not sure it if its possible in RN layer. If not then how can i do the same in Android layer.

Thanks in advance

Body:
you could try something like this where eventKeyAction is an integer value that represents button press(down/up).where "key up" is 1, "key down" is 0.
so you could use that to serve your purpose

const [isfastForwarding, setisfastForwarding] = useState(false);

 const _enableTVEventHandler = () => {
    _tvEventHandler = new TVEventHandler();
    _tvEventHandler.enable(this, (cmp, { eventType, eventKeyAction }) => {
      // eventKeyAction is an integer value representing button press(key down) and release(key up). "key up" is 1, "key down" is 0.
      if (eventType === "fastForward" && eventKeyAction === 0) {
        setisfastForwarding(true);
      }
      if (eventType === "fastForward" && eventKeyAction === 1) {
        setisfastForwarding(false);
      }
    });
  };

you can also add some delay if you wish to


来源: stackexchange

问:
I want to shorten this method, can you help me?
I want to write this method in a shorter way. Do you have any ideas? I didn´t get something which runs...</p>

```<code>public static AudioFile getInstance(String pathname) {
    String ending = null;
    int auxvar = pathname.lastIndexOf('.');

    if (auxvar<0) {
        throw new RuntimeException("Unknown suffix for AudioFile: \""+ pathname + "\"");
    }else {
        ending = pathname.substring(auxvar+1);
        ending = ending.toLowerCase();
        if (ending.equalsIgnoreCase("wav")) {
            return new WavFile(pathname);
        }else if (ending.equalsIgnoreCase("mp3") || ending.equalsIgnoreCase("ogg")) {
            return new TaggedFile(pathname);
        }else {
            throw new RuntimeException("Unknown suffix for AudioFile: \" "+ pathname + "\" ");
        }
    }
}
</code>```

答:
Well, if you want that code, but shorter:

```<code>public static AudioFile getInstance(String path) {
    String pathc = path.toLowerCase();
    if (pathc.endsWith(".wav")) return new WavFile(path);
    if (pathc.endsWith("mp3") || pathc.endsWith(".ogg")) return new TaggedFile(path);
    throw new IllegalArgumentException("Unknown suffix for AudioFile: \""+ path + "\"");
}
</code>```

Does the same thing.

ContentLicense: CC BY-SA 4.0

Body:
I want to write this method in a shorter way. Do you have any ideas? I didn´t get something which runs...

public static AudioFile getInstance(String pathname) {
    String ending = null;
    int auxvar = pathname.lastIndexOf('.');

    if (auxvar<0) {
        throw new RuntimeException("Unknown suffix for AudioFile: \""+ pathname + "\"");
    }else {
        ending = pathname.substring(auxvar+1);
        ending = ending.toLowerCase();
        if (ending.equalsIgnoreCase("wav")) {
            return new WavFile(pathname);
        }else if (ending.equalsIgnoreCase("mp3") || ending.equalsIgnoreCase("ogg")) {
            return new TaggedFile(pathname);
        }else {
            throw new RuntimeException("Unknown suffix for AudioFile: \" "+ pathname + "\" ");
        }
    }
}

Body:
Well, if you want that code, but shorter:

public static AudioFile getInstance(String path) {
    String pathc = path.toLowerCase();
    if (pathc.endsWith(".wav")) return new WavFile(path);
    if (pathc.endsWith("mp3") || pathc.endsWith(".ogg")) return new TaggedFile(path);
    throw new IllegalArgumentException("Unknown suffix for AudioFile: \""+ path + "\"");
}

Does the same thing.


问:
how to solve linear regression with conditions in R
I would like to do a linear regression with conditions, like:
Y = ax1 + bx2 +c, a>0 , b <1 and c>=0

```<code>Y <- c(167, 136, 195, 174, 144, 135, 89, 81, 114, 111)
x1 <- c(2.9, 3.4, 0.7, 1.1, 3.5, 5.0, 6.7, 4.7, 3.7, 8.8)
X2 <- c(60, 47, 63, 62, 40, 60, 50, 35, 40, 40)
mydata <- data.frame(Y,X1,X2)
</code>```

Is there an easy way to do this in R? .

Body:
I would like to do a linear regression with conditions, like:
Y = ax1 + bx2 +c, a>0 , b <1 and c>=0

Y <- c(167, 136, 195, 174, 144, 135, 89, 81, 114, 111)
x1 <- c(2.9, 3.4, 0.7, 1.1, 3.5, 5.0, 6.7, 4.7, 3.7, 8.8)
X2 <- c(60, 47, 63, 62, 40, 60, 50, 35, 40, 40)
mydata <- data.frame(Y,X1,X2)

Is there an easy way to do this in R? .

Body:
Here is how you can do this with CVXR:

> library(CVXR)
>
> #
> # data
> #
> Y <- c(167, 136, 195, 174, 144, 135, 89, 81, 114, 111)
> X1 <- c(2.9, 3.4, 0.7, 1.1, 3.5, 5.0, 6.7, 4.7, 3.7, 8.8)
> X2 <- c(60, 47, 63, 62, 40, 60, 50, 35, 40, 40)
>
> #
> # organize as matrix
> #
> X <- cbind(1,X1,X2)
> X
         X1 X2
 [1,] 1 2.9 60
 [2,] 1 3.4 47
 [3,] 1 0.7 63
 [4,] 1 1.1 62
 [5,] 1 3.5 40
 [6,] 1 5.0 60
 [7,] 1 6.7 50
 [8,] 1 4.7 35
 [9,] 1 3.7 40
[10,] 1 8.8 40
>
>
> #
> # standard regression
> #
> lm(Y~X1+X2)

Call:
lm(formula = Y ~ X1 + X2)

Coefficients:
(Intercept)           X1           X2
     82.616       -7.716        1.675

>
> #
> # standard regression as QP
> #
> beta <- Variable(3)
>
> problem <- Problem(Minimize(sum_squares(Y - X %*% beta)))
> result <- solve(problem, verbose=T)
-----------------------------------------------------------------
           OSQP v0.6.0  -  Operator Splitting QP Solver
              (c) Bartolomeo Stellato,  Goran Banjac
        University of Oxford  -  Stanford University 2019
-----------------------------------------------------------------
problem:  variables n = 13, constraints m = 10
          nnz(P) + nnz(A) = 50
settings: linear system solver = qdldl,
          eps_abs = 1.0e-05, eps_rel = 1.0e-05,
          eps_prim_inf = 1.0e-04, eps_dual_inf = 1.0e-04,
          rho = 1.00e-01 (adaptive),
          sigma = 1.00e-06, alpha = 1.60, max_iter = 10000
          check_termination: on (interval 25),
          scaling: on, scaled_termination: off
          warm start: on, polish: on, time_limit: off

iter  objective    pri res    dua res    rho        time
   1   0.0000e+00   1.95e+02   1.70e+05   1.00e-01   3.47e-04s
  50   2.8959e+03   3.20e-07   2.29e-06   1.00e-01   8.43e-04s
plsh   2.8959e+03   4.21e-14   4.51e-13  ---------   1.36e-03s

status:               solved
solution polish:      successful
number of iterations: 50
optimal objective:    2895.8618
run time:             1.36e-03s
optimal rho estimate: 4.57e-02

> result$getValue(beta)
          [,1]
[1,] 82.616486
[2,] -7.716095
[3,]  1.674722
>
> #
> # add constraints
> #      beta[1] >= 0       (constant term)
> #      beta[2] >= 0.0001  (instead of > we do >= with a small tolerance)
> #      beta[3] <= 0.9999  (instead of < we do <= with a small tolerance)
> #
> problem <- Problem(Minimize(sum_squares(Y - X %*% beta)),
+                    list(beta[1]>=0,
+                         beta[2]>=0.0001,
+                         beta[3]<=0.9999))
> result <- solve(problem, verbose=T)
-----------------------------------------------------------------
           OSQP v0.6.0  -  Operator Splitting QP Solver
              (c) Bartolomeo Stellato,  Goran Banjac
        University of Oxford  -  Stanford University 2019
-----------------------------------------------------------------
problem:  variables n = 13, constraints m = 13
          nnz(P) + nnz(A) = 53
settings: linear system solver = qdldl,
          eps_abs = 1.0e-05, eps_rel = 1.0e-05,
          eps_prim_inf = 1.0e-04, eps_dual_inf = 1.0e-04,
          rho = 1.00e-01 (adaptive),
          sigma = 1.00e-06, alpha = 1.60, max_iter = 10000
          check_termination: on (interval 25),
          scaling: on, scaled_termination: off
          warm start: on, polish: on, time_limit: off

iter  objective    pri res    dua res    rho        time
   1   0.0000e+00   1.95e+02   1.71e+05   1.00e-01   5.30e-04s
 150   7.8534e+03   9.37e-05   5.05e-04   4.62e+00   1.51e-03s
plsh   7.8533e+03   5.55e-14   2.84e-14  ---------   1.94e-03s

status:               solved
solution polish:      successful
number of iterations: 150
optimal objective:    7853.3365
run time:             1.94e-03s
optimal rho estimate: 2.98e+00

> result$getValue(beta)
         [,1]
[1,] 84.90456
[2,]  0.00010
[3,]  0.99990
>


问:
Check in file the data match the syntax
i have a scenario where i want to check the below details in files match the syntax

Syntax : NAME/SURNAME/COUNTRY

Note : every record in file should match the syntax. if one records does not match then should display
failed or success

File data

```<code>Ajay/abc/india
Avik/bcs/delhi
Viraj/xyz/
</code>```

As you can see the file data the last record does not match according to the syntax
then should display failed

My code

```<code> for i in `cat /demo/Student.txt`
      do
      check=`echo $i | cut -d '/' -f3`
      if [[ -z $check ]];
      then
        echo failed syntax does not match NAME/SURNAME/COUNTRY
        exit 1
      fi
    done
</code>```

答:
cut -d '/'-f3

This is invalid syntax, as cut freely tells me. Did you not get any console output indicating the problem?

cut: the delimiter must be a single character
  Try 'cut --help' for more information.

Fix that by putting a space before the -f switch.

The script then works for me: it reports an error with your file as-is, then no error if I append a 'country' (hi) to the final line.

Demo:

input:

Ajay/abc/india
Avik/bcs/delhi
Viraj/xyz/
```

<p>output:</p>

<pre class="lang-none prettyprint-override"><code>$ sh -x test.sh
++ cat test.txt
+ for i in `cat test.txt`
++ echo Ajay/abc/india
++ cut -d / -f3
+ check=india
+ [[ -z india ]]
+ for i in `cat test.txt`
++ echo Avik/bcs/delhi
++ cut -d / -f3
+ check=delhi
+ [[ -z delhi ]]
+ for i in `cat test.txt`
++ echo Viraj/xyz/
++ cut -d / -f3
+ check=
+ [[ -z '' ]]
+ echo failed syntax does not match NAME/SURNAME/COUNTRY
failed syntax does not match NAME/SURNAME/COUNTRY
+ exit 1
</code>```

Title: Check in file the data match the syntax

Body:
i have a scenario where i want to check the below details in files match the syntax

Syntax : NAME/SURNAME/COUNTRY

Note : every record in file should match the syntax. if one records does not match then should display
failed or success

File data

Ajay/abc/india
Avik/bcs/delhi
Viraj/xyz/

As you can see the file data the last record does not match according to the syntax
then should display failed

My code

 for i in `cat /demo/Student.txt`
      do
      check=`echo $i | cut -d '/' -f3`
      if [[ -z $check ]];
      then
        echo failed syntax does not match NAME/SURNAME/COUNTRY
        exit 1
      fi
    done

Body:
cut -d '/'-f3

This is invalid syntax, as cut freely tells me. Did you not get any console output indicating the problem?

cut: the delimiter must be a single character
  Try 'cut --help' for more information.

Fix that by putting a space before the -f switch.

The script then works for me: it reports an error with your file as-is, then no error if I append a 'country' (hi) to the final line.

Demo:

input:

Ajay/abc/india
Avik/bcs/delhi
Viraj/xyz/

output:

$ sh -x test.sh
++ cat test.txt
+ for i in `cat test.txt`
++ echo Ajay/abc/india
++ cut -d / -f3
+ check=india
+ [[ -z india ]]
+ for i in `cat test.txt`
++ echo Avik/bcs/delhi
++ cut -d / -f3
+ check=delhi
+ [[ -z delhi ]]
+ for i in `cat test.txt`
++ echo Viraj/xyz/
++ cut -d / -f3
+ check=
+ [[ -z '' ]]
+ echo failed syntax does not match NAME/SURNAME/COUNTRY
failed syntax does not match NAME/SURNAME/COUNTRY
+ exit 1


问:
Regex for city and street name
Hi, I am looking for 2 regex which describe:

1) a valid name of a street

2) a valid name of a city

Valid street names are:

Mainstreet.

Mainstreet

Main Street

Big New mainstreet

Mainstreet-New

Mains Str.

St. Alexander Street

abcÜüßäÄöÖàâäèéêëîï ôœùûüÿçÀÂ-ÄÈÉÊËÎÏÔŒÙÛÜŸÇ.

John Kennedy Street

Not valid street names are:

Mainstreet #+;:_*´`?=)(/&%$§!

Mainstreet#+;:_*´`?=)(/&%$§!

Mainstreet 2

Mainstreet..

Mainstreet§

Valid cities are:

Edinôœùûüÿ

Berlin.

St. Petersburg

New-Berlin

Aue-Bad Schlema

Frankfurt am Main

Nürnberg

Ab

New York CityßäÄöÖàâäèéêëîïôœùûüÿçÀÂ-ÄÈÉÊËÎÏÔŒÙÛÜŸ

Not valid cities are:

Edingburgh 123

Edingburg123

St. Andrews 12

Berlin,#+;:_*´`?=)(/&%$§!

Berlin__

The solutions that I have at the moment matches very close but not perfectly:

For city and street name:

```<code>^[^\W\d_]+(?:[-\s][^\W\d_]+)*[.]?$
</code>```

Unfortunately no match for these examples (the rest works fine):

St. Alexander Street

St. Petersburg

If you have more simple solutions, I am happy to learn sth. new! :-)

答:
To make it match St. Alexander Street and St. Petersburg, you just need to add an optional dot after the letter matching patterns:

```<code>^[^\W\d_]+\.?(?:[-\s][^\W\d_]+\.?)*$
#         ^^^                 ^^^
</code>```

See the regex demo.

Also, it might make sense to add a single apostrophe to the regex:

```<code>^[^\W\d_]+\.?(?:[-\s'’][^\W\d_]+\.?)*$
</code>```

See the regex demo.

Title: Regex for city and street name

Body:
Hi, I am looking for 2 regex which describe:

1) a valid name of a street

2) a valid name of a city

Valid street names are:

Mainstreet.

Mainstreet

Main Street

Big New mainstreet

Mainstreet-New

Mains Str.

St. Alexander Street

abcÜüßäÄöÖàâäèéêëîï ôœùûüÿçÀÂ-ÄÈÉÊËÎÏÔŒÙÛÜŸÇ.

John Kennedy Street

Not valid street names are:

Mainstreet #+;:_*´`?=)(/&%$§!

Mainstreet#+;:_*´`?=)(/&%$§!

Mainstreet 2

Mainstreet..

Mainstreet§

Valid cities are:

Edinôœùûüÿ

Berlin.

St. Petersburg

New-Berlin

Aue-Bad Schlema

Frankfurt am Main

Nürnberg

Ab

New York CityßäÄöÖàâäèéêëîïôœùûüÿçÀÂ-ÄÈÉÊËÎÏÔŒÙÛÜŸ

Not valid cities are:

Edingburgh 123

Edingburg123

St. Andrews 12

Berlin,#+;:_*´`?=)(/&%$§!

Berlin__

The solutions that I have at the moment matches very close but not perfectly:

For city and street name:

^[^\W\d_]+(?:[-\s][^\W\d_]+)*[.]?$

Unfortunately no match for these examples (the rest works fine):

St. Alexander Street

St. Petersburg

If you have more simple solutions, I am happy to learn sth. new! :-)

Body:
To make it match St. Alexander Street and St. Petersburg, you just need to add an optional dot after the letter matching patterns:

^[^\W\d_]+\.?(?:[-\s][^\W\d_]+\.?)*$
#         ^^^                 ^^^

See the regex demo.

Also, it might make sense to add a single apostrophe to the regex:

^[^\W\d_]+\.?(?:[-\s'’][^\W\d_]+\.?)*$

See the regex demo.


问:
LoopBack 4 - Add 'Authorize' button in API explorer
I'm new in LoopBack v4 and I'm trying to send an authorization key with every request.
I used Swagger before, and I used to add the api key, after clicking on the "Authorize" button to the right.
To avoid error due my inexperience, I've started with a fresh app of "Todo List" example.
I tried (with not success) to follow what this post suggests: Nodejs Loopback 4 add bearer token config into swagger explorer

What I did is modify the file src/index.ts with this code:

```<code>export async function main(options: ApplicationConfig = {}) {
  const spec: OpenApiSpec = {
    openapi: '3.0.0',
    info: {
      title: 'LoopBack Application v2',
      version: '1.0.2',
    },
    paths: {
    },
    securityDefinitions: [
      {
        api_key: [
          {
            type: 'apiKey',
            name: 'api_key',
            in: 'header'
          }
        ]
      },
    ],
  };

  const app = new TodoListApplication(options);
  app.api(spec);

  await app.boot();
  await app.start();

  const url = app.restServer.url;
  console.log(`Server is running at ${url}`);
  return app;
}
</code>```

Basically, I added this line: app.api(spec); and the config securityDefinitions. The spec constant changes the title and version, but I still cannot see the "Authorize" button. For sure, I'm missing something or doing something wrong.

Any help is appreciated! Thanks!

答:
create a security spec file in your file system like below

```<code>import {ReferenceObject, SecuritySchemeObject} from '@loopback/openapi-v3';

export const SECURITY_SPEC = [{bearerAuth: []}];
export type SecuritySchemeObjects = {
  [securityScheme: string]: SecuritySchemeObject | ReferenceObject;
};
export const SECURITY_SCHEME_SPEC: SecuritySchemeObjects = {
  bearerAuth: {
    type: 'http',
    scheme: 'bearer',
    bearerFormat: 'JWT',
  },
};
</code>```

add below code in application.ts file in XXXX application class below super(options) and import SECURITY_SCHEME_SPEC, SECURITY_SPEC from the security spec file.

```<code> this.api({
      openapi: '3.0.0',
      info: {title: "package or prject name", version: '1.0'},
      paths: {},
      components: {securitySchemes: SECURITY_SCHEME_SPEC},
      servers: [{url: '/'}],
      security: SECURITY_SPEC
    });
</code>```

Referance loopback link

Body:
I'm new in LoopBack v4 and I'm trying to send an authorization key with every request.
I used Swagger before, and I used to add the api key, after clicking on the "Authorize" button to the right.
To avoid error due my inexperience, I've started with a fresh app of "Todo List" example.
I tried (with not success) to follow what this post suggests: Nodejs Loopback 4 add bearer token config into swagger explorer

What I did is modify the file src/index.ts with this code:

export async function main(options: ApplicationConfig = {}) {
  const spec: OpenApiSpec = {
    openapi: '3.0.0',
    info: {
      title: 'LoopBack Application v2',
      version: '1.0.2',
    },
    paths: {
    },
    securityDefinitions: [
      {
        api_key: [
          {
            type: 'apiKey',
            name: 'api_key',
            in: 'header'
          }
        ]
      },
    ],
  };

  const app = new TodoListApplication(options);
  app.api(spec);

  await app.boot();
  await app.start();

  const url = app.restServer.url;
  console.log(`Server is running at ${url}`);
  return app;
}

Basically, I added this line: app.api(spec); and the config securityDefinitions. The spec constant changes the title and version, but I still cannot see the "Authorize" button. For sure, I'm missing something or doing something wrong.

Any help is appreciated! Thanks!

Body:
create a security spec file in your file system like below

import {ReferenceObject, SecuritySchemeObject} from '@loopback/openapi-v3';

export const SECURITY_SPEC = [{bearerAuth: []}];
export type SecuritySchemeObjects = {
  [securityScheme: string]: SecuritySchemeObject | ReferenceObject;
};
export const SECURITY_SCHEME_SPEC: SecuritySchemeObjects = {
  bearerAuth: {
    type: 'http',
    scheme: 'bearer',
    bearerFormat: 'JWT',
  },
};

add below code in application.ts file in XXXX application class below super(options) and import SECURITY_SCHEME_SPEC, SECURITY_SPEC from the security spec file.

 this.api({
      openapi: '3.0.0',
      info: {title: "package or prject name", version: '1.0'},
      paths: {},
      components: {securitySchemes: SECURITY_SCHEME_SPEC},
      servers: [{url: '/'}],
      security: SECURITY_SPEC
    });

Referance loopback link


问:
Re-render Tweet button via JS
I used to use this snippet to re-render a Tweet button.

```<code>var tweetButton = new twttr.TweetButton(twitterScript);
twttr.render();
</code>```

But it looks like widgets.js (http://platform.twitter.com/widgets.js) has been modified so twttr.TweetButton is no longer a constructor.

Can anyone help with this issue?

答:
Try the @Anywhere library.  Sample js code:</p>

```<code>twttr.anywhere(function (T) {
        T("#tweetbox").tweetBox({
        counter: false,
        defaultContent: "Default text in a Tweet box...",
        label: "Share this page on Twitter"
});
</code>```

ContentLicense: CC BY-SA 3.0

Title: Re-render Tweet button via JS

Body:
I used to use this snippet to re-render a Tweet button.

var tweetButton = new twttr.TweetButton(twitterScript);
twttr.render();

But it looks like widgets.js (http://platform.twitter.com/widgets.js) has been modified so twttr.TweetButton is no longer a constructor.

Can anyone help with this issue?

Body:
Try the @Anywhere library.  Sample js code:

twttr.anywhere(function (T) {
        T("#tweetbox").tweetBox({
        counter: false,
        defaultContent: "Default text in a Tweet box...",
        label: "Share this page on Twitter"
});


问:
Performing search in separate thread delphi
I'm trying to make a search which runs on a separate thread and updates listview with matched items using Synchronize.

previously when  search was working on main thread. i was using onchange event of TButtonedEdit. to detect the string that user wish to search for. & perform search on listview items.

I want to know how to detect change in text of TButtonedEdit inside thread. or how the same can be implemented using thread.

Thanks for Help.

答:
You can't detect change of your TButtonedEdit directly from your worker thread.

What you can do is use your OnChange event to notify your worker thread that change was made.

Or if you are creating your worker thread in your OnChange event you can signal existing thread to terminate and not return any result and then start a new thread to perform search with new search parameters. Do note that your search procedure needs to be designed in a way to allow thread to regularly check Terminated property of your worker thread unless you won't be able to terminate it before search is finished.


问:
Pass an object as a list in subclass' constructor in python
How do I implement the Subclass B for the function getdata() to return the details in the constructor? I could achieve that if the constructor in B takes a single object, but having difficulty if the objects were two or more and passed as a list.

This example shows what I intended. Code lacks the full implementation.

```<code>class A(object):
    def __init__(self, a):
        self.a = a

    def geta(self):
        return str(self.a)

class B(A):
    def __init__(self, b,c, [objA1, objA2]):
        self.b = b
        self.c = c
        super().__init__()
        # ...

    def geta(self):
        return str(self.a)

    def getb(self):
        return str(self.b)

    def getdata(self):
        return str(self.geta()) + str(self.getb()) + ...

obja1 = A('John')
obja2 = A('Doe')
obj = B('123', '456', [obja1, obja2])

# Test1 obj.getdata() == "John Doe 123 456"
</code>```

答:
So you don't need inheritance here. Composition will be enough.

This code produces output according to your requirements:

```<code>class A:
    def __init__(self, a):
        self.a = a

    def __repr__(self):
        return str(self.a)

class B:
    def __init__(self, b, c, others):
        self.b = b
        self.c = c
        self.others = others

    def getdata(self):
        items = self.others + [self.b, self.c]
        return ' '.join([str(item) for item in items])

obja1 = A('John')
obja2 = A('Doe')
obj = B('123', '456', [obja1, obja2])
print(obj.getdata())
</code>```

Output:

```<code>John Doe 123 456
</code>```

Body:
How do I implement the Subclass B for the function getdata() to return the details in the constructor? I could achieve that if the constructor in B takes a single object, but having difficulty if the objects were two or more and passed as a list.

This example shows what I intended. Code lacks the full implementation.

class A(object):
    def __init__(self, a):
        self.a = a

    def geta(self):
        return str(self.a)

class B(A):
    def __init__(self, b,c, [objA1, objA2]):
        self.b = b
        self.c = c
        super().__init__()
        # ...

    def geta(self):
        return str(self.a)

    def getb(self):
        return str(self.b)

    def getdata(self):
        return str(self.geta()) + str(self.getb()) + ...

obja1 = A('John')
obja2 = A('Doe')
obj = B('123', '456', [obja1, obja2])

# Test1 obj.getdata() == "John Doe 123 456"

Body:
So you don't need inheritance here. Composition will be enough.

This code produces output according to your requirements:

class A:
    def __init__(self, a):
        self.a = a

    def __repr__(self):
        return str(self.a)

class B:
    def __init__(self, b, c, others):
        self.b = b
        self.c = c
        self.others = others

    def getdata(self):
        items = self.others + [self.b, self.c]
        return ' '.join([str(item) for item in items])

obja1 = A('John')
obja2 = A('Doe')
obj = B('123', '456', [obja1, obja2])
print(obj.getdata())

Output:

John Doe 123 456


答:
```<code>awk '$3 ~ /TB$/ { $3 *= 1024 }; $3 ~ /GB$/ { $3 += 0 }; 1'
</code>```

The above command works. awk converts strings to numbers automatically from starting part of the string. Here it ignores GB and TB part.

If you care about having 2 digits of precision after decimal even if they are just zeroes than you can use.

```<code>awk '$3 ~ /TB$/ { $3 *= 1024 }; $3 ~ /GB$/ { $3 += 0 };  {$3 = sprintf("%.2f", $3) } 1'
</code>```

Title: Awk conditional if else

Body:
i have a file that doesn't want to messed up the sequence so i'm trying to work out my awk conditional statement.

if $3 has TB(string), remove it and multiply it by 1024 and if it has GB just remove it(remove the string GB) and do nothing.

sast1sis01_002          iresas-p2-ris03    100.00GB   60050912017086C7700000000000021E
sast1sis01_004          iresas-p2-ris03    50.00TB    60050912017086C77000000000000AAF
sast1sis01_003          iresas-p2-ris03    100.00GB   60050912017086C77000000000000BB0
sast1sis01_008          iresas-p2-ris03    100.00GB   60050912017086C77000000000000OO1
sast1sis01_005          iresas-p2-ris03    100.00GB   60050912017086C77000000000000212
sast1sis01_001          iresas-p2-ris03    100.00GB   60050912017086C77000000000000993
arrysas1_356            cbscc-u8-msas1     600.00GB   60050912017086C77000000000000BBA
N8DVP01ABC_007          iresas-z1-pit02    2.44TB     60050912017086C770000000000005EE
n2sql90abc_052          iresas-p2-sql57a   1.00TB     60050912017086C7700000000000089C
n3sq321abc_055          iresas-p2-sql57b   0          60050912017086C7700000000000011C
n6sq222abc_056          iresas-p2-sql57a   1.00GB     60050912017086C7700000000000022D
n7sqbascka_058          iresas-p2-sql57b   0          60050912017086C7700000000000039D

Trying this out:

awk '{s=($3=="TB")?"-":$3=$3*1024; print}';awk '{s=($3=="GB")?"-":'s/GB//g'; print}' file

Body:
awk '$3 ~ /TB$/ { $3 *= 1024 }; $3 ~ /GB$/ { $3 += 0 }; 1'

The above command works. awk converts strings to numbers automatically from starting part of the string. Here it ignores GB and TB part.

If you care about having 2 digits of precision after decimal even if they are just zeroes than you can use.

awk '$3 ~ /TB$/ { $3 *= 1024 }; $3 ~ /GB$/ { $3 += 0 };  {$3 = sprintf("%.2f", $3) } 1'


问:
How do I access subclass variables in a baseclass vector? (for an entity component system)
So I have a vector with "Components". I can access the Component variables easily from the vector, but when I add a subclass to the vector, I cant access those variables.

Maybe this is a really bold question and the solution is probably really complicated, but I don't know where to start and what to try so any help is appreciated.

```<code>struct Component {};
std::vector<Component> components;

struct Transform : Component
{
    int x, y;
};

void Start()
{
    components.push_back(Transform());
    //can't acces x below
    std::cout << components[0].x;
}
</code>```

SOLUTION

make the vector just for unique pointers:

```<code>std::vector<std::unique_ptr<Component>> components;
</code>```

step 2:

```<code>void Start()
{
    //add component (pointer to vector)
    components.push_back(std::make_unique<Transform>());
    //cast to Transform
    Transform const* transform = static_cast<Transform*>(components[0].get());

    std::cout << transform->x;
}
</code>```

答:
First of all you have a problem with object slicing, to sort that you could do something like :

```<code>struct Component {};
std::vector<std::unique_ptr<Component>> components;

struct Transform : Component
{
   int x = 0, y = 0;
};

void Start()
{
    components.push_back(std::make_unique<Transform>());
}
</code>```

As for accessing members of Transform you have a couple of options.
C++ has built in rtti but be warned it's quite slow :

```<code>Transform const* transform = dynamic_cast<Transform*>(components[0].get());
if(transform != nullptr)
    std::cout << transform.x;
</code>```

Another option is to implement a virtual function from Component :

```<code>struct Component
{
    virtual void Update();
};

struct Transform : public Component
{
    int x = 0, y = 0;
    virtual void Update() override
    {
        std::cout << x;
    }
};

void Start()
{
    components.push_back(std::make_unique<Transform>());
    for(Component& component : components)
    {
        component.Update();
    }
}
</code>```

Body:
So I have a vector with "Components". I can access the Component variables easily from the vector, but when I add a subclass to the vector, I cant access those variables.

Maybe this is a really bold question and the solution is probably really complicated, but I don't know where to start and what to try so any help is appreciated.

struct Component {};
std::vector<Component> components;

struct Transform : Component
{
    int x, y;
};

void Start()
{
    components.push_back(Transform());
    //can't acces x below
    std::cout << components[0].x;
}

SOLUTION

make the vector just for unique pointers:

std::vector<std::unique_ptr<Component>> components;

step 2:

void Start()
{
    //add component (pointer to vector)
    components.push_back(std::make_unique<Transform>());
    //cast to Transform
    Transform const* transform = static_cast<Transform*>(components[0].get());

    std::cout << transform->x;
}

Body:
First of all you have a problem with object slicing, to sort that you could do something like :

struct Component {};
std::vector<std::unique_ptr<Component>> components;

struct Transform : Component
{
   int x = 0, y = 0;
};

void Start()
{
    components.push_back(std::make_unique<Transform>());
}

As for accessing members of Transform you have a couple of options.
C++ has built in rtti but be warned it's quite slow :

Transform const* transform = dynamic_cast<Transform*>(components[0].get());
if(transform != nullptr)
    std::cout << transform.x;

Another option is to implement a virtual function from Component :

struct Component
{
    virtual void Update();
};

struct Transform : public Component
{
    int x = 0, y = 0;
    virtual void Update() override
    {
        std::cout << x;
    }
};

void Start()
{
    components.push_back(std::make_unique<Transform>());
    for(Component& component : components)
    {
        component.Update();
    }
}


问:
SQL: Is it possible to join on the same sub-select?
I'd like to know if it possible to join the same sub-select to itself within the same query without actually having to execute the query again? The following query is the actual obfuscated query I want to run

```<code>select * from

       (

        -- Sub query A - same as sub query B
          select bc.service_type,  bc.cid, min(bc.last_modified_date) as last_modified1 from
              (

                 select * from table_a bc2
                where bc2.state != 7
                AND bc2.cid in
                (

                   select cid from table_a TA, table_b TB
                    where TB.name not like '% IS' and TA.state != 7
                    AND TA.service_type = 1
                    AND TA.username is not null
                    and TA.bctid = TB.bctid
                )
              ) bc
           group by service_type, cid
         ) result1,

         (

         // Sub query B - same as sub query A
          select bc.service_type,  bc.cid, min(bc.last_modified_date) as last_modified2 from
              (

                 select * from table_a bc2
                where bc2.state != 7
                AND bc2.cid in
                (

                    -- select affected records
                   select cid from table_a TA, table_b TB
                    where TB.name not like '% IS' and TA.state != 7
                    AND TA.service_type = 1
                    AND TA.username is not null
                    and TA.bctid = TB.bctid
                )
              ) bc
           group by service_type, cid
         ) result2

where result1.service_type = 1
and result2.service_type = 2
and result1.cid = result2.cid
and result1.last_modified1 < result2.last_modified2
</code>```

The explain plan for the duplicate sub-query is expensive given the size of the table, so I ideally don't want to run it twice. What I'm looking for is some way of cloning the result of the first query and joining it to itself!

This is to be run in Oracle in case there is some DB specific extension.

答:
I have a feeling that the original query can be rewritten into (I didn't test this):

```<code>    select * from
    (
        select bc2.cid, min(bc2.last_modified_date) as last_modified1 from table_a bc2
        where bc2.state != 7
        AND bc2.cid in
        (
            select cid from table_a TA, table_b TB
            where TB.name not like '% IS' and TA.state != 7
            AND TA.service_type = 1
            AND TA.username is not null
            and TA.bctid = TB.bctid
        )
        and bc2.service_type = 1
        group by cid
    ) result1,
    (
        select bc2.cid, min(bc2.last_modified_date) as last_modified1 from table_a bc2
        where bc2.state != 7
        AND bc2.cid in
        (
             select cid from table_a TA, table_b TB
             where TB.name not like '% IS' and TA.state != 7
             AND TA.service_type = 1
             AND TA.username is not null
             and TA.bctid = TB.bctid
         )
         and bc2.service_type = 2
         group by cid
    ) result2
    where result1.cid = result2.cid
    and result1.last_modified1 < result2.last_modified2
</code>```

I think you can push up the predicates "where result1.service_type = 1
and result2.service_type = 2". After that you can do what Denis advised.

Body:
I'd like to know if it possible to join the same sub-select to itself within the same query without actually having to execute the query again? The following query is the actual obfuscated query I want to run

select * from

       (

        -- Sub query A - same as sub query B
          select bc.service_type,  bc.cid, min(bc.last_modified_date) as last_modified1 from
              (

                 select * from table_a bc2
                where bc2.state != 7
                AND bc2.cid in
                (

                   select cid from table_a TA, table_b TB
                    where TB.name not like '% IS' and TA.state != 7
                    AND TA.service_type = 1
                    AND TA.username is not null
                    and TA.bctid = TB.bctid
                )
              ) bc
           group by service_type, cid
         ) result1,

         (

         // Sub query B - same as sub query A
          select bc.service_type,  bc.cid, min(bc.last_modified_date) as last_modified2 from
              (

                 select * from table_a bc2
                where bc2.state != 7
                AND bc2.cid in
                (

                    -- select affected records
                   select cid from table_a TA, table_b TB
                    where TB.name not like '% IS' and TA.state != 7
                    AND TA.service_type = 1
                    AND TA.username is not null
                    and TA.bctid = TB.bctid
                )
              ) bc
           group by service_type, cid
         ) result2

where result1.service_type = 1
and result2.service_type = 2
and result1.cid = result2.cid
and result1.last_modified1 < result2.last_modified2

The explain plan for the duplicate sub-query is expensive given the size of the table, so I ideally don't want to run it twice. What I'm looking for is some way of cloning the result of the first query and joining it to itself!

This is to be run in Oracle in case there is some DB specific extension.

Body:
I have a feeling that the original query can be rewritten into (I didn't test this):

    select * from
    (
        select bc2.cid, min(bc2.last_modified_date) as last_modified1 from table_a bc2
        where bc2.state != 7
        AND bc2.cid in
        (
            select cid from table_a TA, table_b TB
            where TB.name not like '% IS' and TA.state != 7
            AND TA.service_type = 1
            AND TA.username is not null
            and TA.bctid = TB.bctid
        )
        and bc2.service_type = 1
        group by cid
    ) result1,
    (
        select bc2.cid, min(bc2.last_modified_date) as last_modified1 from table_a bc2
        where bc2.state != 7
        AND bc2.cid in
        (
             select cid from table_a TA, table_b TB
             where TB.name not like '% IS' and TA.state != 7
             AND TA.service_type = 1
             AND TA.username is not null
             and TA.bctid = TB.bctid
         )
         and bc2.service_type = 2
         group by cid
    ) result2
    where result1.cid = result2.cid
    and result1.last_modified1 < result2.last_modified2

I think you can push up the predicates "where result1.service_type = 1
and result2.service_type = 2". After that you can do what Denis advised.


问:
How to loop a menu if wrong selection occurred
I am trying to loop a menu when the user insert wrong choice:

```<code>public static void main(String[] args) {

    Scanner YourChoice = new Scanner(System.in);

    System.out.println("+-------------------------+");
    System.out.println("|        Welcome          |");
    System.out.println("|    To this program      |");
    System.out.println("+-------------------------+");
    System.out.println();

    System.out.println("Please Choose your preference: ");
    System.out.println();
    System.out.println("Press 1 - Test1");
    System.out.println("Press 2 - Test2");
    System.out.println("Press 3 - Test3");
    System.out.println("Press 0 - Exit");

    System.out.println();
    System.out.print("Your Choice is: ");
    int CHOICE = YourChoice.nextInt();

    if (CHOICE == 1) {
        System.out.println("You want Test1");
    }
    else if (CHOICE == 2) {
        System.out.println("You want Test2");
    }
    else if (CHOICE == 3) {
        System.out.println("You want Test3");
    }
    else if (CHOICE == 0) {
        System.out.println("You want Exit");
    }
    else {
        System.out.println("Wrong Input, please try again");

    }
</code>```

What I want is, if a user inserted wrong number, then the menu should start again, until the user enters a correct value (0 to 3).
I am not sure where and how to put the while loop,
Could you please clarify it?

答:
The best way is to use with switch case , its good for the code efficiency , to use with alot of if and else if its not so good :

```<code>Scanner YourChoice = new Scanner(System.in);

            System.out.println("+-------------------------+");
            System.out.println("|        Welcome          |");
            System.out.println("|    To this program      |");
            System.out.println("+-------------------------+");
            System.out.println();

            boolean flag = false;

            do {
                System.out.println("Please Choose your preference: ");
                System.out.println();
                System.out.println("Press 1 - Test1");
                System.out.println("Press 2 - Test2");
                System.out.println("Press 3 - Test3");
                System.out.println("Press 0 - Exit");

                System.out.println();
                System.out.print("Your Choice is: ");
                int CHOICE = YourChoice.nextInt();

                switch (CHOICE) {
                case 0: {
                    System.out.println("You want Exit");
                    flag = true;
                    break;
                }
                case 1: {
                    System.out.println("You want Test1");
                    flag = true;
                    break;
                }
                case 2: {
                    System.out.println("You want Test2");
                    flag = true;
                    break;
                }
                case 3: {
                    System.out.println("You want Test3");
                    flag = true;
                    break;
                }
                default:{
                    System.out.println("Wrong Input, please try again");
                    break;
                    }
                }

            } while (!flag);
}
}
</code>```

Body:
I am trying to loop a menu when the user insert wrong choice:

public static void main(String[] args) {

    Scanner YourChoice = new Scanner(System.in);

    System.out.println("+-------------------------+");
    System.out.println("|        Welcome          |");
    System.out.println("|    To this program      |");
    System.out.println("+-------------------------+");
    System.out.println();

    System.out.println("Please Choose your preference: ");
    System.out.println();
    System.out.println("Press 1 - Test1");
    System.out.println("Press 2 - Test2");
    System.out.println("Press 3 - Test3");
    System.out.println("Press 0 - Exit");

    System.out.println();
    System.out.print("Your Choice is: ");
    int CHOICE = YourChoice.nextInt();

    if (CHOICE == 1) {
        System.out.println("You want Test1");
    }
    else if (CHOICE == 2) {
        System.out.println("You want Test2");
    }
    else if (CHOICE == 3) {
        System.out.println("You want Test3");
    }
    else if (CHOICE == 0) {
        System.out.println("You want Exit");
    }
    else {
        System.out.println("Wrong Input, please try again");

    }

What I want is, if a user inserted wrong number, then the menu should start again, until the user enters a correct value (0 to 3).
I am not sure where and how to put the while loop,
Could you please clarify it?

Body:
The best way is to use with switch case , its good for the code efficiency , to use with alot of if and else if its not so good :

Scanner YourChoice = new Scanner(System.in);

            System.out.println("+-------------------------+");
            System.out.println("|        Welcome          |");
            System.out.println("|    To this program      |");
            System.out.println("+-------------------------+");
            System.out.println();

            boolean flag = false;

            do {
                System.out.println("Please Choose your preference: ");
                System.out.println();
                System.out.println("Press 1 - Test1");
                System.out.println("Press 2 - Test2");
                System.out.println("Press 3 - Test3");
                System.out.println("Press 0 - Exit");

                System.out.println();
                System.out.print("Your Choice is: ");
                int CHOICE = YourChoice.nextInt();

                switch (CHOICE) {
                case 0: {
                    System.out.println("You want Exit");
                    flag = true;
                    break;
                }
                case 1: {
                    System.out.println("You want Test1");
                    flag = true;
                    break;
                }
                case 2: {
                    System.out.println("You want Test2");
                    flag = true;
                    break;
                }
                case 3: {
                    System.out.println("You want Test3");
                    flag = true;
                    break;
                }
                default:{
                    System.out.println("Wrong Input, please try again");
                    break;
                    }
                }

            } while (!flag);
}
}


问:
In R, extract text between headings using regular expressions
I want to extract all the text between chapter headings, including the first/opening heading but excluding the closing heading. The headings are always uppercase, always preceded by a digit-period or digit-letter-period combination, and always followed by space/s. I want to keep the subheadings (i.e. "6.1", "7A.1") as part of the extracted string. Here's some example text:

```<code>example <- "5. SCOPE This document outlines what to do in case of emergency landing (ignore for non-emergency landings) on tarmac. 6. WHEELS Never land on tarmac. Unless you have lowered the plane wheel mechanism. 6.1 Lower the wheel mechanism using the switch labelled 'wheel mechanism'. 7A WARNING 7A.1 Do not forget to warn passengers."

# The output I want is:

"5. SCOPE This document outlines what to do in case of emergency landing (ignore for non-emergency landings) on tarmac."

"6. WHEELS Never land on tarmac. Unless you have lowered the plane wheel mechanism. 6.1 Lower the wheel mechanism using the switch labelled 'wheel mechanism'."

"7A WARNING 7A.1 Do not forget to warn passengers."
</code>```

Using the stringr package, and with help from this post, I got this far:

```<code>library(stringr)
str_extract_all(example, "(\\d+\\w?\\.?[:blank:]+[:upper:]+)(.*?)(?=\\d+\\w?\\.?[:blank:]+[:upper:]+)")

# Explanation of my regex code:
# (\\d+\\w?\\.?[[:blank:]]+[[:upper:]])
# \\d+   one or more digits
# \\w?   zero or one letter
# \\.?   zero or one period
# [:blank:]+   one or more space/tab
# [:upper]+    one or more capital letters

# (.*?)   non-greedy capture, zero or one or more of any character

# (?=\\d+\\w?\\.?[:blank:]+[:upper:]+)
# ?=   followed by
# \\d+   one or more digits
# \\w?   zero or one letter
# \\.?   zero or one period
# [:blank:]+   one or more space/tab
# [:upper]+    one or more capital letters
</code>```

This came pretty close to what I want, with only two things going wrong. The first is that "6.1" it split into "6." and "1". The second is that text after the last chapter heading isn't captured, and looks like it might be getting split the same as "6.1" was:

```<code>[[1]]
[1] "5. SCOPE This document outlines what to do in case of emergency landing (ignore for non-emergency landings) on tarmac. "
[2] "6. WHEELS Never land on tarmac. Unless you have lowered the plane wheel mechanism. 6."
[3] "1 Lower the wheel mechanism using the switch labelled 'wheel mechanism'. "
[4] "7A WARNING 7A."
</code>```

Where am I going wrong??

答:
This works too:</p>

```<code>str_extract_all(example, "\\d[.A-Z\\d\\s]+[A-Z]{2,}[\\s(.\\w]+")
[[1]]
[1] "5. SCOPE This document outlines what to do in case of emergency landing (ignore for non"
[2] "6. WHEELS Never land on tarmac. Unless you have lowered the plane wheel mechanism. 6.1 Lower the wheel mechanism using the switch labelled "
[3] "7A WARNING 7A.1 Do not forget to warn passengers."
</code>```

Body:
I want to extract all the text between chapter headings, including the first/opening heading but excluding the closing heading. The headings are always uppercase, always preceded by a digit-period or digit-letter-period combination, and always followed by space/s. I want to keep the subheadings (i.e. "6.1", "7A.1") as part of the extracted string. Here's some example text:

example <- "5. SCOPE This document outlines what to do in case of emergency landing (ignore for non-emergency landings) on tarmac. 6. WHEELS Never land on tarmac. Unless you have lowered the plane wheel mechanism. 6.1 Lower the wheel mechanism using the switch labelled 'wheel mechanism'. 7A WARNING 7A.1 Do not forget to warn passengers."

# The output I want is:

"5. SCOPE This document outlines what to do in case of emergency landing (ignore for non-emergency landings) on tarmac."

"6. WHEELS Never land on tarmac. Unless you have lowered the plane wheel mechanism. 6.1 Lower the wheel mechanism using the switch labelled 'wheel mechanism'."

"7A WARNING 7A.1 Do not forget to warn passengers."

Using the stringr package, and with help from this post, I got this far:

library(stringr)
str_extract_all(example, "(\\d+\\w?\\.?[:blank:]+[:upper:]+)(.*?)(?=\\d+\\w?\\.?[:blank:]+[:upper:]+)")

# Explanation of my regex code:
# (\\d+\\w?\\.?[[:blank:]]+[[:upper:]])
# \\d+   one or more digits
# \\w?   zero or one letter
# \\.?   zero or one period
# [:blank:]+   one or more space/tab
# [:upper]+    one or more capital letters

# (.*?)   non-greedy capture, zero or one or more of any character

# (?=\\d+\\w?\\.?[:blank:]+[:upper:]+)
# ?=   followed by
# \\d+   one or more digits
# \\w?   zero or one letter
# \\.?   zero or one period
# [:blank:]+   one or more space/tab
# [:upper]+    one or more capital letters

This came pretty close to what I want, with only two things going wrong. The first is that "6.1" it split into "6." and "1". The second is that text after the last chapter heading isn't captured, and looks like it might be getting split the same as "6.1" was:

[[1]]
[1] "5. SCOPE This document outlines what to do in case of emergency landing (ignore for non-emergency landings) on tarmac. "
[2] "6. WHEELS Never land on tarmac. Unless you have lowered the plane wheel mechanism. 6."
[3] "1 Lower the wheel mechanism using the switch labelled 'wheel mechanism'. "
[4] "7A WARNING 7A."

Where am I going wrong??

Body:
This works too:

str_extract_all(example, "\\d[.A-Z\\d\\s]+[A-Z]{2,}[\\s(.\\w]+")
[[1]]
[1] "5. SCOPE This document outlines what to do in case of emergency landing (ignore for non"
[2] "6. WHEELS Never land on tarmac. Unless you have lowered the plane wheel mechanism. 6.1 Lower the wheel mechanism using the switch labelled "
[3] "7A WARNING 7A.1 Do not forget to warn passengers."


问:
android studio unable to find local maven repository
I placed the files of the repository in the .m2 folder but android studio is unable to resolve it

```<code>Caused by: org.gradle.internal.resolve.ModuleVersionNotFoundException: Could not find com.redcpt:sdk:0.0.1
</code>```

does anyone know what might be the issue

答:
In the comments you mention "the structure of that folder is sdk -> 0.0.1 ->.pom, .jar, .aar files here.". That is the wrong location. A Maven dependency with coordinates com.redcpt:sdk:0.0.1 should be saved in .m2/repository/com/redcpt/sdk/0.0.1/.

It might be simpler to use Maven to install files into your local repository, see also How to add local jar files to a Maven project? (although I don't know what needs to be done to store the .aar file that way).

Body:
I placed the files of the repository in the .m2 folder but android studio is unable to resolve it

Caused by: org.gradle.internal.resolve.ModuleVersionNotFoundException: Could not find com.redcpt:sdk:0.0.1

does anyone know what might be the issue


问:
swiftUI auto delay animation after 2sec
hi guys im learning swiftUI and i have some problem with my project.

i have one main card that will rotate 5 random card, plus the back of the card. and at the bottom 5 button that represent the 5 random card.

when i press any of the 5 buttons to rotate the card, i would like that the card rotate back automatically on the cardBack after 2 sec.

here is my code :

```<code>import SwiftUI

struct CardBack: View {
    var body: some View {

      Image("back_card")
        .resizable()
        .aspectRatio(contentMode: .fit)
        .frame(width: 250)
    }
}

struct ContentView: View {

   @State var flipped = false
   @State private var cardsFront = ["bigCard1", "bigCard2", "bigCard3", "bigCard4", "bigCard5" ]
   @State private var cardBack = "back_card"

    var body: some View {
        VStack {
            Spacer()
            ZStack {

            Image(flipped ? self.cardsFront.randomElement()! : self.cardBack)
              .resizable()
              .aspectRatio(contentMode: .fit)
              .frame(width: 250)
              .rotation3DEffect(Angle(degrees: flipped ? 180 : 0 ), axis: (x: 0, y: 1, z: 0))
            }

            Spacer()
            HStack {
                Button(action: {
                    withAnimation(.spring()) {
                        self.flipped.toggle()
                    }

                }) {
                    Image("circle")
                        .renderingMode(.original)
                }

                Button(action: {

                }) {
                    Image("plus")
                        .renderingMode(.original)
                }

                Button(action: {

                }) {
                    Image("wave")
                        .renderingMode(.original)
                }

                Button(action: {

                }) {
                    Image("square")
                        .renderingMode(.original)
                }

                Button(action: {

                }) {
                    Image("star")
                        .renderingMode(.original)
                }

            }
            Spacer()
        }

    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

</code>```

答:
Here is a demo on one button</p>

```<code>Button(action: {
    withAnimation(.spring()) {
        self.flipped.toggle()
    }
    DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
        withAnimation(.spring()) {
            self.flipped.toggle()
        }
    }
}) {
    Image("circle")
        .renderingMode(.original)
}
</code>```

Title: swiftUI auto delay animation after 2sec

Body:
hi guys im learning swiftUI and i have some problem with my project.

i have one main card that will rotate 5 random card, plus the back of the card. and at the bottom 5 button that represent the 5 random card.

when i press any of the 5 buttons to rotate the card, i would like that the card rotate back automatically on the cardBack after 2 sec.

here is my code :

import SwiftUI

struct CardBack: View {
    var body: some View {

      Image("back_card")
        .resizable()
        .aspectRatio(contentMode: .fit)
        .frame(width: 250)
    }
}

struct ContentView: View {

   @State var flipped = false
   @State private var cardsFront = ["bigCard1", "bigCard2", "bigCard3", "bigCard4", "bigCard5" ]
   @State private var cardBack = "back_card"

    var body: some View {
        VStack {
            Spacer()
            ZStack {

            Image(flipped ? self.cardsFront.randomElement()! : self.cardBack)
              .resizable()
              .aspectRatio(contentMode: .fit)
              .frame(width: 250)
              .rotation3DEffect(Angle(degrees: flipped ? 180 : 0 ), axis: (x: 0, y: 1, z: 0))
            }

            Spacer()
            HStack {
                Button(action: {
                    withAnimation(.spring()) {
                        self.flipped.toggle()
                    }

                }) {
                    Image("circle")
                        .renderingMode(.original)
                }

                Button(action: {

                }) {
                    Image("plus")
                        .renderingMode(.original)
                }

                Button(action: {

                }) {
                    Image("wave")
                        .renderingMode(.original)
                }

                Button(action: {

                }) {
                    Image("square")
                        .renderingMode(.original)
                }

                Button(action: {

                }) {
                    Image("star")
                        .renderingMode(.original)
                }

            }
            Spacer()
        }

    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Body:
Here is a demo on one button

Button(action: {
    withAnimation(.spring()) {
        self.flipped.toggle()
    }
    DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
        withAnimation(.spring()) {
            self.flipped.toggle()
        }
    }
}) {
    Image("circle")
        .renderingMode(.original)
}


问:
How do I run a terminal command in a Swift script? (e.g. xcodebuild)
I want to replace my CI bash scripts with swift.  I can't figure out how to invoke normal terminal command such as ls or xcodebuild

```<code>#!/usr/bin/env xcrun swift

import Foundation // Works
println("Test") // Works
ls // Fails
xcodebuild -workspace myApp.xcworkspace // Fails
</code>```

```<code>$ ./script.swift
./script.swift:5:1: error: use of unresolved identifier 'ls'
ls // Fails
^
... etc ....
</code>```

答:
I've built SwiftExec, a small library for running such commands:

import SwiftExec

var result: ExecResult
do {
    result = try exec(program: "/usr/bin/git", arguments: ["status"])
} catch {
    let error = error as! ExecError
    result = error.execResult
}

print(result.exitCode!)
print(result.stdout!)
print(result.stderr!)
```

It's a single-file library which can easily be copy-pasted into projects or installed using SPM. It's tested and simplifies error handling.

There's also ShellOut, which additionally supports a variety of pre-defined commands.

Body:
I want to replace my CI bash scripts with swift.  I can't figure out how to invoke normal terminal command such as ls or xcodebuild

#!/usr/bin/env xcrun swift

import Foundation // Works
println("Test") // Works
ls // Fails
xcodebuild -workspace myApp.xcworkspace // Fails

$ ./script.swift
./script.swift:5:1: error: use of unresolved identifier 'ls'
ls // Fails
^
... etc ....

Body:
I've built SwiftExec, a small library for running such commands:

import SwiftExec

var result: ExecResult
do {
    result = try exec(program: "/usr/bin/git", arguments: ["status"])
} catch {
    let error = error as! ExecError
    result = error.execResult
}

print(result.exitCode!)
print(result.stdout!)
print(result.stderr!)

It's a single-file library which can easily be copy-pasted into projects or installed using SPM. It's tested and simplifies error handling.

There's also ShellOut, which additionally supports a variety of pre-defined commands.


问:
removing 99999 values from cvs in python?
I am working with a large data set (over 400 columns and 200000 rows) and for some values that wasn't recorded, there is a '-9999.99' value in that slot. How do I remove these values from my imported data through python? I imported using a csv file in pandas. I don't want to remove the whole column, just any data box that has the -9999.99 value since it is meaningless and is messing up my mean and standard deviation values. Thanks!</p>

答:
After loading data in a DataFrame, replace is one option:

```<code>df.replace(-9999.99, '', inplace=True)
</code>```

or

```<code>df.replace(-9999.99, np.nan, inplace=True)
</code>```

Body:
After loading data in a DataFrame, replace is one option:

df.replace(-9999.99, '', inplace=True)

or

df.replace(-9999.99, np.nan, inplace=True)


问:
Why are values in the console but not being displayed in the page?
Values are not displayed on page, but are displayed in console.log

```<code>//app.components.ts
    import { Component } from '@angular/core';
import {AngularFireDatabase } from 'angularfire2/database';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  posts: any[];
  constructor(db: AngularFireDatabase){
    db.list('posts').valueChanges().subscribe(posts => {  this.posts = posts; console.log(this.posts); });

  }
}

//app.component.html

    <ul>
  <li *ngFor="let post of posts">
{{post.$value}}
  </li>
</ul>
</code>```

//firebase

答:
As @Peter Haddad mentioned you have to add {{post}} instead of {{post.$value}} on the list like this:

```<code><ul>
  <li *ngFor="let post of posts">
{{post}}
  </li>
</ul>
</code>```

More info about it:
https://angular.io/guide/displaying-data#add-logic-to-loop-through-data

I hope it helps! :)

Body:
Values are not displayed on page, but are displayed in console.log

//app.components.ts
    import { Component } from '@angular/core';
import {AngularFireDatabase } from 'angularfire2/database';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  posts: any[];
  constructor(db: AngularFireDatabase){
    db.list('posts').valueChanges().subscribe(posts => {  this.posts = posts; console.log(this.posts); });

  }
}

//app.component.html

{{post.$value}}

//firebase

Body:
As @Peter Haddad mentioned you have to add {{post}} instead of {{post.$value}} on the list like this:

<ul>
  <li *ngFor="let post of posts">
{{post}}
  </li>
</ul>

More info about it:
https://angular.io/guide/displaying-data#add-logic-to-loop-through-data

I hope it helps! :)


问:
Reducing the time complexity of the program
I am doing this practice problem where given a string s of lowercase letters, and a position p, I have to print all the occurrences of the letter at position p which occur before the position p.

Eg: If the string is "abaac" and p=3(1 based index) then output is 1 because 'a' occurs one time before the position p.

 There are q queries each giving me a position p. Is there any way to make this code more efficient?
I'm using hashing which is pretty efficient I think? Is there any algorithm that I am not aware of?

```<code>#include<bits/stdc++.h>
using namespace std;
int main()
{
    int n;
    cin>>n;
    string s;
    cin>>s;
    int q;
    cin>>q;
    while(q--)
    {
        int p;
        cin>>p;
        int freq[26] = {0};
        for(int i = 0; i<(p-1); i++)
            freq[s[i]-'a']++;
        cout<<freq[s[p-1]-'a']<<"\n";
    }

}

</code>```

答:
Your code currently does much more than necessary. In pseudo code you do

```<code>while(q--)
{
    read p
    freq[character] = determine count of any character up to position p
    print freq[character at position p]
}
</code>```

You repeat the whole process of counting how often each character appears before position p for each single query but then you only use the information for one single character. Thats not quite efficient. Instead you should do:

```<code>freq[position] = determine occurences of character at each position
while(q--)
{
    read p
    print freq[p]
}
</code>```

The first part can be done by traversing the input string once and then for each query you just have to look up the result from the table.

Body:
I am doing this practice problem where given a string s of lowercase letters, and a position p, I have to print all the occurrences of the letter at position p which occur before the position p.

Eg: If the string is "abaac" and p=3(1 based index) then output is 1 because 'a' occurs one time before the position p.

 There are q queries each giving me a position p. Is there any way to make this code more efficient?
I'm using hashing which is pretty efficient I think? Is there any algorithm that I am not aware of?

#include<bits/stdc++.h>
using namespace std;
int main()
{
    int n;
    cin>>n;
    string s;
    cin>>s;
    int q;
    cin>>q;
    while(q--)
    {
        int p;
        cin>>p;
        int freq[26] = {0};
        for(int i = 0; i<(p-1); i++)
            freq[s[i]-'a']++;
        cout<<freq[s[p-1]-'a']<<"\n";
    }

}

Body:
Your code currently does much more than necessary. In pseudo code you do

while(q--)
{
    read p
    freq[character] = determine count of any character up to position p
    print freq[character at position p]
}

You repeat the whole process of counting how often each character appears before position p for each single query but then you only use the information for one single character. Thats not quite efficient. Instead you should do:

freq[position] = determine occurences of character at each position
while(q--)
{
    read p
    print freq[p]
}

The first part can be done by traversing the input string once and then for each query you just have to look up the result from the table.


问:
Unable to publish shiny application
I have build a shiny application which works completely fine when I am running it through RStudio. But when I am trying to publish my R application through Shiny it is getting as error. This is the message below:</p>

```<code>
Attaching package: ‘shinydashboard’

The following object is masked from ‘package:graphics’:

    box

Loading required package: ggplot2

Attaching package: ‘plotly’

The following object is masked from ‘package:ggplot2’:

    last_plot

The following object is masked from ‘package:stats’:

    filter

The following object is masked from ‘package:graphics’:

    layout

Creating a generic function for ‘toJSON’ from package ‘jsonlite’ in package ‘googleVis’

Welcome to googleVis version 0.6.4

Please read Google's Terms of Use
before you start using the package:
https://developers.google.com/terms/

Note, the plot method of googleVis will by default use
the standard browser to display its output.

See the googleVis package vignettes for more details,
or visit https://github.com/mages/googleVis.

To suppress this message use:
suppressPackageStartupMessages(library(googleVis))

Warning in file(file, "rt") :
  cannot open file 'Cleaned_Prop_Data.csv': No such file or directory
Error in value[[3L]](cond) : cannot open the connection
Calls: local ... tryCatch -> tryCatchList -> tryCatchOne -> <Anonymous>
Execution halted

</code>```

答: It looks as if the file Cleaned_Prop_Data.csv is available on your local machine but not wherever you are publishing your app.</p>

Title: Unable to publish shiny application

Body:
I have build a shiny application which works completely fine when I am running it through RStudio. But when I am trying to publish my R application through Shiny it is getting as error. This is the message below:

Attaching package: ‘shinydashboard’

The following object is masked from ‘package:graphics’:

    box

Loading required package: ggplot2

Attaching package: ‘plotly’

The following object is masked from ‘package:ggplot2’:

    last_plot

The following object is masked from ‘package:stats’:

    filter

The following object is masked from ‘package:graphics’:

    layout

Creating a generic function for ‘toJSON’ from package ‘jsonlite’ in package ‘googleVis’

Welcome to googleVis version 0.6.4

Please read Google's Terms of Use
before you start using the package:
https://developers.google.com/terms/

Note, the plot method of googleVis will by default use
the standard browser to display its output.

See the googleVis package vignettes for more details,
or visit https://github.com/mages/googleVis.

To suppress this message use:
suppressPackageStartupMessages(library(googleVis))

Warning in file(file, "rt") :
  cannot open file 'Cleaned_Prop_Data.csv': No such file or directory
Error in value[[3L]](cond) : cannot open the connection
Calls: local ... tryCatch -> tryCatchList -> tryCatchOne -> <Anonymous>
Execution halted


问:
close a section of a accordion in jquery
It's a simple question, but i don't know how do it. I think there's a way to close all of the sections in the accordion attached to a event click, but i haven't found a method that will allow it to be done. I tried this:</p>

```<code>$(document).ready(initialize);

$("#accordion").accordion("destroy");

$("#accordion").accordion({
    collapsible: true,
    active: false
});

function initialize() {

    $(".btnOk").click(function (e) {
    e.preventDefault();
    $("#accordion").accordion("active", false);
    }
}
</code>```

答:
I think you're looking for the activate method instead of active method. I haven't tried it, but I think you should change:

```<code>$("#accordion").accordion("active", false);
</code>```

to:

```<code>$("#accordion").accordion("activate", false);
</code>```

Hope this helps.

Body:
It's a simple question, but i don't know how do it. I think there's a way to close all of the sections in the accordion attached to a event click, but i haven't found a method that will allow it to be done. I tried this:

$(document).ready(initialize);

$("#accordion").accordion("destroy");

$("#accordion").accordion({
    collapsible: true,
    active: false
});

function initialize() {

    $(".btnOk").click(function (e) {
    e.preventDefault();
    $("#accordion").accordion("active", false);
    }
}

Body:
I think you're looking for the activate method instead of active method. I haven't tried it, but I think you should change:

$("#accordion").accordion("active", false);

to:

$("#accordion").accordion("activate", false);

Hope this helps.


问:
Changing Values of elements in Pandas Datastructure
I have imported .xls file
with

```<code>ene2 = pd.read_excel('Energy Indicators.xls', index=False)
</code>```

head looks like this

```<code>print(ene2.head())
          Country Energy Supply Energy Supply per Capita % Renewable's
15             NaN    Petajoules               Gigajoules             %
16     Afghanistan           321                       10       78.6693
17         Albania           102                       35           100
18         Algeria          1959                       51       0.55101
19  American Samoa           ...                      ...      0.641026
</code>```

lets say that i used FOR loop to exchange some values

```<code>for value in ene2['Energy Supply']:
    if value == 'Petajoules':
        value = 'Gigajoules'
        print(value)
</code>```

inside the loop things looks good

however printing head again,

```<code>print(ene2.head())
</code>```

show me that, no change has been applied to the DataStructure iteslf

and tail looks exactly as above, but i expected it go got change.

QUESTION

What should i do else, to make the change valid and implemented inside Datastructure?

答:
You can simply use Series.replace:

```<code>ene2['Energy Supply'] = ene2['Energy Supply'].replace('Petajoules', 'Gigajoules')
</code>```

Body:
I have imported .xls file
with

ene2 = pd.read_excel('Energy Indicators.xls', index=False)

head looks like this

print(ene2.head())
          Country Energy Supply Energy Supply per Capita % Renewable's
15             NaN    Petajoules               Gigajoules             %
16     Afghanistan           321                       10       78.6693
17         Albania           102                       35           100
18         Algeria          1959                       51       0.55101
19  American Samoa           ...                      ...      0.641026

lets say that i used FOR loop to exchange some values

for value in ene2['Energy Supply']:
    if value == 'Petajoules':
        value = 'Gigajoules'
        print(value)

inside the loop things looks good

however printing head again,

print(ene2.head())

show me that, no change has been applied to the DataStructure iteslf

and tail looks exactly as above, but i expected it go got change.

QUESTION

What should i do else, to make the change valid and implemented inside Datastructure?

Body:
You can simply use Series.replace:

ene2['Energy Supply'] = ene2['Energy Supply'].replace('Petajoules', 'Gigajoules')


问:
Solution for decoding HTML entities through a normalizer function in gatsby-config + gatsby-source-wordpress
This should be easy but I'm struggling to get this to work..

I'm using gatsby-source-wordpress to pull blog content into my gatsby site. The problem is that HTML entities are not decoded so instead of the '&' character, I see something like '&8466;'.

I want to implement a normalized function inside my gatsby-config.js file.

I found this function online that is supposed to remedy the HTML entities issue:

```<code>const decodeHTML = ({input}) => {
    let txt = document.createElement('textarea');
    txt.innerHTML = input;
    return txt.value;
}
</code>```

I've tried importing it into my gatsby-config.js from a separate file; I've also placed the function directly in the gatsby-config.js file. Ideally, I'd like to import this function from a separate project file but that's not the main issue.

To get this function working, I've inlined it directly into my config file:

```<code>{
  resolve: `gatsby-source-wordpress`,
  options: {
    baseUrl: `peakwebsites.ca`,
    protocol: `https`,
    useACF: false,
    verboseOutput: false,
    hostingWPCOM: false,
    normalizer: function decodeHTML({entities}) {
      let txt = document.createElement('textarea');
      txt.innerHTML = entities;
      return txt.value;
    }
  }
},
</code>```

But I'm running into this error:

```<code>success Downloading remote files - 7.158s - 205/205 28.64/s

 ERROR #11321  PLUGIN

"gatsby-source-wordpress" threw an error while running the sourceNodes lifecycle:

Cannot read property 'forEach' of undefined

  299 |       createNode,
  300 |       createContentDigest
> 301 |     }) => normalize.createNodesFromEntities({
      |                     ^
  302 |       entities,
  303 |       createNode,
  304 |       createContentDigest

 File: node_modules\gatsby-source-wordpress\gatsby-node.js:301:21
</code>```

I'm not super familiar with the internals of how the Wordpress source plugin works so there might be some object property that I need to parse. I'm really not sure.

Does anyone have a solution for decoding HTML entities through a normalized function in gatsby-config ?

Thanks,

答:
I'm not familiar with gatsby-source-wordpress, but I feel like I have enough information to put you on the right path:

You won't be able to access document from gatsby-config.js, it runs in Nodejs environment. Use a node library instead, a quick search turned up he.

const he = require('he')

const decode = input => he.decode(input)
```

<ol start="2">
<li>A quick look into gatsby-source-wordpress docs shows that <code>entities</code> is an array. I don't know what its shape looks like, you'd have to log it out to see what it is. Once you know how to access your HTML text, you can use the decode function above:</li>
</ol>

<pre class="lang-js prettyprint-override"><code>{
  resolve: 'gatsby-source-wordpress',
  options: {
    // ...other options
    normalizer: ({ entities }) => entities.map(entity => {
      /* access your raw html somehow, this is just a guess */
      if (entity.__type === 'wordpress_post_or_something') {
        entity.content = decode(entity.content)
      }
      return entity
    })
  }
}

</code>```

Alternatively, you can also add a new field to the nodes created by gatsby-source-wordpress via createNodeField in onCreateNode or createSchemaCustomization. The idea would be to get the html content from the node, decode it, then add it back to that node as a new field.

I'll be happy to remove/update this answer if someone more familiar with wordpress can help.

Body:
This should be easy but I'm struggling to get this to work..

I'm using gatsby-source-wordpress to pull blog content into my gatsby site. The problem is that HTML entities are not decoded so instead of the '&' character, I see something like '&8466;'.

I want to implement a normalized function inside my gatsby-config.js file.

I found this function online that is supposed to remedy the HTML entities issue:

const decodeHTML = ({input}) => {
    let txt = document.createElement('textarea');
    txt.innerHTML = input;
    return txt.value;
}

I've tried importing it into my gatsby-config.js from a separate file; I've also placed the function directly in the gatsby-config.js file. Ideally, I'd like to import this function from a separate project file but that's not the main issue.

To get this function working, I've inlined it directly into my config file:

{
  resolve: `gatsby-source-wordpress`,
  options: {
    baseUrl: `peakwebsites.ca`,
    protocol: `https`,
    useACF: false,
    verboseOutput: false,
    hostingWPCOM: false,
    normalizer: function decodeHTML({entities}) {
      let txt = document.createElement('textarea');
      txt.innerHTML = entities;
      return txt.value;
    }
  }
},

But I'm running into this error:

success Downloading remote files - 7.158s - 205/205 28.64/s

 ERROR #11321  PLUGIN

"gatsby-source-wordpress" threw an error while running the sourceNodes lifecycle:

Cannot read property 'forEach' of undefined

  299 |       createNode,
  300 |       createContentDigest
> 301 |     }) => normalize.createNodesFromEntities({
      |                     ^
  302 |       entities,
  303 |       createNode,
  304 |       createContentDigest

 File: node_modules\gatsby-source-wordpress\gatsby-node.js:301:21

I'm not super familiar with the internals of how the Wordpress source plugin works so there might be some object property that I need to parse. I'm really not sure.

Does anyone have a solution for decoding HTML entities through a normalized function in gatsby-config ?

Thanks,

Body:
I'm not familiar with gatsby-source-wordpress, but I feel like I have enough information to put you on the right path:

You won't be able to access document from gatsby-config.js, it runs in Nodejs environment. Use a node library instead, a quick search turned up he.

const he = require('he')

const decode = input => he.decode(input)

A quick look into gatsby-source-wordpress docs shows that entities is an array. I don't know what its shape looks like, you'd have to log it out to see what it is. Once you know how to access your HTML text, you can use the decode function above:

{
  resolve: 'gatsby-source-wordpress',
  options: {
    // ...other options
    normalizer: ({ entities }) => entities.map(entity => {
      /* access your raw html somehow, this is just a guess */
      if (entity.__type === 'wordpress_post_or_something') {
        entity.content = decode(entity.content)
      }
      return entity
    })
  }
}

Alternatively, you can also add a new field to the nodes created by gatsby-source-wordpress via createNodeField in onCreateNode or createSchemaCustomization. The idea would be to get the html content from the node, decode it, then add it back to that node as a new field.

I'll be happy to remove/update this answer if someone more familiar with wordpress can help.


问:
Trigger an API endpoint when ever a file stored in Azure Blob Storage
I need to trigger an API endpoint when a new file or existing file modified in the Azure Blob storage.

How can I achieve this

答:
If it for using the same code in the Web API. You could make a backgroundservice in the API project there will listen for an event.

Or a service there have the responsibility to listen, and send the information to the endpoint.

https://learn.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-3.1&tabs=visual-studio

Then there are some documentation here on how Azure can help you with trigger things.
https://learn.microsoft.com/en-us/azure/storage/blobs/storage-blob-event-overview


问:
How to create Google Pay link to send or request money?
After looking (Googling) on the web for a while, I can find nothing that can create a link for Google Pay request.

In my Flutter app, I'd like to create a link to accept money using my Phone Number which when tapped will launch the Google Pay app with payment for my phone number already set. However the amount will be entered by the user from the Google pay app.

Something like this:

```<code>String googlePayUrl = "https://pay.google.com?phone=XXXXXXXXXX";
</code>```

This if for Google pay version of India

答:
Thanks to @Soc for the answer. This post is just explained answer for the @Soc Post above. The pdf document was a huge help. My requirement was in Flutter for which I created a link and used url_launcher to open the link. Opening the link will show the list of UPI compatible apps in your phone.

link example:

```<code>String upi_url = 'upi://pay?pa=address@okhdfcbank&pn=Payee Name&tn=Payment Message&cu=INR';

// pa : Payee address, usually found in GooglePay app profile page
// pn : Payee name
// tn : Txn note, basically your message for the payee
// cu : Currency
</code>```

Note : All the mentioned fields are required in order to make a successful payment.

Body:
After looking (Googling) on the web for a while, I can find nothing that can create a link for Google Pay request.

In my Flutter app, I'd like to create a link to accept money using my Phone Number which when tapped will launch the Google Pay app with payment for my phone number already set. However the amount will be entered by the user from the Google pay app.

Something like this:

String googlePayUrl = "https://pay.google.com?phone=XXXXXXXXXX";

This if for Google pay version of India

Body:
Thanks to @Soc for the answer. This post is just explained answer for the @Soc Post above. The pdf document was a huge help. My requirement was in Flutter for which I created a link and used url_launcher to open the link. Opening the link will show the list of UPI compatible apps in your phone.

link example:

String upi_url = 'upi://pay?pa=address@okhdfcbank&pn=Payee Name&tn=Payment Message&cu=INR';

// pa : Payee address, usually found in GooglePay app profile page
// pn : Payee name
// tn : Txn note, basically your message for the payee
// cu : Currency

Note : All the mentioned fields are required in order to make a successful payment.


问:
WooCommerce custom plugin: Error around WC_Customer Object instance
I've built a plugin and I have the following issue:
The WooCommerce Dashboard (in the admin side) will not load the data. It hangs and fails. I have tracked the problem code:

The issue in the

```<code>if ( is_admin() ) {
    //removed
} else if ( !$this->is_login_page() && !wp_doing_ajax() ) {

    $public = new Public();
}
</code>```

It's the public side code that's causing the issue! and neither is_admin or wp_doing_ajax prevent it from happening.

In the public side, I'm calling

```<code>add_action( 'init', array('Dynamic_Rules', 'dynamic_rule_tax_exemption') );
</code>```

Inside the tax exemption function, I have this code in particular which causes the problem:

```<code>$woocommerce = WC();

$user_country = $woocommerce->customer->get_billing_country();

$woocommerce->customer->set_is_vat_exempt(true);
</code>```

So I can only speculate about what happens, perhaps the WC() is somehow sending everything into an infinite loop, which is why the Dashboard does not load the data. Why is_admin() and wp_doing_ajax() don't prevent this from happening I don't know.

Perhaps it's wrong that I'm calling that function on init, but where else could I call it?

Any help is appreciated

答:
Is difficult to find out what your problem can be… Note that "your question should be updated to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem."

What you can try instead, may be:

```<code>$customer = WC()->customer;

if( ! is_a( $customer, 'WC_Customer' ) {
    global $current_user;

    if( $current_user > 0 ) {
        $customer = new WC_Customer( $current_user->ID );
    }
}

if( is_a( $customer, 'WC_Customer' ) {
    $billing_country = $customer->get_billing_country();

    if( ! $customer->is_vat_exempt() ) {
        $customer->set_is_vat_exempt( true );
    }
} else {
    // Some code to throw an error or debug trace
}
</code>```

I hope this will solve your issue.  If not you need to pass the User ID to your code in some way.

Maybe useful: Debugging WooCommerce PHP with Javascript console.log doesn't work

Body:
I've built a plugin and I have the following issue:
The WooCommerce Dashboard (in the admin side) will not load the data. It hangs and fails. I have tracked the problem code:

The issue in the

if ( is_admin() ) {
    //removed
} else if ( !$this->is_login_page() && !wp_doing_ajax() ) {

    $public = new Public();
}

It's the public side code that's causing the issue! and neither is_admin or wp_doing_ajax prevent it from happening.

In the public side, I'm calling

add_action( 'init', array('Dynamic_Rules', 'dynamic_rule_tax_exemption') );

Inside the tax exemption function, I have this code in particular which causes the problem:

$woocommerce = WC();

$user_country = $woocommerce->customer->get_billing_country();

$woocommerce->customer->set_is_vat_exempt(true);

So I can only speculate about what happens, perhaps the WC() is somehow sending everything into an infinite loop, which is why the Dashboard does not load the data. Why is_admin() and wp_doing_ajax() don't prevent this from happening I don't know.

Perhaps it's wrong that I'm calling that function on init, but where else could I call it?

Any help is appreciated

Body:
Is difficult to find out what your problem can be… Note that "your question should be updated to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem."

What you can try instead, may be:

$customer = WC()->customer;

if( ! is_a( $customer, 'WC_Customer' ) {
    global $current_user;

    if( $current_user > 0 ) {
        $customer = new WC_Customer( $current_user->ID );
    }
}

if( is_a( $customer, 'WC_Customer' ) {
    $billing_country = $customer->get_billing_country();

    if( ! $customer->is_vat_exempt() ) {
        $customer->set_is_vat_exempt( true );
    }
} else {
    // Some code to throw an error or debug trace
}

I hope this will solve your issue.  If not you need to pass the User ID to your code in some way.

Maybe useful: Debugging WooCommerce PHP with Javascript console.log doesn't work


问:
How to decide to which interval a number belongs
let's say that I have a car with its front field of vision (180 degrees), and I want to cut those 180 degrees into several intervals, for example by 30 degrees. and I have a set of numbers and I want to decide into which interval the number belongs to.

I know how to hard-code it but how can I automate it in order to create an algorithm which does this based on the number of intervals.

If for example the 180 degrees was split by 45 degrees than those intervals would be
(0 - 45) - index 0, (45 - 90) - index 1, (90 - 135) - index 2, (135 - 180) - index 3
This means that I would have a vector of size four (one element for each interval)

And if I have numbers for example 30 and 150 the vector would look like this: [1, 0, 0, 1]

How can I achieve this?

This is what I tried to do:

```<code>NUMBER_OF_SECTORS = 6
sector_thresholds = []

for i in range(NUMBER_OF_SECTORS+1):
    sector_thresholds.append(180/NUMBER_OF_SECTORS * i)
print(sector_thresholds)

list_of_states = []
state_vector = [0] * (NUMBER_OF_SECTORS + 1)
for i in range(1000):
    random_number = 360*random.random() # If the number is larger than 180 then it should be ignored
    for j in range(NUMBER_OF_SECTORS):
        if j == 0:
            pass
        if sector_thresholds[j-1] <= random_number <= sector_thresholds[j]:
            state_vector[j] = random.choice([1,2]) #This shows an assignment error
    print(state_vector)
    state_vector = []
</code>```

How can I fix this?

Thank you very much for any help

EDIT: I tried to improve my code according to the answer below, like this:

```<code>for i in range(NUMBER_OF_SECTORS+1):
    sector_thresholds.append(180/NUMBER_OF_SECTORS * i)
print(sector_thresholds)

list_of_states = []
state_vector = [0] * (NUMBER_OF_SECTORS + 1)
for i in range(1000):
    random_number = 360*random.random()
    while i % NUMBER_OF_SECTORS: # make sure that the state vector gets cleared after the same amount of iteration as its length
        sector = int(np.floor(random_number /(180/NUMBER_OF_SECTORS)))
        print(f"sector is {sector}")
        if sector <= NUMBER_OF_SECTORS:
            state_vector[sector] = 1
    print(state_vector)
    state_vector = []
</code>```

but I get an error in the line state_vector[sector] = 1 list assignment index out of range I know that there will be surely some "stupid" typo but I cannot find it, thank you again for your help

答:
For equal sectors just use integer division when angle is integer:

```<code>sector = angle // sectorsize
</code>```

or flooring if angle is float

```<code>sector = int(angle / sectorsize)
</code>```

Example:

```<code>import random
NUMBER_OF_SECTORS = 6
sector_size = 180 / NUMBER_OF_SECTORS

state_vector = [0] * (NUMBER_OF_SECTORS + 1)
for i in range(10):
    random_number = 360*random.random()
    sector = int(random_number / sector_size)
    print(f"sector is {sector}")
    if sector <= NUMBER_OF_SECTORS:
        state_vector[sector] = 1
print(state_vector)

>sector is 5
 ...
>[0, 0, 0, 1, 1, 1, 1]
</code>```

Body:
let's say that I have a car with its front field of vision (180 degrees), and I want to cut those 180 degrees into several intervals, for example by 30 degrees. and I have a set of numbers and I want to decide into which interval the number belongs to.

I know how to hard-code it but how can I automate it in order to create an algorithm which does this based on the number of intervals.

If for example the 180 degrees was split by 45 degrees than those intervals would be
(0 - 45) - index 0, (45 - 90) - index 1, (90 - 135) - index 2, (135 - 180) - index 3
This means that I would have a vector of size four (one element for each interval)

And if I have numbers for example 30 and 150 the vector would look like this: [1, 0, 0, 1]

How can I achieve this?

This is what I tried to do:

NUMBER_OF_SECTORS = 6
sector_thresholds = []

for i in range(NUMBER_OF_SECTORS+1):
    sector_thresholds.append(180/NUMBER_OF_SECTORS * i)
print(sector_thresholds)

list_of_states = []
state_vector = [0] * (NUMBER_OF_SECTORS + 1)
for i in range(1000):
    random_number = 360*random.random() # If the number is larger than 180 then it should be ignored
    for j in range(NUMBER_OF_SECTORS):
        if j == 0:
            pass
        if sector_thresholds[j-1] <= random_number <= sector_thresholds[j]:
            state_vector[j] = random.choice([1,2]) #This shows an assignment error
    print(state_vector)
    state_vector = []

How can I fix this?

Thank you very much for any help

EDIT: I tried to improve my code according to the answer below, like this:

for i in range(NUMBER_OF_SECTORS+1):
    sector_thresholds.append(180/NUMBER_OF_SECTORS * i)
print(sector_thresholds)

list_of_states = []
state_vector = [0] * (NUMBER_OF_SECTORS + 1)
for i in range(1000):
    random_number = 360*random.random()
    while i % NUMBER_OF_SECTORS: # make sure that the state vector gets cleared after the same amount of iteration as its length
        sector = int(np.floor(random_number /(180/NUMBER_OF_SECTORS)))
        print(f"sector is {sector}")
        if sector <= NUMBER_OF_SECTORS:
            state_vector[sector] = 1
    print(state_vector)
    state_vector = []

but I get an error in the line state_vector[sector] = 1 list assignment index out of range I know that there will be surely some "stupid" typo but I cannot find it, thank you again for your help

Body:
For equal sectors just use integer division when angle is integer:

sector = angle // sectorsize

or flooring if angle is float

sector = int(angle / sectorsize)

Example:

import random
NUMBER_OF_SECTORS = 6
sector_size = 180 / NUMBER_OF_SECTORS

state_vector = [0] * (NUMBER_OF_SECTORS + 1)
for i in range(10):
    random_number = 360*random.random()
    sector = int(random_number / sector_size)
    print(f"sector is {sector}")
    if sector <= NUMBER_OF_SECTORS:
        state_vector[sector] = 1
print(state_vector)

>sector is 5
 ...
>[0, 0, 0, 1, 1, 1, 1]


问:
Write a cursor to search and insert
I have tables like that:

Main

```<code>id name   isedit
1   kyle   0
2   jhon   1
3   dave   0
</code>```

EditHistory

```<code>id idmain name isedit  Begin                end
1  2      jhon  0      28.05.2020 18:30    28.05.2020 18:35
2  2      jhon  0      28.05.2020 18:35     NULL
3  1      kyle  0      27.05.2020 12:03      NULL
</code>```

I currently use trigger:

```<code>(…)       if update(isedit) and exists (
        select 1
        from Inserted I
        where design = 0

      ) begin
        Insert into dbo.HistoryEdit
            ([idmain][name][isedit][Begin][end]) SELECT id, name, iedit, GETDATE(), null
        from Inserted
      end;
</code>```

I need to create cursor that will check through EditHistory for previous rows with same idmain and if there is such row edit its end date to GETDATE() and insert into HistoryEdit as in my current insert.

I know it can be easily done with IF's and thats how I would do it. But I have to use cursor for that, and I never used cursor before.

答:
I never used cursor before.

Well don't start now.  Just update the older rows before you insert the newer ones:

```<code>declare @d datetime = GetDate()

update EditHistory set end = @d
where id in (select id from inserted)
  and end is null;

Insert into dbo.HistoryEdit
    ([idmain][name][isedit][Begin][end])
SELECT id, name, iedit, @d, null
from Inserted
</code>```

Title: Write a cursor to search and insert

Body:
I have tables like that:

Main

id name   isedit
1   kyle   0
2   jhon   1
3   dave   0

EditHistory

id idmain name isedit  Begin                end
1  2      jhon  0      28.05.2020 18:30    28.05.2020 18:35
2  2      jhon  0      28.05.2020 18:35     NULL
3  1      kyle  0      27.05.2020 12:03      NULL

I currently use trigger:

(…)       if update(isedit) and exists (
        select 1
        from Inserted I
        where design = 0

      ) begin
        Insert into dbo.HistoryEdit
            ([idmain][name][isedit][Begin][end]) SELECT id, name, iedit, GETDATE(), null
        from Inserted
      end;

I need to create cursor that will check through EditHistory for previous rows with same idmain and if there is such row edit its end date to GETDATE() and insert into HistoryEdit as in my current insert.

I know it can be easily done with IF's and thats how I would do it. But I have to use cursor for that, and I never used cursor before.

Body:
I never used cursor before.

Well don't start now.  Just update the older rows before you insert the newer ones:

declare @d datetime = GetDate()

update EditHistory set end = @d
where id in (select id from inserted)
  and end is null;

Insert into dbo.HistoryEdit
    ([idmain][name][isedit][Begin][end])
SELECT id, name, iedit, @d, null
from Inserted


答:
Instead of:

```<code>value = 'Gigajoules'
</code>```

do this:

```<code>ene2.loc[ene2['Energy Supply'] == value, 'Energy Supply'] = 'Gigajoules'
</code>```

You have to set it to the relevant cell, by filtering for the correct rows and columns with .loc. The other answer is the simpler method, but I wanted you to understand that you are not making the changes back to the dataframe with just value = blah.

Title: Changing Values of elements in Pandas Datastructure

Body:
Instead of:

value = 'Gigajoules'

do this:

ene2.loc[ene2['Energy Supply'] == value, 'Energy Supply'] = 'Gigajoules'

You have to set it to the relevant cell, by filtering for the correct rows and columns with .loc. The other answer is the simpler method, but I wanted you to understand that you are not making the changes back to the dataframe with just value = blah.