问:
Member undefined inside parseString method
I have XML file I need to convert to Json so I can use in my application. In my service I return the XML file:

```<code>constructor(private http: HttpClient) { }

loadXml() {
  return this.http.get('../../assets/1bbc5495-3872-4058-886e-aeee2a1cd52c.xml', { responseType: 'text' });
}
</code>```

In my component I try to get the data inside the XML file available:

```<code>parseString = require('xml2js').parseString;
data = [];

constructor(
  private _sharedService: SharedService
) {}

ngOnInit() {
  this.convertXmlToJson();
}

convertXmlToJson() {
  let data;
  this._sharedService.loadXml()
    .subscribe(
      res => {
        this.parseString(res, function (err, result) {
          this.data = result.rss.channel[0];
        });
      }
    )
}
</code>```

This results in the error:

Cannot set property 'data' of undefined

Why can't I use this.data?

//EDIT.

This might not be the best method but it works:

```<code>convertXmlToJson() {
  let data;
  this._sharedService.loadXml()
    .subscribe(
      res => {
        this.setData(res)
      }
    )
}

setData(res) {
  let data;
  this.parseString(res, function (err, result) {
    data = result.rss.channel[0]
  })
  this.data = data;
}
</code>```

I now pass the data from the method in the service to a function that stores it in a function variable and I set that variable on the class member.

答:
You are losing the context(this) inside the subscription's response.

```<code>convertXmlToJson() {
  let data;
  this._sharedService.loadXml()
    .subscribe(
      res => {
        this.parseString(res, (err, result) => this.data = result.rss.channel[0]).bind(this);
      }
    )
}
</code>```

That's why we need to pass with with bind() or call().

bind() mostly for functions that are being called as callbacks and call() for functions out of scope (don't have the this context) but are using the this keyword.

Example:

```<code>function foo() {
  this.myBool = !this.myBool;
}

class MyClass {
  myBool = false;

  foo.call(this); // will read this.myBool because we are passing the context

  someSubscription.subscribe(
    resp => foo().bind(this) // being a callback function you need to pass the this context with a bind()
  );
}
</code>```

Body:
I have XML file I need to convert to Json so I can use in my application. In my service I return the XML file:

constructor(private http: HttpClient) { }

loadXml() {
  return this.http.get('../../assets/1bbc5495-3872-4058-886e-aeee2a1cd52c.xml', { responseType: 'text' });
}

In my component I try to get the data inside the XML file available:

parseString = require('xml2js').parseString;
data = [];

constructor(
  private _sharedService: SharedService
) {}

ngOnInit() {
  this.convertXmlToJson();
}

convertXmlToJson() {
  let data;
  this._sharedService.loadXml()
    .subscribe(
      res => {
        this.parseString(res, function (err, result) {
          this.data = result.rss.channel[0];
        });
      }
    )
}

This results in the error:

Cannot set property 'data' of undefined

Why can't I use this.data?

//EDIT.

This might not be the best method but it works:

convertXmlToJson() {
  let data;
  this._sharedService.loadXml()
    .subscribe(
      res => {
        this.setData(res)
      }
    )
}

setData(res) {
  let data;
  this.parseString(res, function (err, result) {
    data = result.rss.channel[0]
  })
  this.data = data;
}

I now pass the data from the method in the service to a function that stores it in a function variable and I set that variable on the class member.

Body:
You are losing the context(this) inside the subscription's response.

convertXmlToJson() {
  let data;
  this._sharedService.loadXml()
    .subscribe(
      res => {
        this.parseString(res, (err, result) => this.data = result.rss.channel[0]).bind(this);
      }
    )
}

That's why we need to pass with with bind() or call().

bind() mostly for functions that are being called as callbacks and call() for functions out of scope (don't have the this context) but are using the this keyword.

Example:

function foo() {
  this.myBool = !this.myBool;
}

class MyClass {
  myBool = false;

  foo.call(this); // will read this.myBool because we are passing the context

  someSubscription.subscribe(
    resp => foo().bind(this) // being a callback function you need to pass the this context with a bind()
  );
}


来源: stackexchange

问:
Matrix factorization based recommendation using Tensorflow
I am new to tensor Flow and exploring about recommendation system using tensorflow. I have verified few sample codes in in github and come across mostly the same like following as the follwing

https://github.com/songgc/TF-recomm/blob/master/svd_train_val.py

But the question is, how do I pick top recommendation for user U1 in the above code?

If there any sample code or approach, please share. Thanks

答:
It is a little difficult! Basically, when svd returns, it closes the session, and the tensors lose their values (you still keep the graph). There are a few options:

Save the model to a file and restore it later;

Don't put the session in a with tf.Session() as sess: .... block, and instead return the session;

Do the user processing inside the with ... block

The worst option is option 3: you should train your model separately from using it. The best approach is to save your model and weights somewhere, then restore the session. However, you are still left with the question of how you use this session object once you have recovered it. To demonstrate just that part, I am going to solve this problem using option 3, assuming that you know how to restore a session.

```<code>def svd(train, test):
    samples_per_batch = len(train) // BATCH_SIZE

    iter_train = dataio.ShuffleIterator([train["user"],
                                     train["item"],
                                     train["rate"]],
                                    batch_size=BATCH_SIZE)

    iter_test = dataio.OneEpochIterator([test["user"],
                                     test["item"],
                                     test["rate"]],
                                    batch_size=-1)

    user_batch = tf.placeholder(tf.int32, shape=[None], name="id_user")
    item_batch = tf.placeholder(tf.int32, shape=[None], name="id_item")
    rate_batch = tf.placeholder(tf.float32, shape=[None])

    infer, regularizer = ops.inference_svd(user_batch, item_batch, user_num=USER_NUM, item_num=ITEM_NUM, dim=DIM,
                                       device=DEVICE)
    global_step = tf.contrib.framework.get_or_create_global_step()
    _, train_op = ops.optimization(infer, regularizer, rate_batch, learning_rate=0.001, reg=0.05, device=DEVICE)

    init_op = tf.global_variables_initializer()
    with tf.Session() as sess:
        sess.run(init_op)
        summary_writer = tf.summary.FileWriter(logdir="/tmp/svd/log", graph=sess.graph)
        print("{} {} {} {}".format("epoch", "train_error", "val_error", "elapsed_time"))
        errors = deque(maxlen=samples_per_batch)
        start = time.time()
        for i in range(EPOCH_MAX * samples_per_batch):
            users, items, rates = next(iter_train)
            _, pred_batch = sess.run([train_op, infer], feed_dict={user_batch: users, item_batch: items, rate_batch: rates})
            pred_batch = clip(pred_batch)
            errors.append(np.power(pred_batch - rates, 2))
            if i % samples_per_batch == 0:
                train_err = np.sqrt(np.mean(errors))
                test_err2 = np.array([])
                for users, items, rates in iter_test:
                    pred_batch = sess.run(infer, feed_dict={user_batch: users,item_batch: items})
                    pred_batch = clip(pred_batch)
                    test_err2 = np.append(test_err2, np.power(pred_batch - rates, 2))
                end = time.time()
                test_err = np.sqrt(np.mean(test_err2))
                print("{:3d} {:f} {:f} {:f}(s)".format(i // samples_per_batch, train_err, test_err, end - start))
                train_err_summary = make_scalar_summary("training_error", train_err)
                test_err_summary = make_scalar_summary("test_error", test_err)
                summary_writer.add_summary(train_err_summary, i)
                summary_writer.add_summary(test_err_summary, i)
                start = end

        # Get the top rated movie for user #1 for every item in the set
        userNumber = 1
        user_prediction = sess.run(infer, feed_dict={user_batch: np.array([userNumber]), item_batch: np.array(range(ITEM_NUM))})
        # The index number is the same as the item number. Orders from lowest (least recommended)
        # to largeset
        index_rating_order = np.argsort(user_prediction)

        print "Top ten recommended items for user {} are".format(userNumber)
        print index_rating_order[-10:][::-1]  # at the end, reverse the list

        # If you want to include the score:
        items_to_choose = index_rating_order[-10:][::-1]
        for item, score in zip(items_to_choose, user_prediction[items_to_choose]):
            print "{}:  {}".format(item,score)
</code>```

The only changes I made begin at the first commented line. To emphasize again, best practice would be to train in this function, but to actually make your predictions separately.

ContentLicense: CC BY-SA 3.0

Body:
It is a little difficult! Basically, when svd returns, it closes the session, and the tensors lose their values (you still keep the graph). There are a few options:

Save the model to a file and restore it later;

Don't put the session in a with tf.Session() as sess: .... block, and instead return the session;

Do the user processing inside the with ... block

The worst option is option 3: you should train your model separately from using it. The best approach is to save your model and weights somewhere, then restore the session. However, you are still left with the question of how you use this session object once you have recovered it. To demonstrate just that part, I am going to solve this problem using option 3, assuming that you know how to restore a session.

def svd(train, test):
    samples_per_batch = len(train) // BATCH_SIZE

    iter_train = dataio.ShuffleIterator([train["user"],
                                     train["item"],
                                     train["rate"]],
                                    batch_size=BATCH_SIZE)

    iter_test = dataio.OneEpochIterator([test["user"],
                                     test["item"],
                                     test["rate"]],
                                    batch_size=-1)

    user_batch = tf.placeholder(tf.int32, shape=[None], name="id_user")
    item_batch = tf.placeholder(tf.int32, shape=[None], name="id_item")
    rate_batch = tf.placeholder(tf.float32, shape=[None])

    infer, regularizer = ops.inference_svd(user_batch, item_batch, user_num=USER_NUM, item_num=ITEM_NUM, dim=DIM,
                                       device=DEVICE)
    global_step = tf.contrib.framework.get_or_create_global_step()
    _, train_op = ops.optimization(infer, regularizer, rate_batch, learning_rate=0.001, reg=0.05, device=DEVICE)

    init_op = tf.global_variables_initializer()
    with tf.Session() as sess:
        sess.run(init_op)
        summary_writer = tf.summary.FileWriter(logdir="/tmp/svd/log", graph=sess.graph)
        print("{} {} {} {}".format("epoch", "train_error", "val_error", "elapsed_time"))
        errors = deque(maxlen=samples_per_batch)
        start = time.time()
        for i in range(EPOCH_MAX * samples_per_batch):
            users, items, rates = next(iter_train)
            _, pred_batch = sess.run([train_op, infer], feed_dict={user_batch: users, item_batch: items, rate_batch: rates})
            pred_batch = clip(pred_batch)
            errors.append(np.power(pred_batch - rates, 2))
            if i % samples_per_batch == 0:
                train_err = np.sqrt(np.mean(errors))
                test_err2 = np.array([])
                for users, items, rates in iter_test:
                    pred_batch = sess.run(infer, feed_dict={user_batch: users,item_batch: items})
                    pred_batch = clip(pred_batch)
                    test_err2 = np.append(test_err2, np.power(pred_batch - rates, 2))
                end = time.time()
                test_err = np.sqrt(np.mean(test_err2))
                print("{:3d} {:f} {:f} {:f}(s)".format(i // samples_per_batch, train_err, test_err, end - start))
                train_err_summary = make_scalar_summary("training_error", train_err)
                test_err_summary = make_scalar_summary("test_error", test_err)
                summary_writer.add_summary(train_err_summary, i)
                summary_writer.add_summary(test_err_summary, i)
                start = end

        # Get the top rated movie for user #1 for every item in the set
        userNumber = 1
        user_prediction = sess.run(infer, feed_dict={user_batch: np.array([userNumber]), item_batch: np.array(range(ITEM_NUM))})
        # The index number is the same as the item number. Orders from lowest (least recommended)
        # to largeset
        index_rating_order = np.argsort(user_prediction)

        print "Top ten recommended items for user {} are".format(userNumber)
        print index_rating_order[-10:][::-1]  # at the end, reverse the list

        # If you want to include the score:
        items_to_choose = index_rating_order[-10:][::-1]
        for item, score in zip(items_to_choose, user_prediction[items_to_choose]):
            print "{}:  {}".format(item,score)

The only changes I made begin at the first commented line. To emphasize again, best practice would be to train in this function, but to actually make your predictions separately.


问:
Android method onClick doesn't start until another onClick method completes?
Currently my onClickListener for two Buttons 'play' and 'stop' is common and the onClick method is as follows

```<code>    public void onClick(View v) {

        switch (v.getId()) {

            case R.id.play:
                play();
                break;

            case R.id.stop:
                stop();
                break;

            default:
                break;
        }
    }
</code>```

Is there any way for stop() to be run at the same time play() is running? Should I use threads to make the two onClick methods run simultaneously?

答: No, they will not run at the same time because button clicks are handled on main thread. You need to call that method from different threads if You want to start them at the same time.</p>

Body:
Currently my onClickListener for two Buttons 'play' and 'stop' is common and the onClick method is as follows

    public void onClick(View v) {

        switch (v.getId()) {

            case R.id.play:
                play();
                break;

            case R.id.stop:
                stop();
                break;

            default:
                break;
        }
    }

Is there any way for stop() to be run at the same time play() is running? Should I use threads to make the two onClick methods run simultaneously?


问:
Error writing .htaccess to protect Symfony Directories in Web App
I'm trying to publish my first Symfony Project in production, but I'm very worried about security, I have taken the following measures:

1) First: Delete on /var these directories: cache, logs and sessions

2) Second: Changed of default name for cookie session (client side: symfony)

3) Trhee: Creating a .htaccess in root directory of application

My problem is about the .htaccess. The goal is dennied access to others directories of application like: /app, /src, /test, /var, /vendor.

I'll write the follow rules in .htaccess and puted it in root directory of my app: myDevelopedApp/.htaccess.

```<code>.htaccess
#Checking if module is avalaible
<IfModule mod_rewrite.c>
   #Using the rewrite engine
   RewriteEngine On
   RewriteCond %{REQUEST_FILENAME} !-f
   #Rewrite rule to redirect the request
   RewriteRule ^(.*)$ web/$1 [QSA,L]
<IfModule>
</code>```

The problem it's not working, I can not access to web folder when I write the rules. Apache hides the application myDevelopedApp when I try to access it by browser

What I'm wrong?
Any other recommendation to improve security in production enviroment is welcome, thanks so much.

答:
If your are really concerned about security you should follow the Symfony best practices. That means that only the /web folder should be accessible in the vhost.

Moreover if you initialized your project with a standard edition you should already have .htaccess files in the app/ src/ folders.

Body:
I'm trying to publish my first Symfony Project in production, but I'm very worried about security, I have taken the following measures:

1) First: Delete on /var these directories: cache, logs and sessions

