问:
What does `+''`` mean in Ruby?
I have this line of code in a project I am looking at -
cta = send(state + '_cta') || +''

What does the +'' do?

答:
+'' is the unary + operator applied to the string literal '' and the unary + on strings:

+str → str (mutable)

  If the string is frozen, then return duplicated mutable string.

If the string is not frozen, then return the string itself.

It is common to put # frozen_string_literal: true in your Ruby files so that all string literals (such as '') are frozen (i.e. immutable). So '' is often an immutable string but +'' is a mutable version of ''.

That means that this:

```<code>cta = send(state + '_cta') || +''
</code>```

should leave a mutable string in cta.

As an aside, if send(state + '_cta') should give you a String or nil then you could also say:

```<code>cta = send(state + '_cta').to_s
</code>```

since NilClass#to_s gives you an unfrozen ''. If send(state + '_cta') can return false then the +'' and to_s versions are different of course.

Title: What does `+''`` mean in Ruby?

Body:
+'' is the unary + operator applied to the string literal '' and the unary + on strings:

+str → str (mutable)

  If the string is frozen, then return duplicated mutable string.

If the string is not frozen, then return the string itself.

It is common to put # frozen_string_literal: true in your Ruby files so that all string literals (such as '') are frozen (i.e. immutable). So '' is often an immutable string but +'' is a mutable version of ''.

That means that this:

cta = send(state + '_cta') || +''

should leave a mutable string in cta.

As an aside, if send(state + '_cta') should give you a String or nil then you could also say:

cta = send(state + '_cta').to_s

since NilClass#to_s gives you an unfrozen ''. If send(state + '_cta') can return false then the +'' and to_s versions are different of course.


来源: stackexchange

问:
Setup Wordpress with Magento using Nginx
I have a Magento 2 installed in /var/www/html/ folder using mydomain.com and I added a Wordpress in /var/www/html/pub/wp/ folder using mydomain.com/wp/
When I tried to access mydomain.com/wp/readme.html it's working fine but all php files are not accessible so I can't connect to admin mydomain.com/wp/wp-login.php and see my Wordpress.

I added this to my nginx configuration but it's not working :

```<code>location /wp/ {
  index index.html index.php;
  try_files $uri $uri/ /wp/index.php?q=$uri&args;

  location ~ \.php$ {
    fastcgi_pass   127.0.0.1:9000;
    fastcgi_index  /wp/index.php;
    include        fastcgi.conf;
  }
}
</code>```

答:
You have installed WordPress at pub/wp but your Nginx config refers just to /wp/. Either modify your Nginx config to refer to /pub/wp/ or move WordPress to the root (eg. /wp/).

https://fishpig.co.uk/magento/wordpress-integration/nginx/

```<code>upstream fastcgi_backend {
  server  127.0.0.1:9000;
}

server {
  listen 80;

  # Magento 2 base URL
  server_name m2.latest.composer.fp.com;

  # Magento 2 root directory
  set $MAGE_ROOT /home/magento2/html;

  set $MAGE_DEBUG_SHOW_ARGS 1;

  include /home/magento2/html/nginx.conf.sample;

  # WordPress is installed in pub/wp
  location /wp/ {
    index index.html index.php;
    try_files $uri $uri/ /wp/index.php?q=$uri&args;

    location ~ \.php$ {
      fastcgi_pass   127.0.0.1:9000;
      fastcgi_index  /wp/index.php;
      include        fastcgi.conf;
    }
  }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a Magento 2 installed in /var/www/html/ folder using mydomain.com and I added a Wordpress in /var/www/html/pub/wp/ folder using mydomain.com/wp/
When I tried to access mydomain.com/wp/readme.html it's working fine but all php files are not accessible so I can't connect to admin mydomain.com/wp/wp-login.php and see my Wordpress.

I added this to my nginx configuration but it's not working :

location /wp/ {
  index index.html index.php;
  try_files $uri $uri/ /wp/index.php?q=$uri&args;

  location ~ \.php$ {
    fastcgi_pass   127.0.0.1:9000;
    fastcgi_index  /wp/index.php;
    include        fastcgi.conf;
  }
}

Body:
You have installed WordPress at pub/wp but your Nginx config refers just to /wp/. Either modify your Nginx config to refer to /pub/wp/ or move WordPress to the root (eg. /wp/).

https://fishpig.co.uk/magento/wordpress-integration/nginx/

upstream fastcgi_backend {
  server  127.0.0.1:9000;
}

server {
  listen 80;

  # Magento 2 base URL
  server_name m2.latest.composer.fp.com;

  # Magento 2 root directory
  set $MAGE_ROOT /home/magento2/html;

  set $MAGE_DEBUG_SHOW_ARGS 1;

  include /home/magento2/html/nginx.conf.sample;

  # WordPress is installed in pub/wp
  location /wp/ {
    index index.html index.php;
    try_files $uri $uri/ /wp/index.php?q=$uri&args;

    location ~ \.php$ {
      fastcgi_pass   127.0.0.1:9000;
      fastcgi_index  /wp/index.php;
      include        fastcgi.conf;
    }
  }
}


问:
react inner component's state change don't smooth
I'm trying to control inputs with state.

But I'm having a problem with this case which input keep losing it's focus when I hit the keyboard.

See picture below:

https://codesandbox.io/s/how-to-solve-this-7kwj6

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.onBchange = this.onBchange.bind(this);
  }
  state = {
    a: true,
    b: "",
    c: ""
  };

  onBchange(e) {
    const thisClass = this;
    return (async function() {
      await thisClass.setState({ b: e.target.value });
      console.log(thisClass.state.b);
    })();
  }

  onCchange = e => {
    this.setState({ c: e.target.value });
  };

  render() {
    // this cause problem why?
    const Test = ({ b, c, onBchange, onCchange }) => (
      <Fragment>
        B:
        <input value={b} onChange={onBchange} />
        C:
        <input value={c} onChange={onCchange} />
      </Fragment>
    );

    return (

        {this.state.a && (
          <Test
            b={this.state.b}
            c={this.state.c}
            onBchange={this.onBchange}
            onCchange={this.onCchange}
          />
        )}

    );
  }
}

```

Please let me know if you need more info about this.

Any ideas?

答:
Your app is rerendering those elements on each change because each keystroke causes new props to be passed to <Test/> within your App's render method.

Notice that changing the return method in render to this stops the issue:

```<code> <div className="App">
        <span>B: </span>
        <input value={this.state.b} onChange={this.onBchange} />
        <span>C: </span>
        <input value={this.state.c} onChange={this.onCchange} />
        {/* {this.state.a && (
          <Test
            b={this.state.b}
            c={this.state.c}
            onBchange={this.onBchange}
            onCchange={this.onCchange}
          />
        )} */}
      </div>
</code>```

Body:
I'm trying to control inputs with state.

But I'm having a problem with this case which input keep losing it's focus when I hit the keyboard.

See picture below:

https://codesandbox.io/s/how-to-solve-this-7kwj6

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.onBchange = this.onBchange.bind(this);
  }
  state = {
    a: true,
    b: "",
    c: ""
  };

  onBchange(e) {
    const thisClass = this;
    return (async function() {
      await thisClass.setState({ b: e.target.value });
      console.log(thisClass.state.b);
    })();
  }

  onCchange = e => {
    this.setState({ c: e.target.value });
  };

  render() {
    // this cause problem why?
    const Test = ({ b, c, onBchange, onCchange }) => (
      <Fragment>
        B:
        <input value={b} onChange={onBchange} />
        C:
        <input value={c} onChange={onCchange} />
      </Fragment>
    );

    return (

        {this.state.a && (
          <Test
            b={this.state.b}
            c={this.state.c}
            onBchange={this.onBchange}
            onCchange={this.onCchange}
          />
        )}

    );
  }
}

Please let me know if you need more info about this.

Any ideas?

Body:
Your app is rerendering those elements on each change because each keystroke causes new props to be passed to <Test/> within your App's render method.

Notice that changing the return method in render to this stops the issue:

 <div className="App">
        <span>B: </span>
        <input value={this.state.b} onChange={this.onBchange} />
        <span>C: </span>
        <input value={this.state.c} onChange={this.onCchange} />
        {/* {this.state.a && (
          <Test
            b={this.state.b}
            c={this.state.c}
            onBchange={this.onBchange}
            onCchange={this.onCchange}
          />
        )} */}
      </div>


问:
How to replace NA with set of values
I have the following data frame:

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

df <- tibble(
  source = c("a", "b", "c", "d", "e"),
  score = c(10, 5, NA, 3, NA ) )

df
</code>```

It looks like this:

```<code># A tibble: 5 x 2
  source score
  <chr>  <dbl>
1 a         10 . # current max value
2 b          5
3 c         NA
4 d          3
5 e         NA
</code>```

What I want to do is to replace NA in score column with values ranging for existing max  + n onwards. Where n range from 1 to total number of rows of the df

Resulting in this (hand-coded) :

```<code>  source score
  a         10
  b          5
  c         11 # obtained from 10 + 1
  d          3
  e         12 #  obtained from 10 + 2
</code>```

How can I achieve that?

答:
A dplyr solution.

```<code>df %>%
  mutate(na_count = cumsum(is.na(score)),
         score = ifelse(is.na(score), max(score, na.rm = TRUE) + na_count, score)) %>%
  select(-na_count)
## A tibble: 5 x 2
#  source score
#  <chr>  <dbl>
#1 a         10
#2 b          5
#3 c         11
#4 d          3
#5 e         12
</code>```

Title: How to replace NA with set of values

Body:
I have the following data frame:

library(dplyr)
library(tibble)

df <- tibble(
  source = c("a", "b", "c", "d", "e"),
  score = c(10, 5, NA, 3, NA ) )

df

It looks like this:

# A tibble: 5 x 2
  source score
  <chr>  <dbl>
1 a         10 . # current max value
2 b          5
3 c         NA
4 d          3
5 e         NA

What I want to do is to replace NA in score column with values ranging for existing max  + n onwards. Where n range from 1 to total number of rows of the df

Resulting in this (hand-coded) :

  source score
  a         10
  b          5
  c         11 # obtained from 10 + 1
  d          3
  e         12 #  obtained from 10 + 2

How can I achieve that?

Body:
A dplyr solution.

df %>%
  mutate(na_count = cumsum(is.na(score)),
         score = ifelse(is.na(score), max(score, na.rm = TRUE) + na_count, score)) %>%
  select(-na_count)
## A tibble: 5 x 2
#  source score
#  <chr>  <dbl>
#1 a         10
#2 b          5
#3 c         11
#4 d          3
#5 e         12


问:
How to make spacy rule-base matchs only what is between the give pattern
I have the following code:

```<code>doc = nlp("My big pencil is red. Your pencil is green.")
matcher = Matcher(nlp.vocab)
matcher.add("pencil", None, [
    {"LEMMA": "-PRON-"},
    {"OP": "*"},
    {"LEMMA": "pencil"},
])
matches = matcher(doc)
for (entity_key, start_token, end_token) in matches:
    print(start_token, end_token, doc[start_token:end_token])
