问:
What is the difference between pool.query and client.query with the Node pg library?
I am trying to understand pool.query and client.query and the differences between the two and when to use which.

I have an express application that runs the following code at a certain end-point.

```<code>// I am just using params for to a quick setup
router.get("/:username/:password", (req, res) => {
  const { username, password } = req.params;
  // crypt & gen_salt function from pgcrypto
  client // *** here ***
    .query(
      ` SELECT username, email, password FROM users
        WHERE users.username = $1
        AND users.password = crypt($2, password)
      `, [username, password]
    )
    .then(user => {
      console.log("Users ==>", user.rows);
      const userCount = user.rows.length;
      if (userCount < 1) {
        res.status(204).json({ userFound: "No User Found" });
      } else {
        res.status(200).json(user.rows[0]);
      }
    })
    .catch(err => console.log(err));
});
</code>```
```<code>// index.js (starting point of application)
require("dotenv").config({ debug: true });
const app = require("./middleware");

// Port Listener
app.listen(process.env.PORT, () =>
  console.log(
    "Server running on PORT <======= " + process.env.PORT + " =======>"
  )
);

</code>```

I hit the API endpoints up and Both ways return the exact same result, and I have read that using pooling over instantiating a new client instance is better, but I'm honestly not sure if that is true since Node should keep the same client instance because of the way it's being exported as it is beyond my current knowledge base. The readings I found on this topic were kind of sparse, so if any one has any articles they would recommend then I'd be happy to check them out as well.

答:
I believe both are the same. But pool.query will allow you to execute a basic single query when you need to execute from a client that would be accessed from the pool of client threads.

So pool.query could be used to directly run the query rather than acquiring a client and then running the query with that client.

Acquiring Client from Pool

```<code>const { Pool } = require('pg')

const pool = new Pool()

pool.connect((err, client, release) => {
  if (err) {
    return console.error('Error acquiring client', err.stack)
  }
  client.query('SELECT NOW()', (err, result) => { // Default client query which is same as that used when connect to DB with one client.
    release()
    if (err) {
      return console.error('Error executing query', err.stack)
    }
    console.log(result.rows)
  })
})
</code>```

Same as above except without pool

```<code>const { Client } = require('pg').Client
const client = new Client()
client.connect()
client.query('SELECT NOW()', (err, res) => {
  if (err) throw err
  console.log(res)
  client.end()
})
</code>```

Directly calling query on pool

```<code>const { Pool } = require('pg')

const pool = new Pool()

// Direct query without acquiring client object.
pool.query('SELECT $1::text as name', ['brianc'], (err, result) => {
  if (err) {
    return console.error('Error executing query', err.stack)
  }
  console.log(result.rows[0].name) // brianc
})
</code>```

Body:
I am trying to understand pool.query and client.query and the differences between the two and when to use which.

I have an express application that runs the following code at a certain end-point.

// I am just using params for to a quick setup
router.get("/:username/:password", (req, res) => {
  const { username, password } = req.params;
  // crypt & gen_salt function from pgcrypto
  client // *** here ***
    .query(
      ` SELECT username, email, password FROM users
        WHERE users.username = $1
        AND users.password = crypt($2, password)
      `, [username, password]
    )
    .then(user => {
      console.log("Users ==>", user.rows);
      const userCount = user.rows.length;
      if (userCount < 1) {
        res.status(204).json({ userFound: "No User Found" });
      } else {
        res.status(200).json(user.rows[0]);
      }
    })
    .catch(err => console.log(err));
});

// index.js (starting point of application)
require("dotenv").config({ debug: true });
const app = require("./middleware");

// Port Listener
app.listen(process.env.PORT, () =>
  console.log(
    "Server running on PORT <======= " + process.env.PORT + " =======>"
  )
);

I hit the API endpoints up and Both ways return the exact same result, and I have read that using pooling over instantiating a new client instance is better, but I'm honestly not sure if that is true since Node should keep the same client instance because of the way it's being exported as it is beyond my current knowledge base. The readings I found on this topic were kind of sparse, so if any one has any articles they would recommend then I'd be happy to check them out as well.

Body:
I believe both are the same. But pool.query will allow you to execute a basic single query when you need to execute from a client that would be accessed from the pool of client threads.

So pool.query could be used to directly run the query rather than acquiring a client and then running the query with that client.

Acquiring Client from Pool

const { Pool } = require('pg')

const pool = new Pool()

pool.connect((err, client, release) => {
  if (err) {
    return console.error('Error acquiring client', err.stack)
  }
  client.query('SELECT NOW()', (err, result) => { // Default client query which is same as that used when connect to DB with one client.
    release()
    if (err) {
      return console.error('Error executing query', err.stack)
    }
    console.log(result.rows)
  })
})

Same as above except without pool

const { Client } = require('pg').Client
const client = new Client()
client.connect()
client.query('SELECT NOW()', (err, res) => {
  if (err) throw err
  console.log(res)
  client.end()
})

Directly calling query on pool

const { Pool } = require('pg')

const pool = new Pool()

// Direct query without acquiring client object.
pool.query('SELECT $1::text as name', ['brianc'], (err, result) => {
  if (err) {
    return console.error('Error executing query', err.stack)
  }
  console.log(result.rows[0].name) // brianc
})


来源: stackexchange

问:
A Starting Menu for a simple game
I am making this small and simple game with Java, and when I start it up, it just starts the game without any menus or something. Now, I want to make it so that if I run the game, there comes a game menu, or starting menu, where you can select new game, and exit. But, how would I do this? I need some help with this.

Edit:

The game is in a 800x600 screen, and I want like, a menu that takes over the whole 800x600 screen, with just a "Start Game" and a "Exit" button.

答:
The Swing tutorial on menus will be an excellent reference for you as you work through creating a menu.

Here is some sample code for creating a simple menu like you described, assuming your JFrame is called frame.

```<code>//Where the GUI is created:
JMenuBar menuBar;
JMenu menu;
JMenuItem menuItem;

//Create the menu bar.
menuBar = new JMenuBar();

//Build the first menu.
menu = new JMenu("File");
menu.setMnemonic(KeyEvent.VK_F);
menu.getAccessibleContext().setAccessibleDescription(
        "File menu");
menuBar.add(menu);

//JMenuItems show the menu items
menuItem = new JMenuItem("New",
                         new ImageIcon("images/new.gif"));
menuItem.setMnemonic(KeyEvent.VK_N);
menu.add(menuItem);

// add a separator
menu.addSeparator();

menuItem = new JMenuItem("Pause", new ImageIcon("images/pause.gif"));
menuItem.setMnemonic(KeyEvent.VK_P);
menu.add(menuItem);

menuItem = new JMenuItem("Exit", new ImageIcon("images/exit.gif"));
menuItem.setMnemonic(KeyEvent.VK_E);
menu.add(menuItem);

// add menu bar to frame
frame.setJMenuBar(theJMenuBar);
</code>```

The important classes to know are JMenuBar, JMenu, and JMenuItem.

To handle clicks on those menu items, you need to add an ActionListener for each, using code such as:

```<code>menuItem.addActionListener(new ActionListener() { // ...});
</code>```

ContentLicense: CC BY-SA 3.0

Title: A Starting Menu for a simple game

Body:
The Swing tutorial on menus will be an excellent reference for you as you work through creating a menu.

Here is some sample code for creating a simple menu like you described, assuming your JFrame is called frame.

//Where the GUI is created:
JMenuBar menuBar;
JMenu menu;
JMenuItem menuItem;

//Create the menu bar.
menuBar = new JMenuBar();

//Build the first menu.
menu = new JMenu("File");
menu.setMnemonic(KeyEvent.VK_F);
menu.getAccessibleContext().setAccessibleDescription(
        "File menu");
menuBar.add(menu);

//JMenuItems show the menu items
menuItem = new JMenuItem("New",
                         new ImageIcon("images/new.gif"));
menuItem.setMnemonic(KeyEvent.VK_N);
menu.add(menuItem);

// add a separator
menu.addSeparator();

menuItem = new JMenuItem("Pause", new ImageIcon("images/pause.gif"));
menuItem.setMnemonic(KeyEvent.VK_P);
menu.add(menuItem);

menuItem = new JMenuItem("Exit", new ImageIcon("images/exit.gif"));
menuItem.setMnemonic(KeyEvent.VK_E);
menu.add(menuItem);

// add menu bar to frame
frame.setJMenuBar(theJMenuBar);

The important classes to know are JMenuBar, JMenu, and JMenuItem.

To handle clicks on those menu items, you need to add an ActionListener for each, using code such as:

menuItem.addActionListener(new ActionListener() { // ...});


问:
Is there a way to auto-adjust Excel column widths with pandas.ExcelWriter?
I am being asked to generate some Excel reports. I am currently using pandas quite heavily for my data, so naturally I would like to use the pandas.ExcelWriter method to generate these reports.  However the fixed column widths are a problem.

The code I have so far is simple enough.  Say I have a dataframe called df:

```<code>writer = pd.ExcelWriter(excel_file_path, engine='openpyxl')
df.to_excel(writer, sheet_name="Summary")
</code>```

I was looking over the pandas docs, and I don't really see any options to set column widths.  Is there a trick to make it such that the columns auto-adjust to the data? Or is there something I can do after the fact to the xlsx file to adjust the column widths?

(I am using the OpenPyXL library, and generating .xlsx files - if that makes any difference.)

答:
```<code>import re
import openpyxl
..
for col in _ws.columns:
    max_lenght = 0
    print(col[0])
    col_name = re.findall('\w\d', str(col[0]))
    col_name = col_name[0]
    col_name = re.findall('\w', str(col_name))[0]
    print(col_name)
    for cell in col:
        try:
            if len(str(cell.value)) > max_lenght:
                max_lenght = len(cell.value)
        except:
            pass
    adjusted_width = (max_lenght+2)
    _ws.column_dimensions[col_name].width = adjusted_width
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am being asked to generate some Excel reports. I am currently using pandas quite heavily for my data, so naturally I would like to use the pandas.ExcelWriter method to generate these reports.  However the fixed column widths are a problem.

The code I have so far is simple enough.  Say I have a dataframe called df:

writer = pd.ExcelWriter(excel_file_path, engine='openpyxl')
df.to_excel(writer, sheet_name="Summary")

I was looking over the pandas docs, and I don't really see any options to set column widths.  Is there a trick to make it such that the columns auto-adjust to the data? Or is there something I can do after the fact to the xlsx file to adjust the column widths?

(I am using the OpenPyXL library, and generating .xlsx files - if that makes any difference.)


问:
Running a function after the app opens from the background after notification click
I'm pretty new to Android development. I have been able to get a notification to pop up while the app is in the background. When I click on it, it successfully loads the application backup. However I want to load an Alert from the page but only when it is opened from a notification click.

Here is the code for generating the notification. Any help would be appreciated.

```<code>private void getNotificationForPasswordChange() {
    NotificationManager mNotificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        CharSequence name = "Hello";// The user-visible name of the channel.
        int importance = NotificationManager.IMPORTANCE_HIGH;
        NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, name, importance);
        if (mNotificationManager != null)
            mNotificationManager.createNotificationChannel(mChannel);
    }

    Bitmap icon = BitmapFactory.decodeResource(getResources(),
            R.mipmap.ic_launcher);
    Intent i=new Intent(this, MainActivity.class);
    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    i.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent mainIntent = PendingIntent.getActivity(this, 0,
            i, PendingIntent.FLAG_UPDATE_CURRENT);

    Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle("Pronto Tracker")
            .setTicker("Pronto Tracker")
            .setContentText("Cannot connect to server. Location is not being updated.")
            .setSmallIcon(R.mipmap.ic_pronto_logo)
            .setLargeIcon(Bitmap.createScaledBitmap(icon, 128, 128, false))
            .setOngoing(true).setContentIntent(mainIntent).
                    build();
    mNotificationManager.notify(Constants.PASSWORD_CHANGE_NOTIFICATION_ID, notification);
}
</code>```

答:
You should use onCreate function on your MainActivity
Add this code to parce your intent:
Intent receivedIntent = getIntent();</p>

Body:
I'm pretty new to Android development. I have been able to get a notification to pop up while the app is in the background. When I click on it, it successfully loads the application backup. However I want to load an Alert from the page but only when it is opened from a notification click.

Here is the code for generating the notification. Any help would be appreciated.

private void getNotificationForPasswordChange() {
    NotificationManager mNotificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        CharSequence name = "Hello";// The user-visible name of the channel.
        int importance = NotificationManager.IMPORTANCE_HIGH;
        NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, name, importance);
        if (mNotificationManager != null)
            mNotificationManager.createNotificationChannel(mChannel);
    }

    Bitmap icon = BitmapFactory.decodeResource(getResources(),
            R.mipmap.ic_launcher);
    Intent i=new Intent(this, MainActivity.class);
    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    i.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent mainIntent = PendingIntent.getActivity(this, 0,
            i, PendingIntent.FLAG_UPDATE_CURRENT);

    Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle("Pronto Tracker")
            .setTicker("Pronto Tracker")
            .setContentText("Cannot connect to server. Location is not being updated.")
            .setSmallIcon(R.mipmap.ic_pronto_logo)
            .setLargeIcon(Bitmap.createScaledBitmap(icon, 128, 128, false))
            .setOngoing(true).setContentIntent(mainIntent).
                    build();
    mNotificationManager.notify(Constants.PASSWORD_CHANGE_NOTIFICATION_ID, notification);
}


问:
Relationship between stream and buffer?
I'm a newbie programmer, can you help me imagine what a stream is, is it a fixed array of bytes that transfer data from i.e: a file to Y? And what is Y here, a buffer or something else?
In what way is the buffer related to stream?</p>

答:
A stream is either a source (input stream) or sink (output stream) of data, that is available (or provided) in time (as opposed to all at once).

A buffer is an array (a piece of memory) that is used to store data temporarily. An input buffer is typically filled from an input stream by the OS; an output buffer (once filled by the programmer) is consumed by the OS.

Imagine you want to fill a tub with water. You start with a water source like a water tank or public waterworks that can be transfered through a water tap. You put a bucket under the water tap and turn it on. When the bucket is full, you dump it into the tub, and put it back under the tap. You repeat that until your tub is full.

Loading a file, for example, works almost the same way. You have a data source (the file on disk); you open an input stream (a programmatic construct that will give you data generally as fast as the disk can read them). You allocate a buffer (a small memory area) and tell the system to fill it from the stream. When it is full, you append it to the big chunk of allocated memory that you reserved for file contents, then let the buffer be filled again. When the whole file is read, you close the stream.

Title: Relationship between stream and buffer?


答:
You can pass the alert message with notification PendingIntent. Add the message or value you want to show as alert in PendingIntent .putExtra() and also specify the activity in PendingIntent where you want to show the alert in form of dialog or anything.

```<code> Intent intent = new Intent(Application.getAppContext(), MainActivity.class);
 intent.putExtra("is_notification", true);
 intent.putExtra("alert_message", "Hello World!");
 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
 PendingIntent lowIntent = PendingIntent.getActivity(mContext, 100, intent, PendingIntent.FLAG_CANCEL_CURRENT);
</code>```

After that add the PendingIntent to your notification.
Second thing you need to do is to get the data from the Intent when user taps on notification.
In your MainActivity add the following code to get data from Intent:-

```<code>if (getIntent() != null) {
   String message = getIntent().getStringExtra("alert_message");
   boolean isNotification = getIntent().getBooleanExtra("is_notification", false);

    if(is_notification){
       // show alert
      }
    }
