问:
Gmail API Oauth2 Send from different address
I am able to send e-mails using Python and the google libraries (googleapiclient, google_auth_oauthlib.flow, and google.auth.transport.requests). I'm trying to get an alternate "from" or "reply-to" address, and it's not working. My code for creating a message is like so:

```<code># Returns an e-mail message suitable for submission through the gmail api.
def create_message(sender, to, subject, message_text):
    message = MIMEMultipart()
    message['to'] = to
    #message['from'] = sender
    message['from'] = 'derp@nowhere.com'
    message['subject'] = subject
    message.attach(MIMEText(message_text, 'html'))
    return {'raw': base64.urlsafe_b64encode(message.as_string().encode()).decode()}
</code>```

As you can see, I've adjusted the from attribute of the message. When this message is sent, it is from the gmail account owner, not "derp". How do I make the message come from a different address?

答:
Add the e-mail address as whom you want to issue e-mail as a "Send Mail As" account: https://mail.google.com/mail/u/2/#settings/accounts. It is necessary for that other account to verify he has control of that e-mail address.

It appears not to be possible to "spoof" e-mails using gmail oauth without this verification process, though if you use the deprecated "less secure apps", it is still possible.

Body:
I am able to send e-mails using Python and the google libraries (googleapiclient, google_auth_oauthlib.flow, and google.auth.transport.requests). I'm trying to get an alternate "from" or "reply-to" address, and it's not working. My code for creating a message is like so:

# Returns an e-mail message suitable for submission through the gmail api.
def create_message(sender, to, subject, message_text):
    message = MIMEMultipart()
    message['to'] = to
    #message['from'] = sender
    message['from'] = 'derp@nowhere.com'
    message['subject'] = subject
    message.attach(MIMEText(message_text, 'html'))
    return {'raw': base64.urlsafe_b64encode(message.as_string().encode()).decode()}

As you can see, I've adjusted the from attribute of the message. When this message is sent, it is from the gmail account owner, not "derp". How do I make the message come from a different address?


来源: stackexchange

问:
redirect user on previous page after successfull task
What should be good way to redirect user after successful action like edit or delete any item, in delete condition we could use $_SERVER['HTTP_REFERER'] but in case of edit, we show first of all edit form and then user clicks update, so if we use same approach user would be redirected to edit page not main page. I hope you got idea about my confusion. thanks.

答:
If 'update' is handled through a Form post, just put a hidden input in reflecting the landing spot.

```<code><input type="hidden" name="next_url" value="foo.php" />
</code>```

The PHP uses the value as the place to redirect to.

```<code><?php
  // Do operations.
  header('Location: '.$_REQUEST['next_url']);
</code>```

This is especially important because HTTP_REFERER is not guaranteed to work.  It works most of the time, but there are issues with relying on it.

ContentLicense: CC BY-SA 3.0

Body:
If 'update' is handled through a Form post, just put a hidden input in reflecting the landing spot.

<input type="hidden" name="next_url" value="foo.php" />

The PHP uses the value as the place to redirect to.

<?php
  // Do operations.
  header('Location: '.$_REQUEST['next_url']);

This is especially important because HTTP_REFERER is not guaranteed to work.  It works most of the time, but there are issues with relying on it.


问:
Converting generic redis code to Azure Cache for Redis
I have the following Spring Session code:

```<code>@Bean
public LettuceConnectionFactory connectionFactory() {
    String hostName = AcmeProperty.getProperty("spring.redis.host", "localhost");
    int port = Integer.parseInt(AcmeProperty.getProperty("spring.redis.port", "6379"));
    RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration(hostName, port);

    return new LettuceConnectionFactory(redisStandaloneConfiguration);
}
</code>```

It works just fine with the following settings when I'm running redis locally:

```<code>spring.redis.host=localhost
spring.redis.port=6379
</code>```

However when I use Azure Cache for Redis with the following setting:

```<code>spring.redis.host=acmedev.redis.cache.windows.net
spring.redis.port=6380
</code>```

I get this warning and the app hangs:

```<code>WARN (org.springframework.session.config.annotation.web.http.SpringHttpSessionConfiguration:166) || - Unable to obtain SessionCookieConfig: Section 4.4 of the Servlet 3.0 specification does not permit this method to be called from a ServletContextListener that was not defined in web.xml, a web-fragment.xml file nor annotated with @WebListener
</code>```

What do I need to change to get this to work with Azure Cache for Redis?

I've tried this code, but the same thing happens:

```<code>@Bean
public JedisConnectionFactory connectionFactory() {
    String hostName = AcmeProperty.getProperty("spring.redis.host", "localhost");
    int port = Integer.parseInt(AcmeProperty.getProperty("spring.redis.port", "6379"));
    String password = AcmeProperty.getProperty("spring.redis.password");

    SSLSocketFactory sslSocketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
    SSLParameters sslParameters = new SSLParameters();
    sslParameters.setEndpointIdentificationAlgorithm("HTTPS");
    sslParameters.setProtocols(new String[]{"TLSv1.2"});

    String uriStr = String.format("rediss://%s:%s", hostName, port);
    URI uri = URI.create(uriStr);
    JedisShardInfo shardInfo = new JedisShardInfo(uri, sslSocketFactory, sslParameters, null);

    shardInfo.setPassword(password);

    return new JedisConnectionFactory(shardInfo);
}
</code>```

答:
You need to use an XML Spring configuration; a Java configuration won't work.  See "Unable to obtain SessionCookieConfig".</p>

```<code><util:constant id="configureRedisAction"
               static-field="org.springframework.session.data.redis.config.ConfigureRedisAction.NO_OP"/>

<context:annotation-config/>
<bean class="org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration"
      p:configureRedisAction-ref="configureRedisAction"/>

<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
    <property name="maxTotal" value="200" />
    <property name="maxIdle" value="50" />
    <property name="maxWaitMillis" value="30000" />
    <property name="minIdle" value="10"/>
</bean>

<bean class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
    <property name="hostName" value="${spring.redis.host}" />
    <property name="port" value="${spring.redis.port}" />
    <property name="poolConfig" ref="jedisPoolConfig" />
    <property name="usePool" value="true" />
    <property name="useSsl" value="${spring.redis.ssl}"/>
    <property name="password" value="${spring.redis.password}"/>
</bean>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have the following Spring Session code:

@Bean
public LettuceConnectionFactory connectionFactory() {
    String hostName = AcmeProperty.getProperty("spring.redis.host", "localhost");
    int port = Integer.parseInt(AcmeProperty.getProperty("spring.redis.port", "6379"));
    RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration(hostName, port);

    return new LettuceConnectionFactory(redisStandaloneConfiguration);
}

It works just fine with the following settings when I'm running redis locally:

spring.redis.host=localhost
spring.redis.port=6379

However when I use Azure Cache for Redis with the following setting:

spring.redis.host=acmedev.redis.cache.windows.net
spring.redis.port=6380

I get this warning and the app hangs:

WARN (org.springframework.session.config.annotation.web.http.SpringHttpSessionConfiguration:166) || - Unable to obtain SessionCookieConfig: Section 4.4 of the Servlet 3.0 specification does not permit this method to be called from a ServletContextListener that was not defined in web.xml, a web-fragment.xml file nor annotated with @WebListener

What do I need to change to get this to work with Azure Cache for Redis?

I've tried this code, but the same thing happens:

@Bean
public JedisConnectionFactory connectionFactory() {
    String hostName = AcmeProperty.getProperty("spring.redis.host", "localhost");
    int port = Integer.parseInt(AcmeProperty.getProperty("spring.redis.port", "6379"));
    String password = AcmeProperty.getProperty("spring.redis.password");

    SSLSocketFactory sslSocketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
    SSLParameters sslParameters = new SSLParameters();
    sslParameters.setEndpointIdentificationAlgorithm("HTTPS");
    sslParameters.setProtocols(new String[]{"TLSv1.2"});

    String uriStr = String.format("rediss://%s:%s", hostName, port);
    URI uri = URI.create(uriStr);
    JedisShardInfo shardInfo = new JedisShardInfo(uri, sslSocketFactory, sslParameters, null);

    shardInfo.setPassword(password);

    return new JedisConnectionFactory(shardInfo);
}

Body:
You need to use an XML Spring configuration; a Java configuration won't work.  See "Unable to obtain SessionCookieConfig".

<util:constant id="configureRedisAction"
               static-field="org.springframework.session.data.redis.config.ConfigureRedisAction.NO_OP"/>

<context:annotation-config/>
<bean class="org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration"
      p:configureRedisAction-ref="configureRedisAction"/>

<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
    <property name="maxTotal" value="200" />
    <property name="maxIdle" value="50" />
    <property name="maxWaitMillis" value="30000" />
    <property name="minIdle" value="10"/>
</bean>

<bean class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
    <property name="hostName" value="${spring.redis.host}" />
    <property name="port" value="${spring.redis.port}" />
    <property name="poolConfig" ref="jedisPoolConfig" />
    <property name="usePool" value="true" />
    <property name="useSsl" value="${spring.redis.ssl}"/>
    <property name="password" value="${spring.redis.password}"/>
</bean>


问:
How to generate cross validation over different dataframes for supervised classification?
Imagine I have 4 dataframes with different length of rows but same number of columns like this: df1(200 rows, 4 columns), df2(100, 4), df3(300, 4) and df4(250, 4).

I would like to make a supervised classification between these dataframes (always using 3 for training and 1 for test/validation) and discover which combination gives me the better accuracy score. This is an example of a bigger volume of data and I would like to automate it by making a cross validation.

I thought that I could try to create a new column for each dataframe with their specific name and then concat all of them. And then, maybe, create a mask that would differentiate the training and test sets by these new columns. But I still do not know how to do this cross validation between them.

The dataframes would be like this:

```<code>concatenated_dfs:

     feat1    feat2    feat3    feat4    name
0      4        6        57       78      df1
1      1        2        50       78      df1
2      1        1        57       78      df1
.      .        .        .         .       .
.      .        .        .         .       .
.      .        .        .         .       .
849    3        10       50       80      df4
</code>```

Anyone could show me how to do that with some code? You can use any scikit-learn classification algorithm if you want. Thanks!

答:
You can use scikit learn's cross_val_score with a custom iterable to generate the indices for the training-test splits in your data. Here is an example:

```<code># Setup - creating fake data to match your description
df = pd.DataFrame(data={"name":[x for l in [[f"df{i}"]*c for i, c in enumerate(counts, 1)] for x in l]})
for i in range(1, 5):
    df[f"feat{i}"] = np.random.randn(len(df))
X = df[[c for c in df.columns if c != "name"]]
y = np.random.randint(0, 2, len(df))

# Iterable to generate the training-test splits:
indices = list()
for name in df["name"].unique():
    train = df.loc[df["name"] != name].index
    test = df.loc[df["name"] == name].index
    indices.append((train, test))

# Example model - logistic regression
from sklearn.linear_model import LogisticRegression
model = LogisticRegression()

