问:
HA-JDBC Integration with Spring Boot JPA
I am trying to integrate HA-JDBC with Spring Boot JPA. Can any one help to integrate Ha-Jdbc with spring boot JPA,</p>

```<code>import java.util.Arrays;

import javax.naming.NamingException;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import net.sf.hajdbc.SimpleDatabaseClusterConfigurationFactory;
import net.sf.hajdbc.cache.simple.SimpleDatabaseMetaDataCacheFactory;
import net.sf.hajdbc.dialect.oracle.OracleDialectFactory;
import net.sf.hajdbc.distributed.jgroups.JGroupsCommandDispatcherFactory;
import net.sf.hajdbc.sql.DataSource;
import net.sf.hajdbc.sql.DataSourceDatabase;
import net.sf.hajdbc.sql.DataSourceDatabaseClusterConfiguration;
import net.sf.hajdbc.state.simple.SimpleStateManagerFactory;

@Configuration
public class HAJdbcConfig
{
    @Bean
    public DataSourceDatabase db1()
    {
        DataSourceDatabase db1 = new DataSourceDatabase();
        db1.setId("db1");
        db1.setLocation("database url");
        db1.setUser("username");
        db1.setPassword("password");
        return db1;
    }

    @Bean
    public DataSourceDatabase db2()
    {
        DataSourceDatabase db1 = new DataSourceDatabase();
        db1.setId("db1");
        db1.setLocation("database url");
        db1.setUser("username");
        db1.setPassword("password");
        return db1;
    }

    @Bean
    public DataSourceDatabaseClusterConfiguration config() throws NamingException
    {
        DataSourceDatabaseClusterConfiguration config = new DataSourceDatabaseClusterConfiguration();
        config.setDatabases(Arrays.asList(db1(), db2()));
        config.setDialectFactory(new OracleDialectFactory());
        config.setDatabaseMetaDataCacheFactory(new SimpleDatabaseMetaDataCacheFactory());
        SimpleStateManagerFactory state = new SimpleStateManagerFactory();
        config.setStateManagerFactory(state);
        config.setDispatcherFactory(new JGroupsCommandDispatcherFactory());
        return config;
    }

    @Bean
    public javax.sql.DataSource primaryDataSource() throws NamingException
    {
        DataSource ds = new DataSource();
        ds.setCluster("mycluster");
        //ds.setConfig("ha-jdbc-mycluster.xml");
        ds.setConfigurationFactory(
                new SimpleDatabaseClusterConfigurationFactory<javax.sql.DataSource, DataSourceDatabase>(config()));

        return ds;

    }

}
</code>```

```<code>Error retrieving database meta-data; nested exception is org.springframework.jdbc.support.MetaDataAccessException: Could not get Connection for extracting meta-data; nested exception is org.springframework.jdbc.CannotGetJdbcConnectionException: Failed to obtain JDBC Connection; nested exception is java.sql.SQLException: Failed to perform naming lookup of jdbc:oracle:thin:@//localhost:1521/orcl
</code>```

答: Can you use the service name for the database? The simple connection URL is jdbc:oracle:thin:@myhost:1521/myorcldbservicename. Also, you can check out the sample SpringBootApp for an example. </p>

Body:
I am trying to integrate HA-JDBC with Spring Boot JPA. Can any one help to integrate Ha-Jdbc with spring boot JPA,

import java.util.Arrays;

import javax.naming.NamingException;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import net.sf.hajdbc.SimpleDatabaseClusterConfigurationFactory;
import net.sf.hajdbc.cache.simple.SimpleDatabaseMetaDataCacheFactory;
import net.sf.hajdbc.dialect.oracle.OracleDialectFactory;
import net.sf.hajdbc.distributed.jgroups.JGroupsCommandDispatcherFactory;
import net.sf.hajdbc.sql.DataSource;
import net.sf.hajdbc.sql.DataSourceDatabase;
import net.sf.hajdbc.sql.DataSourceDatabaseClusterConfiguration;
import net.sf.hajdbc.state.simple.SimpleStateManagerFactory;

@Configuration
public class HAJdbcConfig
{
    @Bean
    public DataSourceDatabase db1()
    {
        DataSourceDatabase db1 = new DataSourceDatabase();
        db1.setId("db1");
        db1.setLocation("database url");
        db1.setUser("username");
        db1.setPassword("password");
        return db1;
    }

    @Bean
    public DataSourceDatabase db2()
    {
        DataSourceDatabase db1 = new DataSourceDatabase();
        db1.setId("db1");
        db1.setLocation("database url");
        db1.setUser("username");
        db1.setPassword("password");
        return db1;
    }

    @Bean
    public DataSourceDatabaseClusterConfiguration config() throws NamingException
    {
        DataSourceDatabaseClusterConfiguration config = new DataSourceDatabaseClusterConfiguration();
        config.setDatabases(Arrays.asList(db1(), db2()));
        config.setDialectFactory(new OracleDialectFactory());
        config.setDatabaseMetaDataCacheFactory(new SimpleDatabaseMetaDataCacheFactory());
        SimpleStateManagerFactory state = new SimpleStateManagerFactory();
        config.setStateManagerFactory(state);
        config.setDispatcherFactory(new JGroupsCommandDispatcherFactory());
        return config;
    }

    @Bean
    public javax.sql.DataSource primaryDataSource() throws NamingException
    {
        DataSource ds = new DataSource();
        ds.setCluster("mycluster");
        //ds.setConfig("ha-jdbc-mycluster.xml");
        ds.setConfigurationFactory(
                new SimpleDatabaseClusterConfigurationFactory<javax.sql.DataSource, DataSourceDatabase>(config()));

        return ds;

    }

}

Error retrieving database meta-data; nested exception is org.springframework.jdbc.support.MetaDataAccessException: Could not get Connection for extracting meta-data; nested exception is org.springframework.jdbc.CannotGetJdbcConnectionException: Failed to obtain JDBC Connection; nested exception is java.sql.SQLException: Failed to perform naming lookup of jdbc:oracle:thin:@//localhost:1521/orcl


来源: stackexchange

问:
plotting a number of specific lines in python
In my plot the x-axis contains dates, but i want to limit it so that they can start from a certain date and not consider the first years of my data
I have tried this:

```<code>plt.figure
f_linear=interp1d(datasurf.iloc[:,0],datasurf.iloc[:,1])
plt.plot(datasurf.iloc[:,0],datasurf.iloc[:,1], label='Surface level')
plt.xlim(pd.Timestamp('2016-01-01'), pd.Timestamp('2019-09-14'))
plt.xlabel('Date')
plt.ylabel('Lake level(m)')
plt.legend()
</code>```

but I have this error:
Failed to convert value(s) to axis units: Timestamp('2016-01-01 00:00:00')

Can someone suggest me something else please

答:
You need to adjust the inputs a little.
change:

```<code>plt.xlim(pd.Timestamp('2016-01-01'), pd.Timestamp('2019-09-14'))
</code>```

to

```<code>plt.xlim([pd.Timestamp('2016-01-01T12'), pd.Timestamp('2019-09-14T12')])
</code>```

as shown here

also you can use datetime

```<code>ax.set_xlim([datetime.date(2018, 1, 26), datetime.date(2018, 2, 1)])
</code>```

ContentLicense: CC BY-SA 4.0

Body:
In my plot the x-axis contains dates, but i want to limit it so that they can start from a certain date and not consider the first years of my data
I have tried this:

plt.figure
f_linear=interp1d(datasurf.iloc[:,0],datasurf.iloc[:,1])
plt.plot(datasurf.iloc[:,0],datasurf.iloc[:,1], label='Surface level')
plt.xlim(pd.Timestamp('2016-01-01'), pd.Timestamp('2019-09-14'))
plt.xlabel('Date')
plt.ylabel('Lake level(m)')
plt.legend()

but I have this error:
Failed to convert value(s) to axis units: Timestamp('2016-01-01 00:00:00')

Can someone suggest me something else please

Body:
You need to adjust the inputs a little.
change:

plt.xlim(pd.Timestamp('2016-01-01'), pd.Timestamp('2019-09-14'))

to

plt.xlim([pd.Timestamp('2016-01-01T12'), pd.Timestamp('2019-09-14T12')])

as shown here

also you can use datetime

ax.set_xlim([datetime.date(2018, 1, 26), datetime.date(2018, 2, 1)])


问:
Vuejs Option. Get an ID from a selected item
I'm actually using VueJS and encountered a little problem

I have a selector, that needs to memorize an ID to be sent in an axios request later. In the "selected" var, we need to keep only the name of the "type" for user friendly reasons. So, I need to get the ID selected by the user without displaying it. Actually, the code looks like this.

```<code><select v-model="selected">
 <label for="lg_type" class="sr-only">Type de personnage</label>
  <option disabled value="">Choisir un type</option>
  <option v-for="onetype in playertype" class="form-control" id="lg_type" name="lg_type" v-bind:key="onetype.idType">
      {{onetype.idType}}-{{ onetype.name }}
  </option>
</select>
</code>```

Selected is the actual name of the selected type. Since it's vue, when I click on another Type from my selector, it changes it automatically

onetype contains two things : A name, and an idType
playertype contains an array of all types