</code>```

Title: Running a function after the app opens from the background after notification click

Body:
You can pass the alert message with notification PendingIntent. Add the message or value you want to show as alert in PendingIntent .putExtra() and also specify the activity in PendingIntent where you want to show the alert in form of dialog or anything.

 Intent intent = new Intent(Application.getAppContext(), MainActivity.class);
 intent.putExtra("is_notification", true);
 intent.putExtra("alert_message", "Hello World!");
 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
 PendingIntent lowIntent = PendingIntent.getActivity(mContext, 100, intent, PendingIntent.FLAG_CANCEL_CURRENT);

After that add the PendingIntent to your notification.
Second thing you need to do is to get the data from the Intent when user taps on notification.
In your MainActivity add the following code to get data from Intent:-

if (getIntent() != null) {
   String message = getIntent().getStringExtra("alert_message");
   boolean isNotification = getIntent().getBooleanExtra("is_notification", false);

    if(is_notification){
       // show alert
      }
    }


问:
How to do for authorize endpoints for anonymous user with spring security
I am working on a SOAP webservice with spring boot and spring security with basic authentication. The authentication works, but I would like to authorize anonymous user to access at many endpoints. I don't know how to do.
I think to create 2 wsdl, one for endpoints with authentication and another for endpoints without authentication. Is it possible ?
Else is it possible to annotate an endpoint with something like @PreAuthorize(permitAll) or customize spring security ?

What is the proper way to do and how ?

Thanks in advance.

I tried this :

```<code>    @PayloadRoot(namespace = NAMESPACE_URI, localPart = "createAuthorRequest")
@ResponsePayload
@PreAuthorize("permitAll()")
public CreateAuthorResponse createAuthor(
        @RequestPayload CreateAuthorRequest request
) throws WSException {
    return authorService.createAuthor(request);
}
</code>```

or customize spring security :

```<code>           public void configure(HttpSecurity httpSecurity) throws Exception {

    httpSecurity
    .httpBasic()
            .and()
         .authorizeRequests().antMatchers(HttpMethod.POST, "/ws/createAuthor", "/ws/createAuthorRequest", "/ws/createAuthor**").permitAll()
            .antMatchers(HttpMethod.GET, "/ws/createAuthor", "/ws/createAuthorRequest", "/ws/createAuthor**").permitAll()
            .antMatchers(HttpMethod.PUT, "/ws/createAuthor", "/ws/createAuthorRequest", "/ws/createAuthor**").permitAll()
            .anyRequest().authenticated()

            .and()
            .csrf().disable().headers().frameOptions().disable();
</code>```

But it doesn't change. With SOAP, I don't know how to get the name of endpoint called. Here the log of spring security :

```<code>
    2019-05-29 22:49:39.060  INFO 8228 --- [io-8080-exec-10] Spring Security Debugger                 :

************************************************************

Request received for POST '/ws':

org.apache.catalina.connector.RequestFacade@7445a104

servletPath:/ws
pathInfo:null
headers:
accept-encoding: gzip,deflate
content-type: text/xml;charset=UTF-8
soapaction: ""
content-length: 516
host: localhost:8080
connection: Keep-Alive
user-agent: Apache-HttpClient/4.1.1 (java 1.5)
</code>```

答:
is it possible to annotate an endpoint with something like
  @PreAuthorize(permitAll)

if you are using @PreAuthorize in your controllers, you can just add @PreAuthorize("permitAll()").

or customize spring security ?

In you custom security config., add all the endpoints that you want to be available in public or with no authorization in antMatchers then set it to permitAll.

Sample:

```<code>@Configuration
@EnableWebSecurity
public class SecSecurityConfig extends WebSecurityConfigurerAdapter {

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.authorizeRequests()
                // permit all access to these endpoints.
                .antMatchers("/endpoint1", "/endpoint2", "endpoint3/**").permitAll()
                // any other request needs to be authenticated
                .anyRequest().authenticated();
        }
}
</code>```

You may also specify the httpmethod to that you want to permit by adding the method as parameter before the list endpoints.

```<code>.antMatchers(HttpMethod.GET, "/endpoint1", "/endpoint2", "endpoint3/**").permitAll()
.antMatchers(HttpMethod.PUT, "/endpoint1", "endpoint3/**").permitAll()
.antMatchers(HttpMethod.POST, "endpoint3/**").permitAll()
</code>```

Body:
I am working on a SOAP webservice with spring boot and spring security with basic authentication. The authentication works, but I would like to authorize anonymous user to access at many endpoints. I don't know how to do.
I think to create 2 wsdl, one for endpoints with authentication and another for endpoints without authentication. Is it possible ?
Else is it possible to annotate an endpoint with something like @PreAuthorize(permitAll) or customize spring security ?

What is the proper way to do and how ?

Thanks in advance.

I tried this :

    @PayloadRoot(namespace = NAMESPACE_URI, localPart = "createAuthorRequest")
@ResponsePayload
@PreAuthorize("permitAll()")
public CreateAuthorResponse createAuthor(
        @RequestPayload CreateAuthorRequest request
) throws WSException {
    return authorService.createAuthor(request);
}

or customize spring security :

           public void configure(HttpSecurity httpSecurity) throws Exception {

    httpSecurity
    .httpBasic()
            .and()
         .authorizeRequests().antMatchers(HttpMethod.POST, "/ws/createAuthor", "/ws/createAuthorRequest", "/ws/createAuthor**").permitAll()
            .antMatchers(HttpMethod.GET, "/ws/createAuthor", "/ws/createAuthorRequest", "/ws/createAuthor**").permitAll()
            .antMatchers(HttpMethod.PUT, "/ws/createAuthor", "/ws/createAuthorRequest", "/ws/createAuthor**").permitAll()
            .anyRequest().authenticated()

            .and()
            .csrf().disable().headers().frameOptions().disable();

But it doesn't change. With SOAP, I don't know how to get the name of endpoint called. Here the log of spring security :

    2019-05-29 22:49:39.060  INFO 8228 --- [io-8080-exec-10] Spring Security Debugger                 :

************************************************************

Request received for POST '/ws':

org.apache.catalina.connector.RequestFacade@7445a104

servletPath:/ws
pathInfo:null
headers:
accept-encoding: gzip,deflate
content-type: text/xml;charset=UTF-8
soapaction: ""
content-length: 516
host: localhost:8080
connection: Keep-Alive
user-agent: Apache-HttpClient/4.1.1 (java 1.5)

Body:
is it possible to annotate an endpoint with something like
  @PreAuthorize(permitAll)

if you are using @PreAuthorize in your controllers, you can just add @PreAuthorize("permitAll()").

or customize spring security ?

In you custom security config., add all the endpoints that you want to be available in public or with no authorization in antMatchers then set it to permitAll.

Sample:

@Configuration
@EnableWebSecurity
public class SecSecurityConfig extends WebSecurityConfigurerAdapter {

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.authorizeRequests()
                // permit all access to these endpoints.
                .antMatchers("/endpoint1", "/endpoint2", "endpoint3/**").permitAll()
                // any other request needs to be authenticated
                .anyRequest().authenticated();
        }
}

You may also specify the httpmethod to that you want to permit by adding the method as parameter before the list endpoints.

.antMatchers(HttpMethod.GET, "/endpoint1", "/endpoint2", "endpoint3/**").permitAll()
.antMatchers(HttpMethod.PUT, "/endpoint1", "endpoint3/**").permitAll()
.antMatchers(HttpMethod.POST, "endpoint3/**").permitAll()


问:
Firestore transaction update multiple document
I want to update documents in one collection.

```<code>my_collection
     document_1
        field_1
        field_2
     document_2
        field_1
        field_2
</code>```

My code:

```<code>exports.aggregateUsers =
functions.firestore.document('users/{userId}').onWrite(function(change,
context) {
const document = change.after.exists ? change.after.data() : null;
const oldDocument = change.before.data() || null;

return firestore.runTransaction(function(transaction) {
    var oldInstanceRef;
    var instanceRef;

    var oldInstanceDoc;
    var instanceDoc;
    if (document != null) {
        instanceRef = firestore.collection("counters").doc("instance_counter").collection("instances").doc(document.instance);
        instanceDoc = transaction.get(instanceRef);

        var newNumberOfUsers = (instanceDoc.data().number_of_users || 0) + 1;
        transaction.set(instanceRef, { number_of_users: newNumberOfUsers });
    }
    if (oldDocument != null) {
        oldInstanceRef = firestore.collection("counters").doc("instance_counter").collection("instances").doc(oldDocument.instance);
        oldInstanceDoc = transaction.get(oldInstanceRef);

        var newPrevNumberOfUsers = (oldInstanceDoc.data().number_of_users || 0) + 1;
        transaction.set(instanceRef, { number_of_users: newPrevNumberOfUsers });
    }

}).catch(function(error) {
    console.log("invalid-argument", error.code, error.message);
});
});
</code>```

Errors:

```<code>instanceDoc.data is not a function
</code>```

I am using transcation in cloud function to aggregate number of users, not using distributed counter, because of low traffic app. My question is how to update field's value in each document? Thank you

答:
I guess you forgot the async/await.

Try this:

async before transaction parameter

await before transaction.get(<some_ref_here>)

return firestore.runTransaction(async transaction => {
    var oldInstanceRef;
    var instanceRef;

    var oldInstanceDoc;
    var instanceDoc;
    if (document != null) {
        instanceRef = firestore.collection("counters").doc("instance_counter").collection("instances").doc(document.instance);
        instanceDoc = await transaction.get(instanceRef);

        var newNumberOfUsers = (instanceDoc.data().number_of_users || 0) + 1;
        transaction.set(instanceRef, { number_of_users: newNumberOfUsers });
    }
    if (oldDocument != null) {
        oldInstanceRef = firestore.collection("counters").doc("instance_counter").collection("instances").doc(oldDocument.instance);
        oldInstanceDoc = await transaction.get(oldInstanceRef);

        var newPrevNumberOfUsers = (oldInstanceDoc.data().number_of_users || 0) + 1;
        transaction.set(instanceRef, { number_of_users: newPrevNumberOfUsers });
    }

}).catch(function(error) {
    console.log("invalid-argument", error.code, error.message);
});```

Body:
I want to update documents in one collection.

my_collection
     document_1
        field_1
        field_2
     document_2
        field_1
        field_2

My code:

exports.aggregateUsers =
functions.firestore.document('users/{userId}').onWrite(function(change,
context) {
const document = change.after.exists ? change.after.data() : null;
const oldDocument = change.before.data() || null;

return firestore.runTransaction(function(transaction) {
    var oldInstanceRef;
    var instanceRef;

    var oldInstanceDoc;
    var instanceDoc;
    if (document != null) {
        instanceRef = firestore.collection("counters").doc("instance_counter").collection("instances").doc(document.instance);
        instanceDoc = transaction.get(instanceRef);

        var newNumberOfUsers = (instanceDoc.data().number_of_users || 0) + 1;
        transaction.set(instanceRef, { number_of_users: newNumberOfUsers });
    }
    if (oldDocument != null) {
        oldInstanceRef = firestore.collection("counters").doc("instance_counter").collection("instances").doc(oldDocument.instance);
        oldInstanceDoc = transaction.get(oldInstanceRef);

        var newPrevNumberOfUsers = (oldInstanceDoc.data().number_of_users || 0) + 1;
        transaction.set(instanceRef, { number_of_users: newPrevNumberOfUsers });
    }

}).catch(function(error) {
    console.log("invalid-argument", error.code, error.message);
});
});

Errors:

instanceDoc.data is not a function

I am using transcation in cloud function to aggregate number of users, not using distributed counter, because of low traffic app. My question is how to update field's value in each document? Thank you


问:
Java basics: a static function without a name, or return type
```<code>public class Main {
    public static final Logger LOGGER = Logger.getLogger(Main.class.getName());

    static {
        try {
             LOGGER.addHandler(new FileHandler("errors.log",true));
        }
        catch(IOException ex) {
             LOGGER.log(Level.WARNING,ex.toString(),ex);
        }
    }
...
</code>```

I'm wondering what is this nameless static function about.

