问:
Why does an "id variable" in tidymodels/recipes play a predictor role?
This is the same issue as Predict with step_naomit and retain ID using tidymodels , but even though there is an accepted answer, the OP's last comment states the issue the "id variable" is being used as a predictor, as can be seen when looking at model$fit$variable.importance.

I have a dataset with "id variables" I would like to keep.
I thought I would be able to achieve this with a recipe() specification.

library(tidymodels)

# label is an identifier variable I want to keep even though it's not
# a predictor
df <- tibble(label = 1:50,
             x = rnorm(50, 0, 5),
             f = factor(sample(c('a', 'b', 'c'), 50, replace = TRUE)),
             y = factor(sample(c('Y', 'N'), 50, replace = TRUE)) )

df_split <- initial_split(df, prop = 0.70)

# Make up any recipe: just note I specify 'label' as "id variable"
rec <- recipe(training(df_split)) %>%
  update_role(label, new_role = "id variable") %>%
  update_role(y, new_role = "outcome") %>%
  update_role(x, new_role = "predictor") %>%
  update_role(f, new_role = "predictor") %>%
  step_corr(all_numeric(), -all_outcomes()) %>%
  step_dummy(all_predictors(),-all_numeric()) %>%
  step_meanimpute(all_numeric(), -all_outcomes())

train_juiced <- prep(rec, training(df_split)) %>% juice()

logit_fit <- logistic_reg(mode = "classification") %>%
  set_engine(engine = "glm") %>%
  fit(y ~ ., data = train_juiced)

# Why is label a variable in the model ?
logit_fit[['fit']][['coefficients']]
#> (Intercept)       label           x         f_b         f_c
#>  1.03664140 -0.01405316  0.22357266 -1.80701531 -1.66285399
```

<p><sup>Created on 2020-01-27 by the reprex package (v0.3.0)</sup></p>

<p>But even though I did specify <code>label</code> was an id variable, it is being used as a predictor.
So maybe I can use the specific terms I want in the formula and specifically add <code>label</code> as an id variable.</p>

<pre class="lang-r prettyprint-override"><code>rec <- recipe(training(df_split), y ~ x + f) %>%
  update_role(label, new_role = "id variable") %>%
  step_corr(all_numeric(), -all_outcomes()) %>%
  step_dummy(all_predictors(),-all_numeric()) %>%
  step_meanimpute(all_numeric(), -all_outcomes())
#> Error in .f(.x[[i]], ...): object 'label' not found
</code>```

Created on 2020-01-27 by the reprex package (v0.3.0)

I can try not mentioning label

rec <- recipe(training(df_split), y ~ x + f) %>%
  step_corr(all_numeric(), -all_outcomes()) %>%
  step_dummy(all_predictors(),-all_numeric()) %>%
  step_meanimpute(all_numeric(), -all_outcomes())

train_juiced <- prep(rec, training(df_split)) %>% juice()

logit_fit <- logistic_reg(mode = "classification") %>%
  set_engine(engine = "glm") %>%
  fit(y ~ ., data = train_juiced)

# Why is label a variable in the model ?
logit_fit[['fit']][['coefficients']]
#> (Intercept)           x         f_b         f_c
#> -0.98950228  0.03734093  0.98945339  1.27014824

train_juiced
#> # A tibble: 35 x 4
#>          x y       f_b   f_c
#>      <dbl> <fct> <dbl> <dbl>
#>  1 -0.928  Y         1     0
#>  2  4.54   N         0     0
#>  3 -1.14   N         1     0
#>  4 -5.19   N         1     0
#>  5 -4.79   N         0     0
#>  6 -6.00   N         0     0
#>  7  3.83   N         0     1
#>  8 -8.66   Y         1     0
#>  9 -0.0849 Y         1     0
#> 10 -3.57   Y         0     1
#> # ... with 25 more rows
```

Created on 2020-01-27 by the reprex package (v0.3.0)

OK, so the model works, but I have lost my label.

How should I do this ?

答:
The main issue/conceptual problem you are running into is that once you juice() the recipe, it is just data, i.e. just literally a dataframe. When you use that to fit a model, there's no way for the model to know that some of the variables had special roles.

library(tidymodels)

# label is an identifier variable to keep even though it's not a predictor
df <- tibble(label = 1:50,
             x = rnorm(50, 0, 5),
             f = factor(sample(c('a', 'b', 'c'), 50, replace = TRUE)),
             y = factor(sample(c('Y', 'N'), 50, replace = TRUE)) )

df_split <- initial_split(df, prop = 0.70)

rec <- recipe(y ~ ., training(df_split)) %>%
  update_role(label, new_role = "id variable") %>%
  step_corr(all_numeric(), -all_outcomes()) %>%
  step_dummy(all_predictors(),-all_numeric()) %>%
  step_meanimpute(all_numeric(), -all_outcomes()) %>%
  prep()

train_juiced <- juice(rec)
train_juiced
#> # A tibble: 35 x 5
#>    label     x y       f_b   f_c
#>    <int> <dbl> <fct> <dbl> <dbl>
#>  1     1  1.80 N         1     0
#>  2     3  1.45 N         0     0
#>  3     5 -5.00 N         0     0
#>  4     6 -4.15 N         1     0
#>  5     7  1.37 Y         0     1
#>  6     8  1.62 Y         0     1
#>  7    10 -1.77 Y         1     0
#>  8    11 -3.15 N         0     1
#>  9    12 -2.02 Y         0     1
#> 10    13  2.65 Y         0     1
#> # … with 25 more rows
```

<p>Notice that <code>train_juiced</code> is just literally a regular tibble. If you train a model on this tibble using <code>fit()</code>, it won't know anything about the recipe used to transform the data.</p>

<p>The tidymodels framework <em>does</em> have a way to train models using the role information from the recipe. Probably the easiest way to do that is using workflows.</p>

<pre class="lang-r prettyprint-override"><code>logit_spec <- logistic_reg(mode = "classification") %>%
  set_engine(engine = "glm")

wf <- workflow() %>%
  add_model(logit_spec) %>%
  add_recipe(rec)

logit_fit <- fit(wf, training(df_split))

# No more label in the model
logit_fit
#> ══ Workflow [trained] ══════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════
#> Preprocessor: Recipe
#> Model: logistic_reg()
#>
#> ── Preprocessor ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
#> 3 Recipe Steps
#>
#> ● step_corr()
#> ● step_dummy()
#> ● step_meanimpute()
#>
#> ── Model ───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
#>
#> Call:  stats::glm(formula = formula, family = stats::binomial, data = data)
#>
#> Coefficients:
#> (Intercept)            x          f_b          f_c
#>     0.42331     -0.04234     -0.04991      0.64728
#>
#> Degrees of Freedom: 34 Total (i.e. Null);  31 Residual
#> Null Deviance:       45
#> Residual Deviance: 44.41     AIC: 52.41
</code>```

Created on 2020-02-15 by the reprex package (v0.3.0)

No more labels in the model!

Body:
This is the same issue as Predict with step_naomit and retain ID using tidymodels , but even though there is an accepted answer, the OP's last comment states the issue the "id variable" is being used as a predictor, as can be seen when looking at model$fit$variable.importance.

I have a dataset with "id variables" I would like to keep.
I thought I would be able to achieve this with a recipe() specification.

library(tidymodels)

# label is an identifier variable I want to keep even though it's not
# a predictor
df <- tibble(label = 1:50,
             x = rnorm(50, 0, 5),
             f = factor(sample(c('a', 'b', 'c'), 50, replace = TRUE)),
             y = factor(sample(c('Y', 'N'), 50, replace = TRUE)) )

df_split <- initial_split(df, prop = 0.70)

# Make up any recipe: just note I specify 'label' as "id variable"
rec <- recipe(training(df_split)) %>%
  update_role(label, new_role = "id variable") %>%
  update_role(y, new_role = "outcome") %>%
  update_role(x, new_role = "predictor") %>%
  update_role(f, new_role = "predictor") %>%
  step_corr(all_numeric(), -all_outcomes()) %>%
  step_dummy(all_predictors(),-all_numeric()) %>%
  step_meanimpute(all_numeric(), -all_outcomes())

train_juiced <- prep(rec, training(df_split)) %>% juice()

logit_fit <- logistic_reg(mode = "classification") %>%
  set_engine(engine = "glm") %>%
  fit(y ~ ., data = train_juiced)

# Why is label a variable in the model ?
logit_fit[['fit']][['coefficients']]
#> (Intercept)       label           x         f_b         f_c
#>  1.03664140 -0.01405316  0.22357266 -1.80701531 -1.66285399

Created on 2020-01-27 by the reprex package (v0.3.0)

But even though I did specify label was an id variable, it is being used as a predictor.
So maybe I can use the specific terms I want in the formula and specifically add label as an id variable.

rec <- recipe(training(df_split), y ~ x + f) %>%
  update_role(label, new_role = "id variable") %>%
  step_corr(all_numeric(), -all_outcomes()) %>%
  step_dummy(all_predictors(),-all_numeric()) %>%
  step_meanimpute(all_numeric(), -all_outcomes())
#> Error in .f(.x[[i]], ...): object 'label' not found

Created on 2020-01-27 by the reprex package (v0.3.0)

I can try not mentioning label

rec <- recipe(training(df_split), y ~ x + f) %>%
  step_corr(all_numeric(), -all_outcomes()) %>%
  step_dummy(all_predictors(),-all_numeric()) %>%
  step_meanimpute(all_numeric(), -all_outcomes())

train_juiced <- prep(rec, training(df_split)) %>% juice()

logit_fit <- logistic_reg(mode = "classification") %>%
  set_engine(engine = "glm") %>%
  fit(y ~ ., data = train_juiced)

# Why is label a variable in the model ?
logit_fit[['fit']][['coefficients']]
#> (Intercept)           x         f_b         f_c
#> -0.98950228  0.03734093  0.98945339  1.27014824

train_juiced
#> # A tibble: 35 x 4
#>          x y       f_b   f_c
#>      <dbl> <fct> <dbl> <dbl>
#>  1 -0.928  Y         1     0
#>  2  4.54   N         0     0
#>  3 -1.14   N         1     0
#>  4 -5.19   N         1     0
#>  5 -4.79   N         0     0
#>  6 -6.00   N         0     0
#>  7  3.83   N         0     1
#>  8 -8.66   Y         1     0
#>  9 -0.0849 Y         1     0
#> 10 -3.57   Y         0     1
#> # ... with 25 more rows

Created on 2020-01-27 by the reprex package (v0.3.0)

OK, so the model works, but I have lost my label.

How should I do this ?

Body:
The main issue/conceptual problem you are running into is that once you juice() the recipe, it is just data, i.e. just literally a dataframe. When you use that to fit a model, there's no way for the model to know that some of the variables had special roles.

library(tidymodels)

# label is an identifier variable to keep even though it's not a predictor
df <- tibble(label = 1:50,
             x = rnorm(50, 0, 5),
             f = factor(sample(c('a', 'b', 'c'), 50, replace = TRUE)),
             y = factor(sample(c('Y', 'N'), 50, replace = TRUE)) )

df_split <- initial_split(df, prop = 0.70)

rec <- recipe(y ~ ., training(df_split)) %>%
  update_role(label, new_role = "id variable") %>%
  step_corr(all_numeric(), -all_outcomes()) %>%
  step_dummy(all_predictors(),-all_numeric()) %>%
  step_meanimpute(all_numeric(), -all_outcomes()) %>%
  prep()

train_juiced <- juice(rec)
train_juiced
#> # A tibble: 35 x 5
#>    label     x y       f_b   f_c
#>    <int> <dbl> <fct> <dbl> <dbl>
#>  1     1  1.80 N         1     0
#>  2     3  1.45 N         0     0
#>  3     5 -5.00 N         0     0
#>  4     6 -4.15 N         1     0
#>  5     7  1.37 Y         0     1
#>  6     8  1.62 Y         0     1
#>  7    10 -1.77 Y         1     0
#>  8    11 -3.15 N         0     1
#>  9    12 -2.02 Y         0     1
#> 10    13  2.65 Y         0     1
#> # … with 25 more rows

Notice that train_juiced is just literally a regular tibble. If you train a model on this tibble using fit(), it won't know anything about the recipe used to transform the data.

The tidymodels framework does have a way to train models using the role information from the recipe. Probably the easiest way to do that is using workflows.

logit_spec <- logistic_reg(mode = "classification") %>%
  set_engine(engine = "glm")

wf <- workflow() %>%
  add_model(logit_spec) %>%
  add_recipe(rec)

logit_fit <- fit(wf, training(df_split))

# No more label in the model
logit_fit
#> ══ Workflow [trained] ══════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════
#> Preprocessor: Recipe
#> Model: logistic_reg()
#>
#> ── Preprocessor ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
#> 3 Recipe Steps
#>
#> ● step_corr()
#> ● step_dummy()
#> ● step_meanimpute()
#>
#> ── Model ───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
#>
#> Call:  stats::glm(formula = formula, family = stats::binomial, data = data)
#>
#> Coefficients:
#> (Intercept)            x          f_b          f_c
#>     0.42331     -0.04234     -0.04991      0.64728
#>
#> Degrees of Freedom: 34 Total (i.e. Null);  31 Residual
#> Null Deviance:       45
#> Residual Deviance: 44.41     AIC: 52.41

Created on 2020-02-15 by the reprex package (v0.3.0)

No more labels in the model!


来源: stackexchange

问:
How to initialize an NSObject's subclass on iPhone?
I want to write some methods in a class so that other classes can call these methods  using [instance methodName:Parameter].

If the class is a subclass of UIViewController, I can use initWithNibName to initialize it. But I want to write the methods in an NSObject's subclass, how can I initialize it?

答:
I find this may work:</p>

```<code>TheClass *newObject = [[TheClass alloc] init];
//do something here
[newObject release];</code>```

OwnerDisplayName: iphony

ContentLicense: CC BY-SA 3.0

Body:
I find this may work:

TheClass *newObject = [[TheClass alloc] init];
//do something here
[newObject release];

ContentLicense: CC BY-SA 2.5


问:
Mailgun HTTP POST to with Rails 3 - (undefined method `rewind' for #<String:0xb701ace0>)
Does anyone have any theories about this?