</code>```

When I a run it, I get:

```
0 3 My big pencil
6 8 Your pencil
0 8 My big pencil is red. Your pencil
```

However, I just want it return the matches for the start and end tokens:

```
0 3 My big pencil
6 8 Your pencil
```

Is there a way to restrict matcher to only return everything between the start and end tokens?

答:
The third match is a valid match for the pattern -PRON- * pencil.

Since the Matcher doesn't have an option for * to be non-greedy, you will need to filter the matches returned to get the results that you want.

Body:
I have the following code:

doc = nlp("My big pencil is red. Your pencil is green.")
matcher = Matcher(nlp.vocab)
matcher.add("pencil", None, [
    {"LEMMA": "-PRON-"},
    {"OP": "*"},
    {"LEMMA": "pencil"},
])
matches = matcher(doc)
for (entity_key, start_token, end_token) in matches:
    print(start_token, end_token, doc[start_token:end_token])

When I a run it, I get:

0 3 My big pencil
6 8 Your pencil
0 8 My big pencil is red. Your pencil

However, I just want it return the matches for the start and end tokens:

0 3 My big pencil
6 8 Your pencil

Is there a way to restrict matcher to only return everything between the start and end tokens?


问:
sh: 1: rimraf: Permission denied issue on live server
Thanks for looking at my issue.

Basically I am facing problem with making build on production dedicated server.

I have executed "npm run build" command and I have received the
the issue

sh: 1: rimraf: Permission denied issue on live server

I am not sure how exactly we should solve it.

My error logs are as follow below.

```<code>0 info it worked if it ends with ok
1 verbose cli [ '/usr/bin/node', '/usr/bin/npm', 'run', 'build' ]
2 info using npm@6.10.2
3 info using node@v9.11.2
4 verbose run-script [ 'prebuild', 'build', 'postbuild' ]
5 info lifecycle @~prebuild: @
6 info lifecycle @~build: @
7 verbose lifecycle @~build: unsafe-perm in lifecycle true
8 verbose lifecycle @~build: PATH: /usr/lib/node_modules/npm/node_modules/npm-lifecycle/node-gyp-bin:/var/www/html/basepath/moneytransfer/node_modules/.bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games
9 verbose lifecycle @~build: CWD: /var/www/html/basepath/moneytransfer
10 silly lifecycle @~build: Args: [ '-c',
10 silly lifecycle   'npm run clean && webpack --mode development --progress' ]
11 silly lifecycle @~build: Returned: code: 126  signal: null
12 info lifecycle @~build: Failed to exec build script
13 verbose stack Error: @ build: `npm run clean && webpack --mode development --progress`
13 verbose stack Exit status 126
13 verbose stack     at EventEmitter.<anonymous> (/usr/lib/node_modules/npm/node_modules/npm-lifecycle/index.js:326:16)
13 verbose stack     at EventEmitter.emit (events.js:180:13)
13 verbose stack     at ChildProcess.<anonymous> (/usr/lib/node_modules/npm/node_modules/npm-lifecycle/lib/spawn.js:55:14)
13 verbose stack     at ChildProcess.emit (events.js:180:13)
13 verbose stack     at maybeClose (internal/child_process.js:936:16)
13 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:220:5)
14 verbose pkgid @
15 verbose cwd /var/www/html/basepath/moneytransfer
16 verbose Linux 4.15.0-29-generic
17 verbose argv "/usr/bin/node" "/usr/bin/npm" "run" "build"
18 verbose node v9.11.2
19 verbose npm  v6.10.2
20 error code ELIFECYCLE
21 error errno 126
22 error @ build: `npm run clean && webpack --mode development --progress`
22 error Exit status 126
23 error Failed at the @ build script.
23 error This is probably not a problem with npm. There is likely additional logging output above.
24 verbose exit [ 126, true ]
</code>```

答:
```<code>npm i rimraf
</code>```

<p>worked for me because I was not in wifi environment. I had a similar error trace (after porting a project with node_modules from windows to mac) </p>

Body:
Thanks for looking at my issue.

Basically I am facing problem with making build on production dedicated server.

I have executed "npm run build" command and I have received the
the issue

sh: 1: rimraf: Permission denied issue on live server

I am not sure how exactly we should solve it.

My error logs are as follow below.

0 info it worked if it ends with ok
1 verbose cli [ '/usr/bin/node', '/usr/bin/npm', 'run', 'build' ]
2 info using npm@6.10.2
3 info using node@v9.11.2
4 verbose run-script [ 'prebuild', 'build', 'postbuild' ]
5 info lifecycle @~prebuild: @
6 info lifecycle @~build: @
7 verbose lifecycle @~build: unsafe-perm in lifecycle true
8 verbose lifecycle @~build: PATH: /usr/lib/node_modules/npm/node_modules/npm-lifecycle/node-gyp-bin:/var/www/html/basepath/moneytransfer/node_modules/.bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games
9 verbose lifecycle @~build: CWD: /var/www/html/basepath/moneytransfer
10 silly lifecycle @~build: Args: [ '-c',
10 silly lifecycle   'npm run clean && webpack --mode development --progress' ]
11 silly lifecycle @~build: Returned: code: 126  signal: null
12 info lifecycle @~build: Failed to exec build script
13 verbose stack Error: @ build: `npm run clean && webpack --mode development --progress`
13 verbose stack Exit status 126
13 verbose stack     at EventEmitter.<anonymous> (/usr/lib/node_modules/npm/node_modules/npm-lifecycle/index.js:326:16)
13 verbose stack     at EventEmitter.emit (events.js:180:13)
13 verbose stack     at ChildProcess.<anonymous> (/usr/lib/node_modules/npm/node_modules/npm-lifecycle/lib/spawn.js:55:14)
13 verbose stack     at ChildProcess.emit (events.js:180:13)
13 verbose stack     at maybeClose (internal/child_process.js:936:16)
13 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:220:5)
14 verbose pkgid @
15 verbose cwd /var/www/html/basepath/moneytransfer
16 verbose Linux 4.15.0-29-generic
17 verbose argv "/usr/bin/node" "/usr/bin/npm" "run" "build"
18 verbose node v9.11.2
19 verbose npm  v6.10.2
20 error code ELIFECYCLE
21 error errno 126
22 error @ build: `npm run clean && webpack --mode development --progress`
22 error Exit status 126
23 error Failed at the @ build script.
23 error This is probably not a problem with npm. There is likely additional logging output above.
24 verbose exit [ 126, true ]

Body:
npm i rimraf

worked for me because I was not in wifi environment. I had a similar error trace (after porting a project with node_modules from windows to mac)


答:
Here is a dplyr approach,

```<code>df %>%
 mutate(score = replace(score,
                       is.na(score),
                       (max(score, na.rm = TRUE) + (cumsum(is.na(score))))[is.na(score)])
                       )
</code>```

which gives,

```<code># A tibble: 5 x 2
  source score
  <chr>  <dbl>
1 a         10
2 b          5
3 c         11
4 d          3
5 e         12
</code>```

Title: How to replace NA with set of values

Body:
Here is a dplyr approach,

df %>%
 mutate(score = replace(score,
                       is.na(score),
                       (max(score, na.rm = TRUE) + (cumsum(is.na(score))))[is.na(score)])
                       )

which gives,

# A tibble: 5 x 2
  source score
  <chr>  <dbl>
1 a         10
2 b          5
3 c         11
4 d          3
5 e         12


问:
response time in python not the same as postman
When I execute the code below the response time is 0.4, but when I make the exact request in postman the response time is ~4, what's wrong with my code?

```<code>import requests

url = "https://www.wechall.net/challenge/training/mysql/auth_bypass2/index.php"

payload = {'username': 'admin\' and username like \'a%\' and sleep(4)#',
'password': '',
'login': 'Login'}

headers = {
  'Content-Type': 'multipart/form-data; boundary=--------------------------626487670766176098971255'
}

response = requests.request("POST", url, headers=headers, data = payload)

print(response.elapsed.total_seconds())
</code>```

答:
According to https://kite.com/python/docs/requests.Response.elapsed, elapsed measures the time taken between sending the first byte of the request and finishing parsing the headers, and not until the full response has been transfered.

So in this case, time calculated by postman client is the response time for the api.

Body:
When I execute the code below the response time is 0.4, but when I make the exact request in postman the response time is ~4, what's wrong with my code?

import requests

url = "https://www.wechall.net/challenge/training/mysql/auth_bypass2/index.php"

payload = {'username': 'admin\' and username like \'a%\' and sleep(4)#',
'password': '',
'login': 'Login'}

headers = {
  'Content-Type': 'multipart/form-data; boundary=--------------------------626487670766176098971255'
}

response = requests.request("POST", url, headers=headers, data = payload)

print(response.elapsed.total_seconds())


问:
Backbone.js - Access referrer in controller function
I have a list of products (index view) and when a user clicks on a product, a Lightbox opens (show view). Now, when the user closes the lightbox, I want to redirect him back to the page he came from. The problem is that the Lightbox might have been opened from several different places. It's best demonstrated with an example:

Product "Foo" appears on 3 different pages:

```<code>/                  (the home page)
/tag/bar           (all products tagged with "bar")
/tag/baz/page-3    (all products tagged with "baz", paginated)
</code>```

Now I have to decide where to redirect the user when the Lightbox closes. At this stage, there is no information available about which page the Lightbox was opened from.

So I figured I save a "returnTo" path when opening the Lightbox (rendering the show view).
In the controller function, which is triggered by the hash change and renders the show view, I can't seem to get to any "referrer" information, though.

Is there any way to see what page triggered the hash change?
Or is there a better way to solve this problems?

All suggestions are appreciated! :)

EDIT:

I solved the problem by setting a cookie.
The cookie is set anytime a index site (might be any of the three mentioned above) is visited. Then, when the Lightbox is closed, the user is redirected to the cookie value, which is the last opened index site.
It would be great, though, if there was a way built in to Backbone.js to "remember" pathes somehow. Julien mentioned in one of the comments that it might be possible to add such functionality.

答: You can trigger the browser back button within JS. Assuming you set everything right, the browser should go back to the previous set hash and voila. </p>

ContentLicense: CC BY-SA 3.0

Body:
I have a list of products (index view) and when a user clicks on a product, a Lightbox opens (show view). Now, when the user closes the lightbox, I want to redirect him back to the page he came from. The problem is that the Lightbox might have been opened from several different places. It's best demonstrated with an example:

Product "Foo" appears on 3 different pages:

/                  (the home page)
/tag/bar           (all products tagged with "bar")
/tag/baz/page-3    (all products tagged with "baz", paginated)

Now I have to decide where to redirect the user when the Lightbox closes. At this stage, there is no information available about which page the Lightbox was opened from.

So I figured I save a "returnTo" path when opening the Lightbox (rendering the show view).
In the controller function, which is triggered by the hash change and renders the show view, I can't seem to get to any "referrer" information, though.

Is there any way to see what page triggered the hash change?
Or is there a better way to solve this problems?

All suggestions are appreciated! :)

EDIT:

I solved the problem by setting a cookie.
The cookie is set anytime a index site (might be any of the three mentioned above) is visited. Then, when the Lightbox is closed, the user is redirected to the cookie value, which is the last opened index site.
It would be great, though, if there was a way built in to Backbone.js to "remember" pathes somehow. Julien mentioned in one of the comments that it might be possible to add such functionality.


问:
How to detect monotonic decrease in pyspark
I am working with a spark DataFrame where I would like to detect any value from a specific column where the value does not monotonically decrease. For those values, I would like to replace them with the previous value according to the ordering criteria.

Here is a conceptual example, if I have a column of value [65, 66, 62, 100, 40]. the value "100" is not following the monotonic decrease trend and therefore should be replaced by 62. So the resulting list will be [65, 66, 62, 62, 40].

Below is some code that I created to detect the value that must be replaced however I don't know how to replace the value by the previous and also how to ignore the initial null value from the lag.

from pyspark import SparkContext
from pyspark.sql import SQLContext
from pyspark.sql import functions as psf
from pyspark.sql.window import Window

sc = SparkContext(appName="sample-app")
sqlc = SQLContext(sc)

rdd = sc.parallelize([(1, 65), (2, 66), (3, 62), (4, 100), (5, 40)])
df = sqlc.createDataFrame(rdd, ["id", "value"])

window = Window.orderBy(df.id).rowsBetween(-1, -1)
sdf = df.withColumn(
    "__monotonic_col",
    (df.value <= psf.lag(df.value, 1).over(window)) & df.value.isNotNull(),
)

sdf.show()
```

<p>This code produce the following output:</p>

```+---+-----+---------------+
| id|value|__monotonic_col|
+---+-----+---------------+
|  1|   65|           null|
|  2|   66|          false|
|  3|   62|           true|
|  4|  100|          false|
|  5|   40|           true|
+---+-----+---------------+
```

答:
Firstly, if my understanding is correct, shouldn't the 66 also be replaced (by 65) as it does not follow the decreasing trend?

If that is the correct interpretation, then the following should work (I have added an extra column to keep things tidy, but you could wrap everything into a single column creation statement):

```<code>from pyspark.sql import functions as F

sdf = sdf.withColumn(
    "__monotonic_col_value",
    F.when(
        F.col("__monotonic_col")  | F.col("__monotonic_col").isNull(), df.value)
    .otherwise(
        F.lag(df.value, 1).over(window)
    ),
)
</code>```

Body:
I am working with a spark DataFrame where I would like to detect any value from a specific column where the value does not monotonically decrease. For those values, I would like to replace them with the previous value according to the ordering criteria.