# Using cross-val score with the custom indices:
from sklearn.model_selection import cross_val_score
scores = cross_val_score(model, X, y, cv=indices)
</code>```

Body:
Imagine I have 4 dataframes with different length of rows but same number of columns like this: df1(200 rows, 4 columns), df2(100, 4), df3(300, 4) and df4(250, 4).

I would like to make a supervised classification between these dataframes (always using 3 for training and 1 for test/validation) and discover which combination gives me the better accuracy score. This is an example of a bigger volume of data and I would like to automate it by making a cross validation.

I thought that I could try to create a new column for each dataframe with their specific name and then concat all of them. And then, maybe, create a mask that would differentiate the training and test sets by these new columns. But I still do not know how to do this cross validation between them.

The dataframes would be like this:

concatenated_dfs:

     feat1    feat2    feat3    feat4    name
0      4        6        57       78      df1
1      1        2        50       78      df1
2      1        1        57       78      df1
.      .        .        .         .       .
.      .        .        .         .       .
.      .        .        .         .       .
849    3        10       50       80      df4

Anyone could show me how to do that with some code? You can use any scikit-learn classification algorithm if you want. Thanks!

Body:
You can use scikit learn's cross_val_score with a custom iterable to generate the indices for the training-test splits in your data. Here is an example:

# Setup - creating fake data to match your description
df = pd.DataFrame(data={"name":[x for l in [[f"df{i}"]*c for i, c in enumerate(counts, 1)] for x in l]})
for i in range(1, 5):
    df[f"feat{i}"] = np.random.randn(len(df))
X = df[[c for c in df.columns if c != "name"]]
y = np.random.randint(0, 2, len(df))

# Iterable to generate the training-test splits:
indices = list()
for name in df["name"].unique():
    train = df.loc[df["name"] != name].index
    test = df.loc[df["name"] == name].index
    indices.append((train, test))

# Example model - logistic regression
from sklearn.linear_model import LogisticRegression
model = LogisticRegression()

# Using cross-val score with the custom indices:
from sklearn.model_selection import cross_val_score
scores = cross_val_score(model, X, y, cv=indices)


问:
Not able to delete the text after using JavaScript Regex
After using the replace to put a slash after the second character, I became unable to delete it.

答:
Use event.key to check for the pressed key, and if the key is either Backspace or Delete return from the event handler without executing the insertion of the /:

const input = document.querySelector('input');

input.addEventListener('keydown', () => {
    if(event.key === 'Backspace' || event.key === 'Delete') {
       return;
    }
    if(input.value.length === 2)    input.value += '/';
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input></code>```

Body:
Use event.key to check for the pressed key, and if the key is either Backspace or Delete return from the event handler without executing the insertion of the /:

const input = document.querySelector('input');

input.addEventListener('keydown', () => {
    if(event.key === 'Backspace' || event.key === 'Delete') {
       return;
    }
    if(input.value.length === 2)    input.value += '/';
});

<input>


问:
Select2 doesn't show selected value
Select2 loads all items from my list successful, the issue I found when try to select a specific value when page loads. Example:

:: put select2 in a specific html element, no value is selected even all items are loaded.

```<code>$('#my_id').select2();
</code>```

:: When the page is loaded I'm trying to show a specific item selected, but doesn't work as expected, because even selected, the select2 doesn't show it.

```<code>$('#my_id').val('3'); //select the right option, but doesn't render it on page loads.
</code>```

How to make a selected option to pop up when pages loads?

Thanks in advance.

#UPDATED

:: How I load all select2 items (sorry, its jade, not pure HTML):

```<code>label(for='category') Category
    span.required *
select(id='category', style='width:230px', name='category')
    option(value='') - Select -
    each cat in categories
        option(value='#{cat.id}') #{cat.description}
</code>```

P.S.: All items from my list are loaded.

:: How I initialize the select2:

Just put the following line code on my javascript and it does successful:

```<code>$('#category').select2();
</code>```

:: How I'm trying to select a specific value:

First attempt:

```<code>  $('#category').select2(
      {
          initSelection: function(element, callback) {
              callback($('#field-category').val());
          }
      }
  );
</code>```

Second attempt:

```<code>  $('#category').val($('#field-category').val());
</code>```

P.S.: #field-category has a value its a hidden input field and works OK.

答:
trigger just select2 to set the value

```<code>$('#my_id').val('3').trigger("change.select2");
</code>```

and this will trigger select2 with dropdown

```<code>$('#my_id').val('3').trigger("change");
</code>```

Title: Select2 doesn't show selected value

Body:
Select2 loads all items from my list successful, the issue I found when try to select a specific value when page loads. Example:

:: put select2 in a specific html element, no value is selected even all items are loaded.

$('#my_id').select2();

:: When the page is loaded I'm trying to show a specific item selected, but doesn't work as expected, because even selected, the select2 doesn't show it.

$('#my_id').val('3'); //select the right option, but doesn't render it on page loads.

How to make a selected option to pop up when pages loads?

Thanks in advance.

#UPDATED

:: How I load all select2 items (sorry, its jade, not pure HTML):

label(for='category') Category
    span.required *
select(id='category', style='width:230px', name='category')
    option(value='') - Select -
    each cat in categories
        option(value='#{cat.id}') #{cat.description}

P.S.: All items from my list are loaded.

:: How I initialize the select2:

Just put the following line code on my javascript and it does successful:

$('#category').select2();

:: How I'm trying to select a specific value:

First attempt:

  $('#category').select2(
      {
          initSelection: function(element, callback) {
              callback($('#field-category').val());
          }
      }
  );

Second attempt:

  $('#category').val($('#field-category').val());

P.S.: #field-category has a value its a hidden input field and works OK.

Body:
trigger just select2 to set the value

$('#my_id').val('3').trigger("change.select2");

and this will trigger select2 with dropdown

$('#my_id').val('3').trigger("change");


问:
What is the role of tbl() in a sparklyr query?
Let's say I have a query (character string) stored in an R object named my_query. I want to execute this query within my Spark context. I register some tables in my Spark context first.

```<code>my_table <- sparklyr::spark_read_orc(
  sc,
  name = "my_table",
  path = "wasbs://my_table",
  memory = FALSE
)
</code>```

Now I execute my query.

```<code>my_query %>%
  dplyr::sql() %>%
  dplyr::tbl(sc, .) %>%
  sparklyr::spark_write_orc(path = "result_path", mode = "overwrite")
</code>```

What exactly is the role of the tbl() function here? Does the tbl() function here bring the data into Spark memory? i.e. is the query still lazily evaluated? Does this depend on the type of query? For example I imagine that simple SELECT and WHERE statements don't require data to be brought into memory but if you are creating new columns in some form of dplyr::mutate() (or equivalent SQL code), it would need to bring that into memory?

答:
What exactly is the role of the tbl() function here

It is generic method used to fetch table from external source.

Since sparklyr behaves effectively like a database connection it will follow the standard dbplyr path, by invoking dblyr::tbl_sql, which main responsibility is to prepare data structure representing the (lazy) data source, and resolve the schema, by invoking corresponding db_query_fields implementation.

The last part is pretty much the only Spark-specific component, which at the moment is implemented as show below

```<code>#' @export
#' @importFrom dplyr db_query_fields
#' @importFrom dplyr sql_select
#' @importFrom dplyr sql_subquery
#' @keywords internal
db_query_fields.spark_connection <- function(con, sql, ...) {
  sqlFields <- sql_select(
    con,
    sql("*"),
    sql_subquery(con, sql),
    where = sql("0 = 1")
  )

  hive_context(con) %>%
    invoke("sql", as.character(sqlFields)) %>%
    invoke("schema") %>%
    invoke("fieldNames") %>%
    as.character()
}
</code>```

As you see there is not much going on here, and alone there is not much to worry about here.

As of arbitrary case it is impossible to provide a single answer. sparklyr design choices of being eagerish (by showing user the partial output) as well as eager caching used all over the package, can have unexpected implications.

Additionally Spark SQL is not strictly eager, and different types of operations might by itself result in partial evaluation.

However using tbl here, doesn't make your code any worse than using my_table directly.

Body:
Let's say I have a query (character string) stored in an R object named my_query. I want to execute this query within my Spark context. I register some tables in my Spark context first.

my_table <- sparklyr::spark_read_orc(
  sc,
  name = "my_table",
  path = "wasbs://my_table",
  memory = FALSE
)

Now I execute my query.

my_query %>%
  dplyr::sql() %>%
  dplyr::tbl(sc, .) %>%
  sparklyr::spark_write_orc(path = "result_path", mode = "overwrite")

What exactly is the role of the tbl() function here? Does the tbl() function here bring the data into Spark memory? i.e. is the query still lazily evaluated? Does this depend on the type of query? For example I imagine that simple SELECT and WHERE statements don't require data to be brought into memory but if you are creating new columns in some form of dplyr::mutate() (or equivalent SQL code), it would need to bring that into memory?

Body:
What exactly is the role of the tbl() function here

It is generic method used to fetch table from external source.

Since sparklyr behaves effectively like a database connection it will follow the standard dbplyr path, by invoking dblyr::tbl_sql, which main responsibility is to prepare data structure representing the (lazy) data source, and resolve the schema, by invoking corresponding db_query_fields implementation.

The last part is pretty much the only Spark-specific component, which at the moment is implemented as show below

#' @export
#' @importFrom dplyr db_query_fields
#' @importFrom dplyr sql_select
#' @importFrom dplyr sql_subquery
#' @keywords internal
db_query_fields.spark_connection <- function(con, sql, ...) {
  sqlFields <- sql_select(
    con,
    sql("*"),
    sql_subquery(con, sql),
    where = sql("0 = 1")
  )

  hive_context(con) %>%
    invoke("sql", as.character(sqlFields)) %>%
    invoke("schema") %>%
    invoke("fieldNames") %>%
    as.character()
}

As you see there is not much going on here, and alone there is not much to worry about here.

As of arbitrary case it is impossible to provide a single answer. sparklyr design choices of being eagerish (by showing user the partial output) as well as eager caching used all over the package, can have unexpected implications.

Additionally Spark SQL is not strictly eager, and different types of operations might by itself result in partial evaluation.

However using tbl here, doesn't make your code any worse than using my_table directly.


问:
get the unique values from the associative array in PHP?
I am having the array like below

```<code>Array
(
    [0] => Array
        (
            [catid] => 3
            [parent_id] => 1
            [catname] => Uncategorized
            [catdesc] =>
            [nleft] => 20
            [nright] => 21
            [nlevel] => 1
        )

    [1] => Array
        (
            [catid] => 5
            [parent_id] => 2
            [catname] => Category 2
            [catdesc] =>
            [nleft] => 7
            [nright] => 8
            [nlevel] => 2
        )

    [2] => Array
        (
            [catid] => 3
            [parent_id] => 1
            [catname] => Uncategorized
            [catdesc] =>
            [nleft] => 20
            [nright] => 21
            [nlevel] => 1
        )

    [3] => Array
        (
            [catid] => 3
            [parent_id] => 1
            [catname] => Uncategorized
            [catdesc] =>
            [nleft] => 20
            [nright] => 21
            [nlevel] => 1
        )

    [4] => Array
        (
            [catid] => 7
            [parent_id] => 2
            [catname] => Flower
            [catdesc] =>
            [nleft] => 11
            [nright] => 18
            [nlevel] => 2
        )

    [5] => Array
        (
            [catid] => 8
            [parent_id] => 7
            [catname] => Lillies
            [catdesc] =>
            [nleft] => 12
            [nright] => 13
            [nlevel] => 3
        )

    [6] => Array
        (
            [catid] => 10
            [parent_id] => 7
            [catname] => Jasmine
            [catdesc] =>
            [nleft] => 16
            [nright] => 17
            [nlevel] => 3
        )

    [7] => Array
        (
            [catid] => 7
            [parent_id] => 2
            [catname] => Flower
            [catdesc] =>
            [nleft] => 11
            [nright] => 18
            [nlevel] => 2
        )

    [8] => Array
        (
            [catid] => 8
            [parent_id] => 7
            [catname] => Lillies
            [catdesc] =>
            [nleft] => 12
            [nright] => 13
            [nlevel] => 3
        )

    [9] => Array
        (
            [catid] => 10
            [parent_id] => 7
            [catname] => Jasmine
            [catdesc] =>
            [nleft] => 16
            [nright] => 17
            [nlevel] => 3
        )

    [10] => Array
        (
            [catid] => 3
            [parent_id] => 1
            [catname] => Uncategorized
            [catdesc] =>
            [nleft] => 20
            [nright] => 21
            [nlevel] => 1
        )

    [11] => Array
        (
            [catid] => 3
            [parent_id] => 1
            [catname] => Uncategorized
            [catdesc] =>
            [nleft] => 20
            [nright] => 21
            [nlevel] => 1
        )

    [12] => Array
        (
            [catid] => 10
            [parent_id] => 7
            [catname] => Jasmine
            [catdesc] =>
            [nleft] => 16
            [nright] => 17
            [nlevel] => 3
        )

    [13] => Array
        (
            [catid] => 3
            [parent_id] => 1
            [catname] => Uncategorized
            [catdesc] =>
            [nleft] => 20
            [nright] => 21
            [nlevel] => 1
        )

    [14] => Array
        (
            [catid] => 8
            [parent_id] => 7
            [catname] => Lillies
            [catdesc] =>
            [nleft] => 12
            [nright] => 13
            [nlevel] => 3
        )

)
</code>```