I have a feeling this is a Rails 3.x bug.

I'm using a service called mailgun that routes incoming e-mails to url's for further processing. Rails 3 chokes on these requests. Rails 2 does not.

I'm at a loss. I'm not sure exactly where the issue is.

```<code>Started POST "/posts/upload" for 174.37.214.195 at Fri Mar 11 20:22:41 -0500 2011
  SQL (0.1ms)  SET search_path TO public
  SQL (0.2ms)  SHOW client_min_messages
  SQL (0.1ms)  SET client_min_messages TO 'panic'
  SQL (0.1ms)  SET standard_conforming_strings = on
  SQL (0.1ms)  SET client_min_messages TO 'notice'
  SQL (0.4ms)  SET time zone 'UTC'
  SQL (0.1ms)  SHOW TIME ZONE

NoMethodError (undefined method `rewind' for #<String:0xb6d1c624>):

Rendered /usr/lib/ruby/gems/1.8/gems/actionpack-3.0.4/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (1.0ms)
Error during failsafe response: ActionView::Template::Error
  /usr/lib/ruby/gems/1.8/gems/activesupport-3.0.4/lib/active_support/whiny_nil.rb:48:in `method_missing'
  /usr/lib/ruby/gems/1.8/gems/actionpack-3.0.4/lib/action_dispatch/http/parameters.rb:10:in `parameters'
  /usr/lib/ruby/gems/1.8/gems/actionpack-3.0.4/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb:3:in `__usr_lib_ruby_gems_____gems_actionpack_______lib_action_dispatch_middleware_templates_rescues_diagnostics_erb___359554262__609638518_0'
  /usr/lib/ruby/gems/1.8/gems/actionpack-3.0.4/lib/action_view/template.rb:135:in `send'
  /usr/lib/ruby/gems/1.8/gems/actionpack-3.0.4/lib/action_view/template.rb:135:in `render'
  /usr/lib/ruby/gems/1.8/gems/activesupport-3.0.4/lib/active_support/notifications.rb:54:in `instrument'
  /usr/lib/ruby/gems/1.8/gems/actionpack-3.0.4/lib/action_view/template.rb:127:in `render'
  /usr/lib/ruby/gems/1.8/gems/actionpack-3.0.4/lib/action_view/render/rendering.rb:59:in `_render_template'
  /usr/lib/ruby/gems/1.8/gems/activesupport-3.0.4/lib/active_support/notifications.rb:52:in `instrument'
  /usr/lib/ruby/gems/1.8/gems/activesupport-3.0.4/lib/active_support/notifications/instrumenter.rb:21:in `instrument'
  /usr/lib/ruby/gems/1.8/gems/activesupport-3.0.4/lib/active_support/notifications.rb:52:in `instrument'
  /usr/lib/ruby/gems/1.8/gems/actionpack-3.0.4/lib/action_view/render/rendering.rb:56:in `_render_template'
  /usr/lib/ruby/gems/1.8/gems/actionpack-3.0.4/lib/action_view/render/rendering.rb:26:in `render_without_haml'
  /usr/lib/ruby/gems/1.8/gems/haml-3.0.25/lib/haml/helpers/action_view_mods.rb:13:in `render'
  /usr/lib/ruby/gems/1.8/gems/actionpack-3.0.4/lib/action_dispatch/middleware/show_exceptions.rb:88:in `rescue_action_locally'
  /usr/lib/ruby/gems/1.8/gems/actionpack-3.0.4/lib/action_dispatch/middleware/show_exceptions.rb:68:in `render_exception'
  /usr/lib/ruby/gems/1.8/gems/actionpack-3.0.4/lib/action_dispatch/middleware/show_exceptions.rb:59:in `call'
  /usr/lib/ruby/gems/1.8/gems/railties-3.0.4/lib/rails/rack/logger.rb:13:in `call'
  /usr/lib/ruby/gems/1.8/gems/rack-1.2.1/lib/rack/runtime.rb:17:in `call'
  /usr/lib/ruby/gems/1.8/gems/activesupport-3.0.4/lib/active_support/cache/strategy/local_cache.rb:72:in `call'
  /usr/lib/ruby/gems/1.8/gems/rack-1.2.1/lib/rack/lock.rb:11:in `call'
  /usr/lib/ruby/gems/1.8/gems/rack-1.2.1/lib/rack/lock.rb:11:in `synchronize'
  /usr/lib/ruby/gems/1.8/gems/rack-1.2.1/lib/rack/lock.rb:11:in `call'
  /usr/lib/ruby/gems/1.8/gems/actionpack-3.0.4/lib/action_dispatch/middleware/static.rb:30:in `call'
  /usr/lib/ruby/gems/1.8/gems/railties-3.0.4/lib/rails/application.rb:168:in `call'
  /usr/lib/ruby/gems/1.8/gems/railties-3.0.4/lib/rails/application.rb:77:in `send'
  /usr/lib/ruby/gems/1.8/gems/railties-3.0.4/lib/rails/application.rb:77:in `method_missing'
  /usr/lib/ruby/gems/1.8/gems/railties-3.0.4/lib/rails/rack/log_tailer.rb:14:in `call'
  /usr/lib/ruby/gems/1.8/gems/rack-1.2.1/lib/rack/content_length.rb:13:in `call'
  /usr/lib/ruby/gems/1.8/gems/rack-1.2.1/lib/rack/handler/webrick.rb:52:in `service'
  /usr/lib/ruby/1.8/webrick/httpserver.rb:104:in `service'
  /usr/lib/ruby/1.8/webrick/httpserver.rb:65:in `run'
  /usr/lib/ruby/1.8/webrick/server.rb:173:in `start_thread'
  /usr/lib/ruby/1.8/webrick/server.rb:162:in `start'
  /usr/lib/ruby/1.8/webrick/server.rb:162:in `start_thread'
  /usr/lib/ruby/1.8/webrick/server.rb:95:in `start'
  /usr/lib/ruby/1.8/webrick/server.rb:92:in `each'
  /usr/lib/ruby/1.8/webrick/server.rb:92:in `start'
  /usr/lib/ruby/1.8/webrick/server.rb:23:in `start'
  /usr/lib/ruby/1.8/webrick/server.rb:82:in `start'
  /usr/lib/ruby/gems/1.8/gems/rack-1.2.1/lib/rack/handler/webrick.rb:13:in `run'
  /usr/lib/ruby/gems/1.8/gems/rack-1.2.1/lib/rack/server.rb:213:in `start'
  /usr/lib/ruby/gems/1.8/gems/railties-3.0.4/lib/rails/commands/server.rb:65:in `start'
  /usr/lib/ruby/gems/1.8/gems/railties-3.0.4/lib/rails/commands.rb:30
  /usr/lib/ruby/gems/1.8/gems/railties-3.0.4/lib/rails/commands.rb:27:in `tap'
  /usr/lib/ruby/gems/1.8/gems/railties-3.0.4/lib/rails/commands.rb:27
  script/rails:6:in `require'
  script/rails:6

Started POST "/posts" for 174.37.214.196 at Fri Mar 11 20:24:24 -0500 2011

NoMethodError (undefined method `rewind' for #<String:0xb701ace0>):

Rendered /usr/lib/ruby/gems/1.8/gems/actionpack-3.0.4/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (1.1ms)
</code>```

答: Two ideas: either your routing is configured differently, or there's "forgery protection" going on. Not exactly a rails expert here... :)</p>

Body:
Does anyone have any theories about this?

I have a feeling this is a Rails 3.x bug.

I'm using a service called mailgun that routes incoming e-mails to url's for further processing. Rails 3 chokes on these requests. Rails 2 does not.

I'm at a loss. I'm not sure exactly where the issue is.

Started POST "/posts/upload" for 174.37.214.195 at Fri Mar 11 20:22:41 -0500 2011
  SQL (0.1ms)  SET search_path TO public
  SQL (0.2ms)  SHOW client_min_messages
  SQL (0.1ms)  SET client_min_messages TO 'panic'
  SQL (0.1ms)  SET standard_conforming_strings = on
  SQL (0.1ms)  SET client_min_messages TO 'notice'
  SQL (0.4ms)  SET time zone 'UTC'
  SQL (0.1ms)  SHOW TIME ZONE

NoMethodError (undefined method `rewind' for #<String:0xb6d1c624>):