Here is a conceptual example, if I have a column of value [65, 66, 62, 100, 40]. the value "100" is not following the monotonic decrease trend and therefore should be replaced by 62. So the resulting list will be [65, 66, 62, 62, 40].

Below is some code that I created to detect the value that must be replaced however I don't know how to replace the value by the previous and also how to ignore the initial null value from the lag.

from pyspark import SparkContext
from pyspark.sql import SQLContext
from pyspark.sql import functions as psf
from pyspark.sql.window import Window

sc = SparkContext(appName="sample-app")
sqlc = SQLContext(sc)

rdd = sc.parallelize([(1, 65), (2, 66), (3, 62), (4, 100), (5, 40)])
df = sqlc.createDataFrame(rdd, ["id", "value"])

window = Window.orderBy(df.id).rowsBetween(-1, -1)
sdf = df.withColumn(
    "__monotonic_col",
    (df.value <= psf.lag(df.value, 1).over(window)) & df.value.isNotNull(),
)

sdf.show()

This code produce the following output:

+---+-----+---------------+
| id|value|__monotonic_col|
+---+-----+---------------+
|  1|   65|           null|
|  2|   66|          false|
|  3|   62|           true|
|  4|  100|          false|
|  5|   40|           true|
+---+-----+---------------+

Body:
Firstly, if my understanding is correct, shouldn't the 66 also be replaced (by 65) as it does not follow the decreasing trend?

If that is the correct interpretation, then the following should work (I have added an extra column to keep things tidy, but you could wrap everything into a single column creation statement):

from pyspark.sql import functions as F

sdf = sdf.withColumn(
    "__monotonic_col_value",
    F.when(
        F.col("__monotonic_col")  | F.col("__monotonic_col").isNull(), df.value)
    .otherwise(
        F.lag(df.value, 1).over(window)
    ),
)


问:
Point dynamic the Firebase database
I would like to build a simple framework on Flutter + Firebase, but unfortunately I have a big problem.
Construction of the framework makes sense when you can dynamically point any database in the application downloaded from the store (each customer has a different database, but the application in the store is one).
Unfortunately, from what I understand, the connection data to Fierbase must be in the google-service.json file in the source code.
Is there any way to point dynamic the Firebase database?</p>

答: google-services.json is not required to initialize Firebase.  You can take control of initialization by calling FirebaseApp.initializeApp() on your own with the values you specify.  You can also use the Play services documentation to help.</p>

Title: Point dynamic the Firebase database


问:
Map some names and values using java
I have a set of values as a repsonse like this.
from this

```<code>4,0,1581664239228,6,799,0,845,253,0,0,0,0,0,0,0,0,0,0,1448,594,0,1276257,0,0,0,0,1100,0,0,0,0,0,0,0,2047,2158,0,13,1
</code>```

I have to map these values to below one..The order should be same like version: 4 , build: 0, tuneStartBaseUTCMS: 1581664239228 etc etc

```<code>version,build,tuneStartBaseUTCMS,ManifestDLStartTime,ManifestDLTotalTime,ManifestDLFailCount,VideoPlaylistDLStartTime,VideoPlaylistDLTotalTime,VideoPlaylistDLFailCount,AudioPlaylistDLStartTime,AudioPlaylistDLTotalTime,AudioPlaylistDLFailCount,VideoInitDLStartTime,VideoInitDLTotalTime,VideoInitDLFailCount,AudioInitDLStartTime,AudioInitDLTotalTime,AudioInitDLFailCount,VideoFragmentDLStartTime,VideoFragmentDLTotalTime,VideoFragmentDLFailCount,VideoBitRate,AudioFragmentDLStartTime,AudioFragmentDLTotalTime,AudioFragmentDLFailCount,AudioBitRate,drmLicenseAcqStartTime,drmLicenseAcqTotalTime,drmFailErrorCode,LicenseAcqPreProcessingDuration,LicenseAcqNetworkDuration,LicenseAcqPostProcDuration,VideoFragmentDecryptDuration,AudioFragmentDecryptDuration,gstPlayStartTime,gstFirstFrameTime,contentType,streamType,firstTune
</code>```

I have written as follows...but it is not working as ex

```<code>String abcd = "4,0,1581664239228,6,799,0,845,253,0,0,0,0,0,0,0,0,0,0,1448,594,0,1276257,0,0,0,0,1100,0,0,0,0,0,0,0,2047,2158,0,13,1";
</code>```

```<code>String valueName = "version,build,tuneStartBaseUTCMS,ManifestDLStartTime,ManifestDLTotalTime,ManifestDLFailCount,VideoPlaylistDLStartTime,VideoPlaylistDLTotalTime,VideoPlaylistDLFailCount,AudioPlaylistDLStartTime,AudioPlaylistDLTotalTime,AudioPlaylistDLFailCount,VideoInitDLStartTime,VideoInitDLTotalTime,VideoInitDLFailCount,AudioInitDLStartTime,AudioInitDLTotalTime,AudioInitDLFailCount,VideoFragmentDLStartTime,VideoFragmentDLTotalTime,VideoFragmentDLFailCount,VideoBitRate,AudioFragmentDLStartTime,AudioFragmentDLTotalTime,AudioFragmentDLFailCount,AudioBitRate,drmLicenseAcqStartTime,drmLicenseAcqTotalTime,drmFailErrorCode,LicenseAcqPreProcessingDuration,LicenseAcqNetworkDuration,LicenseAcqPostProcDuration,VideoFragmentDecryptDuration,AudioFragmentDecryptDuration,gstPlayStartTime,gstFirstFrameTime,contentType,streamType,firstTune";

String[] valueArr = abcd.split(",");

String[] valueNameArr = valueName.split(",");

List<String> valueList = Arrays.asList(valueArr);

List<String> valueNameList = Arrays.asList(valueNameArr);

System.out.println(valueList.size() + "jjj: " + "valueNameList::: " + valueNameList.size());
LinkedHashMap<String, String> result = new LinkedHashMap<String, String>();

for (String name : valueNameList) {
    System.out.println("name: " + name);
    for (String value : valueList) {
      System.out.println("value: " + value);
      result.put(name, value);
    }
}

System.out.println("RESULT::::::::::::::::::::::::::::" + result);
</code>```

Result prints:

```<code>{version=1, build=1, tuneStartBaseUTCMS=1, ManifestDLStartTime=1, ManifestDLTotalTime=1, ManifestDLFailCount=1, VideoPlaylistDLStartTime=1, VideoPlaylistDLTotalTime=1, VideoPlaylistDLFailCount=1, AudioPlaylistDLStartTime=1, AudioPlaylistDLTotalTime=1, AudioPlaylistDLFailCount=1, VideoInitDLStartTime=1, VideoInitDLTotalTime=1, VideoInitDLFailCount=1, AudioInitDLStartTime=1, AudioInitDLTotalTime=1, AudioInitDLFailCount=1, VideoFragmentDLStartTime=1, VideoFragmentDLTotalTime=1, VideoFragmentDLFailCount=1, VideoBitRate=1, AudioFragmentDLStartTime=1, AudioFragmentDLTotalTime=1, AudioFragmentDLFailCount=1, AudioBitRate=1, drmLicenseAcqStartTime=1, drmLicenseAcqTotalTime=1, drmFailErrorCode=1, LicenseAcqPreProcessingDuration=1, LicenseAcqNetworkDuration=1, LicenseAcqPostProcDuration=1, VideoFragmentDecryptDuration=1, AudioFragmentDecryptDuration=1, gstPlayStartTime=1, gstFirstFrameTime=1, contentType=1, streamType=1, firstTune=1}
</code>```

答:
Your loop is wrong
Try this</p>

```<code>for(int i = 0; i < valueList.size(); i++){
  result.put(valueNameList(i), valueList(i));
}
</code>```

Title: Map some names and values using java

Body:
I have a set of values as a repsonse like this.
from this

4,0,1581664239228,6,799,0,845,253,0,0,0,0,0,0,0,0,0,0,1448,594,0,1276257,0,0,0,0,1100,0,0,0,0,0,0,0,2047,2158,0,13,1

I have to map these values to below one..The order should be same like version: 4 , build: 0, tuneStartBaseUTCMS: 1581664239228 etc etc

version,build,tuneStartBaseUTCMS,ManifestDLStartTime,ManifestDLTotalTime,ManifestDLFailCount,VideoPlaylistDLStartTime,VideoPlaylistDLTotalTime,VideoPlaylistDLFailCount,AudioPlaylistDLStartTime,AudioPlaylistDLTotalTime,AudioPlaylistDLFailCount,VideoInitDLStartTime,VideoInitDLTotalTime,VideoInitDLFailCount,AudioInitDLStartTime,AudioInitDLTotalTime,AudioInitDLFailCount,VideoFragmentDLStartTime,VideoFragmentDLTotalTime,VideoFragmentDLFailCount,VideoBitRate,AudioFragmentDLStartTime,AudioFragmentDLTotalTime,AudioFragmentDLFailCount,AudioBitRate,drmLicenseAcqStartTime,drmLicenseAcqTotalTime,drmFailErrorCode,LicenseAcqPreProcessingDuration,LicenseAcqNetworkDuration,LicenseAcqPostProcDuration,VideoFragmentDecryptDuration,AudioFragmentDecryptDuration,gstPlayStartTime,gstFirstFrameTime,contentType,streamType,firstTune

I have written as follows...but it is not working as ex

String abcd = "4,0,1581664239228,6,799,0,845,253,0,0,0,0,0,0,0,0,0,0,1448,594,0,1276257,0,0,0,0,1100,0,0,0,0,0,0,0,2047,2158,0,13,1";

String valueName = "version,build,tuneStartBaseUTCMS,ManifestDLStartTime,ManifestDLTotalTime,ManifestDLFailCount,VideoPlaylistDLStartTime,VideoPlaylistDLTotalTime,VideoPlaylistDLFailCount,AudioPlaylistDLStartTime,AudioPlaylistDLTotalTime,AudioPlaylistDLFailCount,VideoInitDLStartTime,VideoInitDLTotalTime,VideoInitDLFailCount,AudioInitDLStartTime,AudioInitDLTotalTime,AudioInitDLFailCount,VideoFragmentDLStartTime,VideoFragmentDLTotalTime,VideoFragmentDLFailCount,VideoBitRate,AudioFragmentDLStartTime,AudioFragmentDLTotalTime,AudioFragmentDLFailCount,AudioBitRate,drmLicenseAcqStartTime,drmLicenseAcqTotalTime,drmFailErrorCode,LicenseAcqPreProcessingDuration,LicenseAcqNetworkDuration,LicenseAcqPostProcDuration,VideoFragmentDecryptDuration,AudioFragmentDecryptDuration,gstPlayStartTime,gstFirstFrameTime,contentType,streamType,firstTune";

String[] valueArr = abcd.split(",");

String[] valueNameArr = valueName.split(",");

List<String> valueList = Arrays.asList(valueArr);

List<String> valueNameList = Arrays.asList(valueNameArr);

System.out.println(valueList.size() + "jjj: " + "valueNameList::: " + valueNameList.size());
LinkedHashMap<String, String> result = new LinkedHashMap<String, String>();

for (String name : valueNameList) {
    System.out.println("name: " + name);
    for (String value : valueList) {
      System.out.println("value: " + value);
      result.put(name, value);
    }
}

System.out.println("RESULT::::::::::::::::::::::::::::" + result);

Result prints:

{version=1, build=1, tuneStartBaseUTCMS=1, ManifestDLStartTime=1, ManifestDLTotalTime=1, ManifestDLFailCount=1, VideoPlaylistDLStartTime=1, VideoPlaylistDLTotalTime=1, VideoPlaylistDLFailCount=1, AudioPlaylistDLStartTime=1, AudioPlaylistDLTotalTime=1, AudioPlaylistDLFailCount=1, VideoInitDLStartTime=1, VideoInitDLTotalTime=1, VideoInitDLFailCount=1, AudioInitDLStartTime=1, AudioInitDLTotalTime=1, AudioInitDLFailCount=1, VideoFragmentDLStartTime=1, VideoFragmentDLTotalTime=1, VideoFragmentDLFailCount=1, VideoBitRate=1, AudioFragmentDLStartTime=1, AudioFragmentDLTotalTime=1, AudioFragmentDLFailCount=1, AudioBitRate=1, drmLicenseAcqStartTime=1, drmLicenseAcqTotalTime=1, drmFailErrorCode=1, LicenseAcqPreProcessingDuration=1, LicenseAcqNetworkDuration=1, LicenseAcqPostProcDuration=1, VideoFragmentDecryptDuration=1, AudioFragmentDecryptDuration=1, gstPlayStartTime=1, gstFirstFrameTime=1, contentType=1, streamType=1, firstTune=1}