From this array I want to get the Unique Arrays.ie. If catId is same it needs to eliminate from the list.
How can I do this?

答:
Presuming you're using PHP >5.3, you could use array_filter:

```<code>$catIds = array();
$myarray = array_filter($myarray, function($el) use (&$catIds) {
    if (in_array($el['catid'], $catIds)) { // if the id has already been seen
        return false; // remove it
    } else {
        $catIds[] = $el['catid']; // the id has now been seen
        return true; // but keep the first occurrence of it
    }
});
</code>```

Body:
I am having the array like below

Array
(
    [0] => Array
        (
            [catid] => 3
            [parent_id] => 1
            [catname] => Uncategorized
            [catdesc] =>
            [nleft] => 20
            [nright] => 21
            [nlevel] => 1
        )

    [1] => Array
        (
            [catid] => 5
            [parent_id] => 2
            [catname] => Category 2
            [catdesc] =>
            [nleft] => 7
            [nright] => 8
            [nlevel] => 2
        )

    [2] => Array
        (
            [catid] => 3
            [parent_id] => 1
            [catname] => Uncategorized
            [catdesc] =>
            [nleft] => 20
            [nright] => 21
            [nlevel] => 1
        )

    [3] => Array
        (
            [catid] => 3
            [parent_id] => 1
            [catname] => Uncategorized
            [catdesc] =>
            [nleft] => 20
            [nright] => 21
            [nlevel] => 1
        )

    [4] => Array
        (
            [catid] => 7
            [parent_id] => 2
            [catname] => Flower
            [catdesc] =>
            [nleft] => 11
            [nright] => 18
            [nlevel] => 2
        )

    [5] => Array
        (
            [catid] => 8
            [parent_id] => 7
            [catname] => Lillies
            [catdesc] =>
            [nleft] => 12
            [nright] => 13
            [nlevel] => 3
        )

    [6] => Array
        (
            [catid] => 10
            [parent_id] => 7
            [catname] => Jasmine
            [catdesc] =>
            [nleft] => 16
            [nright] => 17
            [nlevel] => 3
        )

    [7] => Array
        (
            [catid] => 7
            [parent_id] => 2
            [catname] => Flower
            [catdesc] =>
            [nleft] => 11
            [nright] => 18
            [nlevel] => 2
        )

    [8] => Array
        (
            [catid] => 8
            [parent_id] => 7
            [catname] => Lillies
            [catdesc] =>
            [nleft] => 12
            [nright] => 13
            [nlevel] => 3
        )

    [9] => Array
        (
            [catid] => 10
            [parent_id] => 7
            [catname] => Jasmine
            [catdesc] =>
            [nleft] => 16
            [nright] => 17
            [nlevel] => 3
        )

    [10] => Array
        (
            [catid] => 3
            [parent_id] => 1
            [catname] => Uncategorized
            [catdesc] =>
            [nleft] => 20
            [nright] => 21
            [nlevel] => 1
        )

    [11] => Array
        (
            [catid] => 3
            [parent_id] => 1
            [catname] => Uncategorized
            [catdesc] =>
            [nleft] => 20
            [nright] => 21
            [nlevel] => 1
        )

    [12] => Array
        (
            [catid] => 10
            [parent_id] => 7
            [catname] => Jasmine
            [catdesc] =>
            [nleft] => 16
            [nright] => 17
            [nlevel] => 3
        )

    [13] => Array
        (
            [catid] => 3
            [parent_id] => 1
            [catname] => Uncategorized
            [catdesc] =>
            [nleft] => 20
            [nright] => 21
            [nlevel] => 1
        )

    [14] => Array
        (
            [catid] => 8
            [parent_id] => 7
            [catname] => Lillies
            [catdesc] =>
            [nleft] => 12
            [nright] => 13
            [nlevel] => 3
        )

)

From this array I want to get the Unique Arrays.ie. If catId is same it needs to eliminate from the list.
How can I do this?

Body:
Presuming you're using PHP >5.3, you could use array_filter:

$catIds = array();
$myarray = array_filter($myarray, function($el) use (&$catIds) {
    if (in_array($el['catid'], $catIds)) { // if the id has already been seen
        return false; // remove it
    } else {
        $catIds[] = $el['catid']; // the id has now been seen
        return true; // but keep the first occurrence of it
    }
});


问:
Python assert with paranthesis allows for only part of the condition to be written within them
Could someone please explain me why this absolutely weird syntax works in Python (I tested in Python 3.7)? Functionally, it seems perfectly equivalent to the logically corect assert(5+1 == 6), but I have no idea why this would be valid syntax.

```<code>assert(5) + 1 == 6
</code>```

答:
assert is not a function; it's a statement.

In both cases, your parentheses are part of the expression following the keyword assert. The expressions (5) + 1 == 6, (5+1 == 6), and 5 + 1 == 6 are equivalent, with the parentheses in the first two cases being unnecessary.

You can see the parser treats them identically:

```<code>>>> import ast
>>> ast.dump(ast.parse("assert(5) + 1 == 6"))
'Module(body=[Assert(test=Compare(left=BinOp(left=Num(n=5), op=Add(), right=Num(n=1)), ops=[Eq()], comparators=[Num(n=6)]), msg=None)])'
>>> ast.dump(ast.parse("assert(5 + 1 == 6)"))
'Module(body=[Assert(test=Compare(left=BinOp(left=Num(n=5), op=Add(), right=Num(n=1)), ops=[Eq()], comparators=[Num(n=6)]), msg=None)])'
>>> ast.dump(ast.parse("assert 5 + 1 == 6"))
'Module(body=[Assert(test=Compare(left=BinOp(left=Num(n=5), op=Add(), right=Num(n=1)), ops=[Eq()], comparators=[Num(n=6)]), msg=None)])'
</code>```

or letting Python compare the strings for you,

```<code>>>> exprs = ["assert(5) + 1 == 6", "assert(5 + 1 ==  6)", "assert 5 + 1 == 6"]
>>> len(set(ast.dump(ast.parse(x)) for x in exprs))
1
</code>```

More formally, the assert statement consists of the assert keyword followed by one or two additional expressions.

```<code>assert_stmt: 'assert' test [',' test]
</code>```

The first one is evaluated as a Boolean expression, producing True or False as the result. The value of the second one, if present, is used to construct the AssertionError raised by the statement if the first expression is False.

```<code>>>> assert False
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AssertionError
>>> assert False, 3
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AssertionError: 3
>>> assert True
>>> assert True, 3
</code>```

Body:
Could someone please explain me why this absolutely weird syntax works in Python (I tested in Python 3.7)? Functionally, it seems perfectly equivalent to the logically corect assert(5+1 == 6), but I have no idea why this would be valid syntax.

assert(5) + 1 == 6

Body:
assert is not a function; it's a statement.

In both cases, your parentheses are part of the expression following the keyword assert. The expressions (5) + 1 == 6, (5+1 == 6), and 5 + 1 == 6 are equivalent, with the parentheses in the first two cases being unnecessary.

You can see the parser treats them identically:

>>> import ast
>>> ast.dump(ast.parse("assert(5) + 1 == 6"))
'Module(body=[Assert(test=Compare(left=BinOp(left=Num(n=5), op=Add(), right=Num(n=1)), ops=[Eq()], comparators=[Num(n=6)]), msg=None)])'
>>> ast.dump(ast.parse("assert(5 + 1 == 6)"))
'Module(body=[Assert(test=Compare(left=BinOp(left=Num(n=5), op=Add(), right=Num(n=1)), ops=[Eq()], comparators=[Num(n=6)]), msg=None)])'
>>> ast.dump(ast.parse("assert 5 + 1 == 6"))
'Module(body=[Assert(test=Compare(left=BinOp(left=Num(n=5), op=Add(), right=Num(n=1)), ops=[Eq()], comparators=[Num(n=6)]), msg=None)])'

or letting Python compare the strings for you,

>>> exprs = ["assert(5) + 1 == 6", "assert(5 + 1 ==  6)", "assert 5 + 1 == 6"]
>>> len(set(ast.dump(ast.parse(x)) for x in exprs))
1

More formally, the assert statement consists of the assert keyword followed by one or two additional expressions.

assert_stmt: 'assert' test [',' test]

The first one is evaluated as a Boolean expression, producing True or False as the result. The value of the second one, if present, is used to construct the AssertionError raised by the statement if the first expression is False.

>>> assert False
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AssertionError
>>> assert False, 3
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AssertionError: 3
>>> assert True
>>> assert True, 3


问:
Codeigniter bootstrap load only on index.php page
I'm loading bootstrap this way on my view page :

```<code><link rel="stylesheet" href="<? echo base_url('assets/css/bootstrap.min.css')?>">
</code>```

autoload:  $autoload['helper'] = array('url');

configs:  $config['base_url'] = 'http://localhost/helloby/';

Below is the path of the controller:

http://localhost/helloby/index.php/login/home

But when I copy the same code at welcome_message view bootstrap loads normally. I don't know why it's happening.

答:
Try using site_url() instead of base_url()

base_url returns the url without index.php

Check if you are loading the bootstrap css in every view, you cant just load it in one view and expect that all other views know about it.

Common way of doing things like this is to create header and footer files that are shared between all views.

Body:
I'm loading bootstrap this way on my view page :

<link rel="stylesheet" href="<? echo base_url('assets/css/bootstrap.min.css')?>">

autoload:  $autoload['helper'] = array('url');

configs:  $config['base_url'] = 'http://localhost/helloby/';

Below is the path of the controller:

http://localhost/helloby/index.php/login/home

But when I copy the same code at welcome_message view bootstrap loads normally. I don't know why it's happening.


问:
How do I sort dictionary by Key in Python
I need to sort below dictionary and print first five items from sorted dictionary:

```<code>station_dict_platOne = {'6': 'Daly City', '12': 'Daly City', '19': 'Daly City', 'Leaving': 'Millbrae', '16': 'SF Airport', '28': 'Millbrae', '10': 'SF Airport', '22': 'SF Airport'}
</code>```

I am using this code:

```<code>j=0
for i in sorted(station_dict_platOne):
        if j<5:
        print(i+" "+"min", station_dict_platOne[i])
        j = j+1
</code>```

But, I am getting below output and this is not the correct output.