I never saw anything like this in java (which I'm currently learning).

What is it for ?

When is it typically used ?

When is this gonna be executed in the program ?

答:
That is called a static block and will only be executed once during initialization.  Also, if there are more than one static initialization blocks, the run time guarantees that they will be called in the order they appear in the source code.

Here is a pretty good explanation with some example code a.
https://www.geeksforgeeks.org/g-fact-79/

Body:
public class Main {
    public static final Logger LOGGER = Logger.getLogger(Main.class.getName());

    static {
        try {
             LOGGER.addHandler(new FileHandler("errors.log",true));
        }
        catch(IOException ex) {
             LOGGER.log(Level.WARNING,ex.toString(),ex);
        }
    }
...

I'm wondering what is this nameless static function about.

I never saw anything like this in java (which I'm currently learning).

What is it for ?

When is it typically used ?

When is this gonna be executed in the program ?


问:
Need help to write elasticsearch query which should search based on text of one field and another array field with (passed values or null)
I have data in the mysql database which have been stored into elasticsearch as documents using logstash job.

```<code>**Data example in database:**

firstname(text), lastname(text), email(text), tags(text & nullable)
</code>```

Here, tags conains value as per this in mysql : "t1,t2,t3" or ""

While adding data into elasticsearch, custom analyzer/tokenizer has been applied using ",(comma)".

I need data as per this and need to write the query for this:

```<code>firstname = "text", tags = ["t1","t2"]

"Get all records which contain this firstname and tags with either "t1 or t2 or (t1 & t2) or null" (any in which tags are empty)".
</code>```

I have tried a few queries to get this kind of result but nothing worked.
(It doesn't return records with null tags as well tags with (t1,t2))

```<code>GET /posts/_search
{
  "query": {
    "bool": {
      "should": [
        {
          "bool": {
            "must": [
              {
                "multi_match": {
                  "query": "some_text",
                  "fields": [
                    "firstname^1.0"
                  ]
                }
              },
              {
                "bool": {
                  "should": [
                    {
                      "terms": {
                        "tags": [
                          "t2"
                        ]
                      }
                    }
                  ]
                }
              }
            ]
          }
        },
        {
          "bool": {
            "must": [
              {
                "multi_match": {
                  "query": "some_text",
                  "fields": [
                    "firstname^1.0"
                  ]
                }
              },
              {
                "bool": {
                  "should": [
                    {
                      "terms": {
                        "tags": [
                          ""
                        ]
                      }
                    }
                  ]
                }
              }
            ]
          }
        }
      ]
    }
  }
}
</code>```

```<code>GET /posts/_search
{
  "query": {
    "bool": {
      "should": [
        {
          "bool": {
            "must": [
              {
                "multi_match": {
                  "query": "some_text",
                  "fields": [
                    "firstname^1.0"
                  ]
                }
              },
              {
                "bool": {
                  "should": [
                    {
                      "terms": {
                        "tags": [
                          "t2"
                        ]
                      }
                    }
                  ]
                }
              }
            ]
          }
        },
        {
          "bool": {
            "must": [
              {
                "multi_match": {
                  "query": "some_text",
                  "fields": [
                    "firstname^1.0"
                  ]
                }
              },
              {
                "bool": {
                   "must_not": {
                      "exists": {
                          "field": "tags"
                       }
                    }
                 }
              }
            ]
          }
        }
      ]
    }
  }
}
</code>```

答:
Place the null check (nust_not -> exists) inside the should clause along with the terms query for tags.

```<code>{
  "query": {
    "bool": {
      "must": [
        {
          "multi_match": {
            "query": "some_text",
            "fields": [
              "firstname^1.0"
            ]
          }
        }
      ],
      "should": [
        {
          "terms": {
            "tags": [
              "t1",
              "t2",
              ""
            ]
          }
        },
        {
          "bool": {
            "must_not": {
              "exists": {
                "field": "tags"
              }
            }
          }
        }
      ],
      "minimum_should_match": 1
    }
  }
}
</code>```

OR

```<code>{
  "query": {
    "bool": {
      "must": [
        {
          "multi_match": {
            "query": "some_text",
            "fields": [
              "firstname^1.0"
            ]
          }
        },
        {
          "bool": {
            "should": [
              {
                "terms": {
                  "tags": [
                    "t1",
                    "t2",
                    ""
                  ]
                }
              },
              {
                "bool": {
                  "must_not": {
                    "exists": {
                      "field": "tags"
                    }
                  }
                }
              }
            ]
          }
        }
      ]
    }
  }
}
</code>```

Body:
I have data in the mysql database which have been stored into elasticsearch as documents using logstash job.

**Data example in database:**

firstname(text), lastname(text), email(text), tags(text & nullable)

Here, tags conains value as per this in mysql : "t1,t2,t3" or ""

While adding data into elasticsearch, custom analyzer/tokenizer has been applied using ",(comma)".

I need data as per this and need to write the query for this:

firstname = "text", tags = ["t1","t2"]

"Get all records which contain this firstname and tags with either "t1 or t2 or (t1 & t2) or null" (any in which tags are empty)".

I have tried a few queries to get this kind of result but nothing worked.
(It doesn't return records with null tags as well tags with (t1,t2))

GET /posts/_search
{
  "query": {
    "bool": {
      "should": [
        {
          "bool": {
            "must": [
              {
                "multi_match": {
                  "query": "some_text",
                  "fields": [
                    "firstname^1.0"
                  ]
                }
              },
              {
                "bool": {
                  "should": [
                    {
                      "terms": {
                        "tags": [
                          "t2"
                        ]
                      }
                    }
                  ]
                }
              }
            ]
          }
        },
        {
          "bool": {
            "must": [
              {
                "multi_match": {
                  "query": "some_text",
                  "fields": [
                    "firstname^1.0"
                  ]
                }
              },
              {
                "bool": {
                  "should": [
                    {
                      "terms": {
                        "tags": [
                          ""
                        ]
                      }
                    }
                  ]
                }
              }
            ]
          }
        }
      ]
    }
  }
}

GET /posts/_search
{
  "query": {
    "bool": {
      "should": [
        {
          "bool": {
            "must": [
              {
                "multi_match": {
                  "query": "some_text",
                  "fields": [
                    "firstname^1.0"
                  ]
                }
              },
              {
                "bool": {
                  "should": [
                    {
                      "terms": {
                        "tags": [
                          "t2"
                        ]
                      }
                    }
                  ]
                }
              }
            ]
          }
        },
        {
          "bool": {
            "must": [
              {
                "multi_match": {
                  "query": "some_text",
                  "fields": [
                    "firstname^1.0"
                  ]
                }
              },
              {
                "bool": {
                   "must_not": {
                      "exists": {
                          "field": "tags"
                       }
                    }
                 }
              }
            ]
          }
        }
      ]
    }
  }
}

Body:
Place the null check (nust_not -> exists) inside the should clause along with the terms query for tags.

{
  "query": {
    "bool": {
      "must": [
        {
          "multi_match": {
            "query": "some_text",
            "fields": [
              "firstname^1.0"
            ]
          }
        }
      ],
      "should": [
        {
          "terms": {
            "tags": [
              "t1",
              "t2",
              ""
            ]
          }
        },
        {
          "bool": {
            "must_not": {
              "exists": {
                "field": "tags"
              }
            }
          }
        }
      ],
      "minimum_should_match": 1
    }
  }
}

OR

{
  "query": {
    "bool": {
      "must": [
        {
          "multi_match": {
            "query": "some_text",
            "fields": [
              "firstname^1.0"
            ]
          }
        },
        {
          "bool": {
            "should": [
              {
                "terms": {
                  "tags": [
                    "t1",
                    "t2",
                    ""
                  ]
                }
              },
              {
                "bool": {
                  "must_not": {
                    "exists": {
                      "field": "tags"
                    }
                  }
                }
              }
            ]
          }
        }
      ]
    }
  }
}


问:
Eloquent sub query got changed in derived query
I have an Eloquent query where I join some tables together then apply different filters on that query, but after one filter, the original sub query got modified with the first filter in other filter.

this is the original query:

```<code>$circle = DB::table('circles')
            ->joinSub($member, 'member', function ($join) {
                $join->on('circles.id', '=', 'member.circle_id');
            })->joinSub($place, 'place', function ($join) {
                $join->on('circles.place_id', '=', 'place.placeID');
            })->joinSub($dep, 'dep', function ($join) {
                $join->on('department_id', '=', 'depID');
            })->where('use_classification', UseClassificationEnum::USES)
            ->select('id', 'circle_name', 'circle_code', 'department_name', 'place_name', 'numMem', 'leader');
</code>```

then apply different filters

```<code>$current_circle = session('circle.id');
$circle_active = $circle->where('id', $current_circle)->first();
$circle_other = $circle->where('id', '<>', $current_circle)->get();
</code>```

In $circle_other query, the original $circle was included with where('id', $current_circle) so it results nothing.

If I put the $circle_active and $circle_other in reverse order, then the later will result nothing.

I don't want to repeat the query just to apply different filters.
Where did I go wrong? Please help.

答:
Based on my understanding of Laravel Query Builder source from Github.

where() builds a query in the instance of $circle on your $circle_active query hence it's reflected in $circle_other.

What you can do in this situation is to create a helper like this.

public static function buildCircleQuery() {
   return DB::table('circles')
            ->joinSub($member, 'member', function ($join) {
                $join->on('circles.id', '=', 'member.circle_id');
            })->joinSub($place, 'place', function ($join) {
                $join->on('circles.place_id', '=', 'place.placeID');
            })->joinSub($dep, 'dep', function ($join) {
                $join->on('department_id', '=', 'depID');
            })->where('use_classification', UseClassificationEnum::USES)
            ->select('id', 'circle_name', 'circle_code', 'department_name',
    'place_name', 'numMem', 'leader');
}
```

<p>Then you can do this</p>

<pre class="lang-php prettyprint-override"><code>// Note that Helper:: is based on your helper class name
$circle_active = Helper::buildCircleQuery()->where('id', $current_circle)->first();
$circle_other = Helper::buildCircleQuery()->where('id', '<>', $current_circle)->get();
</code>```

Body:
I have an Eloquent query where I join some tables together then apply different filters on that query, but after one filter, the original sub query got modified with the first filter in other filter.

this is the original query:

$circle = DB::table('circles')
            ->joinSub($member, 'member', function ($join) {
                $join->on('circles.id', '=', 'member.circle_id');
            })->joinSub($place, 'place', function ($join) {
                $join->on('circles.place_id', '=', 'place.placeID');
            })->joinSub($dep, 'dep', function ($join) {
                $join->on('department_id', '=', 'depID');
            })->where('use_classification', UseClassificationEnum::USES)
            ->select('id', 'circle_name', 'circle_code', 'department_name', 'place_name', 'numMem', 'leader');

then apply different filters

$current_circle = session('circle.id');
$circle_active = $circle->where('id', $current_circle)->first();
$circle_other = $circle->where('id', '<>', $current_circle)->get();

In $circle_other query, the original $circle was included with where('id', $current_circle) so it results nothing.

If I put the $circle_active and $circle_other in reverse order, then the later will result nothing.

I don't want to repeat the query just to apply different filters.
Where did I go wrong? Please help.

Body:
Based on my understanding of Laravel Query Builder source from Github.

where() builds a query in the instance of $circle on your $circle_active query hence it's reflected in $circle_other.

What you can do in this situation is to create a helper like this.

public static function buildCircleQuery() {
   return DB::table('circles')
            ->joinSub($member, 'member', function ($join) {
                $join->on('circles.id', '=', 'member.circle_id');
            })->joinSub($place, 'place', function ($join) {
                $join->on('circles.place_id', '=', 'place.placeID');
            })->joinSub($dep, 'dep', function ($join) {
                $join->on('department_id', '=', 'depID');
            })->where('use_classification', UseClassificationEnum::USES)
            ->select('id', 'circle_name', 'circle_code', 'department_name',
    'place_name', 'numMem', 'leader');
}

Then you can do this

// Note that Helper:: is based on your helper class name
$circle_active = Helper::buildCircleQuery()->where('id', $current_circle)->first();
$circle_other = Helper::buildCircleQuery()->where('id', '<>', $current_circle)->get();


问:
Generate PDF when clicking on a link
MY PROBLEM STATEMENT IS,

I have a set of links in a webpage,which was created in javascript.

Now what I want is if anybody clicks the link it should go to that
   corresponding page and a pdf file should generate automatically. In
   Ubuntu OS there is an option to generate PDF of any page, but how would I use it
   to generate automatically, if need with some condition also.

答: You have to build your PDF as you build an other page. Try to use TCPDF plugin (http://www.tcpdf.org/).</p>

Title: Generate PDF when clicking on a link


问:
How can I remove this element from the list?
There are total 9 elements which contains the name of drinks. What I need to do is remove any elements that contains "Americano"

However, I am not able to debug my code and it keep shows an error. How can I remove list1's element [0,2,3,6] which contains "Americano"?

```<code>list1 = [ ['3', 'Americano', '7', '14000'], ['4', 'Smoothie_queen', '4', '12000'], ['5', 'Americano', '2', '4000'], ['6', 'Americano', '17', '34000'], ['7', 'Cafe_mocha', '4', '11200'], ['8', 'Cafe_latte', '11', '27500'], ['9', 'Americano', '17', '34000'], ['10', 'Amorparty', '2', '4000'], ['11', 'Plain_yogurt', '13', '45500']]

while True:
        if " Americano" in list1[i]:
            del list1[0]
    if i < x:
        i = i + 1
        continue

    if i >= x:
        break

print(list1)
</code>```

Body:
There are total 9 elements which contains the name of drinks. What I need to do is remove any elements that contains "Americano"

However, I am not able to debug my code and it keep shows an error. How can I remove list1's element [0,2,3,6] which contains "Americano"?

list1 = [ ['3', 'Americano', '7', '14000'], ['4', 'Smoothie_queen', '4', '12000'], ['5', 'Americano', '2', '4000'], ['6', 'Americano', '17', '34000'], ['7', 'Cafe_mocha', '4', '11200'], ['8', 'Cafe_latte', '11', '27500'], ['9', 'Americano', '17', '34000'], ['10', 'Amorparty', '2', '4000'], ['11', 'Plain_yogurt', '13', '45500']]

while True:
        if " Americano" in list1[i]:
            del list1[0]
    if i < x:
        i = i + 1
        continue

    if i >= x:
        break

print(list1)

Body:
using filter function, this will create a new list and make result

list1 = [ ['3', 'Americano', '7', '14000'], ['4', 'Smoothie_queen', '4', '12000'], ['5', 'Americano', '2', '4000'], ['6', 'Americano', '17', '34000'], ['7', 'Cafe_mocha', '4', '11200'], ['8', 'Cafe_latte', '11', '27500'], ['9', 'Americano', '17', '34000'], ['10', 'Amorparty', '2', '4000'], ['11', 'Plain_yogurt', '13', '45500']]
result =list(filter(lambda x: 'Americano' not in x , list1))
print(result)

output

[['4', 'Smoothie_queen', '4', '12000'],
 ['6', 'Americano', '17', '34000'],
 ['7', 'Cafe_mocha', '4', '11200'],
 ['8', 'Cafe_latte', '11', '27500'],
 ['10', 'Amorparty', '2', '4000'],
 ['11', 'Plain_yogurt', '13', '45500']]

using enumerate and list.remove() function, on existing list it modify it
accordingly without creating new list

list1 = [ ['3', 'Americano', '7', '14000'], ['4', 'Smoothie_queen', '4', '12000'], ['5', 'Americano', '2', '4000'], ['6', 'Americano', '17', '34000'], ['7', 'Cafe_mocha', '4', '11200'], ['8', 'Cafe_latte', '11', '27500'], ['9', 'Americano', '17', '34000'], ['10', 'Amorparty', '2', '4000'], ['11', 'Plain_yogurt', '13', '45500']]
for index, value in enumerate(list1):
    if 'Americano' in value:
        list1.remove(value)

print(list1)

output

[['4', 'Smoothie_queen', '4', '12000'],
 ['6', 'Americano', '17', '34000'],
 ['7', 'Cafe_mocha', '4', '11200'],
 ['8', 'Cafe_latte', '11', '27500'],
 ['10', 'Amorparty', '2', '4000'],
 ['11', 'Plain_yogurt', '13', '45500']]


问:
Best practices for managing multiple language code in same repository
Currently, I am working on an application which uses 3 programming languages. Now our company is using Mercurial based version control system.
We expect to go with git base system ( most probably we have to go with Azure
DevOps Repos).

Java : Server application and stand-alone application

C# : windows application

Sencha framework(Ext Js) : web front end

Currently,
we are managing all the code in the same repository because it is easy to manage the versions. We build applications manually(No any build tool).

When we are using git base system(Azure DevOps Repos),
What is the best practice of managing these kinds of situations?

答:
You can keep the monorepo approach.

there are good reasons to do so), considering its content is text-based (code in different language.

The default behavior of a polyrepo is isolation — that’s the whole point.

  The default behavior of a monorepo is shared responsibility and visibility — that’s the whole point

The trade-offs coming with a Git monorepo won't be different than the ones with a Mercurial monorepo.


问:
How to create GPUImage Lookup.png Resource
I use GPUImage Framework to create Filter like this

```<code>GPUImagePicture *sourceImagePic = [[GPUImagePicture alloc] initWithImage:sourceImage];
GPUImagePicture *lookupImageSource = [[GPUImagePicture alloc] initWithImage:[UIImage imageNamed:@"lookup.png"]];

GPUImageLookupFilter *lookupImageFilter = [[GPUImageLookupFilter alloc] init];
[sourceImagePic addTarget:lookupImageFilter];
[lookupImageSource addTarget:lookupImageFilter];

[lookupImageFilter useNextFrameForImageCapture];
[sourceImagePic processImage];
[lookupImageSource processImage];

resultImage = [lookupImageFilter imageFromCurrentFramebufferWithOrientation:UIImageOrientationUp];

return resultImage;
</code>```

i want to know how to create lookupImageSource Resource ? like this

i know i can use photoshop to finish this work, i just want to know can i use another way to export some kind of this picture ?

答:
This is 512x512 image containing information about color lookup.

You have to get original png. It is called neutral-lut.

In photoshop, you should apply your color-change layers to this original neutral-lut image.

I have this one.

But I don't know about image quality reduction during uploading to stackoverflow.

So If you have time, you may find neutral-lut in google.

After apply your color-change layer to this image, you can use this png to GPUImage Lookup Filter.

Happy coding!

Body:
I use GPUImage Framework to create Filter like this

GPUImagePicture *sourceImagePic = [[GPUImagePicture alloc] initWithImage:sourceImage];
GPUImagePicture *lookupImageSource = [[GPUImagePicture alloc] initWithImage:[UIImage imageNamed:@"lookup.png"]];

GPUImageLookupFilter *lookupImageFilter = [[GPUImageLookupFilter alloc] init];
[sourceImagePic addTarget:lookupImageFilter];
[lookupImageSource addTarget:lookupImageFilter];

[lookupImageFilter useNextFrameForImageCapture];
[sourceImagePic processImage];
[lookupImageSource processImage];

resultImage = [lookupImageFilter imageFromCurrentFramebufferWithOrientation:UIImageOrientationUp];

return resultImage;

i want to know how to create lookupImageSource Resource ? like this

i know i can use photoshop to finish this work, i just want to know can i use another way to export some kind of this picture ?


问:
How to loop multiple axvspan shades for recurring events?
I am trying to loop 2 time series, on the same plot, and mark the condition they were collected in as an axvspan block.
The data looks something like this:

```<code>    time    seriesA sereiesB    Condition
0.00    10  2   A
0.12    4   20  A
0.24    14  16  A
0.36    5   16  A
0.48    8   13  A
0.6     5   16  B
0.72    17  3   B
0.84    8   20  B
0.96    3   3   B
1.08    18  20  C
1.20    11  13  C
1.32    8   10  C
1.44    17  11  A
1.56    15  2   A
1.68    1   1   A
1.8     20  2   A
1.92    11  19  B
2.04    8   13  B
2.16    5   8   B
2.28    14  18  B
2.40    7   2   B
2.52    12  5   C
2.64    4   11  C
2.76    1   13  C
2.88    16  9   C
3       14  17  C
</code>```

I would like to look something like this:
shaded time-series example

答:
Here is my attempt. The code is for the data given and may or may not work on other data.

data = """
time,seriesA,seriesB,Condition
0.00 ,   10 , 2  ,A
0.12 ,   4  , 20 ,A
0.24 ,   14 , 16 ,A
0.36 ,   5  , 16 ,A
0.48 ,   8  , 13 ,A
0.6  ,   5  , 16 ,B
0.72 ,   17 , 3  ,B
0.84 ,   8  , 20 ,B
0.96 ,   3  , 3  ,B
1.08 ,   18 , 20 ,C
1.20 ,   11 , 13 ,C
1.32 ,   8  , 10 ,C
1.44 ,   17 , 11 ,A
1.56 ,   15 , 2  ,A
1.68 ,   1  , 1  ,A
1.8  ,   20 , 2  ,A
1.92 ,   11 , 19 ,B
2.04 ,   8  , 13 ,B
2.16 ,   5  , 8  ,B
2.28 ,   14 , 18 ,B
2.40 ,   7  , 2  ,B
2.52 ,   12 , 5  ,C
2.64 ,   4  , 11 ,C
2.76 ,   1  , 13 ,C
2.88 ,   16 , 9  ,C
3    ,   14 , 17 ,C
"""
with open("time_series_with_axspan.txt", "wt") as f:
    f.write(data)

d = pd.read_csv("time_series_with_axspan.txt")

d.plot(x='time', y=['seriesA', 'seriesB'])

ax = plt.gca()

# create spans; is there an easier way of doing this in pandas?
condition = d['Condition']
current_c = condition[0]
spans = [[0, 0]]
for i, c in enumerate(condition):
    if c != current_c:
        # change to i-1 if gap between two conditions is to be left empty
        spans[-1][-1] = i
        spans.append([i, None])
        current_c = c
# assumes that the last condition is not on its own but same as previous
spans[-1][-1] = len(condition)-1

# The following works since are three unique conditions appearing one after
# the other. Any three colors will work for example
# color=cycle(['r', 'g', 'b'])
from itertools import cycle
colors = cycle(plt.rcParams['axes.prop_cycle'].by_key()['color'][-3:])
for span in spans:
    ax.axvspan(d.iloc[span[0], 0], d.iloc[span[1], 0], color=next(colors))
```

Hope this helps.

Body:
I am trying to loop 2 time series, on the same plot, and mark the condition they were collected in as an axvspan block.
The data looks something like this:

    time    seriesA sereiesB    Condition
0.00    10  2   A
0.12    4   20  A
0.24    14  16  A
0.36    5   16  A
0.48    8   13  A
0.6     5   16  B
0.72    17  3   B
0.84    8   20  B
0.96    3   3   B
1.08    18  20  C
1.20    11  13  C
1.32    8   10  C
1.44    17  11  A
1.56    15  2   A
1.68    1   1   A
1.8     20  2   A
1.92    11  19  B
2.04    8   13  B
2.16    5   8   B
2.28    14  18  B
2.40    7   2   B
2.52    12  5   C
2.64    4   11  C
2.76    1   13  C
2.88    16  9   C
3       14  17  C

I would like to look something like this:
shaded time-series example

Body:
Here is my attempt. The code is for the data given and may or may not work on other data.

data = """
time,seriesA,seriesB,Condition
0.00 ,   10 , 2  ,A
0.12 ,   4  , 20 ,A
0.24 ,   14 , 16 ,A
0.36 ,   5  , 16 ,A
0.48 ,   8  , 13 ,A
0.6  ,   5  , 16 ,B
0.72 ,   17 , 3  ,B
0.84 ,   8  , 20 ,B
0.96 ,   3  , 3  ,B
1.08 ,   18 , 20 ,C
1.20 ,   11 , 13 ,C
1.32 ,   8  , 10 ,C
1.44 ,   17 , 11 ,A
1.56 ,   15 , 2  ,A
1.68 ,   1  , 1  ,A
1.8  ,   20 , 2  ,A
1.92 ,   11 , 19 ,B
2.04 ,   8  , 13 ,B
2.16 ,   5  , 8  ,B
2.28 ,   14 , 18 ,B
2.40 ,   7  , 2  ,B
2.52 ,   12 , 5  ,C
2.64 ,   4  , 11 ,C
2.76 ,   1  , 13 ,C
2.88 ,   16 , 9  ,C
3    ,   14 , 17 ,C
"""
with open("time_series_with_axspan.txt", "wt") as f:
    f.write(data)

d = pd.read_csv("time_series_with_axspan.txt")

d.plot(x='time', y=['seriesA', 'seriesB'])

ax = plt.gca()

# create spans; is there an easier way of doing this in pandas?
condition = d['Condition']
current_c = condition[0]
spans = [[0, 0]]
for i, c in enumerate(condition):
    if c != current_c:
        # change to i-1 if gap between two conditions is to be left empty
        spans[-1][-1] = i
        spans.append([i, None])
        current_c = c
# assumes that the last condition is not on its own but same as previous
spans[-1][-1] = len(condition)-1

# The following works since are three unique conditions appearing one after
# the other. Any three colors will work for example
# color=cycle(['r', 'g', 'b'])
from itertools import cycle
colors = cycle(plt.rcParams['axes.prop_cycle'].by_key()['color'][-3:])
for span in spans:
    ax.axvspan(d.iloc[span[0], 0], d.iloc[span[1], 0], color=next(colors))

Hope this helps.


问:
Emails very delayed getting from mandrill to gmail
For the past 4 months we have been seeing large delays when sending emails through mandrill to gmail addresses. Sometimes it takes 15 minutes but other times it can be up to an hour. When i check the mandrill outbound section shortly after the email is sent it shows the email was delivered, but it usually takes a while before it actually shows up in my inbox. We are using this service for welcome emails and password resets so waiting long periods of time isn't acceptable.

It has been very hard to find any information on this issue. Has anyone seen this issue? Any recommendations on what i could do to fix it?

答:
My experience has been that the Google SMTP servers are causing the delay (not Mandrill). Verify this by looking at the original email headers (in gmail, with email opened, in the top right More > Show Original) and pasting the email header into the google Message header analyzer will show you the path your email took and how long it was delayed at each server. This report will also tell you if you DKIM / SPF is invalid.

Why the delay is occurring is still a mystery to me. I suspect however that because the domain I am using to send is new, perhaps the gmail spam filters are grey listing the emails until enough users have opened emails and not clicked the spam button? I don't know.


问:
How do list all applications in Graph Explorer with my Azure free account?
I want to learn Azure directory services, so I created a free Microsoft Azure account to play around with Azure, and then I created a new App registration at portal.azure.com. So I have this registered application in Azure with a Client ID, Tenant ID, and even a Client Secret, because I want to learn API permissions with this app.

Now in the Microsoft Graph Explorer, I want to try using API methods like Get Application and List Applications.

However, if I log in and run the API to list my applications (GET https://graph.microsoft.com/beta/applications), the response has an empty array of applications.

Also if I try to GET the specific app that I registered in AD, I get a 404: Resource Not Found found error.

What am I doing wrong? How can I use the Graph Explorer with my test Azure account so my registered application can be retrieved and edited with Microsoft Graph APIs?

More Details Below

When I run GET https://graph.microsoft.com/beta/applications in Microsoft Graph Explorer, I expect a list of my applications, including the one app I registered in Azure. Instead, here is the response:

```<code>{
    "@odata.context": "https://graph.microsoft.com/beta/$metadata#applications",
    "value": []
}
</code>```

When I run GET https://graph.microsoft.com/beta/applications/{client-id}, with my registered app's client-id, I expect all the details of my registered app, but instead, the response is error 404:

```<code>{
    "error": {
        "code": "ResourceNotFound",
        "message": "Resource not found.",
        "innerError": {
            "request-id": "*****",<--I commented this out
            "date": "2019-05-28T20:17:11"
        }
    }
}
</code>```

If this were a permissions issue, I would expect unauthorized errors instead of "resource not found". I've tried adding Microsoft Graph permissions to my registered App (Directory.Read.All, Directory.ReadWrite.All), but this hasn't helped.

答:
This is nothing to do with Azure free account. If you login in Graph Explorer using outlook account, it will identify this account as a personal account(with tenant outlook.com). That's why you can not find the applications you created in your tenant.

It is recommended to create a new user in your tenant to do the tests.

Here are the steps.

1.Click Azure Active Directory->Users->New User. The username should be something like username@{your tenant name}(XXX.onmicrosoft.com)

2.After the creation, add the roles for this user.

Body:
I want to learn Azure directory services, so I created a free Microsoft Azure account to play around with Azure, and then I created a new App registration at portal.azure.com. So I have this registered application in Azure with a Client ID, Tenant ID, and even a Client Secret, because I want to learn API permissions with this app.

Now in the Microsoft Graph Explorer, I want to try using API methods like Get Application and List Applications.

However, if I log in and run the API to list my applications (GET https://graph.microsoft.com/beta/applications), the response has an empty array of applications.

Also if I try to GET the specific app that I registered in AD, I get a 404: Resource Not Found found error.

What am I doing wrong? How can I use the Graph Explorer with my test Azure account so my registered application can be retrieved and edited with Microsoft Graph APIs?

More Details Below

When I run GET https://graph.microsoft.com/beta/applications in Microsoft Graph Explorer, I expect a list of my applications, including the one app I registered in Azure. Instead, here is the response:

{
    "@odata.context": "https://graph.microsoft.com/beta/$metadata#applications",
    "value": []
}

When I run GET https://graph.microsoft.com/beta/applications/{client-id}, with my registered app's client-id, I expect all the details of my registered app, but instead, the response is error 404:

{
    "error": {
        "code": "ResourceNotFound",
        "message": "Resource not found.",
        "innerError": {
            "request-id": "*****",<--I commented this out
            "date": "2019-05-28T20:17:11"
        }
    }
}

If this were a permissions issue, I would expect unauthorized errors instead of "resource not found". I've tried adding Microsoft Graph permissions to my registered App (Directory.Read.All, Directory.ReadWrite.All), but this hasn't helped.


问:
Flutter GridView.count in Row Layout Error
i'm new in flutter and i want to draw a image grid in a row. i used this example Flutter - Layout a Grid but it show me every time a error

```<code>Widget buildView(){
    return new Container(
      color: Colors.white,
      child:
      new Padding(
        padding: EdgeInsets.all(8.0),
        child: new Column(
          children: <Widget>[
            new Row(
              children: <Widget>[
                Flexible(
                  child: new GridView.count(
                      crossAxisCount: 4,
                      childAspectRatio: 1.0,
                      padding: const EdgeInsets.all(4.0),
                      mainAxisSpacing: 4.0,
                      crossAxisSpacing: 4.0,
                      children: <String>[
                        'https://via.placeholder.com/150',
                        'https://via.placeholder.com/150',
                        'https://via.placeholder.com/150',
                        'https://via.placeholder.com/150',
                        'https://via.placeholder.com/150',
                        'https://via.placeholder.com/150',

                      ].map((String url) {
                        return new GridTile(
                            child: new Image.network(url, fit: BoxFit.cover));
                      }).toList()),
                ),
              ],
            ),
              ],
            ),
          ],
        ),
      ),
    );
  }
</code>```

i becode every time this error "Vertical viewport was given unbounded height"

答:
You don't need to wrap GridView in a Row unless you are trying to divide the row. You can just use GridView.

```<code>new GridView.count(
          crossAxisCount: 4,
          childAspectRatio: 1.0,
          padding: const EdgeInsets.all(4.0),
          mainAxisSpacing: 4.0,
          crossAxisSpacing: 4.0,
          children: <String>[
            'https://via.placeholder.com/150',
            'https://via.placeholder.com/150',
            'https://via.placeholder.com/150',
            'https://via.placeholder.com/150',
            'https://via.placeholder.com/150',
            'https://via.placeholder.com/150',

          ].map((String url) {
            return new GridTile(
                child: new Image.network(url, fit: BoxFit.cover));
          }).toList()),
</code>```

If you really want to wrap it inside a row you need wrap GridView with a container and define a width or wrap in a flexible

```<code>Row(
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          Flexible(
            child: new GridView.count(
                crossAxisCount: 4,
                childAspectRatio: 1.0,
                padding: const EdgeInsets.all(4.0),
                mainAxisSpacing: 4.0,
                crossAxisSpacing: 4.0,
                children: <String>[
                  'https://via.placeholder.com/150',
                  'https://via.placeholder.com/150',
                  'https://via.placeholder.com/150',
                  'https://via.placeholder.com/150',
                  'https://via.placeholder.com/150',
                  'https://via.placeholder.com/150',

                ].map((String url) {
                  return new GridTile(
                      child: new Image.network(url, fit: BoxFit.cover));
                }).toList()),
          ),
        ],
      ),
</code>```

If you get unbounded height error just wrap it with a container or sizedbox and define a height

Body:
i'm new in flutter and i want to draw a image grid in a row. i used this example Flutter - Layout a Grid but it show me every time a error

Widget buildView(){
    return new Container(
      color: Colors.white,
      child:
      new Padding(
        padding: EdgeInsets.all(8.0),
        child: new Column(
          children: <Widget>[
            new Row(
              children: <Widget>[
                Flexible(
                  child: new GridView.count(
                      crossAxisCount: 4,
                      childAspectRatio: 1.0,
                      padding: const EdgeInsets.all(4.0),
                      mainAxisSpacing: 4.0,
                      crossAxisSpacing: 4.0,
                      children: <String>[
                        'https://via.placeholder.com/150',
                        'https://via.placeholder.com/150',
                        'https://via.placeholder.com/150',
                        'https://via.placeholder.com/150',
                        'https://via.placeholder.com/150',
                        'https://via.placeholder.com/150',

                      ].map((String url) {
                        return new GridTile(
                            child: new Image.network(url, fit: BoxFit.cover));
                      }).toList()),
                ),
              ],
            ),
              ],
            ),
          ],
        ),
      ),
    );
  }

i becode every time this error "Vertical viewport was given unbounded height"

Body:
You don't need to wrap GridView in a Row unless you are trying to divide the row. You can just use GridView.

new GridView.count(
          crossAxisCount: 4,
          childAspectRatio: 1.0,
          padding: const EdgeInsets.all(4.0),
          mainAxisSpacing: 4.0,
          crossAxisSpacing: 4.0,
          children: <String>[
            'https://via.placeholder.com/150',
            'https://via.placeholder.com/150',
            'https://via.placeholder.com/150',
            'https://via.placeholder.com/150',
            'https://via.placeholder.com/150',
            'https://via.placeholder.com/150',

          ].map((String url) {
            return new GridTile(
                child: new Image.network(url, fit: BoxFit.cover));
          }).toList()),

If you really want to wrap it inside a row you need wrap GridView with a container and define a width or wrap in a flexible

Row(
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          Flexible(
            child: new GridView.count(
                crossAxisCount: 4,
                childAspectRatio: 1.0,
                padding: const EdgeInsets.all(4.0),
                mainAxisSpacing: 4.0,
                crossAxisSpacing: 4.0,
                children: <String>[
                  'https://via.placeholder.com/150',
                  'https://via.placeholder.com/150',
                  'https://via.placeholder.com/150',
                  'https://via.placeholder.com/150',
                  'https://via.placeholder.com/150',
                  'https://via.placeholder.com/150',

                ].map((String url) {
                  return new GridTile(
                      child: new Image.network(url, fit: BoxFit.cover));
                }).toList()),
          ),
        ],
      ),

If you get unbounded height error just wrap it with a container or sizedbox and define a height


问:
Objective-C retain question
In Xcode I have a UINavigationController on wichh I push a UIViewController.

In that UIViewController I init an UIScrollView.

All good.

However, after switching to another view I log the retain count of the controller and to my surprise it's one instead of zero.

Here's the code:

```<code>scroller = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];

[self.view addSubview:scroller];
</code>```

and:

```<code>- (void)dealloc {
    [super dealloc];

    NSLog(@"retaincount, %d", [scroller retainCount]);  //displays 2

    [scroller release];

    NSLog(@"retaincount, %d", [scroller retainCount]); // displays 1
}
</code>```

I only init it ones and add it to the UIViewControllers view.

Kind regards,

Tom

答:
This is why:

```<code>scroller = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
//retain count = 1

[self.view addSubview:scroller];
//retain count + 1 + 1 = 3

//later the AutoreleasePool decrements the count by 1, resulting in a retain count of 2.
</code>```

Methods beginning with init…
return non-autoreleased instances
with a retain count of 1.

Accessing your
subview via self.view: returnes an autoreleased retained pointer to subview.

Adding a
subview to a view via addSubview: retains the
subview.

Removing a subview from its superview via removeFromSuperview: releases it.

You should not rely on an object's retain count though.

Instead you must take care to level out retain and release calls on an object.

Make sure to read Apple's Memory Management Programming Guide in this matter! (the rules section in particular!)

Title: Objective-C retain question

Body:
In Xcode I have a UINavigationController on wichh I push a UIViewController.

In that UIViewController I init an UIScrollView.

All good.

However, after switching to another view I log the retain count of the controller and to my surprise it's one instead of zero.

Here's the code:

scroller = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];

[self.view addSubview:scroller];

and:

- (void)dealloc {
    [super dealloc];

    NSLog(@"retaincount, %d", [scroller retainCount]);  //displays 2

    [scroller release];

    NSLog(@"retaincount, %d", [scroller retainCount]); // displays 1
}

I only init it ones and add it to the UIViewControllers view.

Kind regards,

Tom

Body:
This is why:

scroller = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
//retain count = 1

[self.view addSubview:scroller];
//retain count + 1 + 1 = 3

//later the AutoreleasePool decrements the count by 1, resulting in a retain count of 2.

Methods beginning with init…
return non-autoreleased instances
with a retain count of 1.

Accessing your
subview via self.view: returnes an autoreleased retained pointer to subview.

Adding a
subview to a view via addSubview: retains the
subview.

Removing a subview from its superview via removeFromSuperview: releases it.

You should not rely on an object's retain count though.

Instead you must take care to level out retain and release calls on an object.

Make sure to read Apple's Memory Management Programming Guide in this matter! (the rules section in particular!)


问:
Find the department block number having maximum number of departments
To find the department block number having maximum number of departments.
I tried with my code but its not working

```<code>  select department_block_number
  from department
  where department_id in (select max(department_id)
  from department
   group by department_block_number);
</code>```

The above code shows output of 2 values

202

303

while the expected output is a single value of

303

Please help

答:
You can use the following to fulfill the requirement:

```<code>SQL> select * from department;

DEPARTMENT_ID DEPARTMENT_BLOCK_NUMBER
------------- -----------------------
            1                     303
            2                     303
            3                     303
            4                     303
            5                     202
            6                     202

    -- Your Query
    SELECT
        DEPARTMENT_BLOCK_NUMBER,
        COUNT(1)
    FROM
        DEPARTMENT
    GROUP BY
        DEPARTMENT_BLOCK_NUMBER
    ORDER BY
        2 DESC NULLS LAST
    FETCH FIRST ROW ONLY;
</code>```

Result of the query:

```<code>DEPARTMENT_BLOCK_NUMBER   COUNT(1)
----------------------- ----------
                    303          4
</code>```

You can remove count column as per your requirement.

Body:
To find the department block number having maximum number of departments.
I tried with my code but its not working

  select department_block_number
  from department
  where department_id in (select max(department_id)
  from department
   group by department_block_number);

The above code shows output of 2 values

202

303

while the expected output is a single value of

303

Please help

Body:
You can use the following to fulfill the requirement:

SQL> select * from department;

DEPARTMENT_ID DEPARTMENT_BLOCK_NUMBER
------------- -----------------------
            1                     303
            2                     303
            3                     303
            4                     303
            5                     202
            6                     202

    -- Your Query
    SELECT
        DEPARTMENT_BLOCK_NUMBER,
        COUNT(1)
    FROM
        DEPARTMENT
    GROUP BY
        DEPARTMENT_BLOCK_NUMBER
    ORDER BY
        2 DESC NULLS LAST
    FETCH FIRST ROW ONLY;

Result of the query:

DEPARTMENT_BLOCK_NUMBER   COUNT(1)
----------------------- ----------
                    303          4

You can remove count column as per your requirement.


问:
How to connect-azaccount in Azure DevOps release pipeline

In the release pipeline, I am trying to connect to Azure AD by using Connect-Azaccount so I can run Get-AzADgroup to retrieve some Az AD group names and their guid and output to variables.

I created Azure Powershell task with the following inline script.

(Get-AzADGroup -DisplayName "group-name").origin

答:
It seems you need to use a non-interactive login, follow the steps as below.

Create an Azure Active Directory application and create a secret for the app, save the secret and get values for signing in.

In your AD App -> API permissions -> Add a permission -> select Azure Active Directory Graph -> Application permissions -> Directory.Read.All -> click Add permissions -> click Grant admin consent for xxx, refer to the screenshot.

Try the script as below, use the values which you get in step 1,  it works fine on my side.

Note: You need to use the Task version with 4.*(preview) when you use Az powershell module.

```<code>$azureAplicationId ="<your ad app application id>"
$azureTenantId= "<your tenant id>"
$azurePassword = ConvertTo-SecureString "<the secret of your ad app>" -AsPlainText -Force
$psCred = New-Object System.Management.Automation.PSCredential($azureAplicationId , $azurePassword)
Connect-AzAccount -Credential $psCred -TenantId $azureTenantId  -ServicePrincipal
#I just test to get all groups, you could do other operations
Get-AzADGroup
</code>```

Body:
It seems you need to use a non-interactive login, follow the steps as below.

Create an Azure Active Directory application and create a secret for the app, save the secret and get values for signing in.

In your AD App -> API permissions -> Add a permission -> select Azure Active Directory Graph -> Application permissions -> Directory.Read.All -> click Add permissions -> click Grant admin consent for xxx, refer to the screenshot.

Try the script as below, use the values which you get in step 1,  it works fine on my side.

Note: You need to use the Task version with 4.*(preview) when you use Az powershell module.

$azureAplicationId ="<your ad app application id>"
$azureTenantId= "<your tenant id>"
$azurePassword = ConvertTo-SecureString "<the secret of your ad app>" -AsPlainText -Force
$psCred = New-Object System.Management.Automation.PSCredential($azureAplicationId , $azurePassword)
Connect-AzAccount -Credential $psCred -TenantId $azureTenantId  -ServicePrincipal
#I just test to get all groups, you could do other operations
Get-AzADGroup


问:
How to verify token of ldap user in enterprise hashicorp vault
I am trying to lookup token from hashicorp vault (enterprise version ). its giving me permission denied error on linux terminal. I want to check if token is still valid or not. Could you please provide way for it.</p>

```<code>[shell prompt]$ vault token lookup -tls-skip-verify <Vault_Token>
Error looking up token: Error making API request.

URL: POST https://vault.prod.use1.crypto.aws.efx/v1/auth/token/lookup
Code: 403. Errors:

* permission denied
</code>```

答:
The token with which you are authenticating (likely at ~/.vault-token on disk) doesn't have permission to lookup tokens.

Try doing this instead:

```<code>$ VAULT_TOKEN=<Vault_Token> vault token lookup
</code>```

If that also fails, it means the token does not have permission to read information about itself (it's missing the default policy), or it has expired/been deleted.

Body:
I am trying to lookup token from hashicorp vault (enterprise version ). its giving me permission denied error on linux terminal. I want to check if token is still valid or not. Could you please provide way for it.

[shell prompt]$ vault token lookup -tls-skip-verify <Vault_Token>
Error looking up token: Error making API request.

URL: POST https://vault.prod.use1.crypto.aws.efx/v1/auth/token/lookup
Code: 403. Errors:

* permission denied

Body:
The token with which you are authenticating (likely at ~/.vault-token on disk) doesn't have permission to lookup tokens.

Try doing this instead:

$ VAULT_TOKEN=<Vault_Token> vault token lookup

If that also fails, it means the token does not have permission to read information about itself (it's missing the default policy), or it has expired/been deleted.


问:
RegEx for passing punctuation
I am using:

```<code>(.*) CO\s?[\(.*\)|\[.*\]|\{.*\}|''.*''|".*"](.*)
</code>```

to represent

```<code>3M CO 'A'(MINNESOTA MINING AND MANUFACTURING COMPANY).
</code>```

However, the first Single quotation mark cannot be covered by the regex code. Could you please tell me why?

```<code>s/(.*) CO\s?[\(.*\)|\[.*\]|\{.*\}|''.*''|".*"](.*)/$1 CO $2
</code>```

I expect to get:

```<code>3M CO 'A'(MINNESOTA MINING AND MANUFACTURING COMPANY)
</code>```

but I get

```<code>3M CO A'(MINNESOTA MINING AND MANUFACTURING COMPANY)
</code>```

答:
I'm guessing that here we wish to design an expression and match our inputs, part by part, such as:

```<code>(.+?)\s+CO\s+(['"].+?['"])([(\[{]).+?([)\]}])
</code>```

We have added extra boundaries, which can be reduced, if not desired.

We are having three main capturing groups:

```<code>(.+?) # anything before Co;
(['"].+?['"]) # the quotation part; and
([(\[{]).+?([)\]}]) # inside various brackets included those, which we can escape, if required.
</code>```

RegEx Circuit

jex.im visualizes regular expressions:

DEMO

Demo

This snippet just shows that how the capturing groups work:

const regex = /(.+?)\s+CO\s+(['"].+?['"])([(\[{]).+?([)\]}])/mg;
const str = `3M CO 'A'(MINNESOTA MINING AND MANUFACTURING COMPANY)
3M CO 'A'[MINNESOTA MINING AND MANUFACTURING COMPANY]
3M CO 'A'{MINNESOTA MINING AND MANUFACTURING COMPANY}
3M CO "A"{MINNESOTA MINING AND MANUFACTURING COMPANY}`;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }

    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}```

RegEx

If this expression wasn't desired, it can be modified/changed in regex101.com.

Title: RegEx for passing punctuation

Body:
I am using:

(.*) CO\s?[\(.*\)|\[.*\]|\{.*\}|''.*''|".*"](.*)

to represent

3M CO 'A'(MINNESOTA MINING AND MANUFACTURING COMPANY).

However, the first Single quotation mark cannot be covered by the regex code. Could you please tell me why?

s/(.*) CO\s?[\(.*\)|\[.*\]|\{.*\}|''.*''|".*"](.*)/$1 CO $2

I expect to get:

3M CO 'A'(MINNESOTA MINING AND MANUFACTURING COMPANY)

but I get

3M CO A'(MINNESOTA MINING AND MANUFACTURING COMPANY)

Body:
I'm guessing that here we wish to design an expression and match our inputs, part by part, such as:

(.+?)\s+CO\s+(['"].+?['"])([(\[{]).+?([)\]}])

We have added extra boundaries, which can be reduced, if not desired.

We are having three main capturing groups:

(.+?) # anything before Co;
(['"].+?['"]) # the quotation part; and
([(\[{]).+?([)\]}]) # inside various brackets included those, which we can escape, if required.

RegEx Circuit

jex.im visualizes regular expressions:

DEMO

Demo

This snippet just shows that how the capturing groups work:

const regex = /(.+?)\s+CO\s+(['"].+?['"])([(\[{]).+?([)\]}])/mg;
const str = `3M CO 'A'(MINNESOTA MINING AND MANUFACTURING COMPANY)
3M CO 'A'[MINNESOTA MINING AND MANUFACTURING COMPANY]
3M CO 'A'{MINNESOTA MINING AND MANUFACTURING COMPANY}
3M CO "A"{MINNESOTA MINING AND MANUFACTURING COMPANY}`;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }

    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}

RegEx

If this expression wasn't desired, it can be modified/changed in regex101.com.


问:
Package is accessible from more than one module in JDK 11 Module system
We are making use of Zulu JDK 11 and we are facing issue The package com.sample.test is accessible from more than one module: test1.module, test2.sample.

Below is the git url for sample project and screenshot for your reference.

https://github.com/kkvaranasi88/test1.git

答:
A simple solution is to rename the package in your second module tes-2 to say com.sample.another.test and then update your module description to

```<code>module test2.sample {
    exports com.sample.another.test;
    requires transitive test1.module;
}
</code>```

and things shall work fine.

Having said that, the cause for failure is that no two modules should export the same package such that they are both resolved in the module layer as s conflict.

Body:
A simple solution is to rename the package in your second module tes-2 to say com.sample.another.test and then update your module description to

module test2.sample {
    exports com.sample.another.test;
    requires transitive test1.module;
}

and things shall work fine.

Having said that, the cause for failure is that no two modules should export the same package such that they are both resolved in the module layer as s conflict.