2) Second: Changed of default name for cookie session (client side: symfony)

3) Trhee: Creating a .htaccess in root directory of application

My problem is about the .htaccess. The goal is dennied access to others directories of application like: /app, /src, /test, /var, /vendor.

I'll write the follow rules in .htaccess and puted it in root directory of my app: myDevelopedApp/.htaccess.

.htaccess
#Checking if module is avalaible
<IfModule mod_rewrite.c>
   #Using the rewrite engine
   RewriteEngine On
   RewriteCond %{REQUEST_FILENAME} !-f
   #Rewrite rule to redirect the request
   RewriteRule ^(.*)$ web/$1 [QSA,L]
<IfModule>

The problem it's not working, I can not access to web folder when I write the rules. Apache hides the application myDevelopedApp when I try to access it by browser

What I'm wrong?
Any other recommendation to improve security in production enviroment is welcome, thanks so much.


问:
Modify certain values in a data frame by indirect reference to the columns
I'm wrangling some data where we sort fails into bins and compute limited yields for each sort bin by lot.

I have a meta table that describes the sort bins. The rows are arranged in ascending test order and some of the sort labels come in with non-syntactic names.

```<code>sort_tbl <- tibble::tribble(~weight,   ~label,
                                  0, "fail A",
                                  0, "fail B",
                                  0, "fail C",
                                100,   "pass")
> sort_tbl
# A tibble: 4 x 2
  weight  label
   <dbl>  <chr>
1      0 fail A
2      0 fail B
3      0 fail C
4    100   pass
</code>```

I have a data table of limited yield by sort bin with one row per lot and one col for each sort bin. Because this table was constructed from a transposition we get instances where a particular sort never occurred for a lot and the resulting value is NA. Note that the columns in this table are arranged in descending test order.

```<code>yld_tbl <- tibble::tribble(  ~lot, ~pass, ~`fail C`, ~`fail B`, ~`fail A`,
                           "lot1",    NA,        NA,      0.00,        NA,
                           "lot2",    NA,      0.00,      0.80,        NA,
                           "lot3",  0.49,        NA,      0.50,      0.98,
                           "lot4",  0.70,      0.95,      0.74,      0.99)
> yld_tbl
# A tibble: 4 x 5
    lot  pass `fail C` `fail B` `fail A`
  <chr> <dbl>    <dbl>    <dbl>    <dbl>
1  lot1    NA       NA     0.00       NA
2  lot2    NA     0.00     0.80       NA
3  lot3  0.49       NA     0.50     0.98
4  lot4  0.70     0.95     0.74     0.99
</code>```

Some of the missing values imply a limited yield of 100% while others reflect an undefined value because we are zero yield earlier in the flow. My task is to replace the former group of NA's with 1.00 as appropriate.

One algorithm to accomplish this works left to right (descending test order) replacing NA with 1.00 if the subsequent limited yield is not NA. In the first row of the example data set, we don't change fail C since pass is missing. But we do replace fail A with 1.00 since fail B is not missing.

The correct example output would be:

```<code>> fill_ones(yld_tbl, sort_tbl)
# A tibble: 4 x 5
    lot  pass `fail C` `fail B` `fail A`
  <chr> <dbl>    <dbl>    <dbl>    <dbl>
1  lot1    NA       NA     0.00     1.00
2  lot2    NA     0.00     0.80     1.00
3  lot3  0.49     1.00     0.50     0.98
4  lot4  0.70     0.95     0.74     0.99
</code>```

答:
To generate the output table I have written the following function:

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