```<code>10 min SF Airport
12 min Daly City
16 min SF Airport
19 min Daly City
22 min SF Airport
</code>```

答:
Your error is probably not in the code, but in the typing:
The keys are strings (texts) and not ints (numbers), so '10' < '6' == True.

Either use numbers for keys (just 6: 'Daly City', without the quotation marks) or parse them while ordering (call sorted(station_dict_platOne, key=lambda t: int(t)) in the for-loop).

Note: both ways will fail with your 'Leaving' key. You have to filter it, or use some special case!

Body:
I need to sort below dictionary and print first five items from sorted dictionary:

station_dict_platOne = {'6': 'Daly City', '12': 'Daly City', '19': 'Daly City', 'Leaving': 'Millbrae', '16': 'SF Airport', '28': 'Millbrae', '10': 'SF Airport', '22': 'SF Airport'}

I am using this code:

j=0
for i in sorted(station_dict_platOne):
        if j<5:
        print(i+" "+"min", station_dict_platOne[i])
        j = j+1

But, I am getting below output and this is not the correct output.

10 min SF Airport
12 min Daly City
16 min SF Airport
19 min Daly City
22 min SF Airport


问:
Simple Kernel Mode Driver
I'm creating simple Kernel Mode Driver (Empty Project) to try some

read/write memory operations on user mode apps.

I'm getting errors while compiling the project On these lines :

```<code>NTSTATUS NTAPI MmCopyVirtualMemory(PEPROCESS SourceProcess, PVOID
SourceAddress, PEPROCESS TargetProcess, PVOID TargetAddress, SIZE_T
BufferSize, KPROCESSOR_MODE PreviousMode, PSIZE_T ReturnSize);

NTSTATUS PsLookupProcessByProcessId(_In_ HANDLE ProcessId, _Outptr_
PEPROCESS *Process);

KernelWPM(Process, &Writeval, 0x010F29B0, sizeof(__int32));
</code>```

VS Compiling errors :

```<code>Severity    Code    Description Project File    Line    Suppression State
Error   C2371   'PEPROCESS': redefinition; different basic types    INR
C:\Program Files (x86)\Windows Kits\10\Include\10.0.16299.0\km\ntifs.h  85
Warning C4022   'GetProcessByID': pointer mismatch for actual parameter 1
INR C:\Users\NAKEDRAT\Desktop\INR\INR\main.c    62
Error   C2371   'PETHREAD': redefinition; different basic types INR
C:\Program Files (x86)\Windows Kits\10\Include\10.0.16299.0\km\ntifs.h  86
Warning C4047   'function': 'PEPROCESS' differs in levels of indirection
from 'PEPROCESS **' INR C:\Users\NAKEDRAT\Desktop\INR\INR\main.c    62
Warning C4024   'GetProcessByID': different types for formal and actual
parameter 2 INR C:\Users\NAKEDRAT\Desktop\INR\INR\main.c    62
Warning C4047   'function': 'PEPROCESS' differs in levels of indirection
from 'PEPROCESS *'  INR C:\Users\NAKEDRAT\Desktop\INR\INR\main.c    64
Warning C4024   'KernelWPM': different types for formal and actual parameter
1   INR C:\Users\NAKEDRAT\Desktop\INR\INR\main.c    64
Warning C4022   'KernelWPM': pointer mismatch for actual parameter 3    INR
C:\Users\NAKEDRAT\Desktop\INR\INR\main.c    64
</code>```

Here is my code :
Also using the same SDK & WDK version

```<code>#include <ntddk.h>
#include <ntdef.h>
#include <ntifs.h>

DRIVER_INITIALIZE DriverEntry;

#pragma alloc_text(INIT, DriverEntry)

NTSTATUS NTAPI MmCopyVirtualMemory(PEPROCESS SourceProcess, PVOID
SourceAddress, PEPROCESS TargetProcess, PVOID TargetAddress, SIZE_T
BufferSize, KPROCESSOR_MODE PreviousMode, PSIZE_T ReturnSize);

NTSTATUS PsLookupProcessByProcessId(_In_ HANDLE ProcessId, _Outptr_
PEPROCESS *Process);

NTSTATUS KernelRPM(PEPROCESS Process, PVOID SourceAddress, PVOID
TargetAddress, SIZE_T Size)
{
PEPROCESS SourceProcess = Process;
PEPROCESS TargetProcess = PsGetCurrentProcess();
SIZE_T Result;
if (NT_SUCCESS(MmCopyVirtualMemory(SourceProcess, SourceAddress,
TargetProcess, TargetAddress, Size, KernelMode, &Result)))
    return STATUS_SUCCESS;
else
    return STATUS_ACCESS_DENIED;
}

NTSTATUS KernelWPM(PEPROCESS Process, PVOID SourceAddress, PVOID
TargetAddress, SIZE_T Size)
{
PEPROCESS SourceProcess = PsGetCurrentProcess();
PEPROCESS TargetProcess = Process;
SIZE_T Result;

if (NT_SUCCESS(MmCopyVirtualMemory(SourceProcess, SourceAddress,
TargetProcess, TargetAddress, Size, KernelMode, &Result)))
    return STATUS_SUCCESS;
else
    return STATUS_ACCESS_DENIED;
}

NTSTATUS DriverEntry(_In_  struct _DRIVER_OBJECT *DriverObject, _In_
PUNICODE_STRING RegistryPath)
{
int Writeval = 666;

PEPROCESS *Process;

GetProcessByID(4872, &Process);

KernelWPM(Process, &Writeval, 0x010F29B0, sizeof(__int32));

DbgPrint("Value of int i: %d", Writeval);

return STATUS_SUCCESS;
}
</code>```

What am i doing wrong? How i could improve that,
Any suggestions ?
Thanks.

答: Including ntifs.h before ntddk.h fixed it for me. </p>

Title: Simple Kernel Mode Driver

Body:
I'm creating simple Kernel Mode Driver (Empty Project) to try some

read/write memory operations on user mode apps.

I'm getting errors while compiling the project On these lines :

NTSTATUS NTAPI MmCopyVirtualMemory(PEPROCESS SourceProcess, PVOID
SourceAddress, PEPROCESS TargetProcess, PVOID TargetAddress, SIZE_T
BufferSize, KPROCESSOR_MODE PreviousMode, PSIZE_T ReturnSize);

NTSTATUS PsLookupProcessByProcessId(_In_ HANDLE ProcessId, _Outptr_
PEPROCESS *Process);

KernelWPM(Process, &Writeval, 0x010F29B0, sizeof(__int32));

VS Compiling errors :

Severity    Code    Description Project File    Line    Suppression State
Error   C2371   'PEPROCESS': redefinition; different basic types    INR
C:\Program Files (x86)\Windows Kits\10\Include\10.0.16299.0\km\ntifs.h  85
Warning C4022   'GetProcessByID': pointer mismatch for actual parameter 1
INR C:\Users\NAKEDRAT\Desktop\INR\INR\main.c    62
Error   C2371   'PETHREAD': redefinition; different basic types INR
C:\Program Files (x86)\Windows Kits\10\Include\10.0.16299.0\km\ntifs.h  86
Warning C4047   'function': 'PEPROCESS' differs in levels of indirection
from 'PEPROCESS **' INR C:\Users\NAKEDRAT\Desktop\INR\INR\main.c    62
Warning C4024   'GetProcessByID': different types for formal and actual
parameter 2 INR C:\Users\NAKEDRAT\Desktop\INR\INR\main.c    62
Warning C4047   'function': 'PEPROCESS' differs in levels of indirection
from 'PEPROCESS *'  INR C:\Users\NAKEDRAT\Desktop\INR\INR\main.c    64
Warning C4024   'KernelWPM': different types for formal and actual parameter
1   INR C:\Users\NAKEDRAT\Desktop\INR\INR\main.c    64
Warning C4022   'KernelWPM': pointer mismatch for actual parameter 3    INR
C:\Users\NAKEDRAT\Desktop\INR\INR\main.c    64

Here is my code :
Also using the same SDK & WDK version

#include <ntddk.h>
#include <ntdef.h>
#include <ntifs.h>

DRIVER_INITIALIZE DriverEntry;

#pragma alloc_text(INIT, DriverEntry)

NTSTATUS NTAPI MmCopyVirtualMemory(PEPROCESS SourceProcess, PVOID
SourceAddress, PEPROCESS TargetProcess, PVOID TargetAddress, SIZE_T
BufferSize, KPROCESSOR_MODE PreviousMode, PSIZE_T ReturnSize);

NTSTATUS PsLookupProcessByProcessId(_In_ HANDLE ProcessId, _Outptr_
PEPROCESS *Process);

NTSTATUS KernelRPM(PEPROCESS Process, PVOID SourceAddress, PVOID
TargetAddress, SIZE_T Size)
{
PEPROCESS SourceProcess = Process;
PEPROCESS TargetProcess = PsGetCurrentProcess();
SIZE_T Result;
if (NT_SUCCESS(MmCopyVirtualMemory(SourceProcess, SourceAddress,
TargetProcess, TargetAddress, Size, KernelMode, &Result)))
    return STATUS_SUCCESS;
else
    return STATUS_ACCESS_DENIED;
}

NTSTATUS KernelWPM(PEPROCESS Process, PVOID SourceAddress, PVOID
TargetAddress, SIZE_T Size)
{
PEPROCESS SourceProcess = PsGetCurrentProcess();
PEPROCESS TargetProcess = Process;
SIZE_T Result;

if (NT_SUCCESS(MmCopyVirtualMemory(SourceProcess, SourceAddress,
TargetProcess, TargetAddress, Size, KernelMode, &Result)))
    return STATUS_SUCCESS;
else
    return STATUS_ACCESS_DENIED;
}

NTSTATUS DriverEntry(_In_  struct _DRIVER_OBJECT *DriverObject, _In_
PUNICODE_STRING RegistryPath)
{
int Writeval = 666;

PEPROCESS *Process;

GetProcessByID(4872, &Process);

KernelWPM(Process, &Writeval, 0x010F29B0, sizeof(__int32));

DbgPrint("Value of int i: %d", Writeval);

return STATUS_SUCCESS;
}

What am i doing wrong? How i could improve that,
Any suggestions ?
Thanks.


问:
Node.js MySQL INSERT ... ON DUPLICATE KEY UPDATE doesn't insert/update more than one row
I have a database on MariaDB (a MySQL-like implementation) with a table like this:

product_qts

```<code>  product_id  |    name    |    value
-----------------------------------------
       1      |     xxs    |      2
       1      |      l     |      1

CREATE TABLE IF NOT EXISTS products_qts (
product_id MEDIUMINT NOT NULL,
name CHAR(50) NOT NULL,
value TINYINT NOT NULL DEFAULT 0,
PRIMARY KEY (product_id, name),
CONSTRAINT product_qt_fk FOREIGN KEY (product_id)
REFERENCES products(id) ON DELETE CASCADE) ENGINE=INNODB
</code>```

I set product_id and name as primary keys.

The DB is accessed through a node.js back-end.

So when the user wants to update a product he submit the new quantities
and then I call this function:

```<code>updateQtsById: (qtsArray) => {

    return new Promise(function (resolve, reject) {
        pool.query('INSERT INTO products_qts (product_id, name, value) ' +
                'VALUES ? ' +
                'ON DUPLICATE KEY UPDATE ' +
                'value=VALUES (value) ',
                qtsArray
            )
            .then(result => {
                resolve(result.affectedRows);
            })
            .catch(error => {
                reject(error);
            });
    });
}
</code>```

The parameter I sent to it is like this:

```<code>[ [ 1, 'onesize', 3 ], [ 1, 'xxs', 2 ], [ 1, 'xs', 1 ] ]
</code>```

Now it does not rise any error, but instead of insert multiple values it update the first one and then stops. Where am I wrong? Which is the best way?

EDIT:

product_id is a FOREIGN KEY

答:
When you insert a new row into a table if the row causes a duplicate
  in UNIQUE index or PRIMARY KEY , MySQL will issue an error.

However, if you specify the ON DUPLICATE KEY UPDATE option in the INSERT statement, MySQL will update the existing row with the new values instead.

The syntax of INSERT ON DUPLICATE KEY UPDATE statement is as follows:

```<code>INSERT INTO products_qts (product_id, name, value)
VALUES ( 1, 'onesize', 3  )
ON DUPLICATE KEY UPDATE
   name = onesize,
   value = 3,
   ...;
</code>```

AND all this should be in loop

like

```<code>qtsArray.forEach(function(item) {

 }).
</code>```

Body:
I have a database on MariaDB (a MySQL-like implementation) with a table like this:

product_qts

  product_id  |    name    |    value
-----------------------------------------
       1      |     xxs    |      2
       1      |      l     |      1

CREATE TABLE IF NOT EXISTS products_qts (
product_id MEDIUMINT NOT NULL,
name CHAR(50) NOT NULL,
value TINYINT NOT NULL DEFAULT 0,
PRIMARY KEY (product_id, name),
CONSTRAINT product_qt_fk FOREIGN KEY (product_id)
REFERENCES products(id) ON DELETE CASCADE) ENGINE=INNODB

I set product_id and name as primary keys.

The DB is accessed through a node.js back-end.

So when the user wants to update a product he submit the new quantities
and then I call this function:

updateQtsById: (qtsArray) => {

    return new Promise(function (resolve, reject) {
        pool.query('INSERT INTO products_qts (product_id, name, value) ' +
                'VALUES ? ' +
                'ON DUPLICATE KEY UPDATE ' +
                'value=VALUES (value) ',
                qtsArray
            )
            .then(result => {
                resolve(result.affectedRows);
            })
            .catch(error => {
                reject(error);
            });
    });
}

The parameter I sent to it is like this:

[ [ 1, 'onesize', 3 ], [ 1, 'xxs', 2 ], [ 1, 'xs', 1 ] ]

Now it does not rise any error, but instead of insert multiple values it update the first one and then stops. Where am I wrong? Which is the best way?

EDIT:

product_id is a FOREIGN KEY

Body:
When you insert a new row into a table if the row causes a duplicate
  in UNIQUE index or PRIMARY KEY , MySQL will issue an error.

However, if you specify the ON DUPLICATE KEY UPDATE option in the INSERT statement, MySQL will update the existing row with the new values instead.

The syntax of INSERT ON DUPLICATE KEY UPDATE statement is as follows:

INSERT INTO products_qts (product_id, name, value)
VALUES ( 1, 'onesize', 3  )
ON DUPLICATE KEY UPDATE
   name = onesize,
   value = 3,
   ...;

AND all this should be in loop

like

qtsArray.forEach(function(item) {

 }).


问:
Is there a way to also select the row count from the same following query?
Would I be able to add a rowcount to this same query or would I need to create a separate one?</p>

```<code>SELECT DISTINCT c.TABLE_SCHEMA, c.TABLE_NAME, c.COLUMN_NAME, c.DATA_TYPE, \
                ( \
                    SELECT DISTINCT p.CONSTRAINT_TYPE \
                    FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu \
                        INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS p ON p.CONSTRAINT_NAME=kcu.CONSTRAINT_NAME AND p.CONSTRAINT_TYPE=\'PRIMARY KEY\' \
                    WHERE kcu.TABLE_NAME = c.TABLE_NAME AND kcu.COLUMN_NAME=c.COLUMN_NAME \
                ) AS CONSTRAINT_TYPE, NULL AS DATA_PRECISION, NULL AS DATA_SCALE \
                FROM INFORMATION_SCHEMA.COLUMNS c
</code>```

答:
You can do it with a cte</p>

```<code>    with cte as
    (
    SELECT DISTINCT c.TABLE_SCHEMA, c.TABLE_NAME, c.COLUMN_NAME, c.DATA_TYPE,
                    (
                        SELECT DISTINCT p.CONSTRAINT_TYPE
                        FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu
                            INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS p ON p.CONSTRAINT_NAME=kcu.CONSTRAINT_NAME AND p.CONSTRAINT_TYPE='PRIMARY KEY'
                        WHERE kcu.TABLE_NAME = c.TABLE_NAME AND kcu.COLUMN_NAME=c.COLUMN_NAME
                    ) AS CONSTRAINT_TYPE, NULL AS DATA_PRECISION, NULL AS DATA_SCALE
                    FROM INFORMATION_SCHEMA.COLUMNS c
    )
select *, (select count(*) from cte)  as  _Count
from
cte
</code>```

Body:
Would I be able to add a rowcount to this same query or would I need to create a separate one?