As we can see in the code, i display things like this "idType - name", but I only want to display "name" (so just erase onetype.idType), but I need to get the id to send it elswhere (I can't use onetype.idType to get the id to my axios method)

I don't know if it's clear enough, but I need to send the onetype.idType to an axios method, but I can't use it this way.

Thanks you in advance, this is driving me crazy and I feel I've missed something obvious ><

答:
Use value attribute and you will get it in v-model instead of displayed option:

```<code><select v-model="selected">
  <label for="lg_type" class="sr-only">Type de personnage</label>
  <option disabled value="">Choisir un type</option>
  <option
    v-for="onetype in playertype"
    :value="onetype.idType"
    class="form-control"
    id="lg_type"
    name="lg_type"
    v-bind:key="onetype.idType"
  >{{ onetype.idType }}-{{ onetype.name }}</option>
</select>
</code>```

Body:
I'm actually using VueJS and encountered a little problem

I have a selector, that needs to memorize an ID to be sent in an axios request later. In the "selected" var, we need to keep only the name of the "type" for user friendly reasons. So, I need to get the ID selected by the user without displaying it. Actually, the code looks like this.

<select v-model="selected">
 Type de personnage
  <option disabled value="">Choisir un type</option>
  <option v-for="onetype in playertype" class="form-control" id="lg_type" name="lg_type" v-bind:key="onetype.idType">
      {{onetype.idType}}-{{ onetype.name }}
  </option>
</select>

Selected is the actual name of the selected type. Since it's vue, when I click on another Type from my selector, it changes it automatically

onetype contains two things : A name, and an idType
playertype contains an array of all types

As we can see in the code, i display things like this "idType - name", but I only want to display "name" (so just erase onetype.idType), but I need to get the id to send it elswhere (I can't use onetype.idType to get the id to my axios method)

I don't know if it's clear enough, but I need to send the onetype.idType to an axios method, but I can't use it this way.

Thanks you in advance, this is driving me crazy and I feel I've missed something obvious ><

Body:
Use value attribute and you will get it in v-model instead of displayed option:

<select v-model="selected">
  <label for="lg_type" class="sr-only">Type de personnage</label>
  <option disabled value="">Choisir un type</option>
  <option
    v-for="onetype in playertype"
    :value="onetype.idType"
    class="form-control"
    id="lg_type"
    name="lg_type"
    v-bind:key="onetype.idType"
  >{{ onetype.idType }}-{{ onetype.name }}</option>
</select>


问:
sql, big query: aggregate all entries between two strings in a variable
I have to solve this problem within bigQuery. I have this column in my table:

```<code>event            | time
_________________|____________________
start            | 1
end              | 2
random_event_X   | 3
start            | 4
error_X          | 5
error_Y          | 6
end              | 7
start            | 8
error_F          | 9
start            | 10
random_event_Y   | 11
error_z          | 12
end              | 13
</code>```

I would like to, from the end event record everything until start appear and then count it. Everything can happen between start and end and outside of it. If there is an end, there is a start, but if there is a start, there is not necessarily an end.

The desire output would be like:

```<code>string_agg                            | count
"start, end"                          |  1
"start, error_X, error_Y, end"        |  1
"start, random_event_Y error_Z, end"  |  1
</code>```

So everything between each start and end if start has an end. So without the random_event_X at time 3, the start at time 8 or the error_F at time 9.

I was not able to find the solution and have struggle understanding how to approach this problem. Any help or advice is welcome.

答:
SQL tables represent unordered sets -- this is particularly true in massively parallel, columnar databases such as BigQuery.

So, I have to assume that you have some other column that specifies the ordering.  If so, you can use a cumulative sum to identify the groups and then aggregation:

```<code>select grp,
       string_agg(event, ',' order by time)
from (select t.*,
             countif(event = 'start') over (order by time) as grp
      from t
     ) t
group by grp
order by min(time);
</code>```

Note:  I would also advise you to use array_agg() instead of string_agg().  Arrays are generally easier to work with than strings.

EDIT:

I see, you only want up to end.  In that case, another level of window funtions:

```<code>select grp,
       string_agg(event, ',' order by <ordering col>)
from (select t.*,
             max(case when event = 'end' then time end) over (partition by grp) as max_end_time
      from (select t.*,
                   countif(event = 'start') over (order by <ordering col>) as grp
            from t
           ) t
     ) t
where max_end_time is null or time <= max_end_time
group by grp
order by min(<ordering col>);
</code>```

Body:
I have to solve this problem within bigQuery. I have this column in my table:

event            | time
_________________|____________________
start            | 1
end              | 2
random_event_X   | 3
start            | 4
error_X          | 5
error_Y          | 6
end              | 7
start            | 8
error_F          | 9
start            | 10
random_event_Y   | 11
error_z          | 12
end              | 13

I would like to, from the end event record everything until start appear and then count it. Everything can happen between start and end and outside of it. If there is an end, there is a start, but if there is a start, there is not necessarily an end.

The desire output would be like:

string_agg                            | count
"start, end"                          |  1
"start, error_X, error_Y, end"        |  1
"start, random_event_Y error_Z, end"  |  1

So everything between each start and end if start has an end. So without the random_event_X at time 3, the start at time 8 or the error_F at time 9.

I was not able to find the solution and have struggle understanding how to approach this problem. Any help or advice is welcome.

Body:
SQL tables represent unordered sets -- this is particularly true in massively parallel, columnar databases such as BigQuery.

So, I have to assume that you have some other column that specifies the ordering.  If so, you can use a cumulative sum to identify the groups and then aggregation:

select grp,
       string_agg(event, ',' order by time)
from (select t.*,
             countif(event = 'start') over (order by time) as grp
      from t
     ) t
group by grp
order by min(time);

Note:  I would also advise you to use array_agg() instead of string_agg().  Arrays are generally easier to work with than strings.

EDIT:

I see, you only want up to end.  In that case, another level of window funtions:

select grp,
       string_agg(event, ',' order by <ordering col>)
from (select t.*,
             max(case when event = 'end' then time end) over (partition by grp) as max_end_time
      from (select t.*,
                   countif(event = 'start') over (order by <ordering col>) as grp
            from t
           ) t
     ) t
where max_end_time is null or time <= max_end_time
group by grp
order by min(<ordering col>);


问:
Groupby upon multiple columns, then append
i am trying to count the number of occurrences of the same packet in my dataframe, a packet is the same if it has these matching fields:

```<code>['SourceIP', 'SourcePort', 'DestinationIP', 'DestinationPort', 'Protocol']
</code>```

I want to make a new column in my dataframe with the occurrence values and have this column be called 'PerSec'

I have tried to implement the solution to this problem found here Pandas create new column with count from groupby

However when I run:

```<code>df['PerSec'] = df.groupby(['SourceIP', 'SourcePort', 'DestinationIP', 'DestinationPort', 'Protocol']['SourceIP', 'SourcePort', 'DestinationIP', 'DestinationPort', 'Protocol'].transform('PerSec'))
with pd.option_context('display.max_rows', None, 'display.max_columns', None):
    print(df)
</code>```

I receive this error:

TypeError: list indices must be integers or slices, not tuple

Does this mean the groupby method will only work upon one column?

答:
Add only one column after groupby and pass to groupby some aggregate function, e.g. GroupBy.count:

```<code>cols = ['SourceIP', 'SourcePort', 'DestinationIP', 'DestinationPort', 'Protocol']
df['PerSec'] = df.groupby(cols)['SourceIP'].transform('count')
</code>```

Body:
i am trying to count the number of occurrences of the same packet in my dataframe, a packet is the same if it has these matching fields:

['SourceIP', 'SourcePort', 'DestinationIP', 'DestinationPort', 'Protocol']

I want to make a new column in my dataframe with the occurrence values and have this column be called 'PerSec'

I have tried to implement the solution to this problem found here Pandas create new column with count from groupby

However when I run:

df['PerSec'] = df.groupby(['SourceIP', 'SourcePort', 'DestinationIP', 'DestinationPort', 'Protocol']['SourceIP', 'SourcePort', 'DestinationIP', 'DestinationPort', 'Protocol'].transform('PerSec'))
with pd.option_context('display.max_rows', None, 'display.max_columns', None):
    print(df)

I receive this error:

TypeError: list indices must be integers or slices, not tuple

Does this mean the groupby method will only work upon one column?

Body:
Add only one column after groupby and pass to groupby some aggregate function, e.g. GroupBy.count:

cols = ['SourceIP', 'SourcePort', 'DestinationIP', 'DestinationPort', 'Protocol']
df['PerSec'] = df.groupby(cols)['SourceIP'].transform('count')


问:
Take 2 variables from a list search in another list
I am working with GeoNames dump file and would like to make a script working. It should:
1) take a row from first txt file, e.g.

Jalalabad, AF

2) Take "Jalalabad" as var1 and "AF" as var2 and use it in search in another txt file which has a line for example:

7053281 Jalālābād   Jalalabad   Bihsud,Jalalabad,Jalālābād,bhswd,jlal abad,بهسود,جلال آباد  34.42189    70.46353    A   ADM2    AF      18  801         0       571 Asia/Kabul  2018-02-13

If found in the 2nd list, I would like to copy whole row (example above) to third file, also in txt. This is my script:

```<code>myfile ='Geo.txt'
myfile2 = 'allADM.txt'

myfile3 = open('GeoSearch.txt','w',encoding="utf-8")

mylist = []
mylist2 = []

with open(myfile,'r',encoding='utf-8') as myfile:
    for row in myfile:
        row = row.split(", ")
        var1, var2 = row
        mylist.append(row)

with open(myfile2,'r',encoding='utf-8') as myfile2:
    for row in myfile2:
        row = row.strip()
        mylist2.append(row)

for i in mylist:
    if i[0] in mylist2.row and i[1] in mylist2.row:
            myfile3.write(f"{mylist2.row}\n")
    else:
        pass
</code>```

I get the error:
Traceback (most recent call last):
  File "C:/Users/xxx/Documents/python work/GeoNameSearch.py", line 24, in
    if i[0] in mylist2.row and i[1] in mylist2.row:
AttributeError: 'list' object has no attribute 'row'

myfile ='Geo.txt' - all the things I want to query

myfile2 = 'allADM.txt' - A massive dump file I want to search in