Body:
Your loop is wrong
Try this

for(int i = 0; i < valueList.size(); i++){
  result.put(valueNameList(i), valueList(i));
}


问:
Connecting SQL Server on Docker to Python
I am trying to perform a table creation using pyodbc on a SQL Server 2017 database hosted using Docker. I'm also using a network so that I can connect to it later from another Docker image. However, I get the following error

```<code>pyodbc.OperationalError: ('HYT00', '[HYT00] [Microsoft][ODBC Driver 17 for SQL Server]Login timeout expired (0) (SQLDriverConnect)')
</code>```

This is how I went about creating the connection.

To create and run the DB server,

```<code>docker run --name mssqldocker -e 'ACCEPT_EULA=Y' -e 'SA_PASSWORD=<password>' -e 'MSSQL_PID=Express' -p 7000:7000 --network=lambda-local-mssql -v <my_path> -d mcr.microsoft.com/mssql/server:2017-latest-ubuntu
</code>```

I also tried adding

```<code>-h "mssqldocker"
</code>```

to the command for running the Docker image and then using "mssqldocker" instead of localhost, but to no avail, since mismatched hostnames seem to be the recurring theme when using DBs and Docker together. Also tried adding in \sqlexpress without effect as well. The Python code is as follows

```<code>import pyodbc
import sql_clauses
from settings import ENDPOINT, PORT, USERNAME, PASSWORD

cnxn = pyodbc.connect(
       'DRIVER={ODBC Driver 17 for SQL Server}' +
       ';SERVER=' + ENDPOINT + ';UID=' + USERNAME +
       ';PWD=' + PASSWORD)

cursor = db.cursor()
cursor.execute(create_database(dbname))
cnxn.commit()
cnxn.close()
print("Database created")
</code>```

The settings file is as follows

```<code>ENDPOINT="localhost"
PORT = 7000
USERNAME="SA"
PASSWORD=<password>
</code>```

答:
In your docker run command you specify -p 7000:7000. This translates in "map the host port 7000 (first 7000 - published) to the container port 7000 (the second 7000 - exposed)". If you have MSSQL running on a different port inside your container (which probably you do) then you have to change that second 7000 to the correct port.

Once you do that you should be able to connect to MSSQL from host using "localhost:7000". This applies if your python application runs directly on host.