SELECT DISTINCT c.TABLE_SCHEMA, c.TABLE_NAME, c.COLUMN_NAME, c.DATA_TYPE, \
                ( \
                    SELECT DISTINCT p.CONSTRAINT_TYPE \
                    FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu \
                        INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS p ON p.CONSTRAINT_NAME=kcu.CONSTRAINT_NAME AND p.CONSTRAINT_TYPE=\'PRIMARY KEY\' \
                    WHERE kcu.TABLE_NAME = c.TABLE_NAME AND kcu.COLUMN_NAME=c.COLUMN_NAME \
                ) AS CONSTRAINT_TYPE, NULL AS DATA_PRECISION, NULL AS DATA_SCALE \
                FROM INFORMATION_SCHEMA.COLUMNS c

Body:
You can do it with a cte

    with cte as
    (
    SELECT DISTINCT c.TABLE_SCHEMA, c.TABLE_NAME, c.COLUMN_NAME, c.DATA_TYPE,
                    (
                        SELECT DISTINCT p.CONSTRAINT_TYPE
                        FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu
                            INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS p ON p.CONSTRAINT_NAME=kcu.CONSTRAINT_NAME AND p.CONSTRAINT_TYPE='PRIMARY KEY'
                        WHERE kcu.TABLE_NAME = c.TABLE_NAME AND kcu.COLUMN_NAME=c.COLUMN_NAME
                    ) AS CONSTRAINT_TYPE, NULL AS DATA_PRECISION, NULL AS DATA_SCALE
                    FROM INFORMATION_SCHEMA.COLUMNS c
    )
select *, (select count(*) from cte)  as  _Count
from
cte


问:
Check for NULL ggplot object before adding layers in dplyr pipe
I have template plot functions that check whether a data frame has > 0 rows before running:

```<code>library(tidyverse)

plot_fun <- function(df) {
  if (nrow(df) > 0) {
    df %>%
      ggplot(., aes(Sepal.Length, Sepal.Width)) +
      geom_point()
  }
}
</code>```

Then I use this within pipes and add bespoke layers:

```<code>iris %>% plot_fun() + ggtitle("Plot me")
</code>```

However if the data framed piped in has 0 rows I get an error because I am trying to add layers to nothing:

```<code>iris %>%
  filter(Sepal.Length > 1000) %>%
  plot_fun() +
  ggtitle("Plot me")
</code>```

Error in iris %>% filter(Sepal.Length > 1000) %>% plot_fun() +
  ggtitle("Plot me") :    non-numeric argument to binary operator

I can build a check mid pipe to avoid the error:

```<code>iris %>%
  filter(Sepal.Length > 1000) %>%
  plot_fun() %>%
  {
    if (!is.null(.)) {
      . +
        ggtitle("Plot me")
    }
  }
</code>```

That works but that seems clunky. Is it possible to make a function check_df_pipe() or something to stop the pipe if preceding filters remove all data? Or maybe to check if the pipe . is NULL at a point?

```<code>check_df_pipe <- function(x) {
  if(nrow(x) > 0) {
    x
  } else{
    stop("Dont return an error just to exit pipe")
  }
}

iris %>%
  filter(Sepal.Length > 1000) %>%
  check_df_pipe() %>%
  plot_fun() +
  ggtitle("Plot me")
</code>```

Error in check_df_pipe(.) : Dont return an error just to exit pipe

Or any other ideas on how to deal with this? I don't want to add ggtitle("Plot me") into plot_fun because I wan't plot_fun to stay generic.

答:
I would not recommend such piping. It can be confusing to decode such a code. But here is a solution:</p>

```<code>cond_pipe <- function(x) {
  if (nrow(x) > 0) {
    x %>%
      plot_fun() +
      ggtitle("Plot me")
  } else {
    warning("Dont return an error just to exit pipe")
  }
}

iris %>%
  filter(Sepal.Length > 1000) %>%
  cond_pipe()
</code>```

Body:
I have template plot functions that check whether a data frame has > 0 rows before running:

library(tidyverse)

plot_fun <- function(df) {
  if (nrow(df) > 0) {
    df %>%
      ggplot(., aes(Sepal.Length, Sepal.Width)) +
      geom_point()
  }
}

Then I use this within pipes and add bespoke layers:

iris %>% plot_fun() + ggtitle("Plot me")

However if the data framed piped in has 0 rows I get an error because I am trying to add layers to nothing:

iris %>%
  filter(Sepal.Length > 1000) %>%
  plot_fun() +
  ggtitle("Plot me")

Error in iris %>% filter(Sepal.Length > 1000) %>% plot_fun() +
  ggtitle("Plot me") :    non-numeric argument to binary operator

I can build a check mid pipe to avoid the error:

iris %>%
  filter(Sepal.Length > 1000) %>%
  plot_fun() %>%
  {
    if (!is.null(.)) {
      . +
        ggtitle("Plot me")
    }
  }

That works but that seems clunky. Is it possible to make a function check_df_pipe() or something to stop the pipe if preceding filters remove all data? Or maybe to check if the pipe . is NULL at a point?

check_df_pipe <- function(x) {
  if(nrow(x) > 0) {
    x
  } else{
    stop("Dont return an error just to exit pipe")
  }
}

iris %>%
  filter(Sepal.Length > 1000) %>%
  check_df_pipe() %>%
  plot_fun() +
  ggtitle("Plot me")

Error in check_df_pipe(.) : Dont return an error just to exit pipe

Or any other ideas on how to deal with this? I don't want to add ggtitle("Plot me") into plot_fun because I wan't plot_fun to stay generic.

Body:
I would not recommend such piping. It can be confusing to decode such a code. But here is a solution:

cond_pipe <- function(x) {
  if (nrow(x) > 0) {
    x %>%
      plot_fun() +
      ggtitle("Plot me")
  } else {
    warning("Dont return an error just to exit pipe")
  }
}

iris %>%
  filter(Sepal.Length > 1000) %>%
  cond_pipe()


问:
SqlBulkCopy.WriteToServerAsync does not respect the `await` keyword. Why?
SqlBulkCopy.WriteToServerAsync does not respect the await keyword. Why?

Here is my code:

```<code>public async Task UpdateDBWithXML(Action<Func<DataTable, Task>> readXmlInBatches, string hashKey, string hash)
{
    using (var transaction = this.Context.Database.BeginTransaction(IsolationLevel.ReadUncommitted))
    using (var bulk = new SqlBulkCopy((SqlConnection)this.Connection, SqlBulkCopyOptions.Default, (SqlTransaction)transaction.UnderlyingTransaction))
    {
        //this.Context.Database.ExecuteSqlCommand("DELETE FROM [dbo].[LegalContractorTemps]");

        bulk.DestinationTableName = "LegalContractorTemps";
        readXmlInBatches(async (DataTable table) =>
        {
            if (bulk.ColumnMappings.Count == 0)
            {
                foreach (DataColumn column in table.Columns)
                {
                    bulk.ColumnMappings.Add(new SqlBulkCopyColumnMapping(column.ColumnName, column.ColumnName));
                }
            }

            await bulk.WriteToServerAsync(table);
        });

        await this.Context.Database.ExecuteSqlCommandAsync(
            "EXECUTE dbo.LegalContractorsDataSynchronize @hashKey, @hash",
            new SqlParameter("@hashKey", hashKey),
            new SqlParameter("@hash", hash)
        );

        transaction.Commit();
    }
}
</code>```

In the readXmlInBatches parameter I pass the following function as an argument:

```<code>public void ReadXMLInBatches(Func<DataTable, Task> processBatch)
{
    int batchSize = 10000;
    var table = new DataTable();
    foreach (var col in columnNames)
    {
        table.Columns.Add(col);
    }

    using (var reader = new StreamReader(pathToXml, Encoding.GetEncoding(encoding)))
    using (var xmlReader = XmlReader.Create(reader))
    {
        string lastElement = null;
        DataRow lastRow = null;
        while (xmlReader.Read())
        {
            switch (xmlReader.NodeType)
            {
                case XmlNodeType.Element:
                    if (xmlReader.Name == "RECORD")
                    {
                        if (table.Rows.Count >= batchSize)
                        {
                            processBatch(table);
                            table.Rows.Clear();
                        }

                        lastRow = table.Rows.Add();
                    }
                    lastElement = xmlReader.Name;
                    break;
                case XmlNodeType.Text:
                    ReadMember(lastRow, lastElement, xmlReader.Value);
                    break;
            }
        }
        if (table.Rows.Count > 0)
        {
            processBatch(table);
            table.Rows.Clear();
        }
    }
}
</code>```

I have in the XML something about 1.7 million records. After my program have read a few batches I am getting the error:

System.Data.RowNotInTableException: 'This row has been removed from a table and does not have any data.  BeginEdit() will allow creation of new data in this row.'

I researched the source code of the SqlBulkCopy. And found the method which throws an error:

```<code>public Task WriteToServerAsync(DataTable table, DataRowState rowState, CancellationToken cancellationToken) {
            Task resultTask = null;
            SqlConnection.ExecutePermission.Demand();

            if (table == null) {
                throw new ArgumentNullException("table");
            }

            if (_isBulkCopyingInProgress){
                throw SQL.BulkLoadPendingOperation();
            }

            SqlStatistics statistics = Statistics;
            try {
                statistics = SqlStatistics.StartTimer(Statistics);
                _rowStateToSkip = ((rowState == 0) || (rowState == DataRowState.Deleted)) ? DataRowState.Deleted : ~rowState | DataRowState.Deleted;
                _rowSource = table;
                _SqlDataReaderRowSource = null;
                _dataTableSource = table;
                _rowSourceType = ValueSourceType.DataTable;
                _rowEnumerator = table.Rows.GetEnumerator();
                _isAsyncBulkCopy = true;
                resultTask = WriteRowSourceToServerAsync(table.Columns.Count, cancellationToken); //It returns Task since _isAsyncBulkCopy = true;
            }
            finally {
                SqlStatistics.StopTimer(statistics);
            }
            return resultTask;
        }
</code>```

I noticed the field _isBulkCopyingInProgress and decided to check it while debugging. And I found out that when the error is thrown the field is true. How is that possible? I would expect the bulk insert to happen first (before the execution continues and the WriteToServerAsync will be called a second time)  since I add the await here: await bulk.WriteToServerAsync(table);.

What could I be missing?

答:
You are passing an asynchronous function to ReadXMLInBatches, but it's execution isn't being awaited inside your method, therefore ReadXMLInBatches may terminate before all the calls to WriteToServerAsync have completed.

Try the following changes:

```<code>public async Task ReadXMLInBatchesAsync(Func<DataTable, Task> processBatch)
{
    //...
    await processBatch(table);
    //...
}

public async Task UpdateDBWithXML(Func<Func<DataTable, Task>, Task> readXmlInBatches, string hashKey, string hash)
{
    //...
    await readXmlInBatches(async (DataTable table) =>
    //...
}
</code>```

Body:
SqlBulkCopy.WriteToServerAsync does not respect the await keyword. Why?

Here is my code:

public async Task UpdateDBWithXML(Action<Func<DataTable, Task>> readXmlInBatches, string hashKey, string hash)
{
    using (var transaction = this.Context.Database.BeginTransaction(IsolationLevel.ReadUncommitted))
    using (var bulk = new SqlBulkCopy((SqlConnection)this.Connection, SqlBulkCopyOptions.Default, (SqlTransaction)transaction.UnderlyingTransaction))
    {
        //this.Context.Database.ExecuteSqlCommand("DELETE FROM [dbo].[LegalContractorTemps]");

        bulk.DestinationTableName = "LegalContractorTemps";
        readXmlInBatches(async (DataTable table) =>
        {
            if (bulk.ColumnMappings.Count == 0)
            {
                foreach (DataColumn column in table.Columns)
                {
                    bulk.ColumnMappings.Add(new SqlBulkCopyColumnMapping(column.ColumnName, column.ColumnName));
                }
            }

            await bulk.WriteToServerAsync(table);
        });

        await this.Context.Database.ExecuteSqlCommandAsync(
            "EXECUTE dbo.LegalContractorsDataSynchronize @hashKey, @hash",
            new SqlParameter("@hashKey", hashKey),
            new SqlParameter("@hash", hash)
        );

        transaction.Commit();
    }
}

In the readXmlInBatches parameter I pass the following function as an argument:

public void ReadXMLInBatches(Func<DataTable, Task> processBatch)
{
    int batchSize = 10000;
    var table = new DataTable();
    foreach (var col in columnNames)
    {
        table.Columns.Add(col);
    }

    using (var reader = new StreamReader(pathToXml, Encoding.GetEncoding(encoding)))
    using (var xmlReader = XmlReader.Create(reader))
    {
        string lastElement = null;
        DataRow lastRow = null;
        while (xmlReader.Read())
        {
            switch (xmlReader.NodeType)
            {
                case XmlNodeType.Element:
                    if (xmlReader.Name == "RECORD")
                    {
                        if (table.Rows.Count >= batchSize)
                        {
                            processBatch(table);
                            table.Rows.Clear();
                        }

                        lastRow = table.Rows.Add();
                    }
                    lastElement = xmlReader.Name;
                    break;
                case XmlNodeType.Text:
                    ReadMember(lastRow, lastElement, xmlReader.Value);
                    break;
            }
        }
        if (table.Rows.Count > 0)
        {
            processBatch(table);
            table.Rows.Clear();
        }
    }
}

I have in the XML something about 1.7 million records. After my program have read a few batches I am getting the error:

System.Data.RowNotInTableException: 'This row has been removed from a table and does not have any data.  BeginEdit() will allow creation of new data in this row.'

I researched the source code of the SqlBulkCopy. And found the method which throws an error:

public Task WriteToServerAsync(DataTable table, DataRowState rowState, CancellationToken cancellationToken) {
            Task resultTask = null;
            SqlConnection.ExecutePermission.Demand();

            if (table == null) {
                throw new ArgumentNullException("table");
            }

            if (_isBulkCopyingInProgress){
                throw SQL.BulkLoadPendingOperation();
            }

            SqlStatistics statistics = Statistics;
            try {
                statistics = SqlStatistics.StartTimer(Statistics);
                _rowStateToSkip = ((rowState == 0) || (rowState == DataRowState.Deleted)) ? DataRowState.Deleted : ~rowState | DataRowState.Deleted;
                _rowSource = table;
                _SqlDataReaderRowSource = null;
                _dataTableSource = table;
                _rowSourceType = ValueSourceType.DataTable;
                _rowEnumerator = table.Rows.GetEnumerator();
                _isAsyncBulkCopy = true;
                resultTask = WriteRowSourceToServerAsync(table.Columns.Count, cancellationToken); //It returns Task since _isAsyncBulkCopy = true;
            }
            finally {
                SqlStatistics.StopTimer(statistics);
            }
            return resultTask;
        }

I noticed the field _isBulkCopyingInProgress and decided to check it while debugging. And I found out that when the error is thrown the field is true. How is that possible? I would expect the bulk insert to happen first (before the execution continues and the WriteToServerAsync will be called a second time)  since I add the await here: await bulk.WriteToServerAsync(table);.

What could I be missing?

Body:
You are passing an asynchronous function to ReadXMLInBatches, but it's execution isn't being awaited inside your method, therefore ReadXMLInBatches may terminate before all the calls to WriteToServerAsync have completed.

Try the following changes:

public async Task ReadXMLInBatchesAsync(Func<DataTable, Task> processBatch)
{
    //...
    await processBatch(table);
    //...
}

public async Task UpdateDBWithXML(Func<Func<DataTable, Task>, Task> readXmlInBatches, string hashKey, string hash)
{
    //...
    await readXmlInBatches(async (DataTable table) =>
    //...
}


问:
ActionView::Template::Error (Mysql2::Error::ConnectionError: Wrong or unknown protocol: SELECT
I get this weird error in my rails application

```<code>Completed 500 Internal Server Error in 176742ms (ActiveRecord: 148.5ms)

ActionView::Template::Error (Mysql2::Error::ConnectionError: Wrong or unknown protocol: SELECT  `lines`.* FROM `lines` WHERE `lines`.`id` = 15 LIMIT 1):
    22:               <% if defined?(Haml) && respond_to?(:block_is_haml?) && block_is_haml?(block) %>
    23:                 <% capture_haml(day, sorted_events.fetch(day, []), &block) %>
    24:               <% else %>
    25:                 <% block.call day, sorted_events.fetch(day, []) %>
    26:               <% end %>
    27:             <% end %>
    28:           <% end %>

app/views/presences/index.html.erb:47:in `block (2 levels) in _app_views_presences_index_html_erb__679688437_89682920'
app/views/presences/index.html.erb:7:in `each'
app/views/presences/index.html.erb:7:in `block in _app_views_presences_index_html_erb__679688437_89682920'
app/views/presences/index.html.erb:3:in `_app_views_presences_index_html_erb__679688437_89682920'
</code>```

app/views/presences/index.html.erb:47:

```<code><th style="background: greenyellow"><%= Line.find(l).name + " bla: " + tmp.size.to_s %></th>
</code>```

Does anyone know how to fix this one or has an idea why the mysql error appears? In my code in front I do a few select and detect statements on arrays. There are not many mysql queries... And this error just happens in my test environment (copy of production environment on different VM). On my dev environment everything works like a charm.

答: I solved the issue with reinstalling the MySQL server on the current version with a new config. Somehow there were no code changes needed... </p>

Body:
I get this weird error in my rails application

Completed 500 Internal Server Error in 176742ms (ActiveRecord: 148.5ms)

ActionView::Template::Error (Mysql2::Error::ConnectionError: Wrong or unknown protocol: SELECT  `lines`.* FROM `lines` WHERE `lines`.`id` = 15 LIMIT 1):
    22:               <% if defined?(Haml) && respond_to?(:block_is_haml?) && block_is_haml?(block) %>
    23:                 <% capture_haml(day, sorted_events.fetch(day, []), &block) %>
    24:               <% else %>
    25:                 <% block.call day, sorted_events.fetch(day, []) %>
    26:               <% end %>
    27:             <% end %>
    28:           <% end %>

app/views/presences/index.html.erb:47:in `block (2 levels) in _app_views_presences_index_html_erb__679688437_89682920'
app/views/presences/index.html.erb:7:in `each'
app/views/presences/index.html.erb:7:in `block in _app_views_presences_index_html_erb__679688437_89682920'
app/views/presences/index.html.erb:3:in `_app_views_presences_index_html_erb__679688437_89682920'

app/views/presences/index.html.erb:47:

<%= Line.find(l).name + " bla: " + tmp.size.to_s %>

Does anyone know how to fix this one or has an idea why the mysql error appears? In my code in front I do a few select and detect statements on arrays. There are not many mysql queries... And this error just happens in my test environment (copy of production environment on different VM). On my dev environment everything works like a charm.


问:
How to parse special characters in XML for iPad?
I am getting problem while parsing xml files that contains some special characters like single quote,double quote (', "")etc.I am using NSXMLParser's parser:foundCharacters:method to collect characters in my code.

```<code><synctext type = "word" >They raced to the park Arthur pointed to a sign "Whats that say" he asked Zoo said DW Easy as pie</synctext>
</code>```

When i parse and save the text from above tag of my xml file,the resultant string is appearing,in GDB, as

"\n\t\tThey raced to the park Arthur pointed to a sign \"Whats that say\" he asked Zoo said DW Easy as pie";

Observe there are 2 issues:

1)Unwanted characters at the beginning of the string.

2)The double quotes around Whats that say.

Can any one please help me how to get rid of these unwanted characters and how to read special characters properly.

答:
The parser is apparently returning exactly what's in the string.  That is, the XML was coded with the starting tag on one line, a newline, two tabs, and the start of the string.  And quotes in the string are obviously there in the original (and it's not clear in at least this example why you'd want to delete them).

But if you want these characters gone then you need to post-process the string.  You can use Rams' statement to eliminate the newline and tabs, and stringByReplacingOccurrencesOfString:WithString: to zap the quotes.

(Note that some XML parsers can be instructed to return strings like this with the leading/trailing stuff stripped, but I'm not sure about this one.  The quotes will always be there, though.)

Body:
I am getting problem while parsing xml files that contains some special characters like single quote,double quote (', "")etc.I am using NSXMLParser's parser:foundCharacters:method to collect characters in my code.

<synctext type = "word" >They raced to the park Arthur pointed to a sign "Whats that say" he asked Zoo said DW Easy as pie</synctext>

When i parse and save the text from above tag of my xml file,the resultant string is appearing,in GDB, as

"\n\t\tThey raced to the park Arthur pointed to a sign \"Whats that say\" he asked Zoo said DW Easy as pie";

Observe there are 2 issues:

1)Unwanted characters at the beginning of the string.

2)The double quotes around Whats that say.

Can any one please help me how to get rid of these unwanted characters and how to read special characters properly.


问:
How to convert a List< Long> into a double[] in Java
I am trying to convert a List<Long> to a double[] in Java,

I did in the following way,

```<code>  List<Long> longList = ........;

  int len = longList.size();

  double[] doubleArray = new double[len];

  for (int i = 0; i < len; i++)
     doubleArray[i] = (double) longList.get(i);
</code>```

I am wondering if I can do it in a smarter way (and how) since I'm using Java-8, I saw some conversion using the stream method. But couldn't find anything that can solve my problem.

答:
If you are using Java 8 try this:</p>

```<code>list.stream().map(v -> (double)v)
    .toArray(Double[]::new);
</code>```

Body:
I am trying to convert a List<Long> to a double[] in Java,

I did in the following way,

  List<Long> longList = ........;

  int len = longList.size();

  double[] doubleArray = new double[len];

  for (int i = 0; i < len; i++)
     doubleArray[i] = (double) longList.get(i);

I am wondering if I can do it in a smarter way (and how) since I'm using Java-8, I saw some conversion using the stream method. But couldn't find anything that can solve my problem.

Body:
If you are using Java 8 try this:

list.stream().map(v -> (double)v)
    .toArray(Double[]::new);


答:
You could indeed do it using a stream:

```<code>double[] result = longList.stream()
                          .mapToDouble(Long::doubleValue)
                          .toArray();
</code>```

It's maybe a little shorter and cleaner but you won't gain anything performance wise.

Title: How to convert a List< Long> into a double[] in Java

Body:
You could indeed do it using a stream:

double[] result = longList.stream()
                          .mapToDouble(Long::doubleValue)
                          .toArray();

It's maybe a little shorter and cleaner but you won't gain anything performance wise.


问:
Null response from restshap by asp.net
I've developed with Visual Studio 2019 a ConsoleApp C# where a make a request with restsharp and work good.

here there is the code that I've used for make a request:

```<code>using RestSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Data;
using System.Data.SqlClient;

namespace RetailerUrlStatusChecker
{
    public class Program
    {

        static async Task Main(string[] args)
        {
            await ProcessRepositories();

        }

        private static async Task ProcessRepositories()
        {

            var client = new RestClient("https://api-developer.com/products");
            client.Timeout = -1;
            var request = new RestRequest(Method.POST);
            request.AddHeader("Content-Type", "application/json");
            request.AddHeader("Accept", "application/json");
            request.AddParameter("application/json", "{\"category\": \"all\"}", ParameterType.RequestBody);

            var response2 = await client.ExecuteTaskAsync<List>(request);
            List products= response2.Data;

            //INSERT DATA INTO DB SQL SERVER
            string connectionString = "Data Source=utente-pc\\SQLEXPRESS;Initial Catalog=MYDB;Persist Security Info=True;User ID=user;Password=sa";
            SqlConnection connection = new SqlConnection(connectionString);

            try
            {

                SqlCommand cmd = new SqlCommand("INSERT INTO PRODUCT (code, name, description) VALUES (@code, @name, @description)", connection);
                cmd.Parameters.AddWithValue("@code", products.code);
                cmd.Parameters.AddWithValue("@name", products.name);
                cmd.Parameters.AddWithValue("@description", products.description);

                connection.Open();
                cmd.ExecuteNonQuery();
            }

            catch
            {
                //Label4.Text = "uh oh";
            }

        }
    }

    public class List
    {

        public string code{ get; set; }
        public string name{ get; set; }
        public string description{ get; set; }
    }

}
</code>```

I need to implement this request in a project web form asp.net, I've try to write the same code but it don't work, I receved a response null.

This is the code about my page asp.net

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using RestSharp;
using System.Data;
using System.Data.SqlClient;
using System.Threading.Tasks;

namespace WebApplication2
{
    public partial class _Default : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            RegisterAsyncTask(new PageAsyncTask(GetGizmosSvcAsync));
        }

        public async Task GetGizmosSvcAsync()
        {
            var client = new RestClient("https://api-developer.com/products");
            client.Timeout = -1;
            var request = new RestRequest(Method.POST);
            request.AddHeader("Content-Type", "application/json");
            request.AddHeader("Accept", "application/json");
            request.AddParameter("application/json", "{\"category\": \"all\"}", ParameterType.RequestBody);

            var response2 = await client.ExecuteTaskAsync<List>(request);
            List products= response2.Data;

            //INSERT DATA INTO DB SQL SERVER
            string connectionString = "Data Source=utente-pc\\SQLEXPRESS;Initial Catalog=MYDB;Persist Security Info=True;User ID=user;Password=sa";
            SqlConnection connection = new SqlConnection(connectionString);

            try
            {

                SqlCommand cmd = new SqlCommand("INSERT INTO PRODUCT (code, name, description) VALUES (@code, @name, @description)", connection);
                cmd.Parameters.AddWithValue("@code", products.code);
                cmd.Parameters.AddWithValue("@name", products.name);
                cmd.Parameters.AddWithValue("@description", products.description);

                connection.Open();
                cmd.ExecuteNonQuery();
            }

            catch
            {
                //Label4.Text = "uh oh";
            }
        }
    }

    public class List
    {

        public string code{ get; set; }
        public string name{ get; set; }
        public string description{ get; set; }
    }

}
</code>```

I've set Async="true" in <%@ page title in my page asp.net

I don't understand why the same code work good on consoleapp c#, but don't work on asp.net c#

Thanks for any help!

The scheme of response is:

```<code>{
   "code": {
      "type": "string"
    },
    "name": {
      "type": "string"
    },
    "description": {
      "type": "string"
    }

}
</code>```

UPDATE:

I've read in other forum that there is an incompatibility with the last version of restsharp and framework..
I've understand that the consoleapp use CORE.NET and webapp use FRAMEWORK.NET, and there are some different with component and NuGet.. So I've try to create a webform and install restsharp v106.1.0 and now it work!!!
So all code was ok, the problem was the update restsharp v106.10.1

Thanks to all for help me and I apologize for the trouble.

答:
Without knowing what endpoint response structure, its hard to assist you. But based on name ("https://api-developer.com/products"), am assuming it returns collection of prodcuts. So, try modifying var response2 = await client.ExecuteTaskAsync<List>(request); statement to var response2 = await client.ExecuteTaskAsync<System.Collections.Generic.List<List>>(request);

Or based on your next statement List products = response2.Data; am assuming request returns some object which contains Data which is collection of List objects something like below:

```<code>public class RootObject()
{
    public System.Collections.Generic.List<List> Data { get; set; }
}
</code>```

If that is the case, then try modifying var response2 = await client.ExecuteTaskAsync<List>(request); to var response2 = await client.ExecuteTaskAsync<RootObject>(request);

So, your final GetGizmosSvcAsync method looks like below:

```<code>public async Task GetGizmosSvcAsync()
{
    var client = new RestClient("https://api-developer.com/products");
    client.Timeout = -1;
    var request = new RestRequest(Method.POST);
    request.AddHeader("Content-Type", "application/json");
    request.AddHeader("Accept", "application/json");
    request.AddParameter("application/json", "{\"category\": \"all\"}", ParameterType.RequestBody);

    var response2 = await client.ExecuteTaskAsync<RootObject>(request);
    var products = response2.Data;  //List products = response2.Data;

    //INSERT DATA INTO DB SQL SERVER
    string connectionString = "Data Source=utente-pc\\SQLEXPRESS;Initial Catalog=MYDB;Persist Security Info=True;User ID=user;Password=sa";
    SqlConnection connection = new SqlConnection(connectionString);

    try
    {

        SqlCommand cmd = new SqlCommand("INSERT INTO PRODUCT (code, name, description) VALUES (@code, @name, @description)", connection);
        connection.Open();

        foreach (var product in products)
        {
            cmd.Parameters.AddWithValue("@code", product.code);
            cmd.Parameters.AddWithValue("@name", product.name);
            cmd.Parameters.AddWithValue("@description", product.description);
            cmd.ExecuteNonQuery();
        }
    }

    catch
    {
        //Label4.Text = "uh oh";
    }
}
</code>```

Title: Null response from restshap by asp.net

Body:
I've developed with Visual Studio 2019 a ConsoleApp C# where a make a request with restsharp and work good.

here there is the code that I've used for make a request:

using RestSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Data;
using System.Data.SqlClient;

namespace RetailerUrlStatusChecker
{
    public class Program
    {

        static async Task Main(string[] args)
        {
            await ProcessRepositories();

        }

        private static async Task ProcessRepositories()
        {

            var client = new RestClient("https://api-developer.com/products");
            client.Timeout = -1;
            var request = new RestRequest(Method.POST);
            request.AddHeader("Content-Type", "application/json");
            request.AddHeader("Accept", "application/json");
            request.AddParameter("application/json", "{\"category\": \"all\"}", ParameterType.RequestBody);

            var response2 = await client.ExecuteTaskAsync<List>(request);
            List products= response2.Data;

            //INSERT DATA INTO DB SQL SERVER
            string connectionString = "Data Source=utente-pc\\SQLEXPRESS;Initial Catalog=MYDB;Persist Security Info=True;User ID=user;Password=sa";
            SqlConnection connection = new SqlConnection(connectionString);

            try
            {

                SqlCommand cmd = new SqlCommand("INSERT INTO PRODUCT (code, name, description) VALUES (@code, @name, @description)", connection);
                cmd.Parameters.AddWithValue("@code", products.code);
                cmd.Parameters.AddWithValue("@name", products.name);
                cmd.Parameters.AddWithValue("@description", products.description);

                connection.Open();
                cmd.ExecuteNonQuery();
            }

            catch
            {
                //Label4.Text = "uh oh";
            }

        }
    }

    public class List
    {

        public string code{ get; set; }
        public string name{ get; set; }
        public string description{ get; set; }
    }

}

I need to implement this request in a project web form asp.net, I've try to write the same code but it don't work, I receved a response null.

This is the code about my page asp.net

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using RestSharp;
using System.Data;
using System.Data.SqlClient;
using System.Threading.Tasks;

namespace WebApplication2
{
    public partial class _Default : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            RegisterAsyncTask(new PageAsyncTask(GetGizmosSvcAsync));
        }

        public async Task GetGizmosSvcAsync()
        {
            var client = new RestClient("https://api-developer.com/products");
            client.Timeout = -1;
            var request = new RestRequest(Method.POST);
            request.AddHeader("Content-Type", "application/json");
            request.AddHeader("Accept", "application/json");
            request.AddParameter("application/json", "{\"category\": \"all\"}", ParameterType.RequestBody);

            var response2 = await client.ExecuteTaskAsync<List>(request);
            List products= response2.Data;

            //INSERT DATA INTO DB SQL SERVER
            string connectionString = "Data Source=utente-pc\\SQLEXPRESS;Initial Catalog=MYDB;Persist Security Info=True;User ID=user;Password=sa";
            SqlConnection connection = new SqlConnection(connectionString);

            try
            {

                SqlCommand cmd = new SqlCommand("INSERT INTO PRODUCT (code, name, description) VALUES (@code, @name, @description)", connection);
                cmd.Parameters.AddWithValue("@code", products.code);
                cmd.Parameters.AddWithValue("@name", products.name);
                cmd.Parameters.AddWithValue("@description", products.description);

                connection.Open();
                cmd.ExecuteNonQuery();
            }

            catch
            {
                //Label4.Text = "uh oh";
            }
        }
    }

    public class List
    {

        public string code{ get; set; }
        public string name{ get; set; }
        public string description{ get; set; }
    }

}

I've set Async="true" in <%@ page title in my page asp.net

I don't understand why the same code work good on consoleapp c#, but don't work on asp.net c#

Thanks for any help!

The scheme of response is:

{
   "code": {
      "type": "string"
    },
    "name": {
      "type": "string"
    },
    "description": {
      "type": "string"
    }

}

UPDATE:

I've read in other forum that there is an incompatibility with the last version of restsharp and framework..
I've understand that the consoleapp use CORE.NET and webapp use FRAMEWORK.NET, and there are some different with component and NuGet.. So I've try to create a webform and install restsharp v106.1.0 and now it work!!!
So all code was ok, the problem was the update restsharp v106.10.1

Thanks to all for help me and I apologize for the trouble.

Body:
Without knowing what endpoint response structure, its hard to assist you. But based on name ("https://api-developer.com/products"), am assuming it returns collection of prodcuts. So, try modifying var response2 = await client.ExecuteTaskAsync<List>(request); statement to var response2 = await client.ExecuteTaskAsync<System.Collections.Generic.List<List>>(request);

Or based on your next statement List products = response2.Data; am assuming request returns some object which contains Data which is collection of List objects something like below:

public class RootObject()
{
    public System.Collections.Generic.List<List> Data { get; set; }
}

If that is the case, then try modifying var response2 = await client.ExecuteTaskAsync<List>(request); to var response2 = await client.ExecuteTaskAsync<RootObject>(request);

So, your final GetGizmosSvcAsync method looks like below:

public async Task GetGizmosSvcAsync()
{
    var client = new RestClient("https://api-developer.com/products");
    client.Timeout = -1;
    var request = new RestRequest(Method.POST);
    request.AddHeader("Content-Type", "application/json");
    request.AddHeader("Accept", "application/json");
    request.AddParameter("application/json", "{\"category\": \"all\"}", ParameterType.RequestBody);

    var response2 = await client.ExecuteTaskAsync<RootObject>(request);
    var products = response2.Data;  //List products = response2.Data;

    //INSERT DATA INTO DB SQL SERVER
    string connectionString = "Data Source=utente-pc\\SQLEXPRESS;Initial Catalog=MYDB;Persist Security Info=True;User ID=user;Password=sa";
    SqlConnection connection = new SqlConnection(connectionString);

    try
    {

        SqlCommand cmd = new SqlCommand("INSERT INTO PRODUCT (code, name, description) VALUES (@code, @name, @description)", connection);
        connection.Open();

        foreach (var product in products)
        {
            cmd.Parameters.AddWithValue("@code", product.code);
            cmd.Parameters.AddWithValue("@name", product.name);
            cmd.Parameters.AddWithValue("@description", product.description);
            cmd.ExecuteNonQuery();
        }
    }

    catch
    {
        //Label4.Text = "uh oh";
    }
}


问:
How to bind input of type time with blazor
Hello i have 2 variables of type int that i would like to bind to the min and max values of an input of type time.

How can i do this?

I do not know what to place in the bind field since there are 2 different variables.
Also there is the min and max attributes.

<input type="time" min="@model.min" max="@model.max" bind=?/>

What should i put in the bind ?

Update
On a more thoroughly analysis i decided i will need 2 variables of type Timespan and i will bind these to 2 inputs of type time.

答:
Previous solution was not working for me with .net Core 3.1 so I'll add an updated one:

Use Blazor :

```<code><EditForm Model=@model OnValidSubmit="Submit">
    <InputText type="time" @bind-Value="TimeProxy" />