myfile 3 = output file

Any help appreciated!

EDIT1:
Changed the last part:

```<code>for i in mylist2:
    if var1 in i and var2 in i:
            myfile3.write(f"{i}\n")
    else:
        pass
</code>```

which resulted in that I got the last result from my search file (12.5k lines). Seems the variables var1 and var2 kept resetting so that it only searched it once.

EDIT2, second script (suggested below + tweaks) also returns empty list:

```<code>with open('Geo.txt', 'r', encoding='utf-8') as queries:
    search_data = set(queries.readlines())

with open('12.txt', 'r', encoding='utf-8') as dataset:
    data = dataset.readlines()

matching_lines = []

for params in search_data:
    param1, param2 = params.split(', ')

for line in data:
    if param1 in line and param2 in line:
        matching_lines.append(line)

with open('GeoSearch.txt', 'w', encoding='utf-8') as result:
    for res in matching_lines:
        result.write(f'{param1}|{param2}|{res}\n')
</code>```

答:
Instead of using for loop you can use readlines()

```<code>with open(myfile, 'r', encoding='utf-8') as myfile:
    mylist = myfile.readlines()

# Do same opration with the second one
with open(myfile2, 'r', encoding='utf-8') as myfile2:
    mylist2 = myfile2.readlines()
</code>```

Now i contains single string, So you can easily compare the two.

```<code>for i in mylist:
    if i in mylist2 and i in mylist2:
        myfile3.write(f"{i}\n")
    else:
        pass
</code>```

It much simplify your work.

Body:
I am working with GeoNames dump file and would like to make a script working. It should:
1) take a row from first txt file, e.g.

Jalalabad, AF

2) Take "Jalalabad" as var1 and "AF" as var2 and use it in search in another txt file which has a line for example:

7053281 Jalālābād   Jalalabad   Bihsud,Jalalabad,Jalālābād,bhswd,jlal abad,بهسود,جلال آباد  34.42189    70.46353    A   ADM2    AF      18  801         0       571 Asia/Kabul  2018-02-13

If found in the 2nd list, I would like to copy whole row (example above) to third file, also in txt. This is my script:

myfile ='Geo.txt'
myfile2 = 'allADM.txt'

myfile3 = open('GeoSearch.txt','w',encoding="utf-8")

mylist = []
mylist2 = []

with open(myfile,'r',encoding='utf-8') as myfile:
    for row in myfile:
        row = row.split(", ")
        var1, var2 = row
        mylist.append(row)

with open(myfile2,'r',encoding='utf-8') as myfile2:
    for row in myfile2:
        row = row.strip()
        mylist2.append(row)

for i in mylist:
    if i[0] in mylist2.row and i[1] in mylist2.row:
            myfile3.write(f"{mylist2.row}\n")
    else:
        pass

I get the error:
Traceback (most recent call last):
  File "C:/Users/xxx/Documents/python work/GeoNameSearch.py", line 24, in
    if i[0] in mylist2.row and i[1] in mylist2.row:
AttributeError: 'list' object has no attribute 'row'

myfile ='Geo.txt' - all the things I want to query

myfile2 = 'allADM.txt' - A massive dump file I want to search in

myfile 3 = output file

Any help appreciated!

EDIT1:
Changed the last part:

for i in mylist2:
    if var1 in i and var2 in i:
            myfile3.write(f"{i}\n")
    else:
        pass

which resulted in that I got the last result from my search file (12.5k lines). Seems the variables var1 and var2 kept resetting so that it only searched it once.

EDIT2, second script (suggested below + tweaks) also returns empty list:

with open('Geo.txt', 'r', encoding='utf-8') as queries:
    search_data = set(queries.readlines())

with open('12.txt', 'r', encoding='utf-8') as dataset:
    data = dataset.readlines()

matching_lines = []

for params in search_data:
    param1, param2 = params.split(', ')

for line in data:
    if param1 in line and param2 in line:
        matching_lines.append(line)

with open('GeoSearch.txt', 'w', encoding='utf-8') as result:
    for res in matching_lines:
        result.write(f'{param1}|{param2}|{res}\n')

Body:
Instead of using for loop you can use readlines()

with open(myfile, 'r', encoding='utf-8') as myfile:
    mylist = myfile.readlines()

# Do same opration with the second one
with open(myfile2, 'r', encoding='utf-8') as myfile2:
    mylist2 = myfile2.readlines()

Now i contains single string, So you can easily compare the two.

for i in mylist:
    if i in mylist2 and i in mylist2:
        myfile3.write(f"{i}\n")
    else:
        pass

It much simplify your work.


问:
How to change label on input focus when input comes after label?
```<code><div id="my-field">
    <label class="my-label">Label</label>
    <input class="my-input" value="input" />
</div>
</code>```

```<code>#my-field{
}
.my-label {
}
.my-input{
}
</code>```

Is there any way I can customize the CSS of .my-label when input is in focus without touching the HTML? There are multiple ways to select successor sibling elements. But any way to select predecessor(s)?

Note: There is a restriction in the project that HTML cannot be modified here. Everything has to be done in CSS only. No jQuery/JS either.

答:
In this case (since the input doesn't have any other siblings), you can use the sibling CSS selector ~.</p>

```<code>input:focus ~ label {...}
</code>```

Body:
    Label
    <input class="my-input" value="input" />

#my-field{
}
.my-label {
}
.my-input{
}

Is there any way I can customize the CSS of .my-label when input is in focus without touching the HTML? There are multiple ways to select successor sibling elements. But any way to select predecessor(s)?

Note: There is a restriction in the project that HTML cannot be modified here. Everything has to be done in CSS only. No jQuery/JS either.

Body:
In this case (since the input doesn't have any other siblings), you can use the sibling CSS selector ~.

input:focus ~ label {...}


问:
MySQL JOIN: Only return rows where all values from right table are NULL
I have two MySQL tables like this:

```<code>orders:
+----------+------+
| order_id | name |
+----------+------+
| 1        | Mary |
| 2        | John |
| 3        | Anne |
+----------+------+

order_details:
+----------+----------------+
| order_id | shipped        |
+----------+----------------+
| 1        | null           |
| 1        | null           |
| 1        | SHIPPED-123ABC |
| 2        | null           |
| 2        | null           |
| 3        | SHIPPED-XYZ    |
| 3        | SHIPPED-XYZ    |
| 3        | null           |
+----------+----------------+
</code>```

Now I want to join the order_details-table to the orders-table but only show the entries that only  have NULL shipped values in the order_details table. So in this example only order_id #2 would get returned.

So the result would be:

```<code>+----------+------+---------+
| order_id | name | shipped |
+----------+------+---------+
| 2        | John | null    |
+----------+------+---------+
</code>```

Thank you!

答:
Check whether below query gives what you want.</p>

```<code>SELECT
  o.order_id,
  o.name,
  od.shipped
FROM
  orders o
  INNER JOIN order_details od ON od.order_id = o.order_id
WHERE
  od.shipped IS NULL
  AND od.shipped NOT IN
(
SELECT od.shipped
WHERE
    od.shipped IS NOT NULL
     )
</code>```

Body:
I have two MySQL tables like this:

orders:
+----------+------+
| order_id | name |
+----------+------+
| 1        | Mary |
| 2        | John |
| 3        | Anne |
+----------+------+

order_details:
+----------+----------------+
| order_id | shipped        |
+----------+----------------+
| 1        | null           |
| 1        | null           |
| 1        | SHIPPED-123ABC |
| 2        | null           |
| 2        | null           |
| 3        | SHIPPED-XYZ    |
| 3        | SHIPPED-XYZ    |
| 3        | null           |
+----------+----------------+

Now I want to join the order_details-table to the orders-table but only show the entries that only  have NULL shipped values in the order_details table. So in this example only order_id #2 would get returned.

So the result would be:

+----------+------+---------+
| order_id | name | shipped |
+----------+------+---------+
| 2        | John | null    |
+----------+------+---------+

Thank you!

Body:
Check whether below query gives what you want.

SELECT
  o.order_id,
  o.name,
  od.shipped
FROM
  orders o
  INNER JOIN order_details od ON od.order_id = o.order_id
WHERE
  od.shipped IS NULL
  AND od.shipped NOT IN
(
SELECT od.shipped
WHERE
    od.shipped IS NOT NULL
     )


答:
Put id_test, (quantity * price) & fee in a temporary table.

```<code>WITH cte1 AS (
SELECT
    id_test,
    (quantity * price) AS total,
    fee
FROM
table
)
</code>```

Now add the total for every id

```<code>WITH cte2 AS (
SELECT SUM(total) + fee AS total_id
 FROM cte1
 GROUP BY id_test
)
</code>```

Now find the total sum

```<code> SELECT SUM(total_id) AS SUM
 FROM cte1
</code>```

Title: SQL Query SUM with conditions

Body:
I'm having some difficulties finding the good query I need, looking for help.
After multiple JOIN and a lot of WHERE, I have this columns and values :

+---------+----------+--------+-------+
| id_test | quantity | price  |  fee  |
+---------+----------+--------+-------+
| "1-3"   |        1 | 33.52  | 29.00 |
| "1-5"   |        1 | 33.52  | 29.00 |
| "1-6"   |        1 | 33.52  | 29.00 |
| "1-8"   |        1 | 86.49  | 29.00 |
| "19-1"  |        1 | 176.54 | 29.00 |
| "19-4"  |        1 | 176.54 | 29.00 |
| "19-5"  |        4 | 176.54 | 29.00 |
| "19-6"  |        1 | 199.47 | 29.00 |
| "19-6"  |        1 | 176.54 | 29.00 |
| "20-10" |        2 | 72.67  | 29.00 |
| "20-11" |        2 | 18.95  | 29.00 |
| "20-9"  |        1 | 22.13  | 29.00 |
+---------+----------+--------+-------+

Each id_test object as a quantity, a price and a fee. I would like to SUM everything so to have a global price : (quantity*price)+fee
The thing is, and that's where I'm stuck, the fee has to be added only once by id_test. Yet, I have here two id_test "19-6".

If I SUM everything I have 1827.67 (price*quantity) + 348 (fee).

Since I have two "19-6", I need 1827.67 (price*quantity) + 319 (fee).

How would you do in SQL ?

Thanks

Body:
Put id_test, (quantity * price) & fee in a temporary table.

WITH cte1 AS (
SELECT
    id_test,
    (quantity * price) AS total,
    fee
FROM
table
)

Now add the total for every id

WITH cte2 AS (
SELECT SUM(total) + fee AS total_id
 FROM cte1
 GROUP BY id_test
)

Now find the total sum

 SELECT SUM(total_id) AS SUM
 FROM cte1


问:
Ansible - Environment variables setting
I need to set the environment in the target machine. The environment variables are present in the file called .env337. There are several variables inside that file like

```<code>export AB_HOME=/tl/dev/abinitio/abinitio-V3  #/gcc3p32   # for 32-bit
export PATH=${AB_HOME}/bin:${PATH}
</code>```

I have tried the below playbook to set the environment and register the environment variables in order to use them in the environment keyword to run the other commands in the registered environment, but it didn't worked.

```<code>- hosts: dev
  gather_facts: false
  tasks:
    - name: To set the environment
      shell: . ./.env337
      register: output
</code>```

Is there any other way to resolve this.

答:
Q: "Set the environment and register the environment variables in order to use them in the environment keyword to run the other commands."

A: The environment variables set in the shell command can not be persistent. The shell process will be terminated after the execution of the command(s). For example

```<code>    - shell: |
        cat ./.env337
        . ./.env337
        echo "AB_HOME = $AB_HOME"
        echo "PATH = $PATH"
        exit 0
      register: result

    - debug:
        var: result.stdout_lines

    - shell: |
        echo "AB_HOME = $AB_HOME"
        echo "PATH = $PATH"
        exit 0
      register: result

    - debug:
        var: result.stdout_lines
</code>```

give

```<code>    "result.stdout_lines": [
        "export AB_HOME=/tl/dev/abinitio/abinitio-V3  #/gcc3p32   # for 32-bit",
        "export PATH=${AB_HOME}/bin:${PATH}",
        "",
        "AB_HOME = /tl/dev/abinitio/abinitio-V3",
        "PATH = /tl/dev/abinitio/abinitio-V3/bin:/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin:/home/admin/bin"
    ]

    "result.stdout_lines": [
        "AB_HOME = ",
        "PATH = /sbin:/bin:/usr/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin:/home/admin/bin"
    ]
</code>```

As expected the variables are missing in the second shell task.

Q: "what if I don't know what are all the variables present inside the env file. Is there any other way to print all variables instead of using echo."

A: Short answer: Create a dictionary env_dict_add with the environment variables. Use it in the shell module to create the environment environment: "{{ env_dict_add }}".

Details

1) Create a list of unknown variables. For example