If your python project also runs in a container, you need to make sure it runs on the same network as the mssql container (--network=lambda-local-mssql) and then you need to connect using "mssqldocker:mssql_exposed_port". In this case localhost and 7000 (the first part of `-p 7000:...) are not valide anymore since you are on a docker managed network.

Body:
I am trying to perform a table creation using pyodbc on a SQL Server 2017 database hosted using Docker. I'm also using a network so that I can connect to it later from another Docker image. However, I get the following error

pyodbc.OperationalError: ('HYT00', '[HYT00] [Microsoft][ODBC Driver 17 for SQL Server]Login timeout expired (0) (SQLDriverConnect)')

This is how I went about creating the connection.

To create and run the DB server,

docker run --name mssqldocker -e 'ACCEPT_EULA=Y' -e 'SA_PASSWORD=<password>' -e 'MSSQL_PID=Express' -p 7000:7000 --network=lambda-local-mssql -v <my_path> -d mcr.microsoft.com/mssql/server:2017-latest-ubuntu

I also tried adding

-h "mssqldocker"

to the command for running the Docker image and then using "mssqldocker" instead of localhost, but to no avail, since mismatched hostnames seem to be the recurring theme when using DBs and Docker together. Also tried adding in \sqlexpress without effect as well. The Python code is as follows

import pyodbc
import sql_clauses
from settings import ENDPOINT, PORT, USERNAME, PASSWORD

cnxn = pyodbc.connect(
       'DRIVER={ODBC Driver 17 for SQL Server}' +
       ';SERVER=' + ENDPOINT + ';UID=' + USERNAME +
       ';PWD=' + PASSWORD)

cursor = db.cursor()
cursor.execute(create_database(dbname))
cnxn.commit()
cnxn.close()
print("Database created")

The settings file is as follows

ENDPOINT="localhost"
PORT = 7000
USERNAME="SA"
PASSWORD=<password>


问:
Close dropdown upon clicking another
I a working on a to make a reponsive dropdown navigation bar with vanilla JavaScript. In mobile view I want that upon click one dropdown the another should close. JavaScript here:

```<code>dropbtns.forEach(link => {
  link.addEventListener("click", function(e) {
    e.currentTarget.nextElementSibling.classList.toggle("showdd");
  });
});
</code>```

and show dropdown:

```<code>  .showdd {
    height: auto;
  }
</code>```

html code:

```<code><div class="nav-container">
    <div class="brand">
        <a href="#!">Logo</a>
    </div>
    <nav>
        <div class="nav-mobile"><a id="nav-toggle" href="#!"><span></span></a></div>
        <ul id="nav-list">
            <li>
                <a href="#!">Home</a>
            </li>
            <li>
                <a href="#!">About</a>
            </li>
            <li class="dropdown">
                <a href="#!" class='dropbtn'>Services <i class="fas fa-sort-down"></i></a>
                <ul class="nav-dropdown">
                    <li>
                        <a href="#!">Web Design</a>
                    </li>
                    <li>
                        <a href="#!">Web Development</a>
                    </li>
                    <li>
                        <a href="#!">Graphic Design</a>
                    </li>
                </ul>
            </li>
            <li>
                <a href="#!">Pricing</a>
            </li>
            <li class="dropdown">
                <a href="#!" class='dropbtn'>Portfolio <i class="fas fa-sort-down"></i></a>
                <ul class="nav-dropdown">
                    <li>
                        <a href="#!">Web Design</a>
                    </li>
                    <li>
                        <a href="#!">Web Development</a>
                    </li>
                    <li>
                        <a href="#!">Graphic Design</a>
                    </li>
                </ul>
            </li>
            <li>
                <a href="#!">Contact</a>
            </li>
        </ul>
    </nav>
</div>
</code>```

full code can be find here.

答:
So, if you want to collapse all other .nav-dropdown when one is being clicked on, you simply will need to:

Store the reference of the .nav-dropdown of the current element (for comparison later)

Toggle its class (as you're doing already)

Go through all other .nav-dropdown in your DOM tree and iterate through them. If they do not match the current reference, then you know the dropdown belongs to another link and you can remove the class

With that in mind we arrive at the code below:

```<code>dropbtns.forEach(link => {
  link.addEventListener('click', e => {
    const ownDropdown = e.currentTarget.nextElementSibling;
    ownDropdown.classList.toggle('showdd');

    document.querySelectorAll('.dropbtn + .nav-dropdown').forEach(el => {
      if (el !== ownDropdown)
        el.classList.remove('showdd');
    });
  });
});
</code>```

Title: Close dropdown upon clicking another

Body:
I a working on a to make a reponsive dropdown navigation bar with vanilla JavaScript. In mobile view I want that upon click one dropdown the another should close. JavaScript here:

dropbtns.forEach(link => {
  link.addEventListener("click", function(e) {
    e.currentTarget.nextElementSibling.classList.toggle("showdd");
  });
});

and show dropdown:

  .showdd {
    height: auto;
  }

html code:

        Logo

                Home

                About

                Services

                        Web Design

                        Web Development

                        Graphic Design

                Pricing

                Portfolio

                        Web Design

                        Web Development

                        Graphic Design

                Contact

full code can be find here.

Body:
So, if you want to collapse all other .nav-dropdown when one is being clicked on, you simply will need to:

Store the reference of the .nav-dropdown of the current element (for comparison later)

Toggle its class (as you're doing already)

Go through all other .nav-dropdown in your DOM tree and iterate through them. If they do not match the current reference, then you know the dropdown belongs to another link and you can remove the class

With that in mind we arrive at the code below:

dropbtns.forEach(link => {
  link.addEventListener('click', e => {
    const ownDropdown = e.currentTarget.nextElementSibling;
    ownDropdown.classList.toggle('showdd');

    document.querySelectorAll('.dropbtn + .nav-dropdown').forEach(el => {
      if (el !== ownDropdown)
        el.classList.remove('showdd');
    });
  });
});


问:
How to deploy google function from google SDK from local system runtime python
I am trying to deploy Google Cloud Function from local system using the gcloud command-line tool.

My files are compressed in a .zip file. As described in the attached screenshot the zip file contains main.py and requirement.txt

main.py  (took from web for testing)

```<code>from wand.image import Image
from google.cloud import storage
client = storage.Client.from_service_account_json(
         'C:\\Users\\an20086686\\AppData\\Local\\Google\\Cloud SDK\\deploy\\****-*****-poc-e4b410a65986.JSON')
THUMBNAIL_BUCKET = 'a_demo_storage_trigger1'
def make_thumbnail(data, context):

    bucket = client.get_bucket(data['****_my-awesome-bucket'])
    blob = bucket.get_blob(data['name'])
    imagedata = blob.download_as_string()

    newimage = Image(blob=imagedata)
    newimage.sample(200,200)

    bucket = client.get_bucket(THUMBNAIL_BUCKET)
    newblob = bucket.blob('thumbnail-' + data['name'])
    newblob.upload_from_string(newimage.make_blob())
</code>```

requirements.txt

```<code>google-cloud-storage
Wand
</code>```

Using the command below to deploy this function:

```<code>gcloud beta functions deploy make_thumbnail --runtime python37 \
--trigger-bucket ****_my-awesome-bucket \
--trigger-event google.storage.object.finalize
</code>```

Error 1 : (gcloud.beta.functions.deploy) unrecognized arguments:
  google.storage.object.finalize

When I use:

```<code>gcloud beta functions deploy make_thumbnail --runtime python37 \
--trigger-bucket ****_my-awesome-bucket \
--trigger-event google.storage.object.finalize
</code>```

ERROR: (gcloud.beta.functions.deploy) OperationError: code=3,message=Function failed on loading user code.

Error message: File main.py that is expected to define function doesn't exist

Log of the encountered error:

Screenshot

答:
The tutorial doesn't use a ZIP file.

If you want to use a ZIP file, you'd need to specify it with the --source option. See docs.

And not sure if this is a typo in your question, but there needs to be a space before --trigger-event.

Body:
I am trying to deploy Google Cloud Function from local system using the gcloud command-line tool.

My files are compressed in a .zip file. As described in the attached screenshot the zip file contains main.py and requirement.txt

main.py  (took from web for testing)

from wand.image import Image
from google.cloud import storage
client = storage.Client.from_service_account_json(
         'C:\\Users\\an20086686\\AppData\\Local\\Google\\Cloud SDK\\deploy\\****-*****-poc-e4b410a65986.JSON')
THUMBNAIL_BUCKET = 'a_demo_storage_trigger1'
def make_thumbnail(data, context):

    bucket = client.get_bucket(data['****_my-awesome-bucket'])
    blob = bucket.get_blob(data['name'])
    imagedata = blob.download_as_string()

    newimage = Image(blob=imagedata)
    newimage.sample(200,200)

    bucket = client.get_bucket(THUMBNAIL_BUCKET)
    newblob = bucket.blob('thumbnail-' + data['name'])
    newblob.upload_from_string(newimage.make_blob())

requirements.txt

google-cloud-storage
Wand

Using the command below to deploy this function:

gcloud beta functions deploy make_thumbnail --runtime python37 \
--trigger-bucket ****_my-awesome-bucket \
--trigger-event google.storage.object.finalize

Error 1 : (gcloud.beta.functions.deploy) unrecognized arguments:
  google.storage.object.finalize

When I use:

gcloud beta functions deploy make_thumbnail --runtime python37 \
--trigger-bucket ****_my-awesome-bucket \
--trigger-event google.storage.object.finalize

ERROR: (gcloud.beta.functions.deploy) OperationError: code=3,message=Function failed on loading user code.

Error message: File main.py that is expected to define function doesn't exist

Log of the encountered error:

Screenshot


问:
Error using Caffe: "This tool requires OpenCV; compile with USE_OPENCV."
I want to use Caffe's tool, compute_image_mean to compute the mean image, but the command line tells me that:

This tool requires OpenCV; compile with USE_OPENCV.

I've searched the Internet, and one guy said:

Well, this message suggests that you have compiled caffe without
  OpenCV, i.e; with USE_OPENCV set to 0 in your Makefile.config.
  Recompile with that settings commented out (as is the default) and try
  again. And of course you need to have OpenCV installed for this to
  work.

But I have already set USE_OPENCV := 0 when I compiled my Caffe.

Could someone help me to solve this problem?

答:
I met the same error when I tried to make lmdb.

At first I uncomment "USE_OPENCV:=0" in the Makefile.config and recompile for many times, but it does not help.

So I try to comment "USE_OPENCV:=0" with # and recompile the caffe, it success.


问:
Apache POI: Remove Chart from Word Template file entirely
I am using a Word template with Excel graphs which I want to programmatically manipulate with the Java Apache POI library. For this I also need to be able to conditionally delete a Chart which is stored in this template.

Based on Axel Richters post (Removing chart from PowerPoint slide with Apache POI) I think I am almost there, but when I want to open the updated Word file it gives an error about unreadable content. This is what I have thus far:

```<code>PackagePart packagePartChart = xWPFChart.getPackagePart();

PackagePart packagePartWordDoc = xWPFDocument.getPackagePart();
OPCPackage packageWordDoc = packagePartWordDoc.getPackage();

// iterate over all relations the chart has and remove them
for (PackageRelationship chartrelship : packagePartChart.getRelationships()) {
    String partname = chartrelship.getTargetURI().toString();
    PackagePart part = packageWordDoc.getPartsByName(Pattern.compile(partname)).get(0);
    packageWordDoc.removePart(part);
    packagePartChart.removeRelationship(chartrelship.getId());
}

// now remove the chart itself from the word doc
Method removeRelation = POIXMLDocumentPart.class.getDeclaredMethod("removeRelation", POIXMLDocumentPart.class);
removeRelation.setAccessible(true);
removeRelation.invoke(xWPFDocument, xWPFChart);
</code>```

If I unzip the Word file I correctly see that:

the relation between the WordDoc and the Chart are deleted in '\word\ _rels\document.xml.rels'

the chart itself is deleted in folder '\word\charts'

the relations between the documents supporting the Chart itself are deleted in folder '\word\charts\' _rels

the related chart items themselves are deleted:

StyleN / ColorsN in folder '\word\charts' and

Microsoft_Excel_WorksheetN in folder '\word\embeddings'

Anybody any idea on what could be going wrong here?

答:
Indeed the finding of the right paragraph holding the chart was a challenge. In the end, for simplicity sake, I added a one row/one column placeholder table with one cell with a text, let's say 'targetWordString' in it, DIRECTLY before the chart. With the below function I am location the BodyElementID of this table:

```<code>private Integer iBodyElementIterator (XWPFDocument wordDoc,String targetWordString) {
    Iterator<IBodyElement> iter = wordDoc.getBodyElementsIterator();
    Integer bodyElementID = null;
    while (iter.hasNext()) {
       IBodyElement elem = iter.next();
       bodyElementID = wordDoc.getBodyElements().indexOf(elem);
       if (elem instanceof XWPFParagraph) {

           XWPFParagraph paragraph = (XWPFParagraph) elem;
           for (XWPFRun runText : paragraph.getRuns()) {
                String text = runText.getText(0);
               Core.getLogger("WordExporter").trace("Body Element ID:  " + bodyElementID + " Text: " + text);
                if (text != null && text.equals(targetWordString)) {
                    break;
                }
            }

       } else if (elem instanceof XWPFTable) {
           if (((XWPFTable) elem).getRow(0) != null && ((XWPFTable) elem).getRow(0).getCell(0) != null) {
                // the first cell holds the name via the template
                String tableTitle = ((XWPFTable) elem).getRow(0).getCell(0).getText();
                if (tableTitle.equals(targetWordString)) {
                    break;
                }
                Core.getLogger("WordExporter").trace("Body Element ID:  " + bodyElementID + " Text: " + tableTitle);
           } else {
               Core.getLogger("WordExporter").trace("Body Element ID:  " + bodyElementID + " Table removed!");
           }

       }
       else {
           Core.getLogger("WordExporter").trace("Body Element ID:  " + bodyElementID + " Text: ?");
       }
    }
    return bodyElementID;
}
</code>```

In the main part of the code I am calling this function to locate the table, then first delete the chart (ID +1) and then the table (ID)

```<code>int elementIDToBeRemoved = iBodyElementIterator(xWPFWordDoc,targetWordString);

xWPFWordDoc.removeBodyElement(elementIDToBeRemoved + 1);
xWPFWordDoc.removeBodyElement(elementIDToBeRemoved);
</code>```

It needs to be in this order, because the ID's are reordered once you delete a number in between, hence deleting the table first, would mean the chart would get that ID in principle.

Body:
I am using a Word template with Excel graphs which I want to programmatically manipulate with the Java Apache POI library. For this I also need to be able to conditionally delete a Chart which is stored in this template.

Based on Axel Richters post (Removing chart from PowerPoint slide with Apache POI) I think I am almost there, but when I want to open the updated Word file it gives an error about unreadable content. This is what I have thus far:

PackagePart packagePartChart = xWPFChart.getPackagePart();

PackagePart packagePartWordDoc = xWPFDocument.getPackagePart();
OPCPackage packageWordDoc = packagePartWordDoc.getPackage();

// iterate over all relations the chart has and remove them
for (PackageRelationship chartrelship : packagePartChart.getRelationships()) {
    String partname = chartrelship.getTargetURI().toString();
    PackagePart part = packageWordDoc.getPartsByName(Pattern.compile(partname)).get(0);
    packageWordDoc.removePart(part);
    packagePartChart.removeRelationship(chartrelship.getId());
}

// now remove the chart itself from the word doc
Method removeRelation = POIXMLDocumentPart.class.getDeclaredMethod("removeRelation", POIXMLDocumentPart.class);
removeRelation.setAccessible(true);
removeRelation.invoke(xWPFDocument, xWPFChart);

If I unzip the Word file I correctly see that:

the relation between the WordDoc and the Chart are deleted in '\word\ _rels\document.xml.rels'

the chart itself is deleted in folder '\word\charts'

the relations between the documents supporting the Chart itself are deleted in folder '\word\charts\' _rels

the related chart items themselves are deleted:

StyleN / ColorsN in folder '\word\charts' and

Microsoft_Excel_WorksheetN in folder '\word\embeddings'

Anybody any idea on what could be going wrong here?

Body:
Indeed the finding of the right paragraph holding the chart was a challenge. In the end, for simplicity sake, I added a one row/one column placeholder table with one cell with a text, let's say 'targetWordString' in it, DIRECTLY before the chart. With the below function I am location the BodyElementID of this table:

private Integer iBodyElementIterator (XWPFDocument wordDoc,String targetWordString) {
    Iterator<IBodyElement> iter = wordDoc.getBodyElementsIterator();
    Integer bodyElementID = null;
    while (iter.hasNext()) {
       IBodyElement elem = iter.next();
       bodyElementID = wordDoc.getBodyElements().indexOf(elem);
       if (elem instanceof XWPFParagraph) {

           XWPFParagraph paragraph = (XWPFParagraph) elem;
           for (XWPFRun runText : paragraph.getRuns()) {
                String text = runText.getText(0);
               Core.getLogger("WordExporter").trace("Body Element ID:  " + bodyElementID + " Text: " + text);
                if (text != null && text.equals(targetWordString)) {
                    break;
                }
            }

       } else if (elem instanceof XWPFTable) {
           if (((XWPFTable) elem).getRow(0) != null && ((XWPFTable) elem).getRow(0).getCell(0) != null) {
                // the first cell holds the name via the template
                String tableTitle = ((XWPFTable) elem).getRow(0).getCell(0).getText();
                if (tableTitle.equals(targetWordString)) {
                    break;
                }
                Core.getLogger("WordExporter").trace("Body Element ID:  " + bodyElementID + " Text: " + tableTitle);
           } else {
               Core.getLogger("WordExporter").trace("Body Element ID:  " + bodyElementID + " Table removed!");
           }

       }
       else {
           Core.getLogger("WordExporter").trace("Body Element ID:  " + bodyElementID + " Text: ?");
       }
    }
    return bodyElementID;
}

In the main part of the code I am calling this function to locate the table, then first delete the chart (ID +1) and then the table (ID)

int elementIDToBeRemoved = iBodyElementIterator(xWPFWordDoc,targetWordString);

xWPFWordDoc.removeBodyElement(elementIDToBeRemoved + 1);
xWPFWordDoc.removeBodyElement(elementIDToBeRemoved);

It needs to be in this order, because the ID's are reordered once you delete a number in between, hence deleting the table first, would mean the chart would get that ID in principle.


问:
How can I make ON UPDATE CURRENT TIMESTAMP optional?
When I append,

```<code>ON UPDATE CURRENT_TIMESTAMP
</code>```

I know the column will be updated when the row is updated.

Is there any way to make the clause optional?

I mean a way to update the column only when client didn't send the column value.

答:
One simple way to handle your requirement would be to always include the timestamp column in question in the update, but wrap it in COALESCE and use CURRENT_TIMESTAMP as the default value, e.g.

```<code>UPDATE yourTable
SET
    col1 = <some value>,
    co2l = <some other value>,
    ts_col = COALESCE(?, CURRENT_TIMESTAMP)
WHERE ...
</code>```

To the ? placeholder, you would either bind a value, should you want to explicitly update it, or just bind NULL if you don't want to update it.  The NULL value would be replaced with the current timestamp.

Body:
When I append,

ON UPDATE CURRENT_TIMESTAMP

I know the column will be updated when the row is updated.

Is there any way to make the clause optional?

I mean a way to update the column only when client didn't send the column value.

Body:
One simple way to handle your requirement would be to always include the timestamp column in question in the update, but wrap it in COALESCE and use CURRENT_TIMESTAMP as the default value, e.g.

UPDATE yourTable
SET
    col1 = <some value>,
    co2l = <some other value>,
    ts_col = COALESCE(?, CURRENT_TIMESTAMP)
WHERE ...

To the ? placeholder, you would either bind a value, should you want to explicitly update it, or just bind NULL if you don't want to update it.  The NULL value would be replaced with the current timestamp.


问:
Angular Material (8) Validations return strange texts
I am working on a Request form using Angular Material (8). I am trying to write proper Validators and Error Messages for each of the fields on the form. As of now, I am getting the following errors associated with the fields.

Why is this going on within the form? Any help, hints or advice would be appreciated!

TIA

File: register.component.html

```<code>[... snip ...]

   <div class="flex-register-form">

        <!-- Form -->
        <form [formGroup]="registerForm" (ngSubmit)="onSubmit()" class="text-center">

            <div class="form-col">
                <div class="col">
                    <!-- First name -->
                    <div class="md-form">
                        <input required type="text" id="materialRegisterFormFirstName" class="form-control" mdbInput
                            formControlName="firstname" />
                        <label for="materialRegisterFormFirstName">First name</label>
                    </div>
                </div>
                <!-- Last name -->
                <div class="col">
                    <div class="md-form">
                        <input required type="text" id="materialRegisterFormLastName" class="form-control" mdbInput
                            formControlName="lastname" />
                        <label for="materialRegisterFormLastName">Last name</label>
                    </div>
                </div>
[... snip ...]
</code>```

File: register.component.ts

```<code>import { Component, OnInit } from '@angular/core';
import { RegisterModel } from '../../models/register.models';
import { FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms';

@Component({
  selector: 'app-register',
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.scss']
})

export class RegisterComponent implements OnInit {

  user : RegisterModel = new RegisterModel();

  registerForm : FormGroup = new FormGroup( {
      'firstname' : new FormControl( [Validators.required, Validators.maxLength(25)] ),
      'lastname'  : new FormControl( [Validators.required, Validators.maxLength(25)]),
      'email'     : new FormControl( [Validators.required, Validators.email, Validators.maxLength(25) ] ),
      'password'  : new FormControl( [Validators.required, Validators.minLength(8), Validators.maxLength(25)]),
      'agree'     : new FormControl( [Validators.required])
    });

  constructor( private formBuilder: FormBuilder ) {

  }

  ngOnInit() {

  }

onSubmit() {
    console.log(" was submited ");
  }

}
</code>```

答:
The problem in your code is here. It is reading Validators value as default value.

```<code>registerForm : FormGroup = new FormGroup( {
      'firstname' : new FormControl( [Validators.required, Validators.maxLength(25)] ),
      'lastname'  : new FormControl( [Validators.required, Validators.maxLength(25)]),
      'email'     : new FormControl( [Validators.required, Validators.email, Validators.maxLength(25) ] ),
      'password'  : new FormControl( [Validators.required, Validators.minLength(8), Validators.maxLength(25)]),
      'agree'     : new FormControl( [Validators.required])
    });
</code>```

Intialize FormControl with default value say null

'firstname' : new FormControl( null, [Validators.required, Validators.maxLength(25)] )

Now try this way

```<code>registerForm : FormGroup = new FormGroup( {
    'firstname' : new FormControl( null, [Validators.required, Validators.maxLength(25)] ),
    'lastname'  : new FormControl( null, [Validators.required, Validators.maxLength(25)]),
    'email'     : new FormControl( null, [Validators.required, Validators.email, Validators.maxLength(25) ] ),
    'password'  : new FormControl( null, [Validators.required, Validators.minLength(8), Validators.maxLength(25)]),
    'agree'     : new FormControl( null, [Validators.required])
  });
</code>```

Body:
I am working on a Request form using Angular Material (8). I am trying to write proper Validators and Error Messages for each of the fields on the form. As of now, I am getting the following errors associated with the fields.

Why is this going on within the form? Any help, hints or advice would be appreciated!

TIA

File: register.component.html

[... snip ...]

        <form [formGroup]="registerForm" (ngSubmit)="onSubmit()" class="text-center">

                        <input required type="text" id="materialRegisterFormFirstName" class="form-control" mdbInput
                            formControlName="firstname" />
                        First name

                        <input required type="text" id="materialRegisterFormLastName" class="form-control" mdbInput
                            formControlName="lastname" />
                        Last name

[... snip ...]

File: register.component.ts

import { Component, OnInit } from '@angular/core';
import { RegisterModel } from '../../models/register.models';
import { FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms';

@Component({
  selector: 'app-register',
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.scss']
})

export class RegisterComponent implements OnInit {

  user : RegisterModel = new RegisterModel();

  registerForm : FormGroup = new FormGroup( {
      'firstname' : new FormControl( [Validators.required, Validators.maxLength(25)] ),
      'lastname'  : new FormControl( [Validators.required, Validators.maxLength(25)]),
      'email'     : new FormControl( [Validators.required, Validators.email, Validators.maxLength(25) ] ),
      'password'  : new FormControl( [Validators.required, Validators.minLength(8), Validators.maxLength(25)]),
      'agree'     : new FormControl( [Validators.required])
    });

  constructor( private formBuilder: FormBuilder ) {

  }

  ngOnInit() {

  }

onSubmit() {
    console.log(" was submited ");
  }

}

Body:
The problem in your code is here. It is reading Validators value as default value.

registerForm : FormGroup = new FormGroup( {
      'firstname' : new FormControl( [Validators.required, Validators.maxLength(25)] ),
      'lastname'  : new FormControl( [Validators.required, Validators.maxLength(25)]),
      'email'     : new FormControl( [Validators.required, Validators.email, Validators.maxLength(25) ] ),
      'password'  : new FormControl( [Validators.required, Validators.minLength(8), Validators.maxLength(25)]),
      'agree'     : new FormControl( [Validators.required])
    });

Intialize FormControl with default value say null

'firstname' : new FormControl( null, [Validators.required, Validators.maxLength(25)] )

Now try this way

registerForm : FormGroup = new FormGroup( {
    'firstname' : new FormControl( null, [Validators.required, Validators.maxLength(25)] ),
    'lastname'  : new FormControl( null, [Validators.required, Validators.maxLength(25)]),
    'email'     : new FormControl( null, [Validators.required, Validators.email, Validators.maxLength(25) ] ),
    'password'  : new FormControl( null, [Validators.required, Validators.minLength(8), Validators.maxLength(25)]),
    'agree'     : new FormControl( null, [Validators.required])
  });


问:
UIViewController question for iPhone/iPad
I have an App with one MainWindow.xib file.  Then I have ViewControllerA.xib and ViewControllerB.xib.  My MainWindow.xib have one ViewController that points two ViewControllerA.xib.

On ViewControllerA I have a button and I would like the button, when pressed, to move ViewControllerB onto the screen.  How do I do that?

I tried this code, but I think I am missing something:

```<code>- (IBAction)btMyButton:(id)sender
{
    ViewControllerB * viewController = [[ViewControllerB alloc] initWithNibName:@"ViewControllerB" bundle:nil];
    [[UIApplication sharedApplication].keyWindow addSubview:viewController.view];
    [self.navigationController pushViewController:viewController animated:YES];
}
</code>```

My ViewControllerB does appear, but it is squashed at the top of the screen, over the previous view.  Any help is greatly appreciated.

Thank you

答:
Remove the second line:

```<code>[[UIApplication sharedApplication].keyWindow addSubview:viewController.view];
</code>```

You are adding the view twice. The 2nd and 3rd lines both cause the view to be added to the view hierarchy in different places.

--update--
If you remove the 2nd line and are not seeing your view then self.navigationController is most likely nil. Try [self presentModalViewController:] instead.

Body:
I have an App with one MainWindow.xib file.  Then I have ViewControllerA.xib and ViewControllerB.xib.  My MainWindow.xib have one ViewController that points two ViewControllerA.xib.

On ViewControllerA I have a button and I would like the button, when pressed, to move ViewControllerB onto the screen.  How do I do that?

I tried this code, but I think I am missing something:

- (IBAction)btMyButton:(id)sender
{
    ViewControllerB * viewController = [[ViewControllerB alloc] initWithNibName:@"ViewControllerB" bundle:nil];
    [[UIApplication sharedApplication].keyWindow addSubview:viewController.view];
    [self.navigationController pushViewController:viewController animated:YES];
}

My ViewControllerB does appear, but it is squashed at the top of the screen, over the previous view.  Any help is greatly appreciated.

Thank you

Body:
Remove the second line:

[[UIApplication sharedApplication].keyWindow addSubview:viewController.view];

You are adding the view twice. The 2nd and 3rd lines both cause the view to be added to the view hierarchy in different places.

--update--
If you remove the 2nd line and are not seeing your view then self.navigationController is most likely nil. Try [self presentModalViewController:] instead.


答:
Is there not supposed to be a one-to-one relationship between abcd values and valueName ? If there is one-to-one, then an inner loop is wrong isn't it.

```<code>   String abcd = "4,0,1581664239228,6,799,0,845,253,0,0,0,0,0,0,0,0,0,0,1448,594,0,1276257,0,0,0,0,1100,0,0,0,0,0,0,0,2047,2158,0,13,1";
   String valueName = "version,build,tuneStartBaseUTCMS,ManifestDLStartTime,ManifestDLTotalTime,ManifestDLFailCount,VideoPlaylistDLStartTime,VideoPlaylistDLTotalTime,VideoPlaylistDLFailCount,AudioPlaylistDLStartTime,AudioPlaylistDLTotalTime,AudioPlaylistDLFailCount,VideoInitDLStartTime,VideoInitDLTotalTime,VideoInitDLFailCount,AudioInitDLStartTime,AudioInitDLTotalTime,AudioInitDLFailCount,VideoFragmentDLStartTime,VideoFragmentDLTotalTime,VideoFragmentDLFailCount,VideoBitRate,AudioFragmentDLStartTime,AudioFragmentDLTotalTime,AudioFragmentDLFailCount,AudioBitRate,drmLicenseAcqStartTime,drmLicenseAcqTotalTime,drmFailErrorCode,LicenseAcqPreProcessingDuration,LicenseAcqNetworkDuration,LicenseAcqPostProcDuration,VideoFragmentDecryptDuration,AudioFragmentDecryptDuration,gstPlayStartTime,gstFirstFrameTime,contentType,streamType,firstTune";

   String[] list1 = abcd.split(",");
   String[] list2 = valueName.split(",");

   if (list1.length == list2.length) {

       for (int x = 0; x < list1.length; x++) {
           System.out.println(list2[x] + ":" + list1[x]);
       }
   }
</code>```

Simply split and iterate

result

```<code>version:4
build:0
tuneStartBaseUTCMS:1581664239228
ManifestDLStartTime:6
ManifestDLTotalTime:799
ManifestDLFailCount:0
VideoPlaylistDLStartTime:845
VideoPlaylistDLTotalTime:253
VideoPlaylistDLFailCount:0
AudioPlaylistDLStartTime:0
AudioPlaylistDLTotalTime:0
AudioPlaylistDLFailCount:0
VideoInitDLStartTime:0
VideoInitDLTotalTime:0
VideoInitDLFailCount:0
AudioInitDLStartTime:0
AudioInitDLTotalTime:0
AudioInitDLFailCount:0
VideoFragmentDLStartTime:1448
VideoFragmentDLTotalTime:594
VideoFragmentDLFailCount:0
VideoBitRate:1276257
AudioFragmentDLStartTime:0
AudioFragmentDLTotalTime:0
AudioFragmentDLFailCount:0
AudioBitRate:0
drmLicenseAcqStartTime:1100
drmLicenseAcqTotalTime:0
drmFailErrorCode:0
LicenseAcqPreProcessingDuration:0
LicenseAcqNetworkDuration:0
LicenseAcqPostProcDuration:0
VideoFragmentDecryptDuration:0
AudioFragmentDecryptDuration:0
gstPlayStartTime:2047
gstFirstFrameTime:2158
contentType:0
streamType:13
firstTune:1
</code>```

Title: Map some names and values using java

Body:
Is there not supposed to be a one-to-one relationship between abcd values and valueName ? If there is one-to-one, then an inner loop is wrong isn't it.

   String abcd = "4,0,1581664239228,6,799,0,845,253,0,0,0,0,0,0,0,0,0,0,1448,594,0,1276257,0,0,0,0,1100,0,0,0,0,0,0,0,2047,2158,0,13,1";
   String valueName = "version,build,tuneStartBaseUTCMS,ManifestDLStartTime,ManifestDLTotalTime,ManifestDLFailCount,VideoPlaylistDLStartTime,VideoPlaylistDLTotalTime,VideoPlaylistDLFailCount,AudioPlaylistDLStartTime,AudioPlaylistDLTotalTime,AudioPlaylistDLFailCount,VideoInitDLStartTime,VideoInitDLTotalTime,VideoInitDLFailCount,AudioInitDLStartTime,AudioInitDLTotalTime,AudioInitDLFailCount,VideoFragmentDLStartTime,VideoFragmentDLTotalTime,VideoFragmentDLFailCount,VideoBitRate,AudioFragmentDLStartTime,AudioFragmentDLTotalTime,AudioFragmentDLFailCount,AudioBitRate,drmLicenseAcqStartTime,drmLicenseAcqTotalTime,drmFailErrorCode,LicenseAcqPreProcessingDuration,LicenseAcqNetworkDuration,LicenseAcqPostProcDuration,VideoFragmentDecryptDuration,AudioFragmentDecryptDuration,gstPlayStartTime,gstFirstFrameTime,contentType,streamType,firstTune";

   String[] list1 = abcd.split(",");
   String[] list2 = valueName.split(",");

   if (list1.length == list2.length) {

       for (int x = 0; x < list1.length; x++) {
           System.out.println(list2[x] + ":" + list1[x]);
       }
   }

Simply split and iterate

result

version:4
build:0
tuneStartBaseUTCMS:1581664239228
ManifestDLStartTime:6
ManifestDLTotalTime:799
ManifestDLFailCount:0
VideoPlaylistDLStartTime:845
VideoPlaylistDLTotalTime:253
VideoPlaylistDLFailCount:0
AudioPlaylistDLStartTime:0
AudioPlaylistDLTotalTime:0
AudioPlaylistDLFailCount:0
VideoInitDLStartTime:0
VideoInitDLTotalTime:0
VideoInitDLFailCount:0
AudioInitDLStartTime:0
AudioInitDLTotalTime:0
AudioInitDLFailCount:0
VideoFragmentDLStartTime:1448
VideoFragmentDLTotalTime:594
VideoFragmentDLFailCount:0
VideoBitRate:1276257
AudioFragmentDLStartTime:0
AudioFragmentDLTotalTime:0
AudioFragmentDLFailCount:0
AudioBitRate:0
drmLicenseAcqStartTime:1100
drmLicenseAcqTotalTime:0
drmFailErrorCode:0
LicenseAcqPreProcessingDuration:0
LicenseAcqNetworkDuration:0
LicenseAcqPostProcDuration:0
VideoFragmentDecryptDuration:0
AudioFragmentDecryptDuration:0
gstPlayStartTime:2047
gstFirstFrameTime:2158
contentType:0
streamType:13
firstTune:1


问:
C - Is there a way to read a single character of user input, and not have the rest "pushed down" to the next request for input?
So, I'm working on a simple hangman game in C, and I have the function read_guess, shown below.

```<code>void read_guess(char *guesses, char *p_current_guess)
{
    int valid_guess = 0;

    // Repeatedly takes input until guess is valid
    while (valid_guess == 0)
    {
        printf(">>> ");
        fgets(p_current_guess, 2, stdin);

        if (!isalpha(*p_current_guess)) printf("Guesses must be alphabetic. Please try again.\n\n");
        else
        {
            valid_guess = 1;

            // Iterates over array of guesses and checks if letter has already been guessed
            for (int i = 0; guesses[i] != '\0'; i++)
            {
                if (guesses[i] == *p_current_guess)
                {
                    printf("You have already guessed this letter. Please try again.\n\n");
                    valid_guess = 0;
                    break;
                }
            }
        }
    }
}
</code>```

I've tried all the standard input functions (including getchar), but with all of them, when an input larger than one character is supplied, instead of taking just the first character and moving on (or asking again), the rest of the input is "pushed back", and the next time input is requested, whether it be because the input contained a non-alphabetic character or the next round begins, the rest of the input is automatically processed. This repeats for each character of the input.

How can I avoid this?

答:
You can use getch() function on windows to get single character. and this is linux equivalent

What is the equivalent to getch() & getche() in Linux?

Body:
So, I'm working on a simple hangman game in C, and I have the function read_guess, shown below.

void read_guess(char *guesses, char *p_current_guess)
{
    int valid_guess = 0;

    // Repeatedly takes input until guess is valid
    while (valid_guess == 0)
    {
        printf(">>> ");
        fgets(p_current_guess, 2, stdin);

        if (!isalpha(*p_current_guess)) printf("Guesses must be alphabetic. Please try again.\n\n");
        else
        {
            valid_guess = 1;

            // Iterates over array of guesses and checks if letter has already been guessed
            for (int i = 0; guesses[i] != '\0'; i++)
            {
                if (guesses[i] == *p_current_guess)
                {
                    printf("You have already guessed this letter. Please try again.\n\n");
                    valid_guess = 0;
                    break;
                }
            }
        }
    }
}

I've tried all the standard input functions (including getchar), but with all of them, when an input larger than one character is supplied, instead of taking just the first character and moving on (or asking again), the rest of the input is "pushed back", and the next time input is requested, whether it be because the input contained a non-alphabetic character or the next round begins, the rest of the input is automatically processed. This repeats for each character of the input.

How can I avoid this?


问:
Best way to check for current date in where clause of sql query
I'm trying to find out the most efficient (best performance) way to check date field for current date.  Currently we are using:</p>

```<code>SELECT     COUNT(Job) AS Jobs
FROM         dbo.Job
WHERE     (Received BETWEEN DATEADD(d, DATEDIFF(d, 0, GETDATE()), 0)
                        AND DATEADD(d, DATEDIFF(d, 0, GETDATE()), 1))
</code>```

答:
Compare two dates after converting into same format like below.</p>

```<code>where CONVERT(varchar, createddate, 1) = CONVERT(varchar, getdate(), 1);
</code>```

OwnerDisplayName: Cptcecil

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to find out the most efficient (best performance) way to check date field for current date.  Currently we are using:

SELECT     COUNT(Job) AS Jobs
FROM         dbo.Job
WHERE     (Received BETWEEN DATEADD(d, DATEDIFF(d, 0, GETDATE()), 0)
                        AND DATEADD(d, DATEDIFF(d, 0, GETDATE()), 1))

LastEditorDisplayName: Milen A. Radev

Body:
Compare two dates after converting into same format like below.

where CONVERT(varchar, createddate, 1) = CONVERT(varchar, getdate(), 1);


问:
Chrome media hub API
Last week Chrome released the media hub. This is a small button at the right of the browser's top bar, giving access to all the video and audio playing.

https://blog.google/products/chrome/manage-audio-and-video-in-chrome/

Using the <video> element makes your player appears in this media hub, it just works.

But for youtube videos (see above), the media hub seems to be able to find a cover image, a color and a title / sub-title. However, I was not able to find any documentation about how to obtain this aspect with a standard video element. Any idea?

答:
We're all in the same boat, after trying to dig the source in chromium with no luck, I was sending an email to the chromium developer for this question and got the useful link about MediaSession.

So following the docs, You can customize it by setting metadata property in the mediaSession to showing a title, description and artwork (a.k.a. background image) except the background color, That's because the background color is determined by pixels of the image automatically.

```<code>if ('mediaSession' in navigator) {

  navigator.mediaSession.metadata = new MediaMetadata({
    title: 'Never Gonna Give You Up',
    artist: 'Rick Astley',
    album: 'Whenever You Need Somebody',
    artwork: [
      { src: 'https://dummyimage.com/96x96',   sizes: '96x96',   type: 'image/png' },
      { src: 'https://dummyimage.com/128x128', sizes: '128x128', type: 'image/png' },
      { src: 'https://dummyimage.com/192x192', sizes: '192x192', type: 'image/png' },
      { src: 'https://dummyimage.com/256x256', sizes: '256x256', type: 'image/png' },
      { src: 'https://dummyimage.com/384x384', sizes: '384x384', type: 'image/png' },
      { src: 'https://dummyimage.com/512x512', sizes: '512x512', type: 'image/png' },
    ]
  });
}
</code>```

I have created the demo on the JSFiddle. the result shows as following.

Title: Chrome media hub API

Body:
We're all in the same boat, after trying to dig the source in chromium with no luck, I was sending an email to the chromium developer for this question and got the useful link about MediaSession.

So following the docs, You can customize it by setting metadata property in the mediaSession to showing a title, description and artwork (a.k.a. background image) except the background color, That's because the background color is determined by pixels of the image automatically.

if ('mediaSession' in navigator) {

  navigator.mediaSession.metadata = new MediaMetadata({
    title: 'Never Gonna Give You Up',
    artist: 'Rick Astley',
    album: 'Whenever You Need Somebody',
    artwork: [
      { src: 'https://dummyimage.com/96x96',   sizes: '96x96',   type: 'image/png' },
      { src: 'https://dummyimage.com/128x128', sizes: '128x128', type: 'image/png' },
      { src: 'https://dummyimage.com/192x192', sizes: '192x192', type: 'image/png' },
      { src: 'https://dummyimage.com/256x256', sizes: '256x256', type: 'image/png' },
      { src: 'https://dummyimage.com/384x384', sizes: '384x384', type: 'image/png' },
      { src: 'https://dummyimage.com/512x512', sizes: '512x512', type: 'image/png' },
    ]
  });
}

I have created the demo on the JSFiddle. the result shows as following.


问:
How to replace NA with set of values
I have the following data frame:

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

df <- tibble(
  source = c("a", "b", "c", "d", "e"),
  score = c(10, 5, NA, 3, NA ) )

df
</code>```

It looks like this:

```<code># A tibble: 5 x 2
  source score
  <chr>  <dbl>
1 a         10 . # current max value
2 b          5
3 c         NA
4 d          3
5 e         NA
</code>```

What I want to do is to replace NA in score column with values ranging for existing max  + n onwards. Where n range from 1 to total number of rows of the df

Resulting in this (hand-coded) :

```<code>  source score
  a         10
  b          5
  c         11 # obtained from 10 + 1
  d          3
  e         12 #  obtained from 10 + 2
</code>```

How can I achieve that?

答:
With dplyr:

```<code>library(dplyr)

df %>%
  mutate_at("score", ~ ifelse(is.na(.), max(., na.rm = TRUE) + cumsum(is.na(.)), .))
</code>```

Result:

```<code># A tibble: 5 x 2
  source score
  <chr>  <dbl>
1 a         10
2 b          5
3 c         11
4 d          3
5 e         12
</code>```

Title: How to replace NA with set of values

Body:
I have the following data frame:

library(dplyr)
library(tibble)

df <- tibble(
  source = c("a", "b", "c", "d", "e"),
  score = c(10, 5, NA, 3, NA ) )

df

It looks like this:

# A tibble: 5 x 2
  source score
  <chr>  <dbl>
1 a         10 . # current max value
2 b          5
3 c         NA
4 d          3
5 e         NA

What I want to do is to replace NA in score column with values ranging for existing max  + n onwards. Where n range from 1 to total number of rows of the df

Resulting in this (hand-coded) :

  source score
  a         10
  b          5
  c         11 # obtained from 10 + 1
  d          3
  e         12 #  obtained from 10 + 2

How can I achieve that?

Body:
With dplyr:

library(dplyr)

df %>%
  mutate_at("score", ~ ifelse(is.na(.), max(., na.rm = TRUE) + cumsum(is.na(.)), .))

Result:

# A tibble: 5 x 2
  source score
  <chr>  <dbl>
1 a         10
2 b          5
3 c         11
4 d          3
5 e         12


问:
Round Down Decimal Places Javascript
I need a rounding down many many decimal places down, basically roundTo but supposedly rounding down at the spot. Example,

```<code>take the number, 1.087179939485353505
but to the fifth place, with roundTo of 6
roundTo(1.087179939485353505, 6) is 1.08718
</code>```

I need 1.08717 not 1.08718 in javascript.

```<code>var Variable = roundTo(Variable / 1000000000000000000, 6);
</code>```

Resolved
There seems to be no native javascript decimal rounding function that rounds down. One of two options are available.

Convert to string and manipulate the data that way (makes the most sense).

Utilize a number and multiply, floor then re-divide again for your number

答:
How about convert to string, slice and convert back to number.

const roundTo = num => Number(String(num).slice(0, 7));

console.log(roundTo(1.087179939485353505));```

Title: Round Down Decimal Places Javascript

Body:
I need a rounding down many many decimal places down, basically roundTo but supposedly rounding down at the spot. Example,

take the number, 1.087179939485353505
but to the fifth place, with roundTo of 6
roundTo(1.087179939485353505, 6) is 1.08718

I need 1.08717 not 1.08718 in javascript.

var Variable = roundTo(Variable / 1000000000000000000, 6);

Resolved
There seems to be no native javascript decimal rounding function that rounds down. One of two options are available.

Convert to string and manipulate the data that way (makes the most sense).

Utilize a number and multiply, floor then re-divide again for your number


问:
Getting errors in decoding json to swift model class
I am trying to decode a JSON Response and getting the error every time. I also tried to make a model class from online tool but it doesn't decode it to the swift model class. When I printed the localized description it tells that The given data is not in the correct format. Below is my model class. Where as the error says

Swift.DecodingError.typeMismatch(Swift.Dictionary,
  Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue:
  "ResponseDescription", intValue: nil)], debugDescription: "Expected to
  decode Dictionary but found a string/data instead.",
  underlyingError: nil))

Model Class

```<code>struct ResponseLogin: Decodable{
    let Status:Bool
    let Message: String
    let ResponseDescription: ResponseDescription
    let EncryptStatus: Bool

    struct ResponseDescription: Decodable{
        let ID:Int
        let CustomerWebID: Int
        let CustomerWalletID: Int
        let CellNo: String
        let FirstName: String
        let LastName: String
        let Email: String
        let SahulatWalletCard: String
        let City: String
        let Address: String
        let ProfilePicture: String
        let TokenNo: String
        let ResponseStatus: String
        let ResponseMessage: String
    }
}
</code>```

JSON response

```<code>{
"Status": true,
"Message":"Login Successfully",
"ResponseDescription":
{
"ID": 1459,
"CustomerWebID": 6275,
"CustomerWalletID": 321123,
"CellNo": "0332334001",
"FirstName": "Haris",
"LastName": "Khan",
"Email": "myemail@gmail.com",
"SahulatWalletCard": "3085040101018537",
"City": "Karachi",
"RegionID": 1,
"Address": "Test1",
"ProfilePicture": "http://images/mypic.png",
"TokenNo": "Xxxx==2121mcmvjmdx!",
"ResponseStatus": true,
"ResponseMessage": "Data Found"
},
"EncryptStatus": true
}

Decrypted JSON
{
  "Status": true,
  "Message": "Login Successfully",
  "ResponseDescription":"Qmw25wKdmOpbUxP3pMRGnVP9yHcsJhVISyA6s3oBHrkpGsAlbR27xsbcsZqXd0z3A6h1tB1i/sOZFuZaMTNMBTevq3N7xG8KBw50WauLDHFqJ4JbAkh6RKUPOLcpmdIrEZ2jgfJrA+dNrftbjIjnEohg4jF/oLDKs7sjE1Ozk/3C1JnFTHNnc5vSrQNNUUOzrB4+QOxMGqpdNrF4BCh7YQ9xT1w/8D3BNM/7LXhb5txqbCEdRI7yf6R+tw5Mey4NR6NXAYdfGCnWKLsrnU2FwTKKRG2PqBZ7hLa2Ee8Uva0OAStvkldMWs8Heh9oS8T3Z39goyxFJme3N7x9JRzZyHmTbc6JqPI2kwWDwYztxxK6bft4tXwumPjJHx91ScNm2JCLQworqvlyHeOa8oBoXK6xym/PrAPCJ3Mwa3MHXhrU8U8mONFmtp3zZdPyXmHayE6E9meZtxbABEihBkOra4257s5rF3Zyr8WtHbwXYMA1dDF/lESwjiyG9Q/KHHgem8QyB3P9xSVi5vKqfFnqZfBusYTMNqDF+V8C2L9YjEp2bdyq7lUPEu0jWMRqpYDyAO+Z864cwbnb0V1fEfE3xI7Z8/PqlQ5hp7mR5VwL4k6pekagZDNXKo4qOTy6PGsod0x7KY0bLddL6qv1MrcyzcH7K1016fy5R/3DemkAmXn0/d6OleVHDr8zpC9D4ZZrY8JghRCA7Vb/b5itX9VC41dL/3PcZBbXsiOFnnJmr/2zNj6QXBK4+b/S42Wh2vBK",
"EncryptStatus": true
}

</code>```

Any kind help can let me point my mistake in this problem.

答:
try this! </p>

```<code>class Welcome: Codable {
    let status: Bool
    let message: String
    let responseDescription: ResponseDescription
    let encryptStatus: Bool

    enum CodingKeys: String, CodingKey {
        case status = "Status"
        case message = "Message"
        case responseDescription = "ResponseDescription"
        case encryptStatus = "EncryptStatus"
    }

    }
   class ResponseDescription: Codable {
    let id, customerWebID, customerWalletID: Int
    let cellNo, firstName, lastName, email: String
    let sahulatWalletCard, city: String
    let regionID: Int
    let address: String
    let profilePicture: String
    let tokenNo: String
    let responseStatus: Bool
    let responseMessage: String

}
</code>```

Body:
I am trying to decode a JSON Response and getting the error every time. I also tried to make a model class from online tool but it doesn't decode it to the swift model class. When I printed the localized description it tells that The given data is not in the correct format. Below is my model class. Where as the error says

Swift.DecodingError.typeMismatch(Swift.Dictionary,
  Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue:
  "ResponseDescription", intValue: nil)], debugDescription: "Expected to
  decode Dictionary but found a string/data instead.",
  underlyingError: nil))

Model Class

struct ResponseLogin: Decodable{
    let Status:Bool
    let Message: String
    let ResponseDescription: ResponseDescription
    let EncryptStatus: Bool

    struct ResponseDescription: Decodable{
        let ID:Int
        let CustomerWebID: Int
        let CustomerWalletID: Int
        let CellNo: String
        let FirstName: String
        let LastName: String
        let Email: String
        let SahulatWalletCard: String
        let City: String
        let Address: String
        let ProfilePicture: String
        let TokenNo: String
        let ResponseStatus: String
        let ResponseMessage: String
    }
}

JSON response

{
"Status": true,
"Message":"Login Successfully",
"ResponseDescription":
{
"ID": 1459,
"CustomerWebID": 6275,
"CustomerWalletID": 321123,
"CellNo": "0332334001",
"FirstName": "Haris",
"LastName": "Khan",
"Email": "myemail@gmail.com",
"SahulatWalletCard": "3085040101018537",
"City": "Karachi",
"RegionID": 1,
"Address": "Test1",
"ProfilePicture": "http://images/mypic.png",
"TokenNo": "Xxxx==2121mcmvjmdx!",
"ResponseStatus": true,
"ResponseMessage": "Data Found"
},
"EncryptStatus": true
}

Decrypted JSON
{
  "Status": true,
  "Message": "Login Successfully",
  "ResponseDescription":"Qmw25wKdmOpbUxP3pMRGnVP9yHcsJhVISyA6s3oBHrkpGsAlbR27xsbcsZqXd0z3A6h1tB1i/sOZFuZaMTNMBTevq3N7xG8KBw50WauLDHFqJ4JbAkh6RKUPOLcpmdIrEZ2jgfJrA+dNrftbjIjnEohg4jF/oLDKs7sjE1Ozk/3C1JnFTHNnc5vSrQNNUUOzrB4+QOxMGqpdNrF4BCh7YQ9xT1w/8D3BNM/7LXhb5txqbCEdRI7yf6R+tw5Mey4NR6NXAYdfGCnWKLsrnU2FwTKKRG2PqBZ7hLa2Ee8Uva0OAStvkldMWs8Heh9oS8T3Z39goyxFJme3N7x9JRzZyHmTbc6JqPI2kwWDwYztxxK6bft4tXwumPjJHx91ScNm2JCLQworqvlyHeOa8oBoXK6xym/PrAPCJ3Mwa3MHXhrU8U8mONFmtp3zZdPyXmHayE6E9meZtxbABEihBkOra4257s5rF3Zyr8WtHbwXYMA1dDF/lESwjiyG9Q/KHHgem8QyB3P9xSVi5vKqfFnqZfBusYTMNqDF+V8C2L9YjEp2bdyq7lUPEu0jWMRqpYDyAO+Z864cwbnb0V1fEfE3xI7Z8/PqlQ5hp7mR5VwL4k6pekagZDNXKo4qOTy6PGsod0x7KY0bLddL6qv1MrcyzcH7K1016fy5R/3DemkAmXn0/d6OleVHDr8zpC9D4ZZrY8JghRCA7Vb/b5itX9VC41dL/3PcZBbXsiOFnnJmr/2zNj6QXBK4+b/S42Wh2vBK",
"EncryptStatus": true
}

Any kind help can let me point my mistake in this problem.

Body:
try this!

class Welcome: Codable {
    let status: Bool
    let message: String
    let responseDescription: ResponseDescription
    let encryptStatus: Bool

    enum CodingKeys: String, CodingKey {
        case status = "Status"
        case message = "Message"
        case responseDescription = "ResponseDescription"
        case encryptStatus = "EncryptStatus"
    }

    }
   class ResponseDescription: Codable {
    let id, customerWebID, customerWalletID: Int
    let cellNo, firstName, lastName, email: String
    let sahulatWalletCard, city: String
    let regionID: Int
    let address: String
    let profilePicture: String
    let tokenNo: String
    let responseStatus: Bool
    let responseMessage: String

}


问:
Java service return the Result message along with Object class
Hi i have to return the ResultMessage  along with my object class in my below code.

```<code>public List<EmployeeInformation> findAll(String IndexName) throws Exception {

        String ResultMessage = new String();
        if (Strings.isNullOrEmpty(IndexName)) {
            ResultMessage= "Index name is null or empty";
        } else if (isTextContainUpperCase(IndexName)) {
            ResultMessage= "Index name should be in lowercase";
        } else if (!checkEsConnection(client)) {
            ResultMessage= "Elasticsearch deployment is not reachable";
        }
        SearchRequest searchRequest = new SearchRequest(IndexName);
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(QueryBuilders.matchAllQuery());
        searchRequest.source(searchSourceBuilder);
        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
        return getSearchResult(searchResponse);
    }

private List<EmployeeInformation> getSearchResult(SearchResponse response) {

        SearchHit[] searchHit = response.getHits().getHits();

        List<EmployeeInformation> EmployeeDocuments = new ArrayList<>();

        for (SearchHit hit : searchHit) {
            EmployeeDocuments
                    .add(objectMapper
                            .convertValue(hit
                                    .getSourceAsMap(), EmployeeInformation.class));
        }

        return EmployeeDocuments;
    }
</code>```

What is the best way to return the ResultMessage along with my employeeinformation object. Could some one Modify the above code accordingly and post your answer or suggest me how to achieve this? thanks in advance

答:
You can return ImmutablePair<ResultMessage, List<EmployeeInformation>>.
This objects then be accessed by getLeft() and getRight() methods. However, you will need org.apache.commons lib for this. It is worth adding this lib as it has many more such utils and wrapper classes. https://mvnrepository.com/artifact/org.apache.commons/commons-lang3

Body:
Hi i have to return the ResultMessage  along with my object class in my below code.

public List<EmployeeInformation> findAll(String IndexName) throws Exception {

        String ResultMessage = new String();
        if (Strings.isNullOrEmpty(IndexName)) {
            ResultMessage= "Index name is null or empty";
        } else if (isTextContainUpperCase(IndexName)) {
            ResultMessage= "Index name should be in lowercase";
        } else if (!checkEsConnection(client)) {
            ResultMessage= "Elasticsearch deployment is not reachable";
        }
        SearchRequest searchRequest = new SearchRequest(IndexName);
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(QueryBuilders.matchAllQuery());
        searchRequest.source(searchSourceBuilder);
        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
        return getSearchResult(searchResponse);
    }

private List<EmployeeInformation> getSearchResult(SearchResponse response) {

        SearchHit[] searchHit = response.getHits().getHits();

        List<EmployeeInformation> EmployeeDocuments = new ArrayList<>();

        for (SearchHit hit : searchHit) {
            EmployeeDocuments
                    .add(objectMapper
                            .convertValue(hit
                                    .getSourceAsMap(), EmployeeInformation.class));
        }

        return EmployeeDocuments;
    }

What is the best way to return the ResultMessage along with my employeeinformation object. Could some one Modify the above code accordingly and post your answer or suggest me how to achieve this? thanks in advance


问:
"Right-hand side of 'instanceof' is not an object" MomentJS
Having some serious issue with momentjs. I keep getting "Right-hand side of 'instanceof' is not an object" and not getting much online.

```<code>var startOfWeek;
$(document).ready(function () {
      startOfWeek = moment($(".datepicker").val()).startOf("isoWeek").toDate();
    });

    function X(){
     var dateS= moment(startOfWeek).add(1, 'd');//error on moment
    }
</code>```

What am I missing? Am I doing it wrong? Kindly assist.

答:
it should be something like that

var startOfWeek = moment("2020-02-16T00:00:00");
var begin = moment(startOfWeek).startOf('week').isoWeekday(1);
console.log(begin)
// make sure startOfWeek  is string so may be you need to convert.
var new_date = moment(startOfWeek, "DD-MM-YYYY").add('days', 5).format('MMMM DD YYYY');
console.log(new_date)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.1.0/moment.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script></code>```

Body:
Having some serious issue with momentjs. I keep getting "Right-hand side of 'instanceof' is not an object" and not getting much online.

var startOfWeek;
$(document).ready(function () {
      startOfWeek = moment($(".datepicker").val()).startOf("isoWeek").toDate();
    });

    function X(){
     var dateS= moment(startOfWeek).add(1, 'd');//error on moment
    }

What am I missing? Am I doing it wrong? Kindly assist.

Body:
it should be something like that

var startOfWeek = moment("2020-02-16T00:00:00");
var begin = moment(startOfWeek).startOf('week').isoWeekday(1);
console.log(begin)
// make sure startOfWeek  is string so may be you need to convert.
var new_date = moment(startOfWeek, "DD-MM-YYYY").add('days', 5).format('MMMM DD YYYY');
console.log(new_date)

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.1.0/moment.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>