</EditForm>
</code>```

Code changes are necessary as well.

```<code>@code {
    // This field is required as you can not use property in out statement
    private TimeSpan LocalTime = TimeSpan.FromHours(0);
    private string TimeProxy {
        get => model.Time.ToString();
        set => TimeSpan.TryParse(value,out LocalTime);
    }
    private void Submit() {
        model.Time = LocalTime;
        // following submit logic...
    }
}
</code>```

Body:
Previous solution was not working for me with .net Core 3.1 so I'll add an updated one:

Use Blazor :

<EditForm Model=@model OnValidSubmit="Submit">
    <InputText type="time" @bind-Value="TimeProxy" />
</EditForm>

Code changes are necessary as well.

@code {
    // This field is required as you can not use property in out statement
    private TimeSpan LocalTime = TimeSpan.FromHours(0);
    private string TimeProxy {
        get => model.Time.ToString();
        set => TimeSpan.TryParse(value,out LocalTime);
    }
    private void Submit() {
        model.Time = LocalTime;
        // following submit logic...
    }
}


问:
Resolving package conflicts in Python 2.7 Environment
My goal is to run a python script from about 2 years ago.

If someone could point me in the direction of an answer or issue that will help me work through the conflicts between packages to create a working environment for this old script it would be hugely appreciated.

It is written in python 2.

Dependencies are

```<code>psycopg2
</code>```

and an internal module that imports

```<code>pandas
geopandas
psycopg2-binary
sqlalchemy
pyyaml
scikit-image
beautifultable
tqdm
statistics
rasterio ; sys_platform=="linux2"
geopandas ; sys_platform=="linux2"
\__Python wheels\pyproj-1.9.6-cp27-cp27m-win_amd64.whl ; sys_platform=="win32"
\__Python wheels\GDAL-2.2.4-cp27-cp27m-win_amd64.whl ; sys_platform=="win32"
\__Python wheels\Shapely-1.6.4.post2-cp27-cp27m-win_amd64.whl ; sys_platform=="win32"
\__Python wheels\Fiona-1.8.13-cp27-cp27m-win_amd64.whl ; sys_platform=="win32"
\__Python wheels\rasterio-1.1.2-cp27-cp27m-win_amd64.whl ; sys_platform=="win32"
\__Python wheels\Rtree-0.9.3-cp27-cp27m-win_amd64.whl ; sys_platform=="win32"
geopandas ; sys_platform=="win32"
osmnx==0.9
psycopg2
psycopg2
sqlalchemy
numpy
shapely
binascii
string
</code>```

I can create a python 2.7 environment in conda easily.

When I try to install geopandas 0.4.0 in that environment conda returns a list of incompatible specifications for example:

```<code>Package six conflicts for:
geopandas=0.4.0 -> six
geopandas=0.4.0 -> fiona -> six[version='>=1.7']
</code>```

If I try to install the current geopandas 0.7.0 I get a similar list of conflicts.

答:
I will suggest creating new conda env

```<code>To install this package with conda run one of the following:
conda install -c conda-forge geopandas
conda install -c conda-forge/label/dev geopandas
conda install -c conda-forge/label/gcc7 geopandas
conda install -c conda-forge/label/broken geopandas
conda install -c conda-forge/label/rc geopandas
conda install -c conda-forge/label/cf201901 geopandas
</code>```

Body:
My goal is to run a python script from about 2 years ago.

If someone could point me in the direction of an answer or issue that will help me work through the conflicts between packages to create a working environment for this old script it would be hugely appreciated.

It is written in python 2.

Dependencies are

psycopg2

and an internal module that imports

pandas
geopandas
psycopg2-binary
sqlalchemy
pyyaml
scikit-image
beautifultable
tqdm
statistics
rasterio ; sys_platform=="linux2"
geopandas ; sys_platform=="linux2"
\__Python wheels\pyproj-1.9.6-cp27-cp27m-win_amd64.whl ; sys_platform=="win32"
\__Python wheels\GDAL-2.2.4-cp27-cp27m-win_amd64.whl ; sys_platform=="win32"
\__Python wheels\Shapely-1.6.4.post2-cp27-cp27m-win_amd64.whl ; sys_platform=="win32"
\__Python wheels\Fiona-1.8.13-cp27-cp27m-win_amd64.whl ; sys_platform=="win32"
\__Python wheels\rasterio-1.1.2-cp27-cp27m-win_amd64.whl ; sys_platform=="win32"
\__Python wheels\Rtree-0.9.3-cp27-cp27m-win_amd64.whl ; sys_platform=="win32"
geopandas ; sys_platform=="win32"
osmnx==0.9
psycopg2
psycopg2
sqlalchemy
numpy
shapely
binascii
string

I can create a python 2.7 environment in conda easily.

When I try to install geopandas 0.4.0 in that environment conda returns a list of incompatible specifications for example:

Package six conflicts for:
geopandas=0.4.0 -> six
geopandas=0.4.0 -> fiona -> six[version='>=1.7']

If I try to install the current geopandas 0.7.0 I get a similar list of conflicts.

Body:
I will suggest creating new conda env

To install this package with conda run one of the following:
conda install -c conda-forge geopandas
conda install -c conda-forge/label/dev geopandas
conda install -c conda-forge/label/gcc7 geopandas
conda install -c conda-forge/label/broken geopandas
conda install -c conda-forge/label/rc geopandas
conda install -c conda-forge/label/cf201901 geopandas