```<code>    - shell: cat ./.env337
      register: result
    - set_fact:
        env_list: "{{ env_list|default([]) +
                      [item.split('=').0.split(' ').1|trim] }}"
      loop: "{{ result.stdout_lines }}"
    - debug:
        var: env_list
</code>```

gives

```<code>    "env_list": [
        "AB_HOME",
        "PATH"
    ]
</code>```

2) Create a dictionary with the environment. For example

```<code>    - shell: |
        . ./.env337
        set
      register: result
    - set_fact:
        env_dict: "{{ env_dict|default({})|
                      combine({my_key: my_value}) }}"
      vars:
        my_key: "{{ item.split('=').0 }}"
        my_value: "{{ item.split('=').1|default('') }}"
      loop: "{{ result.stdout_lines }}"
</code>```

3) Use any environment variable from the dictionary. For example, print whatever variables have been exported by sourcing the file .env337

```<code>    - debug:
        msg: "var: {{ item }} value: {{ env_dict[item] }}"
      loop: "{{ env_list }}"
</code>```

gives

```<code>    "msg": "var: AB_HOME value: /tl/dev/abinitio/abinitio-V3"

    "msg": "var: PATH value: /tl/dev/abinitio/abinitio-V3/bin:/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin:/home/admin/bin"
</code>```

4) Create a dictionary with the additional environment variables only. For example

```<code>    - set_fact:
        env_dict_add: "{{ env_dict_add|default({})|
                          combine({item: env_dict[item]}) }}"
      loop: "{{ env_list }}"
    - debug:
        var: env_dict_add
</code>```

gives

```<code>    "env_dict_add": {
        "AB_HOME": "/tl/dev/abinitio/abinitio-V3",
        "PATH": "/tl/dev/abinitio/abinitio-V3/bin:/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin:/home/admin/bin"
    }
</code>```

5) Use the dictionary env_dict_add to create environment variables in the shell command. For example

```<code>    - shell: echo ${{ item }}
      loop: "{{ env_list }}"
      register: result
      environment: "{{ env_dict_add }}"
    - debug:
        msg: "{{ dict(result.results|json_query('[].[item, stdout]')) }}"
</code>```

give

```<code>    "msg": {
        "AB_HOME": "/tl/dev/abinitio/abinitio-V3",
        "PATH": "/tl/dev/abinitio/abinitio-V3/bin:/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin:/home/admin/bin"
    }
</code>```

Title: Ansible - Environment variables setting

Body:
I need to set the environment in the target machine. The environment variables are present in the file called .env337. There are several variables inside that file like

export AB_HOME=/tl/dev/abinitio/abinitio-V3  #/gcc3p32   # for 32-bit
export PATH=${AB_HOME}/bin:${PATH}

I have tried the below playbook to set the environment and register the environment variables in order to use them in the environment keyword to run the other commands in the registered environment, but it didn't worked.

- hosts: dev
  gather_facts: false
  tasks:
    - name: To set the environment
      shell: . ./.env337
      register: output

Is there any other way to resolve this.

Body:
Q: "Set the environment and register the environment variables in order to use them in the environment keyword to run the other commands."

A: The environment variables set in the shell command can not be persistent. The shell process will be terminated after the execution of the command(s). For example

    - shell: |
        cat ./.env337
        . ./.env337
        echo "AB_HOME = $AB_HOME"
        echo "PATH = $PATH"
        exit 0
      register: result

    - debug:
        var: result.stdout_lines

    - shell: |
        echo "AB_HOME = $AB_HOME"
        echo "PATH = $PATH"
        exit 0
      register: result

    - debug:
        var: result.stdout_lines

give

    "result.stdout_lines": [
        "export AB_HOME=/tl/dev/abinitio/abinitio-V3  #/gcc3p32   # for 32-bit",
        "export PATH=${AB_HOME}/bin:${PATH}",
        "",
        "AB_HOME = /tl/dev/abinitio/abinitio-V3",
        "PATH = /tl/dev/abinitio/abinitio-V3/bin:/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin:/home/admin/bin"
    ]

    "result.stdout_lines": [
        "AB_HOME = ",
        "PATH = /sbin:/bin:/usr/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin:/home/admin/bin"
    ]

As expected the variables are missing in the second shell task.

Q: "what if I don't know what are all the variables present inside the env file. Is there any other way to print all variables instead of using echo."

A: Short answer: Create a dictionary env_dict_add with the environment variables. Use it in the shell module to create the environment environment: "{{ env_dict_add }}".

Details

1) Create a list of unknown variables. For example

    - shell: cat ./.env337
      register: result
    - set_fact:
        env_list: "{{ env_list|default([]) +
                      [item.split('=').0.split(' ').1|trim] }}"
      loop: "{{ result.stdout_lines }}"
    - debug:
        var: env_list

gives

    "env_list": [
        "AB_HOME",
        "PATH"
    ]

2) Create a dictionary with the environment. For example

    - shell: |
        . ./.env337
        set
      register: result
    - set_fact:
        env_dict: "{{ env_dict|default({})|
                      combine({my_key: my_value}) }}"
      vars:
        my_key: "{{ item.split('=').0 }}"
        my_value: "{{ item.split('=').1|default('') }}"
      loop: "{{ result.stdout_lines }}"

3) Use any environment variable from the dictionary. For example, print whatever variables have been exported by sourcing the file .env337

    - debug:
        msg: "var: {{ item }} value: {{ env_dict[item] }}"
      loop: "{{ env_list }}"

gives

    "msg": "var: AB_HOME value: /tl/dev/abinitio/abinitio-V3"

    "msg": "var: PATH value: /tl/dev/abinitio/abinitio-V3/bin:/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin:/home/admin/bin"

4) Create a dictionary with the additional environment variables only. For example

    - set_fact:
        env_dict_add: "{{ env_dict_add|default({})|
                          combine({item: env_dict[item]}) }}"
      loop: "{{ env_list }}"
    - debug:
        var: env_dict_add

gives

    "env_dict_add": {
        "AB_HOME": "/tl/dev/abinitio/abinitio-V3",
        "PATH": "/tl/dev/abinitio/abinitio-V3/bin:/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin:/home/admin/bin"
    }

5) Use the dictionary env_dict_add to create environment variables in the shell command. For example

    - shell: echo ${{ item }}
      loop: "{{ env_list }}"
      register: result
      environment: "{{ env_dict_add }}"
    - debug:
        msg: "{{ dict(result.results|json_query('[].[item, stdout]')) }}"

give

    "msg": {
        "AB_HOME": "/tl/dev/abinitio/abinitio-V3",
        "PATH": "/tl/dev/abinitio/abinitio-V3/bin:/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin:/home/admin/bin"
    }