fill_ones <- function(df, meta) {
  fail_labels <- meta[meta$weight == 0, ]$label
  last_val <- NULL
  for ( i in length(fail_labels):1) {
    if (is.null(last_val)) last_val <- df$pass
    else last_val <- eval_tidy(sym(fail_labels[[i+1]]), df)
    this_name <- sym(fail_labels[[i]])
    this_val  <- eval_tidy(this_name, df)
    this_val[intersect(which(!is.na(last_val)), which(is.na(this_val)))] <- 1
    df <- mutate(df, !!!new_definition(this_name, this_val))
  }
  df
}
</code>```

This function loops over the fail sorts defined in meta and computes changes to the corresponding column in the data table df.

Calls to sym(fail_labels[[i]]) lookup the name of each column and eval_tidy(..., df) extracts the corresponding vector in the data frame.

The expression intersect(which(!is.na(last_val)), which(is.na(this_val))) defines the subset of NA's that will be replaced by a 1.00.

The entire column is over-written with new values using mutate(). To reduce the amount of quoting and unquoting I use new_definition() rather than :=.

I'm not convinced I've reached the simplest syntax for indirectly referring to columns in a data table. Having non-syntactic names doesn't help. Also, we only need to modify a limited number of NA's yet this solution re-writes every data entry column by column. I haven't hit upon a good syntax to avoid this (without turning to data.table).

If anyone has a better approach I would love to hear it.

Body:
I'm wrangling some data where we sort fails into bins and compute limited yields for each sort bin by lot.

I have a meta table that describes the sort bins. The rows are arranged in ascending test order and some of the sort labels come in with non-syntactic names.

sort_tbl <- tibble::tribble(~weight,   ~label,
                                  0, "fail A",
                                  0, "fail B",
                                  0, "fail C",
                                100,   "pass")
> sort_tbl
# A tibble: 4 x 2
  weight  label
   <dbl>  <chr>
1      0 fail A
2      0 fail B
3      0 fail C
4    100   pass

I have a data table of limited yield by sort bin with one row per lot and one col for each sort bin. Because this table was constructed from a transposition we get instances where a particular sort never occurred for a lot and the resulting value is NA. Note that the columns in this table are arranged in descending test order.

yld_tbl <- tibble::tribble(  ~lot, ~pass, ~`fail C`, ~`fail B`, ~`fail A`,
                           "lot1",    NA,        NA,      0.00,        NA,
                           "lot2",    NA,      0.00,      0.80,        NA,
                           "lot3",  0.49,        NA,      0.50,      0.98,
                           "lot4",  0.70,      0.95,      0.74,      0.99)
> yld_tbl
# A tibble: 4 x 5
    lot  pass `fail C` `fail B` `fail A`
  <chr> <dbl>    <dbl>    <dbl>    <dbl>
1  lot1    NA       NA     0.00       NA
2  lot2    NA     0.00     0.80       NA
3  lot3  0.49       NA     0.50     0.98
4  lot4  0.70     0.95     0.74     0.99

Some of the missing values imply a limited yield of 100% while others reflect an undefined value because we are zero yield earlier in the flow. My task is to replace the former group of NA's with 1.00 as appropriate.

One algorithm to accomplish this works left to right (descending test order) replacing NA with 1.00 if the subsequent limited yield is not NA. In the first row of the example data set, we don't change fail C since pass is missing. But we do replace fail A with 1.00 since fail B is not missing.

The correct example output would be:

> fill_ones(yld_tbl, sort_tbl)
# A tibble: 4 x 5
    lot  pass `fail C` `fail B` `fail A`
  <chr> <dbl>    <dbl>    <dbl>    <dbl>
1  lot1    NA       NA     0.00     1.00
2  lot2    NA     0.00     0.80     1.00
3  lot3  0.49     1.00     0.50     0.98
4  lot4  0.70     0.95     0.74     0.99

Body:
To generate the output table I have written the following function:

library(rlang)
library(dplyr)

fill_ones <- function(df, meta) {
  fail_labels <- meta[meta$weight == 0, ]$label
  last_val <- NULL
  for ( i in length(fail_labels):1) {
    if (is.null(last_val)) last_val <- df$pass
    else last_val <- eval_tidy(sym(fail_labels[[i+1]]), df)
    this_name <- sym(fail_labels[[i]])
    this_val  <- eval_tidy(this_name, df)
    this_val[intersect(which(!is.na(last_val)), which(is.na(this_val)))] <- 1
    df <- mutate(df, !!!new_definition(this_name, this_val))
  }
  df
}

This function loops over the fail sorts defined in meta and computes changes to the corresponding column in the data table df.

Calls to sym(fail_labels[[i]]) lookup the name of each column and eval_tidy(..., df) extracts the corresponding vector in the data frame.

The expression intersect(which(!is.na(last_val)), which(is.na(this_val))) defines the subset of NA's that will be replaced by a 1.00.

The entire column is over-written with new values using mutate(). To reduce the amount of quoting and unquoting I use new_definition() rather than :=.

I'm not convinced I've reached the simplest syntax for indirectly referring to columns in a data table. Having non-syntactic names doesn't help. Also, we only need to modify a limited number of NA's yet this solution re-writes every data entry column by column. I haven't hit upon a good syntax to avoid this (without turning to data.table).

If anyone has a better approach I would love to hear it.


问:
Best way to annotate money values in UIMA RUTA
I'm new to UIMA RUTA (but I have experience in plain UIMA and uimaFIT) and I'ld like to know whats the best approach (performance wise) to find money values. If applying a regex in the sentence or creating a new rule (and how it would look like)

My values would look like this:

1.000,00
1000,00
1.100.000,00
100,00
or even 1000000,00 is possible

I created a rule like

```(NUM{BEFORE(PERIOD)})*(NUM{AFTER(COMMA)}) {-> MARK(Value, 1, 2);```

(And even then I can't get this to work properly sometimes, and doesnt cover all my cases)

What would be easier and less resource consuming to do ?

答:
A regular expression is probably the fastest option if you can only work on character level and need no annotations.

Using normal matching rules in UIMA Ruta, it depends on how flexible they should be. Should they also detect other locales like English or French numbers? Afterall, the runtime depends also how many numbers the document contains and so on, and on if ruta is tuned for the use case (lexer, internal indexing, ...)

Your rule won't work as expected since optional elements at the beginning of a rule are not optional (in case there is no manual anchor), and the BEFORE condition will exclude at least the first number.

This rule should do what you want, but is certainly not the fastest:

```<code>(NUM{-PARTOF(Value)} (PERIOD NUM{REGEXP("...")})* COMMA NUM{REGEXP("..")}){-> Value};
</code>```

DISCLAIMER: I am developer of UIMA Ruta

Body:
I'm new to UIMA RUTA (but I have experience in plain UIMA and uimaFIT) and I'ld like to know whats the best approach (performance wise) to find money values. If applying a regex in the sentence or creating a new rule (and how it would look like)

My values would look like this:

1.000,00
1000,00
1.100.000,00
100,00
or even 1000000,00 is possible

I created a rule like

(NUM{BEFORE(PERIOD)})*(NUM{AFTER(COMMA)}) {-> MARK(Value, 1, 2);

(And even then I can't get this to work properly sometimes, and doesnt cover all my cases)

What would be easier and less resource consuming to do ?

Body:
A regular expression is probably the fastest option if you can only work on character level and need no annotations.

Using normal matching rules in UIMA Ruta, it depends on how flexible they should be. Should they also detect other locales like English or French numbers? Afterall, the runtime depends also how many numbers the document contains and so on, and on if ruta is tuned for the use case (lexer, internal indexing, ...)

Your rule won't work as expected since optional elements at the beginning of a rule are not optional (in case there is no manual anchor), and the BEFORE condition will exclude at least the first number.

This rule should do what you want, but is certainly not the fastest:

(NUM{-PARTOF(Value)} (PERIOD NUM{REGEXP("...")})* COMMA NUM{REGEXP("..")}){-> Value};

DISCLAIMER: I am developer of UIMA Ruta


问:
How do I select this check box using Selenium/Java
Can someone help me create a path that will allow me to click this checkbox?

I have a page that features around 50 boxes like this one where the only difference is the text (in this case Answer Flow Designer). I am creating a script that will take a string array and iterate through it selecting each matching checkbox.

```<code><td class="normal">
    <input name="1.48.1.3.2.6.1.1.57.3" type="checkbox" value="0">Answer Flow Designer
</td>
</code>```

答:
You can use below to match required input:

```<code>//td[contains(., "Answer Flow Designer")]/input
</code>```

Note that you cannot use

```<code>//input[contains(text(), "Answer Flow Designer")]
</code>```

as input node cannot contain any child nodes (attributes only) and "Answer Flow Designer" is actually child text node of td

Body:
Can someone help me create a path that will allow me to click this checkbox?

I have a page that features around 50 boxes like this one where the only difference is the text (in this case Answer Flow Designer). I am creating a script that will take a string array and iterate through it selecting each matching checkbox.

    <input name="1.48.1.3.2.6.1.1.57.3" type="checkbox" value="0">Answer Flow Designer

Body:
You can use below to match required input:

//td[contains(., "Answer Flow Designer")]/input

Note that you cannot use

//input[contains(text(), "Answer Flow Designer")]

as input node cannot contain any child nodes (attributes only) and "Answer Flow Designer" is actually child text node of td


问:
strange issue with jQuery
I have a very strange issue with jQuery.

The problem:

```<code>$("#button-prev").attr("disabled", "disabled");
</code>```

This doesn't work. If I check with Firebug I see disabled="" as element attribute

But for example this

```<code>$("#button-prev").attr("disablea", "disabled");
</code>```

works as you should expect. Anyone an idea what it could be?

答:
The disabled is a boolean property. Therefore it's just enough if a truthy value is set.

```<code><button disabled>foo</button>
</code>```

would work aswell in most browsers. You need to either completely remove the property by using

```<code>$('#button-prev').removeAttr('disabled');
</code>```

or set it explicitly to false / 0

```<code>$('#button-prev').attr('disabled', false);
</code>```

It's a common mistake and pretty confusing, consider, a call like

```<code>$(element).attr('disabled', 'false');
</code>```

would also disable the element. Since you passed in a string value which is a truthy value.

Further info: http://www.w3.org/TR/html401/interact/forms.html#h-17.12.1

ContentLicense: CC BY-SA 2.5

Title: strange issue with jQuery

Body:
I have a very strange issue with jQuery.

The problem:

$("#button-prev").attr("disabled", "disabled");

This doesn't work. If I check with Firebug I see disabled="" as element attribute

But for example this

$("#button-prev").attr("disablea", "disabled");

works as you should expect. Anyone an idea what it could be?

Body:
The disabled is a boolean property. Therefore it's just enough if a truthy value is set.

<button disabled>foo</button>

would work aswell in most browsers. You need to either completely remove the property by using

$('#button-prev').removeAttr('disabled');

or set it explicitly to false / 0

$('#button-prev').attr('disabled', false);

It's a common mistake and pretty confusing, consider, a call like

$(element).attr('disabled', 'false');

would also disable the element. Since you passed in a string value which is a truthy value.

Further info: http://www.w3.org/TR/html401/interact/forms.html#h-17.12.1


问:
Angularjs RangeSlider and Checkbox
I found this example on Google.

Is there a way to start with following properties:

```<code>  $scope.slider_all_options = {
minValue: 0,
maxValue: 100,
options: {
  floor: 1,
  ceil: 100,
  step: 1,
  precision: 0,
}
</code>```

};

Then change the minValue to 1 for the RangeSlider if the checkbox is checked and back to 0 when the Checkbox is unchecked? I cannot solve this problem at the moment.

Please take a look at my JSFiddle:

Here is my JSFiddle

答:
I did this JSFiddle, I think it is what do you need.

Just add the model to you checkbox:

```<code><input type="checkbox" ng-click="toggleHighValue()" ng-model="check">
</code>```

And implement the toggle function like this:

```<code>  $scope.toggleHighValue = function() {
  if ($scope.check) {
      $scope.slider_all_options.minValue = 1
    } else {
      $scope.slider_all_options.minValue = 0
    }
  }
</code>```

Title: Angularjs RangeSlider and Checkbox

Body:
I found this example on Google.

Is there a way to start with following properties:

  $scope.slider_all_options = {
minValue: 0,
maxValue: 100,
options: {
  floor: 1,
  ceil: 100,
  step: 1,
  precision: 0,
}

};

Then change the minValue to 1 for the RangeSlider if the checkbox is checked and back to 0 when the Checkbox is unchecked? I cannot solve this problem at the moment.

Please take a look at my JSFiddle:

Here is my JSFiddle

Body:
I did this JSFiddle, I think it is what do you need.

Just add the model to you checkbox:

<input type="checkbox" ng-click="toggleHighValue()" ng-model="check">

And implement the toggle function like this:

  $scope.toggleHighValue = function() {
  if ($scope.check) {
      $scope.slider_all_options.minValue = 1
    } else {
      $scope.slider_all_options.minValue = 0
    }
  }


问:
How to update some part of text using SQL UPDATE statement
I have a query saved in column of a table named sqlcode which is maintaining the metadata. For instance following is a query:

```<code>select
    id, name, address, phone,
    .......
    ......
    , upddate
from
    bank a
join
    bankreg b on a.id = b.id
where
    (condition)
</code>```

I'm trying to update the text of query saved in metadata but I want to only update column names part of the query without making any change to select, from, joins or any other conditions. Any way of only updating column names would be helpful. I've tried using replace function but couldn't got desired output.

I want to update columns of this textual query with the columns present in  master table. If new columns are added in master, I want to add them to metadata query as well which is saved in text form. INFORMATION_SCHEMA.COLUMNS gives me the column names now I just want to update these column names to above query

答:
If you wrap the columns you need to update in brackets, you can update them in your REPLACE, without updating the items in the SELECT portion.

```<code>select
id,name,address,phone,
.......
......
,upddate
from bank a
join bankreg b
on
a.id = b.id
where ([address] = 'My Street')
</code>```

Your update would then be:

```<code>UPDATE MyTable SET MyCol = REPLACE(MyCol , '[address]', '[some_other_field]')
</code>```

Body:
I have a query saved in column of a table named sqlcode which is maintaining the metadata. For instance following is a query:

select
    id, name, address, phone,
    .......
    ......
    , upddate
from
    bank a
join
    bankreg b on a.id = b.id
where
    (condition)

I'm trying to update the text of query saved in metadata but I want to only update column names part of the query without making any change to select, from, joins or any other conditions. Any way of only updating column names would be helpful. I've tried using replace function but couldn't got desired output.

I want to update columns of this textual query with the columns present in  master table. If new columns are added in master, I want to add them to metadata query as well which is saved in text form. INFORMATION_SCHEMA.COLUMNS gives me the column names now I just want to update these column names to above query

Body:
If you wrap the columns you need to update in brackets, you can update them in your REPLACE, without updating the items in the SELECT portion.

select
id,name,address,phone,
.......
......
,upddate
from bank a
join bankreg b
on
a.id = b.id
where ([address] = 'My Street')

Your update would then be:

UPDATE MyTable SET MyCol = REPLACE(MyCol , '[address]', '[some_other_field]')


问:
Extend native interface for element
I want to make a "semi-customized" button. Basically, I want it to extend the <button> tag's initial properties. Here's a minimal example of what I am doing:

```<code>export default class Button extends React.Component<Props, State> {
  public render() {
    const { size, ...buttonProps } = this.props;
    return (
      <button
        {...buttonProps}
        className={classnames({
          [styles.small]: size === 'small',
          [styles.medium]: size === 'medium',
          [styles.large]: size === 'large',
        })}
      />
    );
  }
}
</code>```

However, what I can't figure out is how to create an interface which inherits all of the native HTMLButton's proptypes.

I imagine it would be something like:

```<code>interface Props extends <(Something)> {
  size: 'small' | 'medium' | 'large',
}
</code>```

How would you extend native HTML element properties in typescript?

答:
You can use HTMLProps interface from react.

```<code>import { HTMLProps } from 'react'

interface Props extends HTMLProps<HTMLButtonElement> {
    size: 'small' | 'medium' | 'large'
}
</code>```

Title: Extend native interface for element

Body:
I want to make a "semi-customized" button. Basically, I want it to extend the <button> tag's initial properties. Here's a minimal example of what I am doing:

export default class Button extends React.Component<Props, State> {
  public render() {
    const { size, ...buttonProps } = this.props;
    return (
      <button
        {...buttonProps}
        className={classnames({
          [styles.small]: size === 'small',
          [styles.medium]: size === 'medium',
          [styles.large]: size === 'large',
        })}
      />
    );
  }
}

However, what I can't figure out is how to create an interface which inherits all of the native HTMLButton's proptypes.

I imagine it would be something like:

interface Props extends <(Something)> {
  size: 'small' | 'medium' | 'large',
}

How would you extend native HTML element properties in typescript?

Body:
You can use HTMLProps interface from react.

import { HTMLProps } from 'react'

interface Props extends HTMLProps<HTMLButtonElement> {
    size: 'small' | 'medium' | 'large'
}


答:
You wanna rename names of columns in select part?

Use currentNAme AS NewName, or currentName NewName, for each name you wanna rename.

Depends on the DBMS weather one or other or both syntax are supported (sql-server -> go with AS). Test with 1 column name to see which one works then use that one till end

```<code>select
id AS myNameForId,
name AS myNmeForName,
.......
......
,upddate
from bank AS a
join bankreg AS b
on
a.id = b.id
where (condition)
</code>```

OR

```<code>select
id myNameForId,
name myNmeForName,
.......
......
,upddate
from bank a
join bankreg b
on
a.id = b.id
where (condition)
</code>```

Title: How to update some part of text using SQL UPDATE statement

Body:
You wanna rename names of columns in select part?

Use currentNAme AS NewName, or currentName NewName, for each name you wanna rename.

Depends on the DBMS weather one or other or both syntax are supported (sql-server -> go with AS). Test with 1 column name to see which one works then use that one till end

select
id AS myNameForId,
name AS myNmeForName,
.......
......
,upddate
from bank AS a
join bankreg AS b
on
a.id = b.id
where (condition)

OR

select
id myNameForId,
name myNmeForName,
.......
......
,upddate
from bank a
join bankreg b
on
a.id = b.id
where (condition)


问:
CORS error when calling RESTful services from behind corporate firewall
I am getting the following CORS error when I am trying to make calls to my RESTful web services written in PHP ONLY when I am behind my corporate firewall.

Refused to connect to 'http://prx-9k-40-hadc/?cfru=aHR0cDovL2phY2tzb25uZy5wcm9qZWN0c2JpdC5vcmcvcGl6emFwbGFjZS9sb2dpbl9hZG1pbi5waHA/dXNlcmlkPWFkbWluJnBhc3N3b3JkPWFkbWlu' because it violates the following Content Security Policy directive: "connect-src 'self' data: gap: http://myurl.com https://ssl.gstatic.com 'unsafe-eval' 'self' ws:".

This does not happen when I am not behind the corporate firewall (i.e. I am logging on from home and not connected through corporate VPN).

My content security policy is as follows:

```<code><meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: http://myurl.com https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *">
</code>```

And this is how I did my Ajax call:

```<code>$.ajax({
    url: url,
    type: 'GET',
    data: JSONObject,
    dataType: 'json',
    contentType: "application/json; charset=utf-8",
    success: function (arr) {
        _getLoginResult(arr);
    },
    error: function () {
        validationMsg();
    }
});
</code>```

My headers in my PHP web service look like this:

```<code>header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');
header("Content-Type: application/json; charset=UTF-8");
</code>```

Again, here are the symptoms:

Everything here works fine when I am NOT behind my corporate firewall, and not logged in to my company through its VPN.

Once I am logged in the CORS error occurs and none of the settings changes that I attempted to make in the server, or setting changes to my content security policy changes anything.

I see that it says "refused to connect to http://prx-9k-40-hadc". This is definitely not the URL of my RESTful web services. It feels like my company's proxy server.

Has anyone encountered this? I will like to be able to run my web services behind my corporate firewall.

答:
I solved it. My corporate firewall was configured to strip access control headers it considers dangerous. Obviously it felt that this was dangerous if it isn't access via SSL.

```<code>header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');
header("Content-Type: application/json; charset=UTF-8");
</code>```

So all I did was made my RESTful service calls with https:// instead of http:// and all is fine.

I definitely didn't think this was the problem because less than a week ago, this firewall directive didn't exist.

Body:
I am getting the following CORS error when I am trying to make calls to my RESTful web services written in PHP ONLY when I am behind my corporate firewall.

Refused to connect to 'http://prx-9k-40-hadc/?cfru=aHR0cDovL2phY2tzb25uZy5wcm9qZWN0c2JpdC5vcmcvcGl6emFwbGFjZS9sb2dpbl9hZG1pbi5waHA/dXNlcmlkPWFkbWluJnBhc3N3b3JkPWFkbWlu' because it violates the following Content Security Policy directive: "connect-src 'self' data: gap: http://myurl.com https://ssl.gstatic.com 'unsafe-eval' 'self' ws:".

This does not happen when I am not behind the corporate firewall (i.e. I am logging on from home and not connected through corporate VPN).

My content security policy is as follows:

<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: http://myurl.com https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *">

And this is how I did my Ajax call:

$.ajax({
    url: url,
    type: 'GET',
    data: JSONObject,
    dataType: 'json',
    contentType: "application/json; charset=utf-8",
    success: function (arr) {
        _getLoginResult(arr);
    },
    error: function () {
        validationMsg();
    }
});

My headers in my PHP web service look like this:

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');
header("Content-Type: application/json; charset=UTF-8");

Again, here are the symptoms:

Everything here works fine when I am NOT behind my corporate firewall, and not logged in to my company through its VPN.

Once I am logged in the CORS error occurs and none of the settings changes that I attempted to make in the server, or setting changes to my content security policy changes anything.

I see that it says "refused to connect to http://prx-9k-40-hadc". This is definitely not the URL of my RESTful web services. It feels like my company's proxy server.

Has anyone encountered this? I will like to be able to run my web services behind my corporate firewall.

Body:
I solved it. My corporate firewall was configured to strip access control headers it considers dangerous. Obviously it felt that this was dangerous if it isn't access via SSL.

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');
header("Content-Type: application/json; charset=UTF-8");

So all I did was made my RESTful service calls with https:// instead of http:// and all is fine.

I definitely didn't think this was the problem because less than a week ago, this firewall directive didn't exist.


问:
How can I make countdown time?
So I have my code here:

```<code>import time
from random import uniform
rng = uniform(1, 3)
start = time.time()
while True:
    if time.time() == start + rng:
        print("finally")
</code>```

My question is: how can I make the program print "finally"?

答:
add a break also ;)</p>

```<code>import time
from random import uniform
rng = uniform(1, 3)
start = time.time()
while True:
    if time.time() >= start + rng:    # first edit here (also as suggested by Patrick Haugh)
        print("finally")
        break                         # add this also to skip infinite looping
</code>```

Title: How can I make countdown time?

Body:
So I have my code here:

import time
from random import uniform
rng = uniform(1, 3)
start = time.time()
while True:
    if time.time() == start + rng:
        print("finally")

My question is: how can I make the program print "finally"?

Body:
add a break also ;)

import time
from random import uniform
rng = uniform(1, 3)
start = time.time()
while True:
    if time.time() >= start + rng:    # first edit here (also as suggested by Patrick Haugh)
        print("finally")
        break                         # add this also to skip infinite looping


问:
Add jitter to grouped box plot using markers in R plotly
I'd like the interactive (that means they can be selected with box/lasso selection) jittered points to be displayed on the grouped boxplot. I came out of this question: Add jitter to box plot using markers in plotly. I want exactly the same but the boxplots should be grouped.

I made a boxplot but the points are all mixed up:

```<code>dat %>%
  plot_ly(x = ~as.numeric(IC),
            y = ~xval,
            color = ~gene,
            type = "box",
            hoverinfo = "none",
            boxpoints = FALSE
          ) %>%
  add_markers(x = ~jitter(as.numeric(IC)),
              y = ~xval,
              color = ~gene,
              marker = list(size = 3),
              hoverinfo = "text",
              text = txt,
              showlegend = TRUE) %>%
layout(boxmode = "group")
</code>```

When I try making the X axis grouped by factor (so that each combination is a level) I cannot make my boxplot grouped:

```<code>dat <- dat %>%
  mutate(gene_x_covariate = as.factor(
    paste0(get(facet_title), "-", gene)))

dat %>%
  plot_ly(x = ~as.numeric(gene_x_covariate),
            y = ~xval,
            color = ~gene,
            type = "box",
            hoverinfo = "none",
            boxpoints = FALSE
          ) %>%
  add_markers(x = ~jitter(as.numeric(gene_x_covariate)),
              y = ~xval,
              color = ~gene,
              marker = list(size = 3),
              hoverinfo = "text",
              text = txt,
              showlegend = TRUE) %>%
layout(boxmode = "group")
</code>```

When I try to mix the variables on X axis, I get the points away from the boxplots:

```<code>dat %>%
  plot_ly(x = ~as.numeric(IC),
            y = ~xval,
            color = ~gene,
            type = "box",
            hoverinfo = "none"
          ) %>%
  add_markers(x = ~jitter(as.numeric(gene_x_covariate)),
              y = ~xval,
              color = ~gene,
              marker = list(size = 3),
              hoverinfo = "text",
              text = txt,
              showlegend = TRUE) %>%
layout(boxmode = "group")
</code>```

Any ideas?

答:
does boxpoints works for for you? See this

You can move those points by pointpos parameter.

```<code>iris %>%
  plot_ly(x = ~cut( Sepal.Length, breaks = 4),
          y = ~Petal.Width,
          color = ~Species,
          type = "box",
          marker = list( size = 10),
          boxpoints = "all",
          jitter = 0.4,
          pointpos = 0,
          hoverinfo = "all"
  ) %>% layout( boxmode = "group")
</code>```

Body:
I'd like the interactive (that means they can be selected with box/lasso selection) jittered points to be displayed on the grouped boxplot. I came out of this question: Add jitter to box plot using markers in plotly. I want exactly the same but the boxplots should be grouped.

I made a boxplot but the points are all mixed up:

dat %>%
  plot_ly(x = ~as.numeric(IC),
            y = ~xval,
            color = ~gene,
            type = "box",
            hoverinfo = "none",
            boxpoints = FALSE
          ) %>%
  add_markers(x = ~jitter(as.numeric(IC)),
              y = ~xval,
              color = ~gene,
              marker = list(size = 3),
              hoverinfo = "text",
              text = txt,
              showlegend = TRUE) %>%
layout(boxmode = "group")

When I try making the X axis grouped by factor (so that each combination is a level) I cannot make my boxplot grouped:

dat <- dat %>%
  mutate(gene_x_covariate = as.factor(
    paste0(get(facet_title), "-", gene)))

dat %>%
  plot_ly(x = ~as.numeric(gene_x_covariate),
            y = ~xval,
            color = ~gene,
            type = "box",
            hoverinfo = "none",
            boxpoints = FALSE
          ) %>%
  add_markers(x = ~jitter(as.numeric(gene_x_covariate)),
              y = ~xval,
              color = ~gene,
              marker = list(size = 3),
              hoverinfo = "text",
              text = txt,
              showlegend = TRUE) %>%
layout(boxmode = "group")

When I try to mix the variables on X axis, I get the points away from the boxplots:

dat %>%
  plot_ly(x = ~as.numeric(IC),
            y = ~xval,
            color = ~gene,
            type = "box",
            hoverinfo = "none"
          ) %>%
  add_markers(x = ~jitter(as.numeric(gene_x_covariate)),
              y = ~xval,
              color = ~gene,
              marker = list(size = 3),
              hoverinfo = "text",
              text = txt,
              showlegend = TRUE) %>%
layout(boxmode = "group")

Any ideas?

Body:
does boxpoints works for for you? See this

You can move those points by pointpos parameter.

iris %>%
  plot_ly(x = ~cut( Sepal.Length, breaks = 4),
          y = ~Petal.Width,
          color = ~Species,
          type = "box",
          marker = list( size = 10),
          boxpoints = "all",
          jitter = 0.4,
          pointpos = 0,
          hoverinfo = "all"
  ) %>% layout( boxmode = "group")


问:
How do I compare a Short with an Int in Kotlin?
I have a Short variable that I need to check the value of. But the compiler complains that Operator '==' cannot be applied to 'Short' and 'Int' when I do a simple equals check:

```<code>val myShort: Short = 4
if (myShort == 4) // <-- ERROR
    println("all is well")
</code>```

So what's the simplest, "cleanest" way to do this equals check?

Here are some things I tried.

The first one casts the 4 integer to a short (looks weird, invoking a function on a primitive number)

```<code>val myShort: Short = 4
if (myShort == 4.toShort())
    println("all is well")
</code>```

The next one casts the short to an int (shouldn't be necessary, now I have two ints when I shouldn't really need any)

```<code>val myShort: Short = 4
if (myShort.toInt() == 4)
    println("all is well")
</code>```

答:
Basically, the 'cleanest' way to compare it with a small constant is myShort == 4.toShort().

But if you want to compare a Short with a wider-type variable, convert myShort instead to avoid the overflow: myShort.toInt() == someInt.

looks weird, invoking a function on a primitive number

But it does not actually call the functions, they are intrinsified and compiled to bytecode that operates the numbers in a way that is natural for JVM, for example, the bytecode for myShort == 4.toShort() is:

```<code>ILOAD 2      // loads myShort
ICONST_4     // pushes int constant 4
I2S          // converts the int to short 4
IF_ICMPNE L3 // compares the two shorts
</code>```

See also: another Q&A concerning numeric conversions.

ContentLicense: CC BY-SA 4.0

Body:
I have a Short variable that I need to check the value of. But the compiler complains that Operator '==' cannot be applied to 'Short' and 'Int' when I do a simple equals check:

val myShort: Short = 4
if (myShort == 4) // <-- ERROR
    println("all is well")

So what's the simplest, "cleanest" way to do this equals check?

Here are some things I tried.

The first one casts the 4 integer to a short (looks weird, invoking a function on a primitive number)

val myShort: Short = 4
if (myShort == 4.toShort())
    println("all is well")

The next one casts the short to an int (shouldn't be necessary, now I have two ints when I shouldn't really need any)

val myShort: Short = 4
if (myShort.toInt() == 4)
    println("all is well")

Body:
Basically, the 'cleanest' way to compare it with a small constant is myShort == 4.toShort().

But if you want to compare a Short with a wider-type variable, convert myShort instead to avoid the overflow: myShort.toInt() == someInt.

looks weird, invoking a function on a primitive number

But it does not actually call the functions, they are intrinsified and compiled to bytecode that operates the numbers in a way that is natural for JVM, for example, the bytecode for myShort == 4.toShort() is:

ILOAD 2      // loads myShort
ICONST_4     // pushes int constant 4
I2S          // converts the int to short 4
IF_ICMPNE L3 // compares the two shorts

See also: another Q&A concerning numeric conversions.


问:
Get the amount of records of a person of the last 5 years
I've the following data.table:

```<code>               CODE     ID           VALUE YEAR_MONTH  temp_YEAR_MONTH
      1:       ABOUDERE 12608095     1     199206      1992-06-01
      2:       ABOUDERE 12608095     1     199207      1992-07-01
      3:       ABOUDERE 12608095     1     199208      1992-08-01
      4:       ABOUDERE 12608095     1     199209      1992-09-01
      5:       ABOUDERE 12608095     1     199210      1992-10-01
     ---
1012974:       DCBEZOND    88619     1     201711      2017-11-01
1012975:       ABOUDERE    90325     1     201711      2017-11-01
1012976:       ABOUDERE    91301     1     201711      2017-11-01
1012977:       ABOUDERE    91808     1     201711      2017-11-01
1012978:       ABOUDERE    92866     1     201711      2017-11-01
</code>```

And what I would like to have is, an extra column which tells me how any times an ID appeared, this for the last 5 years... only (max 60)

E.G.

```<code>         CODE     ID           VALUE YEAR_MONTH  temp_YEAR_MONTH   APPEARANCES_LAST_5_YEARS
1:       ABOUDERE 12608095     1     199206      1992-06-01        1
2:       ABOUDERE 12608095     1     199207      1992-07-01        2
3:       ABOUDERE 12608095     1     199208      1992-08-01        3
4:       ABOUDERE 12608095     1     199209      1992-09-01        4
5:       ABOUDERE 12608095     1     199210      1992-10-01        5
---
1012978: ABOUDERE    92866     1     201711      2017-11-01        60
</code>```

The way how I did this was via:

```<code>dt$temp_YEAR_MONTH <- as.Date(paste(dt$YEAR_MONTH,'01'), format = '%Y%m%d')
dt$APPEARANCES_LAST_5_YEARS = 0

tmp.temp_YEAR_MONTH = dt$temp_YEAR_MONTH
tmp.ID= dt$ID

id_date_function <- function(id, date){
  sum(tmp.ID == id & tmp.temp_YEAR_MONTH < as.Date(paste(date,'01'), format = '%Y%m%d') &
    tmp.temp_YEAR_MONTH  > as.Date(paste(as.numeric(date)-500,'01'), format = '%Y%m%d'))
}

print('this will take some time')
dt$APPEARANCES_LAST_5_YEARS <-
  apply(dt, 1, function(x)  id_date_function(x['ID'], x['YEAR_MONTH']))
</code>```

But this is very slow... for 1.000.000 records, it will take +13hours.
Does someone has a better method?

答:
This can be solved using a range join (non-equi join) and aggregating during join using by = .EACHI:

```<code>library(data.table)
library(lubridate)
DT[, mon := ymd(YEAR_MONTH, truncated = 1L)][
  , APPEARANCES_LAST_5_YEARS :=
    .SD[.(ID, mon, mon - months(5L * 12L)),
        on = .(ID, mon <= V2, mon > V3), .N, by = .EACHI]$N][, mon := NULL][]

</code>```

```<code>        CODE       ID VALUE YEAR_MONTH APPEARANCES_LAST_5_YEARS
 1: ABOUDERE 12608095     1     199206                        1
 2: ABOUDERE 12608095     1     199207                        2
 3: ABOUDERE 12608095     1     199208                        3
 4: ABOUDERE 12608095     1     199209                        4
 5: ABOUDERE 12608095     1     199210                        5
 6: DCBEZOND    88619     1     201711                        1
 7: ABOUDERE    90325     1     201711                        1
 8: ABOUDERE    91301     1     201711                        1
 9: ABOUDERE    91808     1     201711                        1
10: ABOUDERE    92866     1     201711                        1
</code>```

Unfortunately, the sample data set provided by the OP isn't large enough to cover a 5 year's period. In order to demonstrate that only a certain period is considered, the period is restricted to 3 months for demonstration purpose:

```<code>DT[, mon := ymd(YEAR_MONTH, truncated = 1L)][
  , APPEARANCES_LAST_3_MONTHS :=
    .SD[.(ID, mon, mon - months(3L)),
        on = .(ID, mon <= V2, mon > V3), .N, by = .EACHI]$N][, mon := NULL][]
</code>```

```<code>        CODE       ID VALUE YEAR_MONTH APPEARANCES_LAST_3_MONTHS
 1: ABOUDERE 12608095     1     199206                         1
 2: ABOUDERE 12608095     1     199207                         2
 3: ABOUDERE 12608095     1     199208                         3
 4: ABOUDERE 12608095     1     199209                         3
 5: ABOUDERE 12608095     1     199210                         3
 6: DCBEZOND    88619     1     201711                         1
 7: ABOUDERE    90325     1     201711                         1
 8: ABOUDERE    91301     1     201711                         1
 9: ABOUDERE    91808     1     201711                         1
10: ABOUDERE    92866     1     201711                         1
</code>```

Data

```<code>library(data.table)
DT <- fread("id               CODE     ID           VALUE YEAR_MONTH  temp_YEAR_MONTH
      1:       ABOUDERE 12608095     1     199206      1992-06-01
      2:       ABOUDERE 12608095     1     199207      1992-07-01
      3:       ABOUDERE 12608095     1     199208      1992-08-01
      4:       ABOUDERE 12608095     1     199209      1992-09-01
      5:       ABOUDERE 12608095     1     199210      1992-10-01
1012974:       DCBEZOND    88619     1     201711      2017-11-01
1012975:       ABOUDERE    90325     1     201711      2017-11-01
1012976:       ABOUDERE    91301     1     201711      2017-11-01
1012977:       ABOUDERE    91808     1     201711      2017-11-01
1012978:       ABOUDERE    92866     1     201711      2017-11-01        ",
            drop = c(1L, 6L))
DT
</code>```

```<code>        CODE       ID VALUE YEAR_MONTH
 1: ABOUDERE 12608095     1     199206
 2: ABOUDERE 12608095     1     199207
 3: ABOUDERE 12608095     1     199208
 4: ABOUDERE 12608095     1     199209
 5: ABOUDERE 12608095     1     199210
 6: DCBEZOND    88619     1     201711
 7: ABOUDERE    90325     1     201711
 8: ABOUDERE    91301     1     201711
 9: ABOUDERE    91808     1     201711
10: ABOUDERE    92866     1     201711
</code>```

Body:
I've the following data.table:

               CODE     ID           VALUE YEAR_MONTH  temp_YEAR_MONTH
      1:       ABOUDERE 12608095     1     199206      1992-06-01
      2:       ABOUDERE 12608095     1     199207      1992-07-01
      3:       ABOUDERE 12608095     1     199208      1992-08-01
      4:       ABOUDERE 12608095     1     199209      1992-09-01
      5:       ABOUDERE 12608095     1     199210      1992-10-01
     ---
1012974:       DCBEZOND    88619     1     201711      2017-11-01
1012975:       ABOUDERE    90325     1     201711      2017-11-01
1012976:       ABOUDERE    91301     1     201711      2017-11-01
1012977:       ABOUDERE    91808     1     201711      2017-11-01
1012978:       ABOUDERE    92866     1     201711      2017-11-01

And what I would like to have is, an extra column which tells me how any times an ID appeared, this for the last 5 years... only (max 60)

E.G.

         CODE     ID           VALUE YEAR_MONTH  temp_YEAR_MONTH   APPEARANCES_LAST_5_YEARS
1:       ABOUDERE 12608095     1     199206      1992-06-01        1
2:       ABOUDERE 12608095     1     199207      1992-07-01        2
3:       ABOUDERE 12608095     1     199208      1992-08-01        3
4:       ABOUDERE 12608095     1     199209      1992-09-01        4
5:       ABOUDERE 12608095     1     199210      1992-10-01        5
---
1012978: ABOUDERE    92866     1     201711      2017-11-01        60

The way how I did this was via:

dt$temp_YEAR_MONTH <- as.Date(paste(dt$YEAR_MONTH,'01'), format = '%Y%m%d')
dt$APPEARANCES_LAST_5_YEARS = 0

tmp.temp_YEAR_MONTH = dt$temp_YEAR_MONTH
tmp.ID= dt$ID

id_date_function <- function(id, date){
  sum(tmp.ID == id & tmp.temp_YEAR_MONTH < as.Date(paste(date,'01'), format = '%Y%m%d') &
    tmp.temp_YEAR_MONTH  > as.Date(paste(as.numeric(date)-500,'01'), format = '%Y%m%d'))
}

print('this will take some time')
dt$APPEARANCES_LAST_5_YEARS <-
  apply(dt, 1, function(x)  id_date_function(x['ID'], x['YEAR_MONTH']))

But this is very slow... for 1.000.000 records, it will take +13hours.
Does someone has a better method?

Body:
This can be solved using a range join (non-equi join) and aggregating during join using by = .EACHI:

library(data.table)
library(lubridate)
DT[, mon := ymd(YEAR_MONTH, truncated = 1L)][
  , APPEARANCES_LAST_5_YEARS :=
    .SD[.(ID, mon, mon - months(5L * 12L)),
        on = .(ID, mon <= V2, mon > V3), .N, by = .EACHI]$N][, mon := NULL][]

        CODE       ID VALUE YEAR_MONTH APPEARANCES_LAST_5_YEARS
 1: ABOUDERE 12608095     1     199206                        1
 2: ABOUDERE 12608095     1     199207                        2
 3: ABOUDERE 12608095     1     199208                        3
 4: ABOUDERE 12608095     1     199209                        4
 5: ABOUDERE 12608095     1     199210                        5
 6: DCBEZOND    88619     1     201711                        1
 7: ABOUDERE    90325     1     201711                        1
 8: ABOUDERE    91301     1     201711                        1
 9: ABOUDERE    91808     1     201711                        1
10: ABOUDERE    92866     1     201711                        1

Unfortunately, the sample data set provided by the OP isn't large enough to cover a 5 year's period. In order to demonstrate that only a certain period is considered, the period is restricted to 3 months for demonstration purpose:

DT[, mon := ymd(YEAR_MONTH, truncated = 1L)][
  , APPEARANCES_LAST_3_MONTHS :=
    .SD[.(ID, mon, mon - months(3L)),
        on = .(ID, mon <= V2, mon > V3), .N, by = .EACHI]$N][, mon := NULL][]

        CODE       ID VALUE YEAR_MONTH APPEARANCES_LAST_3_MONTHS
 1: ABOUDERE 12608095     1     199206                         1
 2: ABOUDERE 12608095     1     199207                         2
 3: ABOUDERE 12608095     1     199208                         3
 4: ABOUDERE 12608095     1     199209                         3
 5: ABOUDERE 12608095     1     199210                         3
 6: DCBEZOND    88619     1     201711                         1
 7: ABOUDERE    90325     1     201711                         1
 8: ABOUDERE    91301     1     201711                         1
 9: ABOUDERE    91808     1     201711                         1
10: ABOUDERE    92866     1     201711                         1

Data

library(data.table)
DT <- fread("id               CODE     ID           VALUE YEAR_MONTH  temp_YEAR_MONTH
      1:       ABOUDERE 12608095     1     199206      1992-06-01
      2:       ABOUDERE 12608095     1     199207      1992-07-01
      3:       ABOUDERE 12608095     1     199208      1992-08-01
      4:       ABOUDERE 12608095     1     199209      1992-09-01
      5:       ABOUDERE 12608095     1     199210      1992-10-01
1012974:       DCBEZOND    88619     1     201711      2017-11-01
1012975:       ABOUDERE    90325     1     201711      2017-11-01
1012976:       ABOUDERE    91301     1     201711      2017-11-01
1012977:       ABOUDERE    91808     1     201711      2017-11-01
1012978:       ABOUDERE    92866     1     201711      2017-11-01        ",
            drop = c(1L, 6L))
DT

        CODE       ID VALUE YEAR_MONTH
 1: ABOUDERE 12608095     1     199206
 2: ABOUDERE 12608095     1     199207
 3: ABOUDERE 12608095     1     199208
 4: ABOUDERE 12608095     1     199209
 5: ABOUDERE 12608095     1     199210
 6: DCBEZOND    88619     1     201711
 7: ABOUDERE    90325     1     201711
 8: ABOUDERE    91301     1     201711
 9: ABOUDERE    91808     1     201711
10: ABOUDERE    92866     1     201711


问:
Using COleDispatchDriver to dynamically load COM object leaking memory
I'm debugging some legacy code. It loads a user defined COM object, allows the user to call functions in it, and then releases it. However, we have found that every time we load and unload the COM object, we leak memory. As a test, we changed the code to load it and hang on to it, and keep re-using it until program exit and the leak went away.

Here are the relevant code snippets:

This C++ codeis is called to load the COM object, pszProgId is a string identifying the target DLL.

```<code>    COleDispatchDriver *pDispatchDriver = NULL;
    pDispatchDriver = new COleDispatchDriver();
    if (!pDispatchDriver->CreateDispatch(pszProgId, &oleException))
    {
     throw &oleException;
    }
    pDispatchDriver->m_bAutoRelease = TRUE;
   *ppvObject = (void *) pDispatchDriver;
</code>```

void ** ppvObject is a pointer we pass around to generically hold different objects. It is part of a much larger structure.
And here is the code we call when releasing the COM object.

After we are done using the COM object, we release it as follows:

```<code>COleDispatchDriver* pDispatchDriver = (COleDispatchDriver*) (*((LONG_PTR*)(ppvObject)));
pDispatchDriver->ReleaseDispatch();
delete pDispatchDriver;
</code>```

This is leaking about 1 meg every call. The target COM object is C#. Anyone have any idea what we're doing wrong or a better way to do what we're trying to do?

We are building this in VisualStudio 2015 in case that is relevant.

Re xMRi:

As already noted, we tried changing that flag to TRUE to no effect. As a sanity check, I tried doing that again after reading your post and again it did nothing to fix the memory leak. So for better clarity, I've updated my code to show it set to TRUE which is almost certainly the right value but still exhibiting the same memory leak described above.

答:
ReleaseDispatch does nothing if you set  m_bAutoRelease to FALSE. So in fact you don't free the instance of this COM object.

See the implementation:

```<code>void COleDispatchDriver::ReleaseDispatch()
{
    if (m_lpDispatch != NULL)
    {
        if (m_bAutoRelease)
            m_lpDispatch->Release();
        m_lpDispatch = NULL;
    }
}
</code>```

So created the problem in setting m_bAutoRelease to FALSE yourself. Check the reasons why you are doing this.

You can directly get the LPDISPTACH pointer and call Release() but this is exactly what should be done when m_bAutoRelease is TRUE.

Body:
I'm debugging some legacy code. It loads a user defined COM object, allows the user to call functions in it, and then releases it. However, we have found that every time we load and unload the COM object, we leak memory. As a test, we changed the code to load it and hang on to it, and keep re-using it until program exit and the leak went away.

Here are the relevant code snippets:

This C++ codeis is called to load the COM object, pszProgId is a string identifying the target DLL.

    COleDispatchDriver *pDispatchDriver = NULL;
    pDispatchDriver = new COleDispatchDriver();
    if (!pDispatchDriver->CreateDispatch(pszProgId, &oleException))
    {
     throw &oleException;
    }
    pDispatchDriver->m_bAutoRelease = TRUE;
   *ppvObject = (void *) pDispatchDriver;

void ** ppvObject is a pointer we pass around to generically hold different objects. It is part of a much larger structure.
And here is the code we call when releasing the COM object.

After we are done using the COM object, we release it as follows:

COleDispatchDriver* pDispatchDriver = (COleDispatchDriver*) (*((LONG_PTR*)(ppvObject)));
pDispatchDriver->ReleaseDispatch();
delete pDispatchDriver;

This is leaking about 1 meg every call. The target COM object is C#. Anyone have any idea what we're doing wrong or a better way to do what we're trying to do?

We are building this in VisualStudio 2015 in case that is relevant.

Re xMRi:

As already noted, we tried changing that flag to TRUE to no effect. As a sanity check, I tried doing that again after reading your post and again it did nothing to fix the memory leak. So for better clarity, I've updated my code to show it set to TRUE which is almost certainly the right value but still exhibiting the same memory leak described above.

Body:
ReleaseDispatch does nothing if you set  m_bAutoRelease to FALSE. So in fact you don't free the instance of this COM object.

See the implementation:

void COleDispatchDriver::ReleaseDispatch()
{
    if (m_lpDispatch != NULL)
    {
        if (m_bAutoRelease)
            m_lpDispatch->Release();
        m_lpDispatch = NULL;
    }
}

So created the problem in setting m_bAutoRelease to FALSE yourself. Check the reasons why you are doing this.

You can directly get the LPDISPTACH pointer and call Release() but this is exactly what should be done when m_bAutoRelease is TRUE.


问:
C# MVC save View as png
i have problem with png HTML renderer,
i am trying to send png of View to email, but on email i get 0B .png
PS: Ticket.pdf is ok</p>

```<code> using (MemoryStream ms = new MemoryStream())
        {

            var pdf = PdfGenerator.GeneratePdf(RenderRazorViewToString("TicketTemplateBig", model), PdfSharp.PageSize.A4);
            pdf.Save(ms, false);

            /////////////////
            //Bitmap bitmap = new Bitmap(Convert.ToInt32(1024), Convert.ToInt32(1024), System.Drawing.Imaging.PixelFormat.Format32bppArgb);
            using (MemoryStream ms2 = new MemoryStream())
            {
                //Image image = TheArtOfDev.HtmlRenderer.WinForms.HtmlRender.RenderToImage(RenderRazorViewToString("TicketTemplateBig", model));

                Bitmap bitmap = (Bitmap)Image.FromFile(@"C:\logo.png");
                bitmap.Save(ms2, ImageFormat.Png);

                /////////////////
                await ms.FlushAsync();
                await ms2.FlushAsync();
                mm.Attachments.Add(new Attachment(ms, string.Format("Ticket.pdf"), "application/pdf"));
                streams.Add(ms);
                mm.Attachments.Add(new Attachment(ms2, string.Format("logo.png"), "application/png"));
                streams.Add(ms2);
                await client.SendMailAsync(mm);
            }
        }
</code>```

答:
problem : stream was on last position

result  :  ms2.Position = 0;

```<code>           using (MemoryStream ms = new MemoryStream())
        {

            var pdf = PdfGenerator.GeneratePdf(RenderRazorViewToString("TicketTemplateBig", model), PdfSharp.PageSize.A4);
            pdf.Save(ms, false);

            using (MemoryStream ms2 = new MemoryStream())
            {
                Image image = TheArtOfDev.HtmlRenderer.WinForms.HtmlRender.RenderToImage(RenderRazorViewToString("TicketTemplateBig", model));
                image.Save(ms2, ImageFormat.Png);
                ms2.Position = 0;
                await ms.FlushAsync();
                await ms2.FlushAsync();
                mm.Attachments.Add(new Attachment(ms, string.Format("Ticket.pdf"), "application/pdf"));
                mm.Attachments.Add(new Attachment(ms2, string.Format("Ticket.png"), "application/png"));
                await client.SendMailAsync(mm);
            }
        }
</code>```

Thanks Guys

Title: C# MVC save View as png

Body:
i have problem with png HTML renderer,
i am trying to send png of View to email, but on email i get 0B .png
PS: Ticket.pdf is ok

 using (MemoryStream ms = new MemoryStream())
        {

            var pdf = PdfGenerator.GeneratePdf(RenderRazorViewToString("TicketTemplateBig", model), PdfSharp.PageSize.A4);
            pdf.Save(ms, false);

            /////////////////
            //Bitmap bitmap = new Bitmap(Convert.ToInt32(1024), Convert.ToInt32(1024), System.Drawing.Imaging.PixelFormat.Format32bppArgb);
            using (MemoryStream ms2 = new MemoryStream())
            {
                //Image image = TheArtOfDev.HtmlRenderer.WinForms.HtmlRender.RenderToImage(RenderRazorViewToString("TicketTemplateBig", model));

                Bitmap bitmap = (Bitmap)Image.FromFile(@"C:\logo.png");
                bitmap.Save(ms2, ImageFormat.Png);

                /////////////////
                await ms.FlushAsync();
                await ms2.FlushAsync();
                mm.Attachments.Add(new Attachment(ms, string.Format("Ticket.pdf"), "application/pdf"));
                streams.Add(ms);
                mm.Attachments.Add(new Attachment(ms2, string.Format("logo.png"), "application/png"));
                streams.Add(ms2);
                await client.SendMailAsync(mm);
            }
        }

Body:
problem : stream was on last position

result  :  ms2.Position = 0;

           using (MemoryStream ms = new MemoryStream())
        {

            var pdf = PdfGenerator.GeneratePdf(RenderRazorViewToString("TicketTemplateBig", model), PdfSharp.PageSize.A4);
            pdf.Save(ms, false);

            using (MemoryStream ms2 = new MemoryStream())
            {
                Image image = TheArtOfDev.HtmlRenderer.WinForms.HtmlRender.RenderToImage(RenderRazorViewToString("TicketTemplateBig", model));
                image.Save(ms2, ImageFormat.Png);
                ms2.Position = 0;
                await ms.FlushAsync();
                await ms2.FlushAsync();
                mm.Attachments.Add(new Attachment(ms, string.Format("Ticket.pdf"), "application/pdf"));
                mm.Attachments.Add(new Attachment(ms2, string.Format("Ticket.png"), "application/png"));
                await client.SendMailAsync(mm);
            }
        }

Thanks Guys


问:
CodeIgniter Form Validation matches got too many error messages
I have an error message problem about form validation matches.
Here is what I set:

```<code>$this->load->library('form_validation');
$this->form_validation->set_rules('password', 'Password', 'required|trim');
$this->form_validation->set_rules('cpassword', 'Confirm Password', 'required|trim|matches[password]');
</code>```

and of course, I have a form with two password input field.

```<code>form_password('password');
form_password('cpassword');
</code>```

I am dealing with error messages using validation_errors() function.

if I let two password fields blank, i got:

```<code>The Password field is required.
The Confirm Password field is required.
</code>```

And if I type something in password and let the Confirm Password field blank, I got:

```<code>The Confirm Password field is required.
</code>```

so far so good until:

I type something in Confirm Password field and let the Password field blank, I got:

```<code>The Password field is required.
The Confirm Password field does not match the Password field.
</code>```

I got two messages instead of one.
I just need the "The Password field is required." only.

What can I do for this? Please help, thanks.

答:
In my own applications, I set up my validation rules like this

```<code>$this->form_validation->set_rules('password', 'Password', 'required|trim|matches[cpassword]');
$this->form_validation->set_rules('cpassword', 'Confirm Password', 'trim');
</code>```

The password is required, and since it has to match cpassword then you are validating cpassword by default.

Body:
I have an error message problem about form validation matches.
Here is what I set:

$this->load->library('form_validation');
$this->form_validation->set_rules('password', 'Password', 'required|trim');
$this->form_validation->set_rules('cpassword', 'Confirm Password', 'required|trim|matches[password]');

and of course, I have a form with two password input field.

form_password('password');
form_password('cpassword');

I am dealing with error messages using validation_errors() function.

if I let two password fields blank, i got:

The Password field is required.
The Confirm Password field is required.

And if I type something in password and let the Confirm Password field blank, I got:

The Confirm Password field is required.

so far so good until:

I type something in Confirm Password field and let the Password field blank, I got:

The Password field is required.
The Confirm Password field does not match the Password field.

I got two messages instead of one.
I just need the "The Password field is required." only.

What can I do for this? Please help, thanks.

Body:
In my own applications, I set up my validation rules like this

$this->form_validation->set_rules('password', 'Password', 'required|trim|matches[cpassword]');
$this->form_validation->set_rules('cpassword', 'Confirm Password', 'trim');

The password is required, and since it has to match cpassword then you are validating cpassword by default.


问:
libcurl-x64.dll was not found
I'm reciving a very odd error. I'm compiling a code which parses JSON data from a url using libcurl. After trial and error I've gotten it compiled without error. However, when trying to run the code I get a system error, saying  libcurl-x64.dll was not found.
Picture of error here
I'm not exactly sure what is finding what, here. My windows system cannot find  libcurl-x64.dll or is it my gcc compiler? Nevertheless, a quick system search shows the location of it. I didn't use it for anything. What exactly do I need to do with  libcurl-x64.dll so that my system can find it? It only pertains to this one parsing program I'm doing, every other cpp/exe file and project works fine. System specs: Windows 10, Dev C++ IDE, mingw g++ compiler.
Here is the location of my supposedly missing file:
FilePath1
FilePath2

答:
The search order of DLLs for desktop Windows applications is as follows:

The directory from which the application loaded.

The system directory. (e.g. \Windows\System32 or \Windows\SysWOW64)

The Windows directory. (e.g. \Windows)

The current directory.

The directories that are listed in the PATH environment variable.

You need to make sure the missing DLL is reachable via one of the above locations.

The best for a quick test is to copy it to the same location where your application (.exe) is located.

Title: libcurl-x64.dll was not found


问:
ActionSheet handler not able to access class variable
I'm doing some POC on Ionic Framework and I needed to use ActionSheet and ActionSheetController. Everything seems to work, however I encountered a strange error when I assign a handler a function that I defined in the class. What's strange is that it's able to call the function as I have put console log but it complains and throws an error if the function uses or references any class variable or services that I have injected. It says undefined for my services or class variables. See the code below:

```<code>addToFavorites() {
console.log('Adding to Favorites', this.game.id);
this.favorite = this.favoriteservice.addFavorite(this.game.id);
this.toastCtrl.create({
  message: this.game.id + ' added as favorite successfully',
  position: 'middle',
  duration: 3000}).present();
}

presentActionSheet() {
let actionSheet = this.actionSheetCtrl.create({
  title: 'Select Actions',
  buttons: [
    {
      text: 'Add To Favorites',
      handler: this.addToFavorites
    },
    {
      text: 'Cancel',
      role: 'cancel',
      handler: () => {
        console.log('Cancel clicked');
      }
    }
  ]
});
actionSheet.present();
}
</code>```

Both are functions defined inside the page class with favoriteService that I have injected and game being the class variable. What I found that it works flawlessly when I call addToFavorites like below:

```<code>presentActionSheet() {
let actionSheet = this.actionSheetCtrl.create({
  title: 'Select Actions',
  buttons: [
    {
      text: 'Add To Favorites',
      handler: () => {
        this.addToFavorites();
      }
    },
    {
      text: 'Cancel',
      role: 'cancel',
      handler: () => {
        console.log('Cancel clicked');
      }
    }
  ]
});
actionSheet.present();
}
</code>```

Can someone explain to me why one works and other didn't? What's the difference?

Thanks.

EDIT: This is the error that comes up when I use the syntax @ewizard suggested:

```<code>[ts]
Argument of type '{ title: string; buttons: ({ text: string; handler: void; } | { text: string; handler: () => void...' is not assignable to parameter of type 'ActionSheetOptions'.
Types of property 'buttons' are incompatible.
Type '({ text: string; handler: void; } | { text: string; handler: () => void; } | { text: string; role...' is not assignable to type '(string | ActionSheetButton)[]'.
  Type '{ text: string; handler: void; } | { text: string; handler: () => void; } | { text: string; role:...' is not assignable to type 'string | ActionSheetButton'.
    Type '{ text: string; handler: void; }' is not assignable to type 'string | ActionSheetButton'.
      Type '{ text: string; handler: void; }' is not assignable to type 'ActionSheetButton'.
        Types of property 'handler' are incompatible.
          Type 'void' is not assignable to type '() => boolean | void'.
</code>```

答:
In your first example, you are missing the () in handler: this.addToFavorites. It should be:

this.addToFavorites().

Body:
I'm doing some POC on Ionic Framework and I needed to use ActionSheet and ActionSheetController. Everything seems to work, however I encountered a strange error when I assign a handler a function that I defined in the class. What's strange is that it's able to call the function as I have put console log but it complains and throws an error if the function uses or references any class variable or services that I have injected. It says undefined for my services or class variables. See the code below:

addToFavorites() {
console.log('Adding to Favorites', this.game.id);
this.favorite = this.favoriteservice.addFavorite(this.game.id);
this.toastCtrl.create({
  message: this.game.id + ' added as favorite successfully',
  position: 'middle',
  duration: 3000}).present();
}

presentActionSheet() {
let actionSheet = this.actionSheetCtrl.create({
  title: 'Select Actions',
  buttons: [
    {
      text: 'Add To Favorites',
      handler: this.addToFavorites
    },
    {
      text: 'Cancel',
      role: 'cancel',
      handler: () => {
        console.log('Cancel clicked');
      }
    }
  ]
});
actionSheet.present();
}

Both are functions defined inside the page class with favoriteService that I have injected and game being the class variable. What I found that it works flawlessly when I call addToFavorites like below:

presentActionSheet() {
let actionSheet = this.actionSheetCtrl.create({
  title: 'Select Actions',
  buttons: [
    {
      text: 'Add To Favorites',
      handler: () => {
        this.addToFavorites();
      }
    },
    {
      text: 'Cancel',
      role: 'cancel',
      handler: () => {
        console.log('Cancel clicked');
      }
    }
  ]
});
actionSheet.present();
}

Can someone explain to me why one works and other didn't? What's the difference?

Thanks.

EDIT: This is the error that comes up when I use the syntax @ewizard suggested:

[ts]
Argument of type '{ title: string; buttons: ({ text: string; handler: void; } | { text: string; handler: () => void...' is not assignable to parameter of type 'ActionSheetOptions'.
Types of property 'buttons' are incompatible.
Type '({ text: string; handler: void; } | { text: string; handler: () => void; } | { text: string; role...' is not assignable to type '(string | ActionSheetButton)[]'.
  Type '{ text: string; handler: void; } | { text: string; handler: () => void; } | { text: string; role:...' is not assignable to type 'string | ActionSheetButton'.
    Type '{ text: string; handler: void; }' is not assignable to type 'string | ActionSheetButton'.
      Type '{ text: string; handler: void; }' is not assignable to type 'ActionSheetButton'.
        Types of property 'handler' are incompatible.
          Type 'void' is not assignable to type '() => boolean | void'.