Rendered /usr/lib/ruby/gems/1.8/gems/actionpack-3.0.4/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (1.0ms)
Error during failsafe response: ActionView::Template::Error
  /usr/lib/ruby/gems/1.8/gems/activesupport-3.0.4/lib/active_support/whiny_nil.rb:48:in `method_missing'
  /usr/lib/ruby/gems/1.8/gems/actionpack-3.0.4/lib/action_dispatch/http/parameters.rb:10:in `parameters'
  /usr/lib/ruby/gems/1.8/gems/actionpack-3.0.4/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb:3:in `__usr_lib_ruby_gems_____gems_actionpack_______lib_action_dispatch_middleware_templates_rescues_diagnostics_erb___359554262__609638518_0'
  /usr/lib/ruby/gems/1.8/gems/actionpack-3.0.4/lib/action_view/template.rb:135:in `send'
  /usr/lib/ruby/gems/1.8/gems/actionpack-3.0.4/lib/action_view/template.rb:135:in `render'
  /usr/lib/ruby/gems/1.8/gems/activesupport-3.0.4/lib/active_support/notifications.rb:54:in `instrument'
  /usr/lib/ruby/gems/1.8/gems/actionpack-3.0.4/lib/action_view/template.rb:127:in `render'
  /usr/lib/ruby/gems/1.8/gems/actionpack-3.0.4/lib/action_view/render/rendering.rb:59:in `_render_template'
  /usr/lib/ruby/gems/1.8/gems/activesupport-3.0.4/lib/active_support/notifications.rb:52:in `instrument'
  /usr/lib/ruby/gems/1.8/gems/activesupport-3.0.4/lib/active_support/notifications/instrumenter.rb:21:in `instrument'
  /usr/lib/ruby/gems/1.8/gems/activesupport-3.0.4/lib/active_support/notifications.rb:52:in `instrument'
  /usr/lib/ruby/gems/1.8/gems/actionpack-3.0.4/lib/action_view/render/rendering.rb:56:in `_render_template'
  /usr/lib/ruby/gems/1.8/gems/actionpack-3.0.4/lib/action_view/render/rendering.rb:26:in `render_without_haml'
  /usr/lib/ruby/gems/1.8/gems/haml-3.0.25/lib/haml/helpers/action_view_mods.rb:13:in `render'
  /usr/lib/ruby/gems/1.8/gems/actionpack-3.0.4/lib/action_dispatch/middleware/show_exceptions.rb:88:in `rescue_action_locally'
  /usr/lib/ruby/gems/1.8/gems/actionpack-3.0.4/lib/action_dispatch/middleware/show_exceptions.rb:68:in `render_exception'
  /usr/lib/ruby/gems/1.8/gems/actionpack-3.0.4/lib/action_dispatch/middleware/show_exceptions.rb:59:in `call'
  /usr/lib/ruby/gems/1.8/gems/railties-3.0.4/lib/rails/rack/logger.rb:13:in `call'
  /usr/lib/ruby/gems/1.8/gems/rack-1.2.1/lib/rack/runtime.rb:17:in `call'
  /usr/lib/ruby/gems/1.8/gems/activesupport-3.0.4/lib/active_support/cache/strategy/local_cache.rb:72:in `call'
  /usr/lib/ruby/gems/1.8/gems/rack-1.2.1/lib/rack/lock.rb:11:in `call'
  /usr/lib/ruby/gems/1.8/gems/rack-1.2.1/lib/rack/lock.rb:11:in `synchronize'
  /usr/lib/ruby/gems/1.8/gems/rack-1.2.1/lib/rack/lock.rb:11:in `call'
  /usr/lib/ruby/gems/1.8/gems/actionpack-3.0.4/lib/action_dispatch/middleware/static.rb:30:in `call'
  /usr/lib/ruby/gems/1.8/gems/railties-3.0.4/lib/rails/application.rb:168:in `call'
  /usr/lib/ruby/gems/1.8/gems/railties-3.0.4/lib/rails/application.rb:77:in `send'
  /usr/lib/ruby/gems/1.8/gems/railties-3.0.4/lib/rails/application.rb:77:in `method_missing'
  /usr/lib/ruby/gems/1.8/gems/railties-3.0.4/lib/rails/rack/log_tailer.rb:14:in `call'
  /usr/lib/ruby/gems/1.8/gems/rack-1.2.1/lib/rack/content_length.rb:13:in `call'
  /usr/lib/ruby/gems/1.8/gems/rack-1.2.1/lib/rack/handler/webrick.rb:52:in `service'
  /usr/lib/ruby/1.8/webrick/httpserver.rb:104:in `service'
  /usr/lib/ruby/1.8/webrick/httpserver.rb:65:in `run'
  /usr/lib/ruby/1.8/webrick/server.rb:173:in `start_thread'
  /usr/lib/ruby/1.8/webrick/server.rb:162:in `start'
  /usr/lib/ruby/1.8/webrick/server.rb:162:in `start_thread'
  /usr/lib/ruby/1.8/webrick/server.rb:95:in `start'
  /usr/lib/ruby/1.8/webrick/server.rb:92:in `each'
  /usr/lib/ruby/1.8/webrick/server.rb:92:in `start'
  /usr/lib/ruby/1.8/webrick/server.rb:23:in `start'
  /usr/lib/ruby/1.8/webrick/server.rb:82:in `start'
  /usr/lib/ruby/gems/1.8/gems/rack-1.2.1/lib/rack/handler/webrick.rb:13:in `run'
  /usr/lib/ruby/gems/1.8/gems/rack-1.2.1/lib/rack/server.rb:213:in `start'
  /usr/lib/ruby/gems/1.8/gems/railties-3.0.4/lib/rails/commands/server.rb:65:in `start'
  /usr/lib/ruby/gems/1.8/gems/railties-3.0.4/lib/rails/commands.rb:30
  /usr/lib/ruby/gems/1.8/gems/railties-3.0.4/lib/rails/commands.rb:27:in `tap'
  /usr/lib/ruby/gems/1.8/gems/railties-3.0.4/lib/rails/commands.rb:27
  script/rails:6:in `require'
  script/rails:6

Started POST "/posts" for 174.37.214.196 at Fri Mar 11 20:24:24 -0500 2011

NoMethodError (undefined method `rewind' for #<String:0xb701ace0>):

Rendered /usr/lib/ruby/gems/1.8/gems/actionpack-3.0.4/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (1.1ms)


问:
Only Keep last 4 or 5 images on ECR
Hello guys as we all know that there's a limit on storing images on ECR and that's why we want to keep only last 4 or 5 images on ECR.
Any leads would be appreciated.</p>

答:
You can use ECR Lifecycle Policies to delete all but the last 4 images with the following policy:</p>

```<code>{
    "rules": [
        {
            "rulePriority": 1,
            "description": "Rule 1",
            "selection": {
                "tagStatus": "any",
                "countType": "imageCountMoreThan",
                "countNumber": 4
            },
            "action": {
                "type": "expire"
            }
        }
    ]
}

</code>```

ContentLicense: CC BY-SA 4.0

Title: Only Keep last 4 or 5 images on ECR

Body:
You can use ECR Lifecycle Policies to delete all but the last 4 images with the following policy:

{
    "rules": [
        {
            "rulePriority": 1,
            "description": "Rule 1",
            "selection": {
                "tagStatus": "any",
                "countType": "imageCountMoreThan",
                "countNumber": 4
            },
            "action": {
                "type": "expire"
            }
        }
    ]
}


问:
ActivityInfo.loadIcon causes OutOfMemoryError if an app icon is a HD
I came through this problem and looking for your input on the best approach on how to solve/avoid it & to bring other developers attention to it.

I'm using this code to fetch the installed apps data (label, icon, etc.). Everything was OK until I found my app using a lot of memory for no clear reason in my code.

```<code>    List<ResolveInfo> availableActivities = getPackageManager().queryIntentActivities(intent, 0);
    for(ResolveInfo ri : availableActivities){
        AppDetail appDetail = new AppDetail();

        appDetail.mAppIcon = ri.activityInfo.loadIcon(getApplicationContext().getPackageManager());
     }
</code>```

答: It turns out that I installed a new app which has a 3000*3000 dimension as an app icon (Really bad practice from the app developer), which increases the memory usage by 47MB. Which affected my app performance especially GridView scrolling.</p>

Body:
I came through this problem and looking for your input on the best approach on how to solve/avoid it & to bring other developers attention to it.

I'm using this code to fetch the installed apps data (label, icon, etc.). Everything was OK until I found my app using a lot of memory for no clear reason in my code.

    List<ResolveInfo> availableActivities = getPackageManager().queryIntentActivities(intent, 0);
    for(ResolveInfo ri : availableActivities){
        AppDetail appDetail = new AppDetail();

        appDetail.mAppIcon = ri.activityInfo.loadIcon(getApplicationContext().getPackageManager());
     }


问:
Spring Data JPA - Named query ignoring null parameters
I have the following repository:

```<code>@Repository
public interface EntityRepository extends JpaRepository<Entity, Long> {

    List<Entity> findAllByFirstId(Long firstId);
    List<Entity> findAllBySecondId(Long secondId);
    List<Entity> findAllByFirstIdAndSecondId(Long firstId, Long secondId);
}
</code>```

The constructor implementing an interface generated with io.swagger:swagger-codegen-maven-plugin uses Optional<Long> as optional request parameters (the underlying service uses also the same parameters):

```<code>ResponseEntity<List<Entity>> entities(Optional<Long> firstId, Optional<Long> secondId);
</code>```

I would like to filter the entities based on the parameters firstId and secondId which are never nulls at the database but can be passed through the constructor (the parameter for searching is optional).

The problem comes with the named queries when the null is passed as the parameter is optional, the JpaReposotory uses the null as a criterion for the searching in the database. That's what I don't want - I want to ignore the filtering based on this parameter as long as it is null.

My workaround solution based on Optional is:

```<code>public List<Entity> entities(Optional<Long> firstId, Optional<Long> secondId) {

    return firstId
        .or(() -> secondId)
        .map(value -> {
            if (firstId.isEmpty()) {
                return entityRepository.findAllBySecondId(value);
            }
            if (secondId.isEmpty()) {
                return entityRepository.findAllByFirstId(value);
            }
            return entityRepository.findAllByFirstIdAndSecondId(
            firstId.get(), secondId.get());
        })
        .orElse(entityRepository.findAll())
        .stream()
        .map(...)     // Mapping between DTO and entity. For sake of brevity
                      // I used the same onject Entity for both controler and repository
                      // as long as it not related to the question

        .collect(Collectors.toList());
}
</code>```

This issue has been already asked: Spring Data - ignore parameter if it has a null value and a ticket created DATAJPA-209.

As long as the question is almost 3 years old and the ticket dates back to 2012, I would like to ask if there exists a more comfortable and universal way to avoid the overhead of handling the Optional and duplicating the repository methods. The solution for 2 such parameters looks acceptable, however I'd like to implement the very same filtering for 4-5 parameters.

答:
I'd suggest you to use specifications instead. See documentation and examples here.

Briefly, the idea is following. For each attribute you define a specification. Then check each attribute in your search criteria and if it is not null add corresponding specification to the "concatenated" specification. Then you search using this "concatenated" specification.

Body:
I have the following repository:

@Repository
public interface EntityRepository extends JpaRepository<Entity, Long> {

    List<Entity> findAllByFirstId(Long firstId);
    List<Entity> findAllBySecondId(Long secondId);
    List<Entity> findAllByFirstIdAndSecondId(Long firstId, Long secondId);
}

The constructor implementing an interface generated with io.swagger:swagger-codegen-maven-plugin uses Optional<Long> as optional request parameters (the underlying service uses also the same parameters):

ResponseEntity<List<Entity>> entities(Optional<Long> firstId, Optional<Long> secondId);

I would like to filter the entities based on the parameters firstId and secondId which are never nulls at the database but can be passed through the constructor (the parameter for searching is optional).

The problem comes with the named queries when the null is passed as the parameter is optional, the JpaReposotory uses the null as a criterion for the searching in the database. That's what I don't want - I want to ignore the filtering based on this parameter as long as it is null.

My workaround solution based on Optional is:

public List<Entity> entities(Optional<Long> firstId, Optional<Long> secondId) {

    return firstId
        .or(() -> secondId)
        .map(value -> {
            if (firstId.isEmpty()) {
                return entityRepository.findAllBySecondId(value);
            }
            if (secondId.isEmpty()) {
                return entityRepository.findAllByFirstId(value);
            }
            return entityRepository.findAllByFirstIdAndSecondId(
            firstId.get(), secondId.get());
        })
        .orElse(entityRepository.findAll())
        .stream()
        .map(...)     // Mapping between DTO and entity. For sake of brevity
                      // I used the same onject Entity for both controler and repository
                      // as long as it not related to the question

        .collect(Collectors.toList());
}

This issue has been already asked: Spring Data - ignore parameter if it has a null value and a ticket created DATAJPA-209.

As long as the question is almost 3 years old and the ticket dates back to 2012, I would like to ask if there exists a more comfortable and universal way to avoid the overhead of handling the Optional and duplicating the repository methods. The solution for 2 such parameters looks acceptable, however I'd like to implement the very same filtering for 4-5 parameters.


问:
Getting a contact by email using the sendgrid api
I'm trying to retrieve contact  id by email using the sendgrid 'Contacts API'. It looks like the way to do this is to POST to the /marketing/contacts/search endpoint.

I'm not familiar with SQL, does anybody know how I'd query the email field as explained here:
https://sendgrid.api-docs.io/v3.0/contacts/search-contacts

答:
on the link that you  provide there is a tab that is called "try it out" click there and you can try it out. Just add your Api token and there is already a query that you just need to add the email address

```<code>    {
        "query": "email LIKE 'ENTER_COMPLETE_OR_PARTIAL_EMAIL_ADDRESS_HERE'"
    }
</code>```

if you are adding a partial email address just add % before or/and after (depending which side is missing info)

Body:
on the link that you  provide there is a tab that is called "try it out" click there and you can try it out. Just add your Api token and there is already a query that you just need to add the email address

    {
        "query": "email LIKE 'ENTER_COMPLETE_OR_PARTIAL_EMAIL_ADDRESS_HERE'"
    }

if you are adding a partial email address just add % before or/and after (depending which side is missing info)


问:
identifying large circle like white color in an image using python
I need suggestion with this two image.

Image A

Image B

I'm trying to identify if an image has an optic nerve glioma.

Image A represents that there is no abnormality, it has a smaller circle like white color on the image. while Image B has a larger one which has the optic nerve glioma. basically what I want to do is identify if the image has a larger circle white color compare to the standard basis which is the Image A

Any suggestion is a big help. Thanks guys!

答:
I would suggest using something like Google Cloud Vision or Azure image detection or some other off the shelf service that does all the heavy lifting.

For example, here is with Azure where you can get the bounding rectangles of various shapes/objects in your image: https://learn.microsoft.com/en-us/azure/cognitive-services/computer-vision/concept-object-detection. From that I would see -- if all image sizes are standardized and the same -- the area of the bounding rectangle in the inner circle can give you a confidence score on whether the optic nerve glioma exists or not.


问:
Idempotence Key in Node.js API
I have a REST API endpoint in node.js that handles monetary transactions. I want to implement something similar to stripe's idempotence key to ensure that the same transaction isn't carried out twice in the event of a network failure.
How can I implement something like that in Node.js?</p>

答:
You will want each client transaction to generate a UID that it sends with the request.  Then, if the client got in any sort of retry scenario, as long as it stays with the same UID, you server could detect a request that was a duplicate of what it had already seen.

There are tons of ways to generate this type of UID.  You could literally just stringify the Date.now() time and then add a random set of digits from Math.random() onto the end.  That gives you time element plus a random element which gives you a good unique token string.

There are also some standards around these types of UID strings.  You can read the various answers here: Create GUID / UUID in JavaScript? for both some libraries and some create your own solutions that follow RFC 4122.

Then, your server needs to keep track of a set of incoming UID tokens so it can detect if a request arrives for a token that has already been processed.

Title: Idempotence Key in Node.js API


问:
What's the use of abstract syntax trees?
I am learning on my own about writing an interpreter for a programming language, and I have read about Abstract Syntax Trees. I have an idea of what they are, but I do not see their use.

Why are ASTs useful?

答:
Late to the question but I thought I'd add something. You don't actually have to build an AST. It is possible to emit instructions directly as you parse the source code. In this case, the AST is implied in the parsing grammar. For simple languages, especially dynamically typed languages, this is a perfectly ok strategy. For more complex languages or where you need to further analyze the source code, an AST can be very useful. For example, if your language is statically typed, ie your variables are declared with fixed types then the AST can be used to check that you're not assigning the wrong type to a variable. eg assigning a string to a variable that is declared to hold an integer would be wrong and this can be caught more conveniently with the AST. </p>

<p>Also, as others have mentioned, the AST offers a clean separation between syntax analysis and code generation and makes the code much more modular. </p>

LastEditorDisplayName: Roger Pate

Body:
Late to the question but I thought I'd add something. You don't actually have to build an AST. It is possible to emit instructions directly as you parse the source code. In this case, the AST is implied in the parsing grammar. For simple languages, especially dynamically typed languages, this is a perfectly ok strategy. For more complex languages or where you need to further analyze the source code, an AST can be very useful. For example, if your language is statically typed, ie your variables are declared with fixed types then the AST can be used to check that you're not assigning the wrong type to a variable. eg assigning a string to a variable that is declared to hold an integer would be wrong and this can be caught more conveniently with the AST.

Also, as others have mentioned, the AST offers a clean separation between syntax analysis and code generation and makes the code much more modular.


问:
MySQL LIKE on Subquery
I am writing a query where I am trying to pull out values based on a portion of a subquery and can't seem to work out how to get the needed values.

The table has only a half-dozen entries containing author names but in some instances, there is more than one author in the field and I need to get their separate individual biographies. Right now this gives no errors but it is pulling up only the single entry that contains both author names rather than the two that contain the actual biographies. I need only the two single-name entries, not the one containing both but it's giving the opposite.

AuthorName has something like this:

```<code>Joe Blow
Jane Doe
Jow Blow and Jane Doe
</code>```

and here is the query

```<code>SELECT a.`ID` AS AuthorID, `AuthorName`, `AuthorPhoto`, `AuthorBio`, `Email`,
FROM authorbiographies a
WHERE `AuthorName` LIKE CONCAT('%',(
SELECT `AuthorName` )
FROM authorbiographies WHERE `AuthorName` LIKE '% and %),'%'
)
AND `ID` <> 3
</code>```

答:
This can be solved by joining a derived tables of all authornames that don't include and with a derived table of all authornames that do include and, as long as the first authorname is part of the second:

```<code>SELECT a1.id, a1.authorname, a1.authorbio
FROM (SELECT *
      FROM authorbiographies
      WHERE authorname NOT LIKE '% and %'
      ) a1
JOIN (SELECT *
      FROM authorbiographies
      WHERE authorname like '% and %'
      ) a2 on a2.authorname LIKE concat('%', a1.authorname, '%')
</code>```

Output (for your sample)

```<code>id  authorname  authorbio
1   Joe Blow    has lived a long time
2   Jane Doe    wrote several books
</code>```

Demo on SQLFiddle

Title: MySQL LIKE on Subquery

Body:
I am writing a query where I am trying to pull out values based on a portion of a subquery and can't seem to work out how to get the needed values.

The table has only a half-dozen entries containing author names but in some instances, there is more than one author in the field and I need to get their separate individual biographies. Right now this gives no errors but it is pulling up only the single entry that contains both author names rather than the two that contain the actual biographies. I need only the two single-name entries, not the one containing both but it's giving the opposite.

AuthorName has something like this:

Joe Blow
Jane Doe
Jow Blow and Jane Doe

and here is the query

SELECT a.`ID` AS AuthorID, `AuthorName`, `AuthorPhoto`, `AuthorBio`, `Email`,
FROM authorbiographies a
WHERE `AuthorName` LIKE CONCAT('%',(
SELECT `AuthorName` )
FROM authorbiographies WHERE `AuthorName` LIKE '% and %),'%'
)
AND `ID` <> 3

Body:
This can be solved by joining a derived tables of all authornames that don't include and with a derived table of all authornames that do include and, as long as the first authorname is part of the second:

SELECT a1.id, a1.authorname, a1.authorbio
FROM (SELECT *
      FROM authorbiographies
      WHERE authorname NOT LIKE '% and %'
      ) a1
JOIN (SELECT *
      FROM authorbiographies
      WHERE authorname like '% and %'
      ) a2 on a2.authorname LIKE concat('%', a1.authorname, '%')

Output (for your sample)

id  authorname  authorbio
1   Joe Blow    has lived a long time
2   Jane Doe    wrote several books

Demo on SQLFiddle


问:
TypeERROR after yarn upgrade (ReactJS project)
I ran the command yarn upgrade and then I got this error next time I did yarn start, and I have no idea why? Hoping someone can tell me whats going on here? No idea what to do to solve it. Tried googling it, without much luck as to what is wrong. </p>

```<code>TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined
at validateString (internal/validators.js:113:11)
at Object.join (path.js:375:7)
at noopServiceWorkerMiddleware (C:\Users\perni\Projects\prime\node_modules\react-dev-utils\noopServiceWorkerMiddleware.js:14:26)
at Layer.handle [as handle_request] (C:\Users\perni\Projects\prime\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (C:\Users\perni\Projects\prime\node_modules\express\lib\router\index.js:317:13)
at C:\Users\perni\Projects\prime\node_modules\express\lib\router\index.js:284:7
at Function.process_params (C:\Users\perni\Projects\prime\node_modules\express\lib\router\index.js:335:12)
at next (C:\Users\perni\Projects\prime\node_modules\express\lib\router\index.js:275:10)
at launchEditorMiddleware (C:\Users\perni\Projects\prime\node_modules\react-dev-utils\errorOverlayMiddleware.js:20:7)
at Layer.handle [as handle_request] (C:\Users\perni\Projects\prime\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (C:\Users\perni\Projects\prime\node_modules\express\lib\router\index.js:317:13)
at C:\Users\perni\Projects\prime\node_modules\express\lib\router\index.js:284:7
at Function.process_params (C:\Users\perni\Projects\prime\node_modules\express\lib\router\index.js:335:12)
at next (C:\Users\perni\Projects\prime\node_modules\express\lib\router\index.js:275:10)
at handleWebpackInternalMiddleware (C:\Users\perni\Projects\prime\node_modules\react-dev-utils\evalSourceMapMiddleware.js:42:7)
at Layer.handle [as handle_request] (C:\Users\perni\Projects\prime\node_modules\express\lib\router\layer.js:95:5)
</code>```

答:
Try running yarn cache list to print out your cached packages, then you can compare with the version in your package.json to make sure they match.
If you still get errors, run yarn cache clean to clear your entire cache and run yarn install to repopulate them.

Body:
I ran the command yarn upgrade and then I got this error next time I did yarn start, and I have no idea why? Hoping someone can tell me whats going on here? No idea what to do to solve it. Tried googling it, without much luck as to what is wrong.

TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined
at validateString (internal/validators.js:113:11)
at Object.join (path.js:375:7)
at noopServiceWorkerMiddleware (C:\Users\perni\Projects\prime\node_modules\react-dev-utils\noopServiceWorkerMiddleware.js:14:26)
at Layer.handle [as handle_request] (C:\Users\perni\Projects\prime\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (C:\Users\perni\Projects\prime\node_modules\express\lib\router\index.js:317:13)
at C:\Users\perni\Projects\prime\node_modules\express\lib\router\index.js:284:7
at Function.process_params (C:\Users\perni\Projects\prime\node_modules\express\lib\router\index.js:335:12)
at next (C:\Users\perni\Projects\prime\node_modules\express\lib\router\index.js:275:10)
at launchEditorMiddleware (C:\Users\perni\Projects\prime\node_modules\react-dev-utils\errorOverlayMiddleware.js:20:7)
at Layer.handle [as handle_request] (C:\Users\perni\Projects\prime\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (C:\Users\perni\Projects\prime\node_modules\express\lib\router\index.js:317:13)
at C:\Users\perni\Projects\prime\node_modules\express\lib\router\index.js:284:7
at Function.process_params (C:\Users\perni\Projects\prime\node_modules\express\lib\router\index.js:335:12)
at next (C:\Users\perni\Projects\prime\node_modules\express\lib\router\index.js:275:10)
at handleWebpackInternalMiddleware (C:\Users\perni\Projects\prime\node_modules\react-dev-utils\evalSourceMapMiddleware.js:42:7)
at Layer.handle [as handle_request] (C:\Users\perni\Projects\prime\node_modules\express\lib\router\layer.js:95:5)


问:
Is there a way to use ROI (Region of Interest) through a Rapsberry Pi in Code?
I'm looking to take images using my raspberry pi v2 camera module and extract a specific part of those using ROI.

```<code>-roi 0.5,0.5,0.25,0.25
</code>```

However, ROI seems to only be a flag for taking still images through the command line, is there any way to use ROI with the 'camera' module in code?.

such as...

```<code>camera.resolution = (2592, 1944)
camera.framerate = 15
#does this next line exist somewhere?
camera.roi = (0.5,0.5,0.25,0.25)
</code>```

Any help would be much appreciated!

答:
I found the PIL Library has a function .crop()
that did exactly what I needed. Link here
PIL Link</p>

Body:
I'm looking to take images using my raspberry pi v2 camera module and extract a specific part of those using ROI.

-roi 0.5,0.5,0.25,0.25

However, ROI seems to only be a flag for taking still images through the command line, is there any way to use ROI with the 'camera' module in code?.

such as...

camera.resolution = (2592, 1944)
camera.framerate = 15
#does this next line exist somewhere?
camera.roi = (0.5,0.5,0.25,0.25)

Any help would be much appreciated!


问:
Ant task to determine if a file is readonly
I need to write an ant task to determine if a certain file is readonly, and if it is, fail.  I would like to avoid using a custom selector to do this do to the nature of our build system.  Anyone have any ideas how to go about doing this? I'm using ant 1.8 + ant-contrib.

Thanks!

答:
Will something like this do the trick?

```<code><condition property="file.is.readonly">
  <not>
    <isfileselected file="${the.file.in.question}">
      <writable />
    </isfileselected>
  </not>
</condition>
<fail if="file.is.readonly" message="${the.file.in.question} is not writeable" />
</code>```

This uses the condition task and the isfileselected condition (not a direct link - you'll have to search down the page) combined with the writable selector (and reversed with a not condition).

Update:

An possibly better alternative would be:

```<code><fail message="${the.file.in.question} is not writeable">
  <condition>
    <not>
      <isfileselected file="${the.file.in.question}">
        <writable />
      </isfileselected>
    </not>
  </condition>
</fail>
</code>```

This has the check and the fail as one distinct action rather than two, so you may find it clearer, and it doesn't require using a property name, so your namespace is cleaner.

Body:
Will something like this do the trick?

<condition property="file.is.readonly">
  <not>
    <isfileselected file="${the.file.in.question}">
      <writable />
    </isfileselected>
  </not>
</condition>
<fail if="file.is.readonly" message="${the.file.in.question} is not writeable" />

This uses the condition task and the isfileselected condition (not a direct link - you'll have to search down the page) combined with the writable selector (and reversed with a not condition).

Update:

An possibly better alternative would be:

<fail message="${the.file.in.question} is not writeable">
  <condition>
    <not>
      <isfileselected file="${the.file.in.question}">
        <writable />
      </isfileselected>
    </not>
  </condition>
</fail>

This has the check and the fail as one distinct action rather than two, so you may find it clearer, and it doesn't require using a property name, so your namespace is cleaner.


问:
Superset useage an/or log in through docker
I have tried to install the Apache Superset tool as directed in the official documentation, but have encountered all sorts of problems.

I decided to go instead through a docker pull and pulled the amancevice/superset image from the Docker Hub and all went well, but now when I start the container and get the Superset landing page it asks me to log in and I don't see any way to know what is the password for the Admin user or the superset user or any other user. Nor I see any way to create a user and password in the containers itself.

答:
You are missing execution of superset-init to setup the credentials.

You might like to try below steps:

```<code># pull docker image
docker pull amancevice/superset

# setup configuration directory
mkdir -p ~/superset/conf & mkdir -p ~/superset/data

# run image (user `0` is root user)
docker run --name superset -u 0 -d -p 8088:8088 -v ~/superset/conf:/etc/superset -v ~/superset/data:/var/lib/superset amancevice/superset

# setup credentials (such as admin/admin)
docker exec -it superset superset-init
</code>```

Then, access the service at http://localhost:8088/

```<code># load examples
docker exec -it superset superset load_examples
</code>```

Body:
You are missing execution of superset-init to setup the credentials.

You might like to try below steps:

# pull docker image
docker pull amancevice/superset

# setup configuration directory
mkdir -p ~/superset/conf & mkdir -p ~/superset/data

# run image (user `0` is root user)
docker run --name superset -u 0 -d -p 8088:8088 -v ~/superset/conf:/etc/superset -v ~/superset/data:/var/lib/superset amancevice/superset

# setup credentials (such as admin/admin)
docker exec -it superset superset-init

Then, access the service at http://localhost:8088/

# load examples
docker exec -it superset superset load_examples


问:
Ignoring commas in string literals while reading in .csv file without using any outside libraries
I am trying to read in a .csv file that has a line that looks something like this:

"Red","Apple, Tomato".

I want to read that line into a dictionary, using "Red" as the key and "Apple, Tomato" as the definition. I also want to do this without using any libraries or modules that need to be imported.

The issue I am facing is that it is trying to split that line into 3 separate pieces because there is a comma between "Apple" and "Tomato" that the code is splitting on. This is what I have right now:

```<code>file_folder = sys.argv[1]
file_path = open(file_folder+ "/food_colors.csv", "r")

food_dict = {}
for line in file_path:
    (color, description) = line.rstrip().split(',')
    print(f"{color}, {description}")
</code>```

But this gives me an error because it has 3 pieces of data, but I am only giving it 2 variables to store the info in. How can I make this ignore the comma inside the string literal?

答:
You can collect the remaining strings into a list, like so

```<code>color, *description = line.rstrip().split(',')
</code>```

You can then join the description strings back together to make the value for your dict

Another way

```<code>color, description = line.rstrip().split(',', 1)
</code>```

Would mean you only perform the split operation once and the rest of the string remains unsplit.

Body:
I am trying to read in a .csv file that has a line that looks something like this:

"Red","Apple, Tomato".

I want to read that line into a dictionary, using "Red" as the key and "Apple, Tomato" as the definition. I also want to do this without using any libraries or modules that need to be imported.

The issue I am facing is that it is trying to split that line into 3 separate pieces because there is a comma between "Apple" and "Tomato" that the code is splitting on. This is what I have right now:

file_folder = sys.argv[1]
file_path = open(file_folder+ "/food_colors.csv", "r")

food_dict = {}
for line in file_path:
    (color, description) = line.rstrip().split(',')
    print(f"{color}, {description}")

But this gives me an error because it has 3 pieces of data, but I am only giving it 2 variables to store the info in. How can I make this ignore the comma inside the string literal?

Body:
You can collect the remaining strings into a list, like so

color, *description = line.rstrip().split(',')

You can then join the description strings back together to make the value for your dict

Another way

color, description = line.rstrip().split(',', 1)

Would mean you only perform the split operation once and the rest of the string remains unsplit.


问:
How do you set an 'active' class in React and CSS?
I have navigation in my React app. However I would like the colour of navigation to change if on that page.

Heres my code Ive added an active className to the items.

```<code>        <Link to='/'>
          <li className='menu-list-item menu-list-logo   active'>Gatsby's</li>
        </Link>
        <Link to='/drink'>
          <li className='menu-list-item active'>Drink</li>
        </Link>
        <Link to='/food'>
          <li className='menu-list-item active'>Food</li>
        </Link>
        <Link to='contact'>
          <li className='menu-list-item active'>Contact</li>
        </Link>
</code>```

The navigation links currently have a background of black. I want the colour to change to lets say red.
P.S I'm using standard CSS for styles.

答:
Light/Fast way to do this would be to change the class at the parent DOM element of these <Link> elements... from there the CSS would do what it works best.

Assuming these <Link> ... </Link> tags are enclosed inside a  ...  tag, which is the parent DOM element.

```<code>{ (onThePage) ? <nav className="onThePageClass"> ... </nav> : <nav className="normalClass"> ... </nav> }
</code>```

Try this else share MVCE if you get stuck so that it serves as a good example for others looking for help

Body:
I have navigation in my React app. However I would like the colour of navigation to change if on that page.

Heres my code Ive added an active className to the items.

        <Link to='/'>

Gatsby's

        </Link>
        <Link to='/drink'>

Drink

        </Link>
        <Link to='/food'>

Food

        </Link>
        <Link to='contact'>

Contact

        </Link>

The navigation links currently have a background of black. I want the colour to change to lets say red.
P.S I'm using standard CSS for styles.

Body:
Light/Fast way to do this would be to change the class at the parent DOM element of these <Link> elements... from there the CSS would do what it works best.

Assuming these <Link> ... </Link> tags are enclosed inside a <nav> ... </nav> tag, which is the parent DOM element.

{ (onThePage) ? <nav className="onThePageClass"> ... </nav> : <nav className="normalClass"> ... </nav> }

Try this else share MVCE if you get stuck so that it serves as a good example for others looking for help


答:
You can use pandas package and use pandas.DataFrame.read_csv.

For example, this works:

```<code>from io import StringIO
import pandas as pd

TESTDATA = StringIO('"Red","Apple, Tomato"')

df = pd.read_csv(TESTDATA, sep=",", header=None)

print(df)
</code>```

Title: Ignoring commas in string literals while reading in .csv file without using any outside libraries

Body:
You can use pandas package and use pandas.DataFrame.read_csv.

For example, this works:

from io import StringIO
import pandas as pd

TESTDATA = StringIO('"Red","Apple, Tomato"')

df = pd.read_csv(TESTDATA, sep=",", header=None)

print(df)


问:
Discord Bot using python sending multiple responses to one command
I'm coding a bot in python for discord using atom and whenever I run a command on my bot (including help) it sends multiple responses to the command, not all of the responses are the same (e.g: s?ping it will answer multiple times with different ping). I think the amount it sends is random and i'm not sure what's wrong with it at all, i've heard that looping does this but i only have one loop and that's to change the status. This is my code (without the token):

import discord
import random
import os
from itertools import cycle
from discord.ext import commands, tasks

client = commands.Bot(command_prefix = 's?')
status = cycle(['s? // Senkuu by Rubix', 's?help - Made by Rubix#8166', 's? // Alpha v0.11.2, Made in Python (discord.py/atom)'])

@client.event
async def on_ready():
    change_status.start()
    print( 'Bot is ready. ')

@tasks.loop(seconds=20)
async def change_status ():
    await client.change_presence(activity=discord.Game(next(status)))

@client.command()
async def ping(ctx):
    await ctx.send(f'Pong! {round(client.latency * 1000)} ms')

@client.event
async def on_command_error(ctx, error):
    if isinstance(error,commands.MissingRequiredArgument):
        await ctx.send('Missing Requirements in Command, Try Again.')

@client.command(aliases=['8ball'])
async def _8ball(ctx, *, question):
    responses = ["It is certain.",
    "It is decidedly so.",
    "Without a doubt.",
    "Yes - definitely.",
    "You may rely on it.",
    "As I see it, yes.",
    "Most likely.",
    "Outlook good.",
    "Yes.",
    "Signs point to yes.",
    "Reply hazy, try again.",
    "Ask again later.",
    "Better not tell you now.",
    "Cannot predict now.",
    "Concentrate and ask again.",
    "Don't count on it.",
    "My reply is no.",
    "My sources say no.",
    "Outlook not so good.",
    "Very doubtful."]
    await ctx.send(f'Question: {question}\nAnswer; {random.choice(responses)}')

@client.command()
@commands.has_role('Moderator [Staff]')
async def purge(ctx, amount : int):
    await ctx.channel.purge(limit=amount)

@client.command()
@commands.has_role('Moderator [Staff]')
async def ban(ctx, member : discord.Member, *, reason=None):
    await member.ban(reason=reason)
    await ctx.send(f'Banned {member.mention}')

@client.command(pass_context=True)
@commands.has_permissions(kick_members=True)
async def kick(self, ctx, user: discord.User, *, reason):
    server = ctx.message.server
    mention = user.mention
    id = user.id
    author = str(ctx.message.author)
    x = discord.utils.get(server.channels, name="criminal-records")
    kick_message = "**Type: Kick**\n**User:** " + user.name + "#" + user.discriminator +"(" + id + ")" \
                    + "(" + mention+")\n" \
            "**Reason:** " + reason +"\n" \
            "**Responsible Moderator: **" + author
    await self.bot.kick(user)
    await self.bot.send_message(x, kick_message)

@client.command()
@commands.has_role('Moderator [Staff]')
async def unban(ctx, *, member):
    banned_users = await ctx.guild.bans()
    member_name, member_discriminator = member.split('#')

    for ban_entry in banned_users:
        user = ban_entry.user

        if (user.name, user.discriminator) == (member_name, member_discriminator):
            await ctx.guild.unban(user)
            await ctx.send(f'Unbanned {user.mention}')
            return

@client.command()
async def load(ctx, extension):
    client.load_extension(f'cogs. {extension}')

@client.command()
async def unload(ctx, extension):
    client.unload_extension(f'cogs. {extension}')

for filename in os.listdir('./cogs'):
    if filename.endswith('.py'):
        client.load_extension(f'cogs.{filename[:-3]}')```
</code>```

This is what it's doing: https://i.stack.imgur.com/9Cisk.png

答: I don't see any reason for it to loop the way it did. Do you have any pong commands in any of your cogs at all? I've corrected your indentation and run it no problem not experiencing the same issue. </p>

Body:
I'm coding a bot in python for discord using atom and whenever I run a command on my bot (including help) it sends multiple responses to the command, not all of the responses are the same (e.g: s?ping it will answer multiple times with different ping). I think the amount it sends is random and i'm not sure what's wrong with it at all, i've heard that looping does this but i only have one loop and that's to change the status. This is my code (without the token):

import discord
import random
import os
from itertools import cycle
from discord.ext import commands, tasks

client = commands.Bot(command_prefix = 's?')
status = cycle(['s? // Senkuu by Rubix', 's?help - Made by Rubix#8166', 's? // Alpha v0.11.2, Made in Python (discord.py/atom)'])

@client.event
async def on_ready():
    change_status.start()
    print( 'Bot is ready. ')

@tasks.loop(seconds=20)
async def change_status ():
    await client.change_presence(activity=discord.Game(next(status)))

@client.command()
async def ping(ctx):
    await ctx.send(f'Pong! {round(client.latency * 1000)} ms')

@client.event
async def on_command_error(ctx, error):
    if isinstance(error,commands.MissingRequiredArgument):
        await ctx.send('Missing Requirements in Command, Try Again.')

@client.command(aliases=['8ball'])
async def _8ball(ctx, *, question):
    responses = ["It is certain.",
    "It is decidedly so.",
    "Without a doubt.",
    "Yes - definitely.",
    "You may rely on it.",
    "As I see it, yes.",
    "Most likely.",
    "Outlook good.",
    "Yes.",
    "Signs point to yes.",
    "Reply hazy, try again.",
    "Ask again later.",
    "Better not tell you now.",
    "Cannot predict now.",
    "Concentrate and ask again.",
    "Don't count on it.",
    "My reply is no.",
    "My sources say no.",
    "Outlook not so good.",
    "Very doubtful."]
    await ctx.send(f'Question: {question}\nAnswer; {random.choice(responses)}')

@client.command()
@commands.has_role('Moderator [Staff]')
async def purge(ctx, amount : int):
    await ctx.channel.purge(limit=amount)

@client.command()
@commands.has_role('Moderator [Staff]')
async def ban(ctx, member : discord.Member, *, reason=None):
    await member.ban(reason=reason)
    await ctx.send(f'Banned {member.mention}')

@client.command(pass_context=True)
@commands.has_permissions(kick_members=True)
async def kick(self, ctx, user: discord.User, *, reason):
    server = ctx.message.server
    mention = user.mention
    id = user.id
    author = str(ctx.message.author)
    x = discord.utils.get(server.channels, name="criminal-records")
    kick_message = "**Type: Kick**\n**User:** " + user.name + "#" + user.discriminator +"(" + id + ")" \
                    + "(" + mention+")\n" \
            "**Reason:** " + reason +"\n" \
            "**Responsible Moderator: **" + author
    await self.bot.kick(user)
    await self.bot.send_message(x, kick_message)

@client.command()
@commands.has_role('Moderator [Staff]')
async def unban(ctx, *, member):
    banned_users = await ctx.guild.bans()
    member_name, member_discriminator = member.split('#')

    for ban_entry in banned_users:
        user = ban_entry.user

        if (user.name, user.discriminator) == (member_name, member_discriminator):
            await ctx.guild.unban(user)
            await ctx.send(f'Unbanned {user.mention}')
            return

@client.command()
async def load(ctx, extension):
    client.load_extension(f'cogs. {extension}')

@client.command()
async def unload(ctx, extension):
    client.unload_extension(f'cogs. {extension}')

for filename in os.listdir('./cogs'):
    if filename.endswith('.py'):
        client.load_extension(f'cogs.{filename[:-3]}')```

This is what it's doing: https://i.stack.imgur.com/9Cisk.png


问:
Get length of an array in golang and store it in a const
I used the go playground to try this code:

```<code>package main

func main() {
    exp := []string{"HELLO"}

    const length = len(exp)
}
</code>```

But it is throwing me this error:

./prog.go:6:8: const initializer len(exp) is not a constant

I can see that this is happening because the length of exp is changeable. How can i get the current length and store it in an integer constant?

I would think that I need the reflect module to do this, but I don't know how to do it. I tried using reflect.ValueOf but it did not work.

```<code>exp := []string{"HELLO"}
const length = len(reflect.ValueOf(exp).Interface().([]string))
</code>```

答:
You can indeed get the current length, but that is by definition not a constant.  Here is what the language specification has to say about this:

The expression len(s) is constant if s is a string constant. The expressions len(s) and cap(s) are constants if the type of s is an array or pointer to an array and the expression s does not contain channel receives or (non-constant) function calls; in this case s is not evaluated. Otherwise, invocations of len and cap are not constant and s is evaluated.

Since your invocation of len is as len(exp) we must test exp against the text above:

Is it a string constant?  No; it is a slice.

Is it an array?  No; it is a slice.

Is it a pointer to an array?  No, it is a slice.

The three cases where len would produce a constant have been exhausted, so len must necessarily produce a non-constant.

If you would like len to produce a constant, you will have to apply it to a string constant, or an array, or a pointer to an array.  Arrays are similar in many ways to slices, so this is possible.  For instance, in your example, simply replacing:

```<code>exp := []string{"HELLO"}
</code>```

with:

```<code>exp := [1]string{"HELLO"}
</code>```

suffices.  Should you wish the compiler to count the initializers, using ... suffices:

```<code>exp := [...]string{"HELLO"}
</code>```

See example on Go Playground.  Note that because exp is now an array, not a slice, some operations cannot be performed on/with exp.

Body:
I used the go playground to try this code:

package main

func main() {
    exp := []string{"HELLO"}

    const length = len(exp)
}

But it is throwing me this error:

./prog.go:6:8: const initializer len(exp) is not a constant

I can see that this is happening because the length of exp is changeable. How can i get the current length and store it in an integer constant?

I would think that I need the reflect module to do this, but I don't know how to do it. I tried using reflect.ValueOf but it did not work.

exp := []string{"HELLO"}
const length = len(reflect.ValueOf(exp).Interface().([]string))

Body:
You can indeed get the current length, but that is by definition not a constant.  Here is what the language specification has to say about this:

The expression len(s) is constant if s is a string constant. The expressions len(s) and cap(s) are constants if the type of s is an array or pointer to an array and the expression s does not contain channel receives or (non-constant) function calls; in this case s is not evaluated. Otherwise, invocations of len and cap are not constant and s is evaluated.

Since your invocation of len is as len(exp) we must test exp against the text above:

Is it a string constant?  No; it is a slice.

Is it an array?  No; it is a slice.

Is it a pointer to an array?  No, it is a slice.

The three cases where len would produce a constant have been exhausted, so len must necessarily produce a non-constant.

If you would like len to produce a constant, you will have to apply it to a string constant, or an array, or a pointer to an array.  Arrays are similar in many ways to slices, so this is possible.  For instance, in your example, simply replacing:

exp := []string{"HELLO"}

with:

exp := [1]string{"HELLO"}

suffices.  Should you wish the compiler to count the initializers, using ... suffices:

exp := [...]string{"HELLO"}

See example on Go Playground.  Note that because exp is now an array, not a slice, some operations cannot be performed on/with exp.


问:
Docker AWS ECR error parsing HTTP 404 response body: invalid character 'p' after top-level value: "404 page not found\n"
Had an issue with not being able to push or pull from an AWS ECR registry with the following cryptic error:

```<code>error parsing HTTP 404 response body: invalid character 'p' after top-level value: "404 page not found\n"
</code>```

Several hours of googling indicated it was a protocol issue. It turns out the image name:

```<code>xxxxxxxxxxxx.dkr.ecr.us-east-1.amazonaws.com/snowshu__test
</code>```

was the issue: AWS ECR errors when the image name contains double underscores.

This contradicts ECR naming documentation.

答:
You cannot have two underscores next to each other in a repository name.

As per the Docker Registry API:

A component of a repository name must be at least one lowercase, alpha-numeric characters, optionally separated by periods, dashes or underscores. More strictly, it must match the regular expression [a-z0-9]+(?:[._-][a-z0-9]+)*.

Body:
Had an issue with not being able to push or pull from an AWS ECR registry with the following cryptic error:

error parsing HTTP 404 response body: invalid character 'p' after top-level value: "404 page not found\n"

Several hours of googling indicated it was a protocol issue. It turns out the image name:

xxxxxxxxxxxx.dkr.ecr.us-east-1.amazonaws.com/snowshu__test

was the issue: AWS ECR errors when the image name contains double underscores.

This contradicts ECR naming documentation.


答:
Eye doc? There are infinite possibilities with machine learning algorithms and neural networks. You'll need to train an image classifier.

https://towardsdatascience.com/all-the-steps-to-build-your-first-image-classifier-with-code-cf244b015799

There's a link ^. If you're doing this for a large-scale project, I'd recommend hiring a developer. It can be done, but it ain't going to be easy except maybe for programmers who've been doing AI work.

Title: identifying large circle like white color in an image using python

Body:
I need suggestion with this two image.

Image A

Image B

I'm trying to identify if an image has an optic nerve glioma.

Image A represents that there is no abnormality, it has a smaller circle like white color on the image. while Image B has a larger one which has the optic nerve glioma. basically what I want to do is identify if the image has a larger circle white color compare to the standard basis which is the Image A

Any suggestion is a big help. Thanks guys!


问:
Convert date with full timezone name to Date in JavaScript
I'm processing some data with dates in the format YYYY-MM-DD hh:mm:ss zz. For example:

2019-04-06 08:24:51 Central Daylight Time

2018-09-06 12:16:12 Central Standard Time

2020-02-14 17:57:33 Central Standard Time

I want to be able to convert these dates to a Date object in browser JavaScript. However, the Date constructor does not recognize this sort of date format, and moment.js isn't much help (unless I'm missing something).

In practice, I'll probably only ever deal with Central Standard Time and Central Daylight Time, but is there a general solution that would allow me to convert this date format to a Date object?

答:
Assuming that Central Standard Time can also be written as CST, you can try

```<code>new Date('2020-02-14 17:57:33 CST'); // default date output
</code>```

which will give you the full date representation.

Or you could use Date.parse() to get the actual timestamp

```<code>Date.parse('2020-02-14 17:57:33 CST'); // 1581724653000 etc
</code>```

Another thought - have you tried Moment timezone?

Body:
Assuming that Central Standard Time can also be written as CST, you can try

new Date('2020-02-14 17:57:33 CST'); // default date output

which will give you the full date representation.

Or you could use Date.parse() to get the actual timestamp

Date.parse('2020-02-14 17:57:33 CST'); // 1581724653000 etc

Another thought - have you tried Moment timezone?


问:
VueJS: $router.push not working with query parameters
In my NuxtJS(v. 2.10.2) application, I have a URL like below where pid is a post's id.

/post?pid=5e4844e34202d6075e593062

This URL works fine and loads the post as per the value passed to the pid query parameter. However, user can add new post by clicking Add Post button on the application bar that opens a dialog. Once the user clicks add, a request to back-end server is made to save the request. And once successful, user is redirected to the new post using vue router push like below

```<code>.then(data => {
  if (data) {
    this.$router.push({ path: `/post?pid=${data.id}` });
  }
})
</code>```

The problem is, user is not redirected to the new post, only the query parameter pid is updated. I suspect VueJS does not acknowledge this as a different URL and hence does nothing.

How to fix this?

Update: As an alternative tried the syntax below but getting the same behavior.

```<code>this.$router.push({ path: "post", query: { pid: data.id } });
</code>```

答:
try this solution

```<code>.then(data => {
  if (data) {
    this.$router.push({ name: 'post', query: { pid: data.id } });
  }
})
</code>```

hints:

```<code>// with query, resulting in /register?plan=private
router.push({ path: 'register', query: { plan: 'private' } })
</code>```

Body:
In my NuxtJS(v. 2.10.2) application, I have a URL like below where pid is a post's id.

/post?pid=5e4844e34202d6075e593062

This URL works fine and loads the post as per the value passed to the pid query parameter. However, user can add new post by clicking Add Post button on the application bar that opens a dialog. Once the user clicks add, a request to back-end server is made to save the request. And once successful, user is redirected to the new post using vue router push like below

.then(data => {
  if (data) {
    this.$router.push({ path: `/post?pid=${data.id}` });
  }
})

The problem is, user is not redirected to the new post, only the query parameter pid is updated. I suspect VueJS does not acknowledge this as a different URL and hence does nothing.

How to fix this?

Update: As an alternative tried the syntax below but getting the same behavior.

this.$router.push({ path: "post", query: { pid: data.id } });

Body:
try this solution

.then(data => {
  if (data) {
    this.$router.push({ name: 'post', query: { pid: data.id } });
  }
})

hints:

// with query, resulting in /register?plan=private
router.push({ path: 'register', query: { plan: 'private' } })


问:
Declare optional last element in array?
I want to declare a Typescript array type in which the last element is optional. Is there any elegant way to achieve this?

```<code>const test = (a: [string, string, any | undefined]) => console.log(a)
test(['foo', 'bar'])
</code>```

In the test(...) function call, ts verbose this error

```<code>Argument of type '[string, string]' is not assignable to parameter of type '[string, string, any]'.
  Property '2' is missing in type '[string, string]' but required in type '[string, string, any]'.(2345)
</code>```

答:
A better pattern would be to use generics so you don't have to declare types for each of array elements as follows const test = (a: Array<string|undefined|null>) => console.log(a)
test(['foo', 'bar', ,"etc"]). This lets you create an array with string or undefined/null elements.

Title: Declare optional last element in array?

Body:
I want to declare a Typescript array type in which the last element is optional. Is there any elegant way to achieve this?

const test = (a: [string, string, any | undefined]) => console.log(a)
test(['foo', 'bar'])

In the test(...) function call, ts verbose this error

Argument of type '[string, string]' is not assignable to parameter of type '[string, string, any]'.
  Property '2' is missing in type '[string, string]' but required in type '[string, string, any]'.(2345)


问:
How to read in integers, separated by commas and spaces, into a 2D array?
I have an input file that looks like this:

```<code>3, 2, 5
2, 4, 9
6, 5, 9
</code>```

And I've made an array[3][3].

My question is: how can I read this into my array, while skipping the spaces and commas?

Also: I can't use stoi (don't have C++11) and I haven't covered vectors yet.

I've tried the code block below, but my resulting array is full of zeroes.

```<code>    string sNum;                     // Current number (as string)
    int num = 0;                     // Current number (as int)
    ifstream inFile;                 // Make input file stream
    inFile.open("Numbers.txt");      // Open my input file of 3x3 numbers

     while (getline(inFile, sNum, ',')) {                                 // Gets 'line' from infile ..
                                                                             // puts it in sNum ..
                                                                             // delimiter is comma (the problem?).
        for (int rowCount=0; rowCount<3; rowCount++) {                    // Go through the rows
                for (int columnCount=0; columnCount<3; columnCount++) {   // Go through the columns

                        num = atoi(sNum.c_str());                         // String 'sNum' to int 'num'
                        array[rowCount][columnCount] = num;               // Put 'num' in array

                } // end columnCount for
        } // end rowCount for
    } // end while
</code>```

I think it is reading in the spaces. How do I ignore the spaces in between getting my ints?

答:
Here's one solution: </p>

```<code>string sNum;
int array[3][3];
int num = 0;
    ifstream inFile;
    stringstream ss;
    inFile.open("Numbers.txt");      // Open the input file of 3x3 numbers
    int row = 0;
    int col = 0;
     while (getline(inFile, sNum)) {  // Gets entire line from inFile and stores in sNum
        ss.str(sNum); //puts the line into a stringstream

        while(ss >> num)
        {
           if(col == 3) //handles our 2D array indexes.
                        //when col reaches 3, set it back to 0 and increment the row.
           {
              row++;
              col = 0;
           }

           array[row][col] = num;
           col++;

           //eliminate any commas and spaces between each number.
           while(ss.peek() == ',' || ss.peek() == ' ')
              ss.ignore();
        }
        ss.clear();
     } //        end while

}

</code>```

Body:
I have an input file that looks like this:

3, 2, 5
2, 4, 9
6, 5, 9

And I've made an array[3][3].

My question is: how can I read this into my array, while skipping the spaces and commas?

Also: I can't use stoi (don't have C++11) and I haven't covered vectors yet.

I've tried the code block below, but my resulting array is full of zeroes.

    string sNum;                     // Current number (as string)
    int num = 0;                     // Current number (as int)
    ifstream inFile;                 // Make input file stream
    inFile.open("Numbers.txt");      // Open my input file of 3x3 numbers

     while (getline(inFile, sNum, ',')) {                                 // Gets 'line' from infile ..
                                                                             // puts it in sNum ..
                                                                             // delimiter is comma (the problem?).
        for (int rowCount=0; rowCount<3; rowCount++) {                    // Go through the rows
                for (int columnCount=0; columnCount<3; columnCount++) {   // Go through the columns

                        num = atoi(sNum.c_str());                         // String 'sNum' to int 'num'
                        array[rowCount][columnCount] = num;               // Put 'num' in array

                } // end columnCount for
        } // end rowCount for
    } // end while

I think it is reading in the spaces. How do I ignore the spaces in between getting my ints?

Body:
Here's one solution:

string sNum;
int array[3][3];
int num = 0;
    ifstream inFile;
    stringstream ss;
    inFile.open("Numbers.txt");      // Open the input file of 3x3 numbers
    int row = 0;
    int col = 0;
     while (getline(inFile, sNum)) {  // Gets entire line from inFile and stores in sNum
        ss.str(sNum); //puts the line into a stringstream

        while(ss >> num)
        {
           if(col == 3) //handles our 2D array indexes.
                        //when col reaches 3, set it back to 0 and increment the row.
           {
              row++;
              col = 0;
           }

           array[row][col] = num;
           col++;

           //eliminate any commas and spaces between each number.
           while(ss.peek() == ',' || ss.peek() == ' ')
              ss.ignore();
        }
        ss.clear();
     } //        end while

}


问:
How can you make a Java DSL servlet using Camel in .war format that can deployed and run in Tomcat?
The past few days I've been searching how to do the below without having any knowledge in Tomcat or Camel and I'm surprised I haven't found any good resources on this:

Make a .war file that will be deployed into Tomcat (e.g. from Manager App) which will accept a request on a given URI /testand will forward the request to an internal service in PHP which runs on localhost:8222/index.php?q=test.

I have managed to have a working example of forwarding a request to a different url by building on top of the camel-archetype-java and the router looks like this:

```<code>package camelinaction;

import org.apache.camel.builder.RouteBuilder;

public class MyRouteBuilder extends RouteBuilder {

    public void configure() {
        String targetUrl = "https://another.service.com/api/test";
        from("jetty:http://127.0.0.1:25566/test?matchOnUriPrefix=true")
                .to("jetty:" + targetUrl + "?bridgeEndpoint=true&throwExceptionOnFailure=false");
    }

}
</code>```

and I have managed also to create a .war file from the camel-example-servlet-tomcat example that in Camel and deploy it successfully in tomcat. That example doesn't have any Java code though in its project folder and is consisted basically from just .xml files and a .html page which is served by the Camel servlet when requests the related servlet path which is served by tomcat.
The basic xml of that project looks like below:

```<code><beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:camel="http://camel.apache.org/schema/spring"
       xsi:schemaLocation="
         http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
         http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd">

  <camelContext xmlns="http://camel.apache.org/schema/spring">

    <route id="helloRoute">
      <!-- incoming requests from the servlet is routed -->
      <from uri="servlet:hello"/>
      <choice>
        <when>
          <!-- is there a header with the key name? -->
          <header>name</header>
          <!-- yes so return back a message to the user -->
          <transform>
            <simple>Hi I am ${sysenv.HOSTNAME}. Hello ${header.name} how are you today?</simple>
          </transform>
        </when>
        <otherwise>
          <!-- if no name parameter then output a syntax to the user -->
          <transform>
            <constant>Add a name parameter to uri, eg ?name=foo</constant>
          </transform>
        </otherwise>
      </choice>
    </route>

  </camelContext>

</beans>
</code>```

How would someone would combine the two examples/functionalities to achieve the end goal of having a request that comes from tomcat to be forwarded with camel to a different endpoint?

答:
Since you are already deploying this WAR in a servlet container that can handle HTTP, there is no need to use camel-jetty component, but could leverage on camel-servlet and camel-servlet-listener components.

Your first example uses Camel's Java DSL and the second one follows XML DSL, it may be a bit intimidating at the first go.  I couldn't find any samples that combine the specific scenario so I have hacked together  a quick demo that could be deployed in a servlet container and could route calls to another HTTP Service. It is a tiny demo and would need some modifications. I tested it with jetty but haven't tried throwing it at a Tomcat.

In the web.xml file, the following section controls the context.

```<code><!-- Camel servlet mapping -->
<servlet-mapping>
<servlet-name>CamelServlet</servlet-name>
<url-pattern>/camel/*</url-pattern>
</servlet-mapping>
</code>```

There's only one java file, the route configuration, as shown below

```<code>public class DefaultRouteBuilder extends RouteBuilder {

@Override
public void configure() throws Exception {

    from("servlet:hello?matchOnUriPrefix=true")
    .routeId("HTTP Bridging Route")
    .log("Request: ${in.header."+ Exchange.HTTP_METHOD +"} to ${in.header."+ Exchange.HTTP_URI +"}")
    .to("https://another.service.com?bridgeEndpoint=true");
}

}
</code>```

Once the servelet starts, you can access the HTTP resource, backed by camel at http://server/<context root>/camel/hello
I hope it helps you to get going.

Body:
The past few days I've been searching how to do the below without having any knowledge in Tomcat or Camel and I'm surprised I haven't found any good resources on this:

Make a .war file that will be deployed into Tomcat (e.g. from Manager App) which will accept a request on a given URI /testand will forward the request to an internal service in PHP which runs on localhost:8222/index.php?q=test.

I have managed to have a working example of forwarding a request to a different url by building on top of the camel-archetype-java and the router looks like this:

package camelinaction;

import org.apache.camel.builder.RouteBuilder;

public class MyRouteBuilder extends RouteBuilder {

    public void configure() {
        String targetUrl = "https://another.service.com/api/test";
        from("jetty:http://127.0.0.1:25566/test?matchOnUriPrefix=true")
                .to("jetty:" + targetUrl + "?bridgeEndpoint=true&throwExceptionOnFailure=false");
    }

}

and I have managed also to create a .war file from the camel-example-servlet-tomcat example that in Camel and deploy it successfully in tomcat. That example doesn't have any Java code though in its project folder and is consisted basically from just .xml files and a .html page which is served by the Camel servlet when requests the related servlet path which is served by tomcat.
The basic xml of that project looks like below:

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:camel="http://camel.apache.org/schema/spring"
       xsi:schemaLocation="
         http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
         http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd">

  <camelContext xmlns="http://camel.apache.org/schema/spring">

    <route id="helloRoute">

      <from uri="servlet:hello"/>
      <choice>
        <when>

          name

          <transform>
            <simple>Hi I am ${sysenv.HOSTNAME}. Hello ${header.name} how are you today?</simple>
          </transform>
        </when>
        <otherwise>

          <transform>
            <constant>Add a name parameter to uri, eg ?name=foo</constant>
          </transform>
        </otherwise>
      </choice>
    </route>

  </camelContext>

</beans>

How would someone would combine the two examples/functionalities to achieve the end goal of having a request that comes from tomcat to be forwarded with camel to a different endpoint?

Body:
Since you are already deploying this WAR in a servlet container that can handle HTTP, there is no need to use camel-jetty component, but could leverage on camel-servlet and camel-servlet-listener components.

Your first example uses Camel's Java DSL and the second one follows XML DSL, it may be a bit intimidating at the first go.  I couldn't find any samples that combine the specific scenario so I have hacked together  a quick demo that could be deployed in a servlet container and could route calls to another HTTP Service. It is a tiny demo and would need some modifications. I tested it with jetty but haven't tried throwing it at a Tomcat.

In the web.xml file, the following section controls the context.

<!-- Camel servlet mapping -->
<servlet-mapping>
<servlet-name>CamelServlet</servlet-name>
<url-pattern>/camel/*</url-pattern>
</servlet-mapping>

There's only one java file, the route configuration, as shown below

public class DefaultRouteBuilder extends RouteBuilder {

@Override
public void configure() throws Exception {

    from("servlet:hello?matchOnUriPrefix=true")
    .routeId("HTTP Bridging Route")
    .log("Request: ${in.header."+ Exchange.HTTP_METHOD +"} to ${in.header."+ Exchange.HTTP_URI +"}")
    .to("https://another.service.com?bridgeEndpoint=true");
}

}

Once the servelet starts, you can access the HTTP resource, backed by camel at http://server/<context root>/camel/hello
I hope it helps you to get going.


问:
Is there a LINQ-oriented method to quicky evaluate nested lists in dictionaries
I have a dictionary constructed like this:

```<code>Dictionary<string, List<MyObject>>
</code>```

And my object has an integer value as one of its properties:

```<code>public class MyObject
{
  public int number {get; set;}
}
</code>```

How would I construct a LINQ-oriented query to evaluate the average number for each Key in the dictionary?

答:
Depending on your needs

```<code>var results = dict.Select(
   x => new
           {
              x.Key,
              avg = x.Value.Average(y => y.number)
           });
</code>```

Or if you want your results in a dictionary

```<code>var results = dict.ToDictionary(x => x.Key, x => x.Value.Average(y => y.number));
</code>```

Body:
I have a dictionary constructed like this:

Dictionary<string, List<MyObject>>

And my object has an integer value as one of its properties:

public class MyObject
{
  public int number {get; set;}
}

How would I construct a LINQ-oriented query to evaluate the average number for each Key in the dictionary?

Body:
Depending on your needs

var results = dict.Select(
   x => new
           {
              x.Key,
              avg = x.Value.Average(y => y.number)
           });

Or if you want your results in a dictionary

var results = dict.ToDictionary(x => x.Key, x => x.Value.Average(y => y.number));


问:
web scraping with selenium on a dynamic table
i'm trying to scrape the table from a dynamic website (it updates information every 10 secs i believe) and load it to a panda dataframe but i can't seem to get pass the first step of getting the first column. can someone advise on what i'm doing wrong? thanks.</p>

```<code># import libraries
import urllib.request
from bs4 import BeautifulSoup
from selenium import webdriver
import time
import pandas as pd

urlpage = 'https://new.cryptoxscanner.com/binance/live'

driver = webdriver.Chrome(executable_path=r"C:\Users\xxxxx\Desktop\chrome\chromedriver.exe")

driver.get(urlpage)
time.sleep(10)
ticker = driver.find_element_by_xpath('//*[@id="scroll-source-1"]/table/tbody/tr[2]')
</code>```

答:
First, you need wait until the data located, use .visibility_of_all_elements_located. You can use this locator to wait:

```<code>//table[contains(@class, "table-sm")]//a
</code>```

After all the data located, then you can extract the table data. Try the below code:

```<code>driver.get('https://new.cryptoxscanner.com/binance/live')

#UPDATED HERE
option = Select(WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, '//select[contains(., "All")]'))))
option.select_by_visible_text('All')

WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.XPATH, '//table[contains(@class, "table-sm")]//a')))
data = driver.find_element_by_class_name('table-responsive')
print(data.text)
</code>```

Following import:

```<code>#UPDATED HERE
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.by import By

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
</code>```

Body:
i'm trying to scrape the table from a dynamic website (it updates information every 10 secs i believe) and load it to a panda dataframe but i can't seem to get pass the first step of getting the first column. can someone advise on what i'm doing wrong? thanks.

# import libraries
import urllib.request
from bs4 import BeautifulSoup
from selenium import webdriver
import time
import pandas as pd

urlpage = 'https://new.cryptoxscanner.com/binance/live'

driver = webdriver.Chrome(executable_path=r"C:\Users\xxxxx\Desktop\chrome\chromedriver.exe")

driver.get(urlpage)
time.sleep(10)
ticker = driver.find_element_by_xpath('//*[@id="scroll-source-1"]/table/tbody/tr[2]')

Body:
First, you need wait until the data located, use .visibility_of_all_elements_located. You can use this locator to wait:

//table[contains(@class, "table-sm")]//a

After all the data located, then you can extract the table data. Try the below code:

driver.get('https://new.cryptoxscanner.com/binance/live')

#UPDATED HERE
option = Select(WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, '//select[contains(., "All")]'))))
option.select_by_visible_text('All')

WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.XPATH, '//table[contains(@class, "table-sm")]//a')))
data = driver.find_element_by_class_name('table-responsive')
print(data.text)

Following import:

#UPDATED HERE
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.by import By

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC


问:
Nested JOIN query in Hibernate
I'm trying to write an Hibernate 4 nested join query but I can't manage to obtain what I want.

I have the classes ProductDetail, Product and Feedback. In both ProductDetail and Feedback I have an attribute product that references to the relative Product.

So separately I may easily obtain joins like this:

First join:

```<code>SELECT ...
FROM ProductDetail d
LEFT JOIN d.product p
</code>```

Second join:

```<code>SELECT ...
FROM Feedback f
LEFT JOIN f.product p
</code>```

How can I put those joins together?

I tried this:

```<code>FROM ProductDetail d
LEFT JOIN d.product p
RIGHT JOIN Feedback f
</code>```

But whenever I try to put something on the right side of a JOIN that is not a path (e.g. d.product) I get the following error:

antlr.SemanticException: Path expected for join!

答:
Try this :</p>

```<code>FROM Product p, ProductDetail pd, Feedback f where p = pd.product and p = f.product
</code>```

Title: Nested JOIN query in Hibernate

Body:
I'm trying to write an Hibernate 4 nested join query but I can't manage to obtain what I want.

I have the classes ProductDetail, Product and Feedback. In both ProductDetail and Feedback I have an attribute product that references to the relative Product.

So separately I may easily obtain joins like this:

First join:

SELECT ...
FROM ProductDetail d
LEFT JOIN d.product p

Second join:

SELECT ...
FROM Feedback f
LEFT JOIN f.product p

How can I put those joins together?

I tried this:

FROM ProductDetail d
LEFT JOIN d.product p
RIGHT JOIN Feedback f

But whenever I try to put something on the right side of a JOIN that is not a path (e.g. d.product) I get the following error:

antlr.SemanticException: Path expected for join!

Body:
Try this :

FROM Product p, ProductDetail pd, Feedback f where p = pd.product and p = f.product


问:
Flash AS3 ... Visible = false not working?
So I have a simple flash movie.

I have created 3 layers (actions, background, header) Background contains an image, header contains a movie clip with an instance name of "mc_header". In the actions layer I have said mc_header.visible = false; Yet when testing the movie it continues to show for no reason.

答:
I have corrected this mistake.

This problem appears if clip not wiped in this frame.

I have done animation with 50 frames, the first and the last frame were key. So when I have added the new clip in the first frame that it did not come up for the last frame - he was only in the first frame !!!
To correct the mistake I have deleted the last key frame and created it once again. Hereon clip came up for all frames. It became available on length whole animation.


问:
How to add equirectangular environment map to gltf model in A-Frame?
When importing a gltf object into an a-frame scene I'd like to set an equirectangular environment map for that object to influence its reflections. I'd like to use the same img DOM id reference as I used in the sky entity. How can I do that?

For example, I'd like to be able to specify code such as this:

I found a cubemap version of this by @donmccurdy but looking for equirectangular instead and also a mechanism to use an already loaded image texture.
https://github.com/donmccurdy/aframe-extras/tree/master/src/misc#cube-env-map

答:
See this answer:
Aframe gltf-model demo with envmap

Another option for the future, investigate scene.environment threejs which may apply the same environment map automatically to all objects with supported materials.