问:
Provide exceptions for wcf webhttpbinding
I have to change a binding for wcf webservices from tcpbinding to webhttpbinding with basic authentication and ssl.

Webservices are self hosted in a console application and in a windows service for production version. Some of local services are with named pipe binding, just if a service call another service.

All works perfectly but not the global error manager (a class that implement IErrorHandler interface)

Some of DAL or business methods throw an exception with a custom message and this message was correctly provide to client (unit test for a while). But since I change binding, exceptions caught in unit test are always a 500 error, internal server error and custom messages are not  in exception object.

Server code :

```<code>// Création de l'URI
var baseAddress = new Uri($"https://localhost/blablabla/{typeof(TBusiness).Name}");

// Création du Host avec le type de la classe Business
var host = new ServiceHost(typeof(TBusiness), baseAddress);

// Liaison WebHttpBinding sécurité transport
var binding = new WebHttpBinding
{
   MaxBufferSize = 2147483647,
   MaxReceivedMessageSize = 2147483647,
   Security = new WebHttpSecurity
   {
       Mode = WebHttpSecurityMode.Transport
   },
};

binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;

// Permet de renvoyer du xml et du json
var webBehavior = new WebHttpBehavior
{
   AutomaticFormatSelectionEnabled = true
};

var ep = host.AddServiceEndpoint(typeof(TContracts), binding, "");
ep.Behaviors.Add(webBehavior);

var sdb = host.Description.Behaviors.Find<ServiceDebugBehavior>();
sdb.HttpHelpPageEnabled = false;

// Activation https
var smb = new ServiceMetadataBehavior
{
   HttpGetEnabled = false,
   HttpsGetEnabled = true,
};

host.Description.Behaviors.Add(smb);

// Ajout de l'authentification
var customAuthenticationBehavior = new ServiceCredentials();
customAuthenticationBehavior.UserNameAuthentication.UserNamePasswordValidationMode = UserNamePasswordValidationMode.Custom;
customAuthenticationBehavior.UserNameAuthentication.CustomUserNamePasswordValidator = new SessionAuthentication();
host.Description.Behaviors.Add(customAuthenticationBehavior);

// Démarrage du host
host.Open();
</code>```

Business method that throw exception :

```<code>public TOUser GetUserByLogin(string login)
{
  using (var service = new ServiceProviderNamedPipe<IBFSessionManager, BSSessionManager>())
  {
     // Récupération de la DALUsers
     var dal = service.Channel.GetDALUsers(OperationContext.Current.ServiceSecurityContext.PrimaryIdentity.Name);
     var user = dal.GetUserByLogin(login);

     if (user == null) throw new FaultException(Errors.DALUsers_Err001);

     return BMToolsEntitiesToTO.UserToTOUser(user);
   }
}
</code>```

Error global manager :

```<code>public class GlobalErrorHandler : IErrorHandler
{
    public bool HandleError(Exception error)
    {
        // Empèche la propagation de l'erreur
        return true;
    }

    public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
    {
        var msg = error.Message;

        // Création de l'exception de retour
        var newEx = new FaultException(msg);
        var msgFault = newEx.CreateMessageFault();
        fault = Message.CreateMessage(version, msgFault, newEx.Action);
    }
}
</code>```

Unit test :

```<code>public void GetUserByLoginWithUnknownLoginTest()
{
    TOUser user = null;
    using (var service = new ServiceProviderHTTP<IBFUsers, BSUsers>(_user))
    {
        try
        {
            user = service.Channel.GetUserByLogin("1234");
        }
        catch (Exception e)
        {
            // e.message always provide "Internal server error instead of custom message (Errors.DALUsers_Err001)
            Assert.AreEqual(Errors.DALUsers_Err001, e.Message);
        }

        Assert.IsNull(user);
    }
}
</code>```

All unit tests that catch exception failed since I change binding.

Thank you for your help.

答:
After several search, I saw that a lot of people have same problem.

Here is my solution :

On server side, always throw a WebFaultException like this with correct HTTP Status code :

```<code>throw new WebFaultException<string>(myStringMessage, HttpStatusCode.NotFound);
</code>```

On client side (only for unit tests or MVC project), cast exception to call GetResponseStream on Response object to get custom message :

```<code>var err = (WebException)e;
using (Stream respStream = err.Response.GetResponseStream())
{
    using (var reader = new StreamReader(respStream))
    {
        var serializer = new XmlSerializer(typeof(string));
        var response = reader.ReadToEnd();
        return response.Substring(response.IndexOf('>') + 1).Replace("</string>", "");
    }
}
</code>```

In ProvideFault method from IErrorHandler, I just add code to write errors in a file but not create a message with Message.CreateMessage method.

It works correctly but generate an EndPointNotFoundException after ProvideFault, in some other posts I saw that a ProtocolException could be thrown.

Thank you for your remarks.

Body:
I have to change a binding for wcf webservices from tcpbinding to webhttpbinding with basic authentication and ssl.

Webservices are self hosted in a console application and in a windows service for production version. Some of local services are with named pipe binding, just if a service call another service.

All works perfectly but not the global error manager (a class that implement IErrorHandler interface)

Some of DAL or business methods throw an exception with a custom message and this message was correctly provide to client (unit test for a while). But since I change binding, exceptions caught in unit test are always a 500 error, internal server error and custom messages are not  in exception object.

Server code :

// Création de l'URI
var baseAddress = new Uri($"https://localhost/blablabla/{typeof(TBusiness).Name}");

// Création du Host avec le type de la classe Business
var host = new ServiceHost(typeof(TBusiness), baseAddress);

// Liaison WebHttpBinding sécurité transport
var binding = new WebHttpBinding
{
   MaxBufferSize = 2147483647,
   MaxReceivedMessageSize = 2147483647,
   Security = new WebHttpSecurity
   {
       Mode = WebHttpSecurityMode.Transport
   },
};

binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;

// Permet de renvoyer du xml et du json
var webBehavior = new WebHttpBehavior
{
   AutomaticFormatSelectionEnabled = true
};

var ep = host.AddServiceEndpoint(typeof(TContracts), binding, "");
ep.Behaviors.Add(webBehavior);

var sdb = host.Description.Behaviors.Find<ServiceDebugBehavior>();
sdb.HttpHelpPageEnabled = false;

// Activation https
var smb = new ServiceMetadataBehavior
{
   HttpGetEnabled = false,
   HttpsGetEnabled = true,
};

host.Description.Behaviors.Add(smb);

// Ajout de l'authentification
var customAuthenticationBehavior = new ServiceCredentials();
customAuthenticationBehavior.UserNameAuthentication.UserNamePasswordValidationMode = UserNamePasswordValidationMode.Custom;
customAuthenticationBehavior.UserNameAuthentication.CustomUserNamePasswordValidator = new SessionAuthentication();
host.Description.Behaviors.Add(customAuthenticationBehavior);

// Démarrage du host
host.Open();

Business method that throw exception :

public TOUser GetUserByLogin(string login)
{
  using (var service = new ServiceProviderNamedPipe<IBFSessionManager, BSSessionManager>())
  {
     // Récupération de la DALUsers
     var dal = service.Channel.GetDALUsers(OperationContext.Current.ServiceSecurityContext.PrimaryIdentity.Name);
     var user = dal.GetUserByLogin(login);

     if (user == null) throw new FaultException(Errors.DALUsers_Err001);

     return BMToolsEntitiesToTO.UserToTOUser(user);
   }
}

Error global manager :

public class GlobalErrorHandler : IErrorHandler
{
    public bool HandleError(Exception error)
    {
        // Empèche la propagation de l'erreur
        return true;
    }

    public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
    {
        var msg = error.Message;

        // Création de l'exception de retour
        var newEx = new FaultException(msg);
        var msgFault = newEx.CreateMessageFault();
        fault = Message.CreateMessage(version, msgFault, newEx.Action);
    }
}

Unit test :

public void GetUserByLoginWithUnknownLoginTest()
{
    TOUser user = null;
    using (var service = new ServiceProviderHTTP<IBFUsers, BSUsers>(_user))
    {
        try
        {
            user = service.Channel.GetUserByLogin("1234");
        }
        catch (Exception e)
        {
            // e.message always provide "Internal server error instead of custom message (Errors.DALUsers_Err001)
            Assert.AreEqual(Errors.DALUsers_Err001, e.Message);
        }

        Assert.IsNull(user);
    }
}

All unit tests that catch exception failed since I change binding.

Thank you for your help.

Body:
After several search, I saw that a lot of people have same problem.

Here is my solution :

On server side, always throw a WebFaultException like this with correct HTTP Status code :

throw new WebFaultException<string>(myStringMessage, HttpStatusCode.NotFound);

On client side (only for unit tests or MVC project), cast exception to call GetResponseStream on Response object to get custom message :

var err = (WebException)e;
using (Stream respStream = err.Response.GetResponseStream())
{
    using (var reader = new StreamReader(respStream))
    {
        var serializer = new XmlSerializer(typeof(string));
        var response = reader.ReadToEnd();
        return response.Substring(response.IndexOf('>') + 1).Replace("</string>", "");
    }
}

In ProvideFault method from IErrorHandler, I just add code to write errors in a file but not create a message with Message.CreateMessage method.

It works correctly but generate an EndPointNotFoundException after ProvideFault, in some other posts I saw that a ProtocolException could be thrown.

Thank you for your remarks.


问:
Find and replace with regex by defining beginning and end of string
How would I replace in PhpStorm (it is not important I guess) all occurrences of (selecting string which starts with {!! and ends with !!}):

{!! $arr['my.key.1234'] !!}
to {!! $arr('my.key.1234') !!}
(note change in braces)

I tried to select the key with this regex:
\{\!\! \$arr\[.*.] !!}  which works but how do I now replace it?

EDIT:

I only want to select array key which is variable so my regex doesn't work - it selects whole line.

答:
In PhpStorm, open the replace dialogue and make sure you've checked the Regex checkbox.

For your find, you can use:

```<code>(\{!!\s*\$\w+)\[('[\w\.]+')\](\s*!!\})
</code>```

This captures the 3 parts you want to keep. You then replace the brackets and use $1, $2 and $3 to insert your original content around the new brackets.

```<code>$1($2)$3
</code>```

Screenshot of how to do this:

Body:
In PhpStorm, open the replace dialogue and make sure you've checked the Regex checkbox.

For your find, you can use:

(\{!!\s*\$\w+)\[('[\w\.]+')\](\s*!!\})

This captures the 3 parts you want to keep. You then replace the brackets and use $1, $2 and $3 to insert your original content around the new brackets.

$1($2)$3

Screenshot of how to do this:


问:
Python - Fetching data from API
I have the below code that fetches data from a API. This works fine, however I see that it only returns back 25 rows. I am trying to see how could I extract all of the data from the API call and not limit to 25</p>

```<code>import requests
import pandas as pd

API_KEY = API_KEY

url = 'https://api.pagerduty.com/incidents/'
headers = {
    'Accept': 'application/vnd.pagerduty+json;version=2',
    'Authorization': 'Token token={token}'.format(token=API_KEY)}
r = requests.get(url, headers=headers)
data = r.content
data_dict = json.loads(data)
data_df = pd.DataFrame(data_dict['incidents'])
</code>```

答:
That is due to pagination in the API response. The call defaults to return 25 incidents. If you pass a limit parameter, you can get more, but only up to 100. If you loop until more is false and increment the offset each call you can get all the incidents.

See here API Reference for limit

Title: Python - Fetching data from API

Body:
I have the below code that fetches data from a API. This works fine, however I see that it only returns back 25 rows. I am trying to see how could I extract all of the data from the API call and not limit to 25

import requests
import pandas as pd

API_KEY = API_KEY

url = 'https://api.pagerduty.com/incidents/'
headers = {
    'Accept': 'application/vnd.pagerduty+json;version=2',
    'Authorization': 'Token token={token}'.format(token=API_KEY)}
r = requests.get(url, headers=headers)
data = r.content
data_dict = json.loads(data)
data_df = pd.DataFrame(data_dict['incidents'])


问:
Restart the whole device from Android
Is there any way to restart a device per code from within android. I can highly customize all software on the device (tablet). As Backgroundinfo: I want a timer that restarts the device after a defined count if he did not get reseted.

Edit:

If there there is no Buildin-Way is it possible to do this anyway?

答:
In general Google dont allow third party apps to Reboot device below are few link might be helpful

http://groups.google.com/group/android-platform/browse_thread/thread/daf7c685e020d296

http://groups.google.com/group/android-developers/browse_thread/thread/5a97467ef5b4bf47/a1fe9379d4f5e30f?pli=1

ContentLicense: CC BY-SA 3.0

Title: Restart the whole device from Android


问:
Why can't you store an extremely large single value in a dynamically allocated block of memory?
Why can't I store a large integer in this allocated block of memory?

```<code>int *dyn = malloc(16);
*dyn = 9999999999;

printf("%lli\n", *dyn);

free(dyn);
</code>```

At compile-time, GCC warns me that an integer overflow will occur. And sure enough, when printed out, it has overflowed.

Why can't I use the entire block of memory to store a single value?

答:
dyn is an integer pointer (actually, pointing to a reserved memory of int array of 16 bytes). *dyn is an integer (first element from this int array). As similar to arrays:

```<code>int dyn[4];
dyn[0]=9999999999;
</code>```

Assigning 9999999999 to int leads to a variable overflow, since int allows on modern platforms only [−2 147 483 648, +2 147 483 647] range (and at least [−32767, +32767]).

Body:
Why can't I store a large integer in this allocated block of memory?

int *dyn = malloc(16);
*dyn = 9999999999;

printf("%lli\n", *dyn);

free(dyn);

At compile-time, GCC warns me that an integer overflow will occur. And sure enough, when printed out, it has overflowed.

Why can't I use the entire block of memory to store a single value?

Body:
dyn is an integer pointer (actually, pointing to a reserved memory of int array of 16 bytes). *dyn is an integer (first element from this int array). As similar to arrays:

int dyn[4];
dyn[0]=9999999999;

Assigning 9999999999 to int leads to a variable overflow, since int allows on modern platforms only [−2 147 483 648, +2 147 483 647] range (and at least [−32767, +32767]).


问:
Error converting data type nvarchar to real
I need to subtract two nvarchar values and store the result in another column. I understand that first I need to convert nvarchar to numeric values, but I always get this error

Error converting data type nvarchar to real

Just to mention in varchar values are stored only numeric values but I can't seem to get this conversion right.

答:
use a case statement. It should be something like (t-sql pseudo code inside a SELECT)

```<code>case when IsNumeric(column1) AND IsNumeric(column2)
     then cast(column1 as decimal) - cast(column2 as decimal)
else NULL end as column3
</code>```

This is a classical example of why you shouldn't mix types (nvarchar and decimal in this case), there are all sorts of shananigans - like ('abc' - 5) or (NULL - NULL) or ('five' - '3  '). If this works, it might be a good idea to look at the "NULL" results, as this might give you valuable insights as to what kind of garbage is being collected in your system.

Body:
use a case statement. It should be something like (t-sql pseudo code inside a SELECT)

case when IsNumeric(column1) AND IsNumeric(column2)
     then cast(column1 as decimal) - cast(column2 as decimal)
else NULL end as column3

This is a classical example of why you shouldn't mix types (nvarchar and decimal in this case), there are all sorts of shananigans - like ('abc' - 5) or (NULL - NULL) or ('five' - '3  '). If this works, it might be a good idea to look at the "NULL" results, as this might give you valuable insights as to what kind of garbage is being collected in your system.


问:
Find the next section by class name
How can I show the next div with class form_section by clicking .btn_next?

$(".form_section").hide();

$(document).on("click", ".btn_next", function(e) {
  $(this).next(".form_section").show();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row form_section">
  <div>
    <div></div>
    <div></div>
    <button class="btn btn-primary btn_next">SHOW NEXT SECTION</button>
  </div>
</div>
<div class="row form_section">
  <div>
    <div></div>
    <div></div>
    <button class="btn btn-primary btn_next">SHOW NEXT SECTION</button>
  </div>
</div>
<div class="row form_section">
  <div>
    <div></div>
    <div></div>
    <button class="btn btn-primary btn_next">SHOW NEXT SECTION</button>
  </div>
</div></code>```

答:
first you need to hide current ".form_section" section (to the button which was clicked), then get the next .form_section to show.

```<code><script>

        //$(".form_section").hide();
        $(document).on("click", ".btn_next", function(e){
            $(this).parents('.form_section').hide();
            $(this).parents('.form_section').next().show();
        });
    </script>
</code>```

Title: Find the next section by class name

Body:
How can I show the next div with class form_section by clicking .btn_next?

$(".form_section").hide();

$(document).on("click", ".btn_next", function(e) {
  $(this).next(".form_section").show();
});

    <button class="btn btn-primary btn_next">SHOW NEXT SECTION</button>

    <button class="btn btn-primary btn_next">SHOW NEXT SECTION</button>

    <button class="btn btn-primary btn_next">SHOW NEXT SECTION</button>

Body:
first you need to hide current ".form_section" section (to the button which was clicked), then get the next .form_section to show.

<script>

        //$(".form_section").hide();
        $(document).on("click", ".btn_next", function(e){
            $(this).parents('.form_section').hide();
            $(this).parents('.form_section').next().show();
        });
    </script>


问:
How to check in MongoDB C# Driver if updated successfully?
I am using the following code to update data  using the MongoDB C# Driver:

```<code>public async Task<bool> UpdateFirstName(string id, string firstName)
    {
        await Collection.UpdateOneAsync(Builders<User>.Filter.Eq(
            "_id", new ObjectId(id)),
            Builders<User>.Update.Set("firstName", firstName)
            .CurrentDate("lastUpdatedDate"));
    }
</code>```

This method returns "bool", because I want to know if the data has been updated successfully. This would be the pseudocode for checking if the data has been updated successfully:

```<code>    if (data updated successfully)
    {
        return true;
    }
    else
    {
        return false;
    }
</code>```

Does anyone know how to write the code for checking if the data updated successfully? Thanks!

答: If the method was executed so the update was done, otherwise the method will throw an exception - In case of async it's important to not forget the await (since using async method without await can't ensure your application stay around long enough to retreive the exception)</p>

Body:
I am using the following code to update data  using the MongoDB C# Driver:

public async Task<bool> UpdateFirstName(string id, string firstName)
    {
        await Collection.UpdateOneAsync(Builders<User>.Filter.Eq(
            "_id", new ObjectId(id)),
            Builders<User>.Update.Set("firstName", firstName)
            .CurrentDate("lastUpdatedDate"));
    }

This method returns "bool", because I want to know if the data has been updated successfully. This would be the pseudocode for checking if the data has been updated successfully:

    if (data updated successfully)
    {
        return true;
    }
    else
    {
        return false;
    }

Does anyone know how to write the code for checking if the data updated successfully? Thanks!


问:
How to replace a comma separated value in table column with user input value oracle

I have a table in oracle with a column with comma separated values. What i need is when a user enters a value and if that value is present in any of the rows, it should be removed.

eg.

COL

123,234

56,123

If user enters 123, the 1st column should have only 234 and second row should have only 56.

How do we do this in oracle??

Please help

Thanks

答:
try this : </p>

```<code>UPDATE t
SET col = REPLACE(REPLACE(col, '&variable', ''), ',', '') FROM t ;
</code>```

Body:
try this :

UPDATE t
SET col = REPLACE(REPLACE(col, '&variable', ''), ',', '') FROM t ;


问:
css selectors first and last occurance
I want to set a style on the first and last of the elements. The number of sections can vary on each odd/even, so I can not do anything like "every 3rd element then use this CSS-rule". The elements are inside one parent element, here a
.

What I want to achieve is that everytime the odd-section occures for the first time in this list of spans, I want to add some style, and the samme with the last occurance of odd-section. Then It begins again with the same logic for the even-section, and again for the odd-section, and then again even-section:

```

Is there a way to do this?

It would be so much better if every odd-section / even-section part had a parent
, but that is not the case here.

答:
You can use the following adjacent sibling selector and first child pseudo selector to select the first of each group

If the spans are always in groups of 3s, then you could use a double adjacent for the last of each group

.odd-section:first-child,
.even-section+.odd-section {
  /* this highlights the first in each group */
  border: 1px solid blue;
}
.odd-section+.odd-section+.odd-section {
  /* this highlights the last in each group */
  border: 1px solid green;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <span class="odd-section">odd</span>
  <span class="odd-section">odd</span>
  <span class="odd-section">odd</span>
  <span class="even-section">even</span>
  <span class="even-section">even</span>
  <span class="even-section">even</span>
  <span class="odd-section">odd</span>
  <span class="odd-section">odd</span>
  <span class="odd-section">odd</span>
  <span class="even-section">even</span>
  <span class="even-section">even</span>
  <span class="even-section">even</span>
</div></code>```

Unfortunately, if your odds and evens are not in groups of three, you will not be able to use css to select the last element of the group, instead you would either need to add a class using your server side language, or use a js approach

Below is a quick example of how you can use jquery to add  a class to the last of each group

$('.odd-section').filter(function() {
  return $(this).is(':last-child') || $(this).next('.even-section').length;
}).addClass('last-section');```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.odd-section:first-child,
.even-section+.odd-section {
  /* this highlights the first in each group */
  border: 1px solid blue;
}
.last-section {
  /* this highlights the last in each group */
  border: 1px solid green;
}</code>```

  odd
  odd
  odd
  even
  even
  even
  odd
  odd
  odd
  even
  even
  even
  odd
  odd

```

Title: css selectors first and last occurance

Body:
I want to set a style on the first and last of the elements. The number of sections can vary on each odd/even, so I can not do anything like "every 3rd element then use this CSS-rule". The elements are inside one parent element, here a
.

What I want to achieve is that everytime the odd-section occures for the first time in this list of spans, I want to add some style, and the samme with the last occurance of odd-section. Then It begins again with the same logic for the even-section, and again for the odd-section, and then again even-section:

Is there a way to do this?

It would be so much better if every odd-section / even-section part had a parent
, but that is not the case here.

Body:
You can use the following adjacent sibling selector and first child pseudo selector to select the first of each group

If the spans are always in groups of 3s, then you could use a double adjacent for the last of each group

.odd-section:first-child,
.even-section+.odd-section {
  /* this highlights the first in each group */
  border: 1px solid blue;
}
.odd-section+.odd-section+.odd-section {
  /* this highlights the last in each group */
  border: 1px solid green;
}

<div>
  <span class="odd-section">odd</span>
  <span class="odd-section">odd</span>
  <span class="odd-section">odd</span>
  <span class="even-section">even</span>
  <span class="even-section">even</span>
  <span class="even-section">even</span>
  <span class="odd-section">odd</span>
  <span class="odd-section">odd</span>
  <span class="odd-section">odd</span>
  <span class="even-section">even</span>
  <span class="even-section">even</span>
  <span class="even-section">even</span>
</div>

Unfortunately, if your odds and evens are not in groups of three, you will not be able to use css to select the last element of the group, instead you would either need to add a class using your server side language, or use a js approach

Below is a quick example of how you can use jquery to add  a class to the last of each group

$('.odd-section').filter(function() {
  return $(this).is(':last-child') || $(this).next('.even-section').length;
}).addClass('last-section');

.odd-section:first-child,
.even-section+.odd-section {
  /* this highlights the first in each group */
  border: 1px solid blue;
}
.last-section {
  /* this highlights the last in each group */
  border: 1px solid green;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <span class="odd-section">odd</span>
  <span class="odd-section">odd</span>
  <span class="odd-section">odd</span>
  <span class="even-section">even</span>
  <span class="even-section">even</span>
  <span class="even-section">even</span>
  <span class="odd-section">odd</span>
  <span class="odd-section">odd</span>
  <span class="odd-section">odd</span>
  <span class="even-section">even</span>
  <span class="even-section">even</span>
  <span class="even-section">even</span>
  <span class="odd-section">odd</span>
  <span class="odd-section">odd</span>
</div>


问:
react filtering an object of arrays
I'm trying to find a better way to remove value pairs of an object that contain an empty string ""

my current state is:

```<code> this.state = {

            searchParams:{
                query: '',
                colors: [],
                text: '',
                legalities: '',
                setName: '',
                pageSize: 4
            }
}
</code>```

I know this won't work with my state since it isn't an array, but something like this is what i'm trying to achieve right now

```<code>var search = this.state.searchParams.filter(function (el) {
            return el !== "";
          });
</code>```

could anyone point me in the right direction and explain a better way to do this with an object, thanks :) ?

答:
If you want to filter out empty strings and strings (with white spaces only) as well, then
we have trim the string and then check its length. If its string and its length is 0 after trimming, then its considered as empty and will be filtered out.

```<code>const params = this.state.searchParams

Object.keys(this.state.searchParams).filter(key =>
  !(typeof params[key] === 'string' && params[key].trim().length === 0)
)
</code>```

If you don't want to trim, then:

```<code>const params = this.state.searchParams

Object.keys(this.state.searchParams).filter(key => params[key] !== '')
</code>```

I would highly suggest you to not to use semicolon, as it takes space and JS can now ignore semicolon as well. Also, not to use double quotes unless required.

Title: react filtering an object of arrays

Body:
I'm trying to find a better way to remove value pairs of an object that contain an empty string ""

my current state is:

 this.state = {

            searchParams:{
                query: '',
                colors: [],
                text: '',
                legalities: '',
                setName: '',
                pageSize: 4
            }
}

I know this won't work with my state since it isn't an array, but something like this is what i'm trying to achieve right now

var search = this.state.searchParams.filter(function (el) {
            return el !== "";
          });

could anyone point me in the right direction and explain a better way to do this with an object, thanks :) ?

Body:
If you want to filter out empty strings and strings (with white spaces only) as well, then
we have trim the string and then check its length. If its string and its length is 0 after trimming, then its considered as empty and will be filtered out.

const params = this.state.searchParams

Object.keys(this.state.searchParams).filter(key =>
  !(typeof params[key] === 'string' && params[key].trim().length === 0)
)

If you don't want to trim, then:

const params = this.state.searchParams

Object.keys(this.state.searchParams).filter(key => params[key] !== '')

I would highly suggest you to not to use semicolon, as it takes space and JS can now ignore semicolon as well. Also, not to use double quotes unless required.


问:
Get total count for table row?
I Have an if Statement in  the function is to make  Row Red... if $ced (which is date value coming from MySQL) is lesser than the current time the code is given below: what I am looking for is how can I get total number of rows like 20,30 or whatever the value is and echo

```<code><tr <?php if(($ced <= time())): ?> style="color:red;" <?php endif; ?>>
 <td><?php  echo $students_rollno_class;?></td>
 <td><?php  echo $students_admission_no;?> </td>
 <td><?php  echo $students_firstname;?></td>
 <td><?php  echo $students_contact;?></td>
 <td><?php  echo $students_reference_no;?></td>
 <td><?php  echo date('d/m/Y', strtotime($students_date));?></td>
 <td><?php  echo $newformat;?></td>
</code>```

what I tried is

```<code>if(($ced <= time())){
$totalCount=$totalCount+1 ;}
</code>```

the problem is its giving me a row numbers like 1,1,1,1,2,2,2,2,4,4,4,4 but i am looking for is single total count like 20

I have a box where I want to show total count the code is given below

```<code><div class="info-box-content">
<span class="info-box-text"><?php echo "Course Ended"; ?></span>
<span class="info-box-number"><?php echo $totalCount; ?></span>
 </div>
</code>```

image for reference as the rows are changing to red and i want to show total count in the box

Loop i Created but with this its giving me value of 384 as per picture i have only 188 students

```<code><?php
if(($ced <= time())){
$totalCount=$totalCount+1 ; ?>
 <tr <?php if(($ced <= time())): ?> style="color:red;" <?php endif; ?>>
 <td><?php  echo $students_rollno_class;?></td>
    <td><?php  echo $students_admission_no;?> </td>
      <td><?php  echo $students_firstname;?></td>
       <td><?php  echo $students_contact;?></td>
        <td><?php  echo $students_reference_no;?></td>
         <td><?php  echo date('d/m/Y', strtotime($students_date));?></td>
          <td><?php  echo date('d/m/Y', $ced);?></td>
             </tr><?php }}?>
                       <?php  echo $totalCount;?>
</code>```

and making all rows red

答:
Just getting directly in your sql request the data filtered by date $ced <= time()

Doing this, you will access directly to the total count without counter, just by calling count($array)

Title: Get total count for table row?

Body:
I Have an if Statement in  the function is to make  Row Red... if $ced (which is date value coming from MySQL) is lesser than the current time the code is given below: what I am looking for is how can I get total number of rows like 20,30 or whatever the value is and echo

<tr <?php if(($ced <= time())): ?> style="color:red;" <?php endif; ?>>
 <?php  echo $students_rollno_class;?>
 <?php  echo $students_admission_no;?>
 <?php  echo $students_firstname;?>
 <?php  echo $students_contact;?>
 <?php  echo $students_reference_no;?>
 <?php  echo date('d/m/Y', strtotime($students_date));?>
 <?php  echo $newformat;?>

what I tried is

if(($ced <= time())){
$totalCount=$totalCount+1 ;}

the problem is its giving me a row numbers like 1,1,1,1,2,2,2,2,4,4,4,4 but i am looking for is single total count like 20

I have a box where I want to show total count the code is given below

<?php echo "Course Ended"; ?>
<?php echo $totalCount; ?>

image for reference as the rows are changing to red and i want to show total count in the box

Loop i Created but with this its giving me value of 384 as per picture i have only 188 students

<?php
if(($ced <= time())){
$totalCount=$totalCount+1 ; ?>
 <tr <?php if(($ced <= time())): ?> style="color:red;" <?php endif; ?>>
 <?php  echo $students_rollno_class;?>
    <?php  echo $students_admission_no;?>
      <?php  echo $students_firstname;?>
       <?php  echo $students_contact;?>
        <?php  echo $students_reference_no;?>
         <?php  echo date('d/m/Y', strtotime($students_date));?>
          <?php  echo date('d/m/Y', $ced);?>

<?php }}?>
                       <?php  echo $totalCount;?>

and making all rows red


问:
Problem with typedefing enums. And bug in visual studio 2005
```<code>struct A
{
    enum E
    {
        FIRST,
        SECOND
    };
};

struct B
{
    typedef A::E E;
};

int main()
{
    B::E e0 = A::FIRST;//OK (this case is clear for me)
    B::E e1 = A::E::FIRST;//OK (this case is clear for me as well)
    B::E e2 = B::FIRST;//Compile Error: FIRST is not member of B (Why isn't this allowed? Don't we lose meaning of typedef of enums in this case?)
    B::E e3 = B::E::FIRST;//Error of compiler (If there were no bug in visual studio 2005 compiler, would this code work?)
    return 0;
}
</code>```

P.S. The question in code.

Update: Actually the bug is fixed in VS2010.

答:
Enums only "overflow" in the surrounding namespace, aka the namespace of struct A. A simple typedef won't yield the same effect for struct B.

Also, if you enable warning level 4 (/W4), you'll get this nice warning:

warning C4482: nonstandard extension used: enum 'A::E' used in qualified name

It is not allowed to used A::E::XXX to refer to the enum values in the current standard.

Body:
struct A
{
    enum E
    {
        FIRST,
        SECOND
    };
};

struct B
{
    typedef A::E E;
};

int main()
{
    B::E e0 = A::FIRST;//OK (this case is clear for me)
    B::E e1 = A::E::FIRST;//OK (this case is clear for me as well)
    B::E e2 = B::FIRST;//Compile Error: FIRST is not member of B (Why isn't this allowed? Don't we lose meaning of typedef of enums in this case?)
    B::E e3 = B::E::FIRST;//Error of compiler (If there were no bug in visual studio 2005 compiler, would this code work?)
    return 0;
}

P.S. The question in code.

Update: Actually the bug is fixed in VS2010.


问:
How to exclude a specific device brand/model when it is not shown in Google Play Console Device Catalog?
I'm trying to exclude the following device brand/model as this is not compatible with my app:

```<code>Brand: Trend
Model: TaintArt for x86
</code>```

However, though this device appears continuously in my Crashlytics report, I cannot find it in the Device Catalog, so I cannot exclude/restrict it.

The following is an image from Crashlytics report:

Navigation to Device Catalog:

```<code>1. Login to Google Play Console
2. Select app
3. Release Management
4. Device Catalog
5. Search for Device (Trend, Taintart, etc.)
6. Result: 0 match your criteria
</code>```

Is there any other way to exclude this brand/model ?

Edit (3/27/2020): Same issue with "Batmobile Defy Mini", which is always crashing due to a strange error caused by android.content.res.Resources$NotFoundException when inflating class.

答: It has appeared in my crashlogs, as well, with the exact same Android version and root state. When searching Google for it, I came across a disassembling project. Possibly someone is using this to get to your app's code. It doesn't seem to be an official device hence sadly it cannot be excluded, at least not in the device catalogue. Sorry :(</p>

Body:
I'm trying to exclude the following device brand/model as this is not compatible with my app:

Brand: Trend
Model: TaintArt for x86

However, though this device appears continuously in my Crashlytics report, I cannot find it in the Device Catalog, so I cannot exclude/restrict it.

The following is an image from Crashlytics report:

Navigation to Device Catalog:

1. Login to Google Play Console
2. Select app
3. Release Management
4. Device Catalog
5. Search for Device (Trend, Taintart, etc.)
6. Result: 0 match your criteria

Is there any other way to exclude this brand/model ?

Edit (3/27/2020): Same issue with "Batmobile Defy Mini", which is always crashing due to a strange error caused by android.content.res.Resources$NotFoundException when inflating class.


答:
The size of int is usually 4 bytes (32 bits). And, it can take 2^32 distinct states from -2147483648 to 2147483647.
So when you try to store this *dyn = 9999999999; , integer overflow occurs.
It is not pointing to the memory location, it is pointing to the value of that variable.

Title: Why can't you store an extremely large single value in a dynamically allocated block of memory?


问:
How to close the task terminal automatically after vscode debugging
launch.json

...
"preLaunchTask": "startDebug",
"postDebugTask": "closeOpenOCDTerminal"
```
<p>tasks.json</p>
<pre class="lang-json prettyprint-override"><code>{
"version": "2.0.0",
"tasks": [
    {
        "label": "startDebug",
        "type": "shell",
        "command": "make -j4; openocd -f interface/cmsis-dap.cfg -c 'transport select swd' -f target/stm32f1x.cfg",
        "isBackground": true,
        "problemMatcher": {
            "pattern": {
                "regexp": "."
            },
            "background": {
                "activeOnStart": true,
                "beginsPattern": ".",
                "endsPattern": "."
            }
        }
    },
    {
        "label": "closeOpenOCDTerminal",
        "type": "process",
        "command":[
            "${command:workbench.action.tasks.terminate}",
            // "${command:workbench.action.acceptSelectedQuickOpenItem}" //invalid
         ]
    }
]
}
</code>```

The OpenOCD service does not end automatically like the make command, only depends on closing the terminal or executing Ctrl + C.
How to automatically close the task terminal after debugging？
Or execute Ctrl + C command automatically in the task terminal to end the Openocd service.
The currently used closeOpenOCDTerminal method requires manual clicking on the pop-up list.

答:
```<code>{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "start",
            "type": "shell",
            "command": "make -j4; openocd -f interface/cmsis-dap.cfg -c 'transport select swd' -f target/stm32f1x.cfg",
            "isBackground": true,
            "problemMatcher": {
                "pattern": {
                    "regexp": "."
                },
                "background": {
                    "activeOnStart": true,
                    "beginsPattern": ".",
                    "endsPattern": "."
                }
            }
        },
        {
            "label": "stop",
            "command": "echo ${input:terminate}",
            "type": "shell",
        }
    ],
    "inputs": [
        {
          "id": "terminate",
          "type": "command",
          "command": "workbench.action.tasks.terminate",
          "args": "terminateAll"
        }
    ]
}
</code>```

This example happens to close the task terminal.

Body:
launch.json

...
"preLaunchTask": "startDebug",
"postDebugTask": "closeOpenOCDTerminal"

tasks.json

{
"version": "2.0.0",
"tasks": [
    {
        "label": "startDebug",
        "type": "shell",
        "command": "make -j4; openocd -f interface/cmsis-dap.cfg -c 'transport select swd' -f target/stm32f1x.cfg",
        "isBackground": true,
        "problemMatcher": {
            "pattern": {
                "regexp": "."
            },
            "background": {
                "activeOnStart": true,
                "beginsPattern": ".",
                "endsPattern": "."
            }
        }
    },
    {
        "label": "closeOpenOCDTerminal",
        "type": "process",
        "command":[
            "${command:workbench.action.tasks.terminate}",
            // "${command:workbench.action.acceptSelectedQuickOpenItem}" //invalid
         ]
    }
]
}

The OpenOCD service does not end automatically like the make command, only depends on closing the terminal or executing Ctrl + C.
How to automatically close the task terminal after debugging？
Or execute Ctrl + C command automatically in the task terminal to end the Openocd service.
The currently used closeOpenOCDTerminal method requires manual clicking on the pop-up list.

Body:
{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "start",
            "type": "shell",
            "command": "make -j4; openocd -f interface/cmsis-dap.cfg -c 'transport select swd' -f target/stm32f1x.cfg",
            "isBackground": true,
            "problemMatcher": {
                "pattern": {
                    "regexp": "."
                },
                "background": {
                    "activeOnStart": true,
                    "beginsPattern": ".",
                    "endsPattern": "."
                }
            }
        },
        {
            "label": "stop",
            "command": "echo ${input:terminate}",
            "type": "shell",
        }
    ],
    "inputs": [
        {
          "id": "terminate",
          "type": "command",
          "command": "workbench.action.tasks.terminate",
          "args": "terminateAll"
        }
    ]
}

This example happens to close the task terminal.


问:
Remember Password alert for the site
In my website login page I can't get the alert "remember password for the site".I had already enabled remember password for the site from tools->options->security->"remember password for the site" but still it is not working . I am using mozilla 3.6 version</p>

答: What you need is the exact opposite of this stackoverflow question. See there for the answer and for more information about it.</p>

Title: Remember Password alert for the site