问:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException at gui.PassengerGui$2.actionPerformed(PassengerGui.java:139)
having problems with the code mentioned below. the eclipse error code is as follows ::

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at gui.PassengerGui$2.actionPerformed(PassengerGui.java:139)

Any recommendations would be very much appreciated? I have have been pulling my hair out for almost one hour trying to figure out what the problem is..

```<code>private JPanel contentPane;
private JFileChooser fileChooser;
private PassengerController controller;
private PassengerTabelPanel tabelPanel;
private JTextField nameField;
private JTextField cityField;
private JTable passengerTable;
private JRadioButton  standardRadio;
private JRadioButton businessRadio;
private ButtonGroup classGroup;
private PassengerFormListener formListener;

/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                PassengerGui frame = new PassengerGui();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the frame.
 */
public PassengerGui() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 584, 368);

    JMenuBar menuBar = new JMenuBar();
    setJMenuBar(menuBar);

    JMenuItem importDataItem = new JMenuItem("Import Data");
    menuBar.add(importDataItem);

    JMenuItem exportDataItem = new JMenuItem("Export Data");
    menuBar.add(exportDataItem);

    fileChooser = new JFileChooser();
    fileChooser.addChoosableFileFilter(new PassengerFileFilter());
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(null);

    classGroup = new ButtonGroup();

    //set up class radio

            classGroup.add(standardRadio);
            classGroup.add(businessRadio);

    JLabel nameLabel = new JLabel("Name: ");
    nameLabel.setFont(new Font("Tahoma", Font.PLAIN, 14));
    nameLabel.setBounds(12, 11, 69, 31);
    contentPane.add(nameLabel);

    JLabel cityLabel = new JLabel("City: ");
    cityLabel.setFont(new Font("Tahoma", Font.PLAIN, 14));
    cityLabel.setBounds(12, 47, 69, 31);
    contentPane.add(cityLabel);

    JLabel lblNewLabel_2 = new JLabel("Class: ");
    lblNewLabel_2.setFont(new Font("Tahoma", Font.PLAIN, 14));
    lblNewLabel_2.setBounds(12, 89, 69, 31);
    contentPane.add(lblNewLabel_2);

    nameField = new JTextField();
    nameField.setBounds(60, 18, 129, 20);
    contentPane.add(nameField);
    nameField.setColumns(10);

    cityField = new JTextField();
    cityField.setColumns(10);
    cityField.setBounds(60, 53, 129, 20);
    contentPane.add(cityField);

    JRadioButton businessRadio = new JRadioButton("Business");
    businessRadio.setBounds(58, 95, 109, 23);
    contentPane.add(businessRadio);

    JRadioButton standardRadio = new JRadioButton("Standard");
    standardRadio.setBounds(60, 127, 109, 23);
    contentPane.add(standardRadio);

    JButton btnSubmit = new JButton("Submit");
    btnSubmit.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            String name = nameField.getText();
            String city = cityField.getText();
            String passengerClass = classGroup.getSelection().getActionCommand();

            PassengerFormEvent ev = new PassengerFormEvent(this, name, passengerClass, city);
</code>```

答:
You aren't instantiating ButtonGroup variable classGroup. You are using dot (.) operator on a null reference.

Do this:

```<code>ButtonGroup classGroup = new ButtonGroup();
</code>```

and Somewhere in your code after this instantiation, do this:

```<code>String passengerClass = classGroup.getSelection().getActionCommand();
</code>```

Body:
having problems with the code mentioned below. the eclipse error code is as follows ::

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at gui.PassengerGui$2.actionPerformed(PassengerGui.java:139)

Any recommendations would be very much appreciated? I have have been pulling my hair out for almost one hour trying to figure out what the problem is..

private JPanel contentPane;
private JFileChooser fileChooser;
private PassengerController controller;
private PassengerTabelPanel tabelPanel;
private JTextField nameField;
private JTextField cityField;
private JTable passengerTable;
private JRadioButton  standardRadio;
private JRadioButton businessRadio;
private ButtonGroup classGroup;
private PassengerFormListener formListener;

/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                PassengerGui frame = new PassengerGui();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the frame.
 */
public PassengerGui() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 584, 368);

    JMenuBar menuBar = new JMenuBar();
    setJMenuBar(menuBar);

    JMenuItem importDataItem = new JMenuItem("Import Data");
    menuBar.add(importDataItem);

    JMenuItem exportDataItem = new JMenuItem("Export Data");
    menuBar.add(exportDataItem);

    fileChooser = new JFileChooser();
    fileChooser.addChoosableFileFilter(new PassengerFileFilter());
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(null);

    classGroup = new ButtonGroup();

    //set up class radio

            classGroup.add(standardRadio);
            classGroup.add(businessRadio);

    JLabel nameLabel = new JLabel("Name: ");
    nameLabel.setFont(new Font("Tahoma", Font.PLAIN, 14));
    nameLabel.setBounds(12, 11, 69, 31);
    contentPane.add(nameLabel);

    JLabel cityLabel = new JLabel("City: ");
    cityLabel.setFont(new Font("Tahoma", Font.PLAIN, 14));
    cityLabel.setBounds(12, 47, 69, 31);
    contentPane.add(cityLabel);

    JLabel lblNewLabel_2 = new JLabel("Class: ");
    lblNewLabel_2.setFont(new Font("Tahoma", Font.PLAIN, 14));
    lblNewLabel_2.setBounds(12, 89, 69, 31);
    contentPane.add(lblNewLabel_2);

    nameField = new JTextField();
    nameField.setBounds(60, 18, 129, 20);
    contentPane.add(nameField);
    nameField.setColumns(10);

    cityField = new JTextField();
    cityField.setColumns(10);
    cityField.setBounds(60, 53, 129, 20);
    contentPane.add(cityField);

    JRadioButton businessRadio = new JRadioButton("Business");
    businessRadio.setBounds(58, 95, 109, 23);
    contentPane.add(businessRadio);

    JRadioButton standardRadio = new JRadioButton("Standard");
    standardRadio.setBounds(60, 127, 109, 23);
    contentPane.add(standardRadio);

    JButton btnSubmit = new JButton("Submit");
    btnSubmit.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            String name = nameField.getText();
            String city = cityField.getText();
            String passengerClass = classGroup.getSelection().getActionCommand();

            PassengerFormEvent ev = new PassengerFormEvent(this, name, passengerClass, city);

Body:
You aren't instantiating ButtonGroup variable classGroup. You are using dot (.) operator on a null reference.

Do this:

ButtonGroup classGroup = new ButtonGroup();

and Somewhere in your code after this instantiation, do this:

String passengerClass = classGroup.getSelection().getActionCommand();


来源: stackexchange

问:
Invalid syntax occurring in my python code
So, I've been working on a code, but I ran into a problem. I would get an invalid syntax. How can I fix this?

```<code>print ("Ok, type away")
    number1 = input("Input the first number \n")
    symbol = input("Input your desired operation (+,-,*,/) \n")
    number2 = input("Input the second number \n")
    if symbol == "+":
        output = (int(number1) + int(number2))
    elif symbol == "-":
        output = (int(number1) - int(number2))
    elif symbol == "*":
        output = (int(number1) * int(number2))
    elif symbol == "/":
        output = (int(number1) / int(number2))

    else:
        print ("Something went wrong, ty again")
        number1 = input("Input the first number \n")
        symbol = input("Input your desired operation (+,-,*,/) \n")
        number2 = input("Input the second number \n")
        if symbol == "+":
            output = (int(number1) + int(number2))
        elif symbol == "-":
            output = (int(number1) - int(number2))
        elif symbol == "*":
            output = (int(number1) * int(number2))
        elif symbol == "/":
            output = (int(number1) / int(number2))
    print ("I'm thinking, Please be Patient")
    time.sleep ((random.randint(2,9))

    print ((output))
</code>```

Note: it's the last print.

答: The line before the last print has unbalanced parentheses.

ContentLicense: CC BY-SA 3.0

Body:
So, I've been working on a code, but I ran into a problem. I would get an invalid syntax. How can I fix this?

print ("Ok, type away")
    number1 = input("Input the first number \n")
    symbol = input("Input your desired operation (+,-,*,/) \n")
    number2 = input("Input the second number \n")
    if symbol == "+":
        output = (int(number1) + int(number2))
    elif symbol == "-":
        output = (int(number1) - int(number2))
    elif symbol == "*":
        output = (int(number1) * int(number2))
    elif symbol == "/":
        output = (int(number1) / int(number2))

    else:
        print ("Something went wrong, ty again")
        number1 = input("Input the first number \n")
        symbol = input("Input your desired operation (+,-,*,/) \n")
        number2 = input("Input the second number \n")
        if symbol == "+":
            output = (int(number1) + int(number2))
        elif symbol == "-":
            output = (int(number1) - int(number2))
        elif symbol == "*":
            output = (int(number1) * int(number2))
        elif symbol == "/":
            output = (int(number1) / int(number2))
    print ("I'm thinking, Please be Patient")
    time.sleep ((random.randint(2,9))

    print ((output))

Note: it's the last print.


问:
Difference in including the .cpp file and .h file (with the same content in cpp)?
I've recently started learning cpp from basics and was very much confused with the folowing:

Lets say I have a header( test.h which contains only declarations) with some content and some source file (source.cpp) and program produced some result.

If I have copied the same content of that header file to a .cpp file (testcpp.cpp) and included this in source.cpp

In this case, I did not understood what difference it makes?

(I'll not include this testcpp.cpp in make file)

I have seen some threads similar to this but couldn't get a clear idea!!!

I learnt the usage of header and cpp files and have used it correctly in projects till now, Please answer specific to this scenario (I know doing this way adds confusion but just want to know). Will there be any difference doing so or it's just a common practice everyone follows ?

答:
what difference it makes?

The extension of a header file has no effect on anything. You could have just as well named the file test.mpg, .test or just test (changing the include directive obviously), and it would have worked just as well. The extension is for the benefit of the programmer, not the toolchain.

However, it is a bad idea to name it anything other than .h, .hpp or whatever is your convention. If you name it .mpg, people will think that it is a video, and not realising that it is a header file, try to play it in a media player. If you name it .cpp, people will think that it is a source file and may attempt to compile it or maybe add definitions into it.

Including a file with the preprocessor is technically just copying contents of one file into another. Nothing more and nothing less. Everything else about them is just convention.

In makefile, when specifying source file, Can I give my source files with any extension(.fsfs, .xxx) rather than .cpp extension

Technically yes, however compilers usually use the source file extension to detect the language which they will fail to do in this case, so you would have to specify it explicitly.


问:
Twitter Embedded Timeline Background Colour
Using the following twitter embed method (https://dev.twitter.com/web/embedded-timelines) specifically using the grid layout, is there a way to control background colour?

The issue in context: http://bitly.com/2aFUuhj

The style I would love to update is within a class "GridLayoutTextOnlyTweet" but this is inside an iFrame.

答:
a.twitter-timeline {
  /* Buttonish */
  display: inline-block;
  padding: 6px 12px 6px 30px;
  margin: 10px 0;
  border: #ccc solid 1px;
  border-radius: 3px;
  background: #f8f8f8 url("") 8px 8px no-repeat;
  background-size: 1em 1em;

  /* Text */
  font: normal 12px/18px Helvetica, Arial, sans-serif;
  color: #333;
  white-space: nowrap;
}```

Reference : https://dev.twitter.com/web/overview/css

Body:
a.twitter-timeline {
  /* Buttonish */
  display: inline-block;
  padding: 6px 12px 6px 30px;
  margin: 10px 0;
  border: #ccc solid 1px;
  border-radius: 3px;
  background: #f8f8f8 url("") 8px 8px no-repeat;
  background-size: 1em 1em;

  /* Text */
  font: normal 12px/18px Helvetica, Arial, sans-serif;
  color: #333;
  white-space: nowrap;
}

Reference : https://dev.twitter.com/web/overview/css


问:
How to Perform Aggregate on Each Data Frame at once in R?
I have thousands of .csv files consists of year and HS information which looks like this:

```<code>Year  HS
1956  1.06
1956  1.07
....
2012  0.95
</code>```

Each csv file represent different location.
What I should be doing are:

Found Maximum HS for each Year on each file

Create thousands separate .csv files which hold information of point 1

So, basically I am repeating a same task for each file.

However, after input all files to data frame with name df1,df2,df3..., I am stuck to perform aggregate for each data frame (unable to looping through data frame). I don't know how to 'call' the data frames:

```<code>    temp = list.files(pattern="*.csv")
for (i in 1:length(temp)) {
  assign(paste0("df",i),
         read.table(temp[i],header=TRUE,sep=";"))
}
for (i in 1:length(temp))
{
  assign(paste0("ag",i),
         aggregate(HS~Year,data=df(i),max))
}
</code>```

I use those script and it show:

```<code>Error in df[i] : object of type 'closure' is not subsettable
</code>```

Then I change to:

```<code>temp = list.files(pattern="*.csv")
for (i in 1:length(temp)) {
  assign(paste0("df",i),
         read.table(temp[i],header=TRUE,sep=";"))
}
for (i in 1:length(temp))
{
  assign(paste0("ag",i),
         aggregate(HS~Year,data=df(i),max))
}
</code>```

And it show:

```<code>Error in df(i) : argument "df1" is missing, with no default
</code>```

I try to work with data list (although I haven't really understand) and write this script:

```<code>    temp = list.files(pattern="*.csv")
for (i in 1:length(temp)) {
  assign(paste0("df",i),
         read.table(temp[i],header=TRUE,sep=";"))
}
dfl=mget(ls(pattern="df[1-length(temp)]"))
for (i in 1:length(dfl)){
       assign(paste0("ag",i),
              aggregate(HS~Year,data=dfl[i],max))
}
</code>```

But it doesn't work and show:

```<code>  Error in eval(predvars, data, env) : object 'HS' not found
</code>```

I don't think that there is any problem with input since it's work when I perform aggregate and write.csv to single dataframe (without looping).
Is there any suggestion for this problem?

Thank you.

Anyway, I am new in R. Like... literally new, less than 30 hours hahaha. So, I realize that I may be writing inefficient script. I will be glad if there is anyone who also want to suggest better script.

答:
Get the file names, files, read them in giving a list of data frames, L, and apply aggregate to each one. Ag will be a list of the aggregated data frames.

```<code>files <- Sys.glob("*.csv")
L <- lapply(files, read.table, header = TRUE, sep = ";")
Ag <- lapply(L, aggregate, formula = HS ~ Year, FUN = max)
</code>```

or if you don't need or can't afford to store L conbine the last two lines into:

```<code>Ag <- lapply(files,
 function(f) aggregate(HS ~ Year, read.table(f, header = TRUE, sep = ";"), max))
</code>```

Body:
I have thousands of .csv files consists of year and HS information which looks like this:

Year  HS
1956  1.06
1956  1.07
....
2012  0.95

Each csv file represent different location.
What I should be doing are:

Found Maximum HS for each Year on each file

Create thousands separate .csv files which hold information of point 1

So, basically I am repeating a same task for each file.

However, after input all files to data frame with name df1,df2,df3..., I am stuck to perform aggregate for each data frame (unable to looping through data frame). I don't know how to 'call' the data frames:

    temp = list.files(pattern="*.csv")
for (i in 1:length(temp)) {
  assign(paste0("df",i),
         read.table(temp[i],header=TRUE,sep=";"))
}
for (i in 1:length(temp))
{
  assign(paste0("ag",i),
         aggregate(HS~Year,data=df(i),max))
}

I use those script and it show:

Error in df[i] : object of type 'closure' is not subsettable

Then I change to:

temp = list.files(pattern="*.csv")
for (i in 1:length(temp)) {
  assign(paste0("df",i),
         read.table(temp[i],header=TRUE,sep=";"))
}
for (i in 1:length(temp))
{
  assign(paste0("ag",i),
         aggregate(HS~Year,data=df(i),max))
}

And it show:

Error in df(i) : argument "df1" is missing, with no default

I try to work with data list (although I haven't really understand) and write this script:

    temp = list.files(pattern="*.csv")
for (i in 1:length(temp)) {
  assign(paste0("df",i),
         read.table(temp[i],header=TRUE,sep=";"))
}
dfl=mget(ls(pattern="df[1-length(temp)]"))
for (i in 1:length(dfl)){
       assign(paste0("ag",i),
              aggregate(HS~Year,data=dfl[i],max))
}

But it doesn't work and show:

  Error in eval(predvars, data, env) : object 'HS' not found

I don't think that there is any problem with input since it's work when I perform aggregate and write.csv to single dataframe (without looping).
Is there any suggestion for this problem?

Thank you.

Anyway, I am new in R. Like... literally new, less than 30 hours hahaha. So, I realize that I may be writing inefficient script. I will be glad if there is anyone who also want to suggest better script.

Body:
Get the file names, files, read them in giving a list of data frames, L, and apply aggregate to each one. Ag will be a list of the aggregated data frames.

files <- Sys.glob("*.csv")
L <- lapply(files, read.table, header = TRUE, sep = ";")
Ag <- lapply(L, aggregate, formula = HS ~ Year, FUN = max)

or if you don't need or can't afford to store L conbine the last two lines into:

Ag <- lapply(files,
 function(f) aggregate(HS ~ Year, read.table(f, header = TRUE, sep = ";"), max))


问:
Hosting Angular SPA on AWS S3 with Authentication Redirects
Our SPA is written in Angular (ie Angular2, Angular4. Not AngularJS) and authenticates using OAuth2 against Azure AD.  We are using an OIDC library to handle the authentication.

The application is hosted in an AWS S3 bucket configured to serve a static website.  For argument's sake, let's pretend the URL is myapp.example.com.

When the user clicks the login button, they are redirected to a microsoft page to handle the authentication. So far, so good.  Once they have authenticated, they are redirected back to myapp.example.com/login.

However there is no artifact in my S3 bucket named login.  The login route is handled by the Angular router, and calls a component within my app.  This all works fine in development when I'm running on my local machine.  But when I run the version hosted in S3, redirection back to myapp.example.com/login fails with a 404 error.

I understand the reason for the error - there isn't an artifact named login in my S3 bucket.  But I imagine this would be a problem for just about any link in my app.  For example, if I shared a link to myapp.example.com/objects/1234 with another user, I imagine that would 404 for them, too.

So the question is, what do I need to do to properly host this SPA in AWS so that redirection and other links work properly?

答:
Configure AWS CloudFront in front of S3 and do the domain mapping for CloudFront(With CNAME). Then using AWS Edge Lambda, you can rewrite the URL for /login to direct to the index.html.

This will load the index.html also for the /login path and trigger the route in Angular from client side, after redirection happens.


问:
Avoiding email filters with legitimate use of spoofing
I have a web application that will be used by committee chairs to communicate with committee members over email.  All these users will have e-mail accounts external to the web application and domain the web application is hosted on.  Any replies from members need to be directed to the e-mail of the committee chair user, not an account on the domain of the web application.  The only two methods of accomplishing this that I've come up with are

In the from of the e-mail, use the e-mail of the sending user.  E-mail applications for many of the committee members block this as spam.

Use an account such as no-reply@applicationdomain.com, and then include instructions in the e-mail of the correct address that replies should be sent to.  Users often get confused and don't send replies to the correct address.

Are there any alternatives I am missing?

答:
Traditionally, this was the purpose of the Sender email header. If you want an email to be From the user, but sent by you, you would just set the Sender header to an email address on your domain but have From be the user. Also, the SMTP envelope sender should also be on your domain. Then, you would be properly declaring that you're the sender of the message for anti-spam purposes, you'll receive any bounce messages, but email clients will know that the email is reportedly from the "real" user, and will direct replies accordingly. Generally, email clients would report both Sender and From, saying something like "From my-server@website.example.net on behalf of real-user@example.com", though obviously the details depend on the email client being used.

Refer to What's the difference between Sender, From and Return-Path? and OpenSPF Web Generated Email Best Practices for more information.

However, now DMARC has come along. It has made the decision that verification should be based only on the From header. The theory is that there's no way for an end-user to know whether a particular Sender is in fact authorized to send mail "on behalf of" the user listed in the From header. While it probably isn't the decision I would have made due to how it ignores the traditional Sender, it's something that needs to be dealt with now, as if the domain of the user listed in the From has a DMARC record that is set to q=reject, then nobody else, including your web form that's trying to send mail with the complete approval of the user, can send mail that's From that domain. More and more domains are turning on DMARC, and as they do so your form won't be able to send email From them, regardless of what other headers are set.

The only other alternative, then, is to have email be From your application entirely, but set the Reply-To header to where the email program should send replies to. Also, the SMTP envelope sender should be your application, and ideally be set to an address that can handle bounce messages or other errors. You shouldn't need to include any instructions, as the Reply-To header is very well supported among email clients as indicating where replies should be directed.

Refer to the DMARC FAQ entry "Why are messages I send on behalf of visitors to my website being blocked?".


问:
C3js Chart - JSON Group Data
I am having troubles to configure C3Chartjs, hope someone can help me.

Here my JSON (data got from user input):

```<code>  obc: [
    { takt: 90, oee: 80, processId: 'Operation 1', processName: 'Cortar', lowRepCycle: 65 },
    { takt: 90, oee: 80, processId: 'Operation 1', processName: 'Dobrar', lowRepCycle: 35 },
    { takt: 90, oee: 80, processId: 'Operation 2', processName: 'Dobrar', lowRepCycle: 65 },
    { takt: 90, oee: 80, processId: 'Operation 2', processName: 'Dobrar', lowRepCycle: 35 }
  ]
</code>```

And this is my C3 config:

```<code>  c3.generate({
    bindto: '#chart',
    data: {
      json: this.obc,
      keys: {
        value: ['lowRepCycle', 'takt', 'oee']
      },
      type: 'bar',
      types: {
        takt: 'line',
        oee: 'line'
      },
      groups: [
        ['processId']
      ]
    }
  })
</code>```

And this is the result of this code:

Actual Result

The problem is that  need data in groups of Operations, like this:

The Result I expect

If someone prefers to see the app in "production", you can access in:

//jsfiddle.net/theuzz1/3pa07ah8/

matheus-lean.herokuapp.com/#/obc

Just click in add Operator and see the graph

答:
This won't work because you can't group values. You can only group columns, e.g. 'takt' and 'oee', then both will stack instead of shown seperately.

To get the desired outcome you have to manipulate your json. Every entry would be an operation with a certain amount of tasks. Then you can goup the tasks.

It would look something like this (fiddle):

```<code> var obc = [
    { takt: 90, oee: 80, processId: 'Operation_1', processName: 'Cortar', task_1: 65, task_2: 35 },
    { takt: 90, oee: 80, processId: 'Operation_2', processName: 'Dobrar', task_1: 65, task_2: 35 }
  ]

var chart =  c3.generate({
    data: {
      json: obc,
      keys: {
        value: ['task_1','task_2','takt', 'oee']
      },
      type: 'bar',
      types: {
        takt: 'line',
        oee: 'line'
      },
      groups: [
        ['task_1', 'task_2']
      ]
    }
  })
</code>```

Title: C3js Chart - JSON Group Data

Body:
I am having troubles to configure C3Chartjs, hope someone can help me.

Here my JSON (data got from user input):

  obc: [
    { takt: 90, oee: 80, processId: 'Operation 1', processName: 'Cortar', lowRepCycle: 65 },
    { takt: 90, oee: 80, processId: 'Operation 1', processName: 'Dobrar', lowRepCycle: 35 },
    { takt: 90, oee: 80, processId: 'Operation 2', processName: 'Dobrar', lowRepCycle: 65 },
    { takt: 90, oee: 80, processId: 'Operation 2', processName: 'Dobrar', lowRepCycle: 35 }
  ]

And this is my C3 config:

  c3.generate({
    bindto: '#chart',
    data: {
      json: this.obc,
      keys: {
        value: ['lowRepCycle', 'takt', 'oee']
      },
      type: 'bar',
      types: {
        takt: 'line',
        oee: 'line'
      },
      groups: [
        ['processId']
      ]
    }
  })

And this is the result of this code:

Actual Result

The problem is that  need data in groups of Operations, like this:

The Result I expect

If someone prefers to see the app in "production", you can access in:

//jsfiddle.net/theuzz1/3pa07ah8/

matheus-lean.herokuapp.com/#/obc

Just click in add Operator and see the graph

Body:
This won't work because you can't group values. You can only group columns, e.g. 'takt' and 'oee', then both will stack instead of shown seperately.

To get the desired outcome you have to manipulate your json. Every entry would be an operation with a certain amount of tasks. Then you can goup the tasks.

It would look something like this (fiddle):

 var obc = [
    { takt: 90, oee: 80, processId: 'Operation_1', processName: 'Cortar', task_1: 65, task_2: 35 },
    { takt: 90, oee: 80, processId: 'Operation_2', processName: 'Dobrar', task_1: 65, task_2: 35 }
  ]

var chart =  c3.generate({
    data: {
      json: obc,
      keys: {
        value: ['task_1','task_2','takt', 'oee']
      },
      type: 'bar',
      types: {
        takt: 'line',
        oee: 'line'
      },
      groups: [
        ['task_1', 'task_2']
      ]
    }
  })


问:
Maven dependency aliasing
I've just noted that my war contains both woodstox-core-asl-4.4.1.jar and woodstox-core-5.0.2.jar.  They are two different version of the same library, but the library changed both groupId and artifactId.  Furthermore both are included in my war as transitive dependencies by two different modules of my project.

I know that I can use exclusions to remove the old version of the library but in this case I should also explicitly "include" the new version in case that module would be used alone (that is not with the other one that includes woodstox-core-5.0.2.jar).

I don't like this solution.  Is there any way to declare that woodstox-core is an alias of woodstox-core-asl so that Maven includes only one of these jars?

A similar problem affects old Spring 2.x that published both an all-in-one artifact and smaller separated artifacts.  However I think that the most common issue is the one related to artifacts that change their groupId and/or artifactId.

答:
There is no way to do this. Maven doesn't understand the concept of aliases. If it did, then that would open the door to a whole other kind of dependency hell.

What you've described -- adding an <exclusion/> for the <dependency/> for all dependencies that need it and then explicitly adding a new <dependency/> for the renamed artifact -- is the only way you can achieve this at the moment.

Title: Maven dependency aliasing


问:
Print each array in object
I have a HTML table, I want to fill it up with a JSON Object. Printing the object works, but I can't get the arrays seperately. When I try to get the value of one 'ingredient' it keeps saying undefined. What's wrong in my code?

JQ:

```<code>function loadIngredients() {
    $.get("js/test.json", (data) => {
        console.log(data);
        $.each(data, function (index) {
            console.log(this.ingredient);
        });
    });
}
</code>```

JSON:

```<code>{
"data":[
    {"ingredient":"Banaan", "hoeveelheid":"50", "energie":"89", "vet":"0,9", "verzagigd vet":"0,3", "eiwit":"1,2", "koolhydraten":"20,4", "vezels":"1,9", "zout":"0,0"},
    {"ingredient":"Appel", "hoeveelheid":"80", "energie":"77", "vet":"0,6", "verzagigd vet":"0,1", "eiwit":"1,1", "koolhydraten":"15,6", "vezels":"2,5", "zout":"0,1"},
    {"ingredient":"Brood", "hoeveelheid":"120", "energie":"320", "vet":"1,1", "verzagigd vet":"0,4", "eiwit":"7,4", "koolhydraten":"30,6", "vezels":"4,8", "zout":"0,8"}
]
}
</code>```

答:
The "data" in your $.each loop is not is the variable that contains the {}. Try use data.data

```<code> $.each(data.data, function(index) {
   console.log(this.ingredient);
 });
</code>```

var data = {
  "data": [{
      "ingredient": "Banaan",
      "hoeveelheid": "50",
      "energie": "89",
      "vet": "0,9",
      "verzagigd vet": "0,3",
      "eiwit": "1,2",
      "koolhydraten": "20,4",
      "vezels": "1,9",
      "zout": "0,0"
    },
    {
      "ingredient": "Appel",
      "hoeveelheid": "80",
      "energie": "77",
      "vet": "0,6",
      "verzagigd vet": "0,1",
      "eiwit": "1,1",
      "koolhydraten": "15,6",
      "vezels": "2,5",
      "zout": "0,1"
    },
    {
      "ingredient": "Brood",
      "hoeveelheid": "120",
      "energie": "320",
      "vet": "1,1",
      "verzagigd vet": "0,4",
      "eiwit": "7,4",
      "koolhydraten": "30,6",
      "vezels": "4,8",
      "zout": "0,8"
    }
  ]
}

function loadIngredients() {
  $.each(data.data, function(index) {
    console.log(this.ingredient);
  });
}

loadIngredients();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></code>```

Title: Print each array in object

Body:
I have a HTML table, I want to fill it up with a JSON Object. Printing the object works, but I can't get the arrays seperately. When I try to get the value of one 'ingredient' it keeps saying undefined. What's wrong in my code?

JQ:

function loadIngredients() {
    $.get("js/test.json", (data) => {
        console.log(data);
        $.each(data, function (index) {
            console.log(this.ingredient);
        });
    });
}

JSON:

{
"data":[
    {"ingredient":"Banaan", "hoeveelheid":"50", "energie":"89", "vet":"0,9", "verzagigd vet":"0,3", "eiwit":"1,2", "koolhydraten":"20,4", "vezels":"1,9", "zout":"0,0"},
    {"ingredient":"Appel", "hoeveelheid":"80", "energie":"77", "vet":"0,6", "verzagigd vet":"0,1", "eiwit":"1,1", "koolhydraten":"15,6", "vezels":"2,5", "zout":"0,1"},
    {"ingredient":"Brood", "hoeveelheid":"120", "energie":"320", "vet":"1,1", "verzagigd vet":"0,4", "eiwit":"7,4", "koolhydraten":"30,6", "vezels":"4,8", "zout":"0,8"}
]
}

Body:
The "data" in your $.each loop is not is the variable that contains the {}. Try use data.data

 $.each(data.data, function(index) {
   console.log(this.ingredient);
 });

var data = {
  "data": [{
      "ingredient": "Banaan",
      "hoeveelheid": "50",
      "energie": "89",
      "vet": "0,9",
      "verzagigd vet": "0,3",
      "eiwit": "1,2",
      "koolhydraten": "20,4",
      "vezels": "1,9",
      "zout": "0,0"
    },
    {
      "ingredient": "Appel",
      "hoeveelheid": "80",
      "energie": "77",
      "vet": "0,6",
      "verzagigd vet": "0,1",
      "eiwit": "1,1",
      "koolhydraten": "15,6",
      "vezels": "2,5",
      "zout": "0,1"
    },
    {
      "ingredient": "Brood",
      "hoeveelheid": "120",
      "energie": "320",
      "vet": "1,1",
      "verzagigd vet": "0,4",
      "eiwit": "7,4",
      "koolhydraten": "30,6",
      "vezels": "4,8",
      "zout": "0,8"
    }
  ]
}

function loadIngredients() {
  $.each(data.data, function(index) {
    console.log(this.ingredient);
  });
}

loadIngredients();

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


问:
total number of rows of a query
I have a very large query that is supposed to return only the top 10 results:

select top 10 ProductId from .....

The problem is that I also want the total number of results that match the criteria without that 'top 10', but in the same time it's considered unaceptable to return all rows (we are talking of roughly 100 thousand results.

Is there a way to get the total number of rows affected by the previous query, either in it or afterwords without running it again?

PS: please no temp tables of 100 000 rows :))

答:
dump the count in a variable and return that</p>

```<code>declare @count int
select @count = count(*) from ..... --same where clause as your query

--now you add that to your query..of course it will be the same for every row..
select top 10 ProductId, @count as TotalCount from .....
</code>```

ContentLicense: CC BY-SA 2.5

Title: total number of rows of a query

Body:
dump the count in a variable and return that

declare @count int
select @count = count(*) from ..... --same where clause as your query

--now you add that to your query..of course it will be the same for every row..
select top 10 ProductId, @count as TotalCount from .....


问:
How to layout view right aligned and bottom of an LinearLayout
I am trying to layout 1 textview (upText) left aligned and 1 textview (downText) and an image view (image) both on the same line and right aligned.

how can I do that? I tried that, but both 'textview' and image view at left aligned.

```<code>        <TextView
            android:id="@+id/uptext"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:gravity="left"/>
        <TextView
            android:id="@+id/downtext"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:singleLine="true"
            android:gravity="right|bottom"/>
        <ImageView
            android:id="@+id/image"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="right|bottom"/>
    </LinearLayout>
</code>```

答:
I realize this post is a bit old but just in case someone comes across this in their search for clarity;

The parent linear layout is where gravity needs to be specified for the child to align with the desired behavior which is why the above posts are explaining that linear layout is not possible for two separate behaviors to occur since a child cannot decide where to align itself within a linear layout.

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="200dp"
android:layout_height="50dp"
android:gravity="bottom|right">

<TextView
    android:layout_width="40dp"
    android:layout_height="20dp"
    android:text="test"/></LinearLayout>
</code>```

It should also be said that the parent linear layout must have a defined size and not be wrap-content or this will not work since wrap content implies that there will be no extra space in the layout for positioning, so at least 'match-parent' for width and height is necessary as well as having a parent with a greater size than wrap-content for the child linear layout itself.

Hope this helps.

Body:
I am trying to layout 1 textview (upText) left aligned and 1 textview (downText) and an image view (image) both on the same line and right aligned.

how can I do that? I tried that, but both 'textview' and image view at left aligned.

        <TextView
            android:id="@+id/uptext"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:gravity="left"/>
        <TextView
            android:id="@+id/downtext"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:singleLine="true"
            android:gravity="right|bottom"/>
        <ImageView
            android:id="@+id/image"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="right|bottom"/>
    </LinearLayout>

Body:
I realize this post is a bit old but just in case someone comes across this in their search for clarity;

The parent linear layout is where gravity needs to be specified for the child to align with the desired behavior which is why the above posts are explaining that linear layout is not possible for two separate behaviors to occur since a child cannot decide where to align itself within a linear layout.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="200dp"
android:layout_height="50dp"
android:gravity="bottom|right">

<TextView
    android:layout_width="40dp"
    android:layout_height="20dp"
    android:text="test"/></LinearLayout>

It should also be said that the parent linear layout must have a defined size and not be wrap-content or this will not work since wrap content implies that there will be no extra space in the layout for positioning, so at least 'match-parent' for width and height is necessary as well as having a parent with a greater size than wrap-content for the child linear layout itself.

Hope this helps.


问:
How to call button event from one activity to another activity for refreshing?
On the first xml page, if I click a button it takes data from server and shows on the second xml.

On second xml using refresh button I tried to do the same. So how to do I call the button event on the first activity to execute so that it refreshes the page.

I tried reloading the same page again and it does not work.

答: Create function that button on first xml page will call, then on the second xml page call the same function from the first one. </p>


问:
Angular route not resolving from observable
I'm trying to resolve a route in Angular and cannot get it to resolve. Whilst the resolver works when I return a value it does not continue to the intended route. My router is defined as follows...

```<code>{
    path: 'sortation',
    component: SortationComponent,
    resolve: {
        cage: 'cageResolveService'
    }
}
</code>```

... which I call using a simple link

```<code>        <a class="btn btn-block btn-danger btn-sm" routerLink="/sortation" routerLinkActive="menu-active">
            Sortation
        </a>
</code>```

... and my cageResolveService reads

```<code>import { Injectable, Inject, OnDestroy } from '@angular/core';
import { Resolve, ActivatedRouteSnapshot } from '@angular/router';
import { Observable } from "rxjs/Observable";
import { Cage } from '../_models/cage';

@Injectable()
export class CageResolveService implements Resolve<any> {

cage;

constructor(
    @Inject('cageService') private cageService,
    @Inject('appUtilityService') private appUtilityService,
    @Inject('flashService') private flashService
) {}

ngOnDestroy() {
    this.cage.unsubscribe();
}

resolve(route: ActivatedRouteSnapshot): any {

    let criteria = {
        "limit": 3,
        "orderBy": "createdAt",
        "state": "PICKED"
    }

    // Subscribe to the observable
    this.cage = this.cageService.load( this.appUtilityService.encode( criteria ) )
    .subscribe();

    return this.cageService.cages$
    .map( cages => {

        if( cages && cages.length )
        {
            let c = cages.find( cage => cage.state === 'PICKED' );
            return c;
        }
        else
        {
            this.flashService.command.next({message: 'Error : No ready cages at this time', type: 'danger'});
            return false;
        }
    });
}
}
</code>```

Can anybody please advise? If I remove the resolver the route works fine. It's a silly issue that is driving me nuts.

答:
For anybody struggling the issue was caused by not closing the observable. I amended my code inside the resolver as follows:

cageResolverService

```<code>import 'rxjs/add/operator/first'
...
... ...

resolve(): any {

    let criteria = {
        "limit": 1,
        "orderBy": "createdAt",
        "state": "PICKED"
    }

    // Subscribe to the observable
    this.cage = this.cageService.load( this.appUtilityService.encode( criteria ) )
    .subscribe();

    var self = this;

    return self.cageService.cages$
    .map( cages => {

        if( cages && cages.length )
        {
            return cages.find( cage => cage.state === 'PICKED' );
        }
        else
        {
            self.flashService.command.next({message: 'Error : No ready cages at this time', type: 'danger'});
            return false;
        }
    })
    .first();
}
</code>```

NOTE: The addition of "first();" at the end of the method which closes the observable and allows the route to render.

Thanks for the help.

Body:
I'm trying to resolve a route in Angular and cannot get it to resolve. Whilst the resolver works when I return a value it does not continue to the intended route. My router is defined as follows...

{
    path: 'sortation',
    component: SortationComponent,
    resolve: {
        cage: 'cageResolveService'
    }
}

... which I call using a simple link

            Sortation

... and my cageResolveService reads

import { Injectable, Inject, OnDestroy } from '@angular/core';
import { Resolve, ActivatedRouteSnapshot } from '@angular/router';
import { Observable } from "rxjs/Observable";
import { Cage } from '../_models/cage';

@Injectable()
export class CageResolveService implements Resolve<any> {

cage;

constructor(
    @Inject('cageService') private cageService,
    @Inject('appUtilityService') private appUtilityService,
    @Inject('flashService') private flashService
) {}

ngOnDestroy() {
    this.cage.unsubscribe();
}

resolve(route: ActivatedRouteSnapshot): any {

    let criteria = {
        "limit": 3,
        "orderBy": "createdAt",
        "state": "PICKED"
    }

    // Subscribe to the observable
    this.cage = this.cageService.load( this.appUtilityService.encode( criteria ) )
    .subscribe();

    return this.cageService.cages$
    .map( cages => {

        if( cages && cages.length )
        {
            let c = cages.find( cage => cage.state === 'PICKED' );
            return c;
        }
        else
        {
            this.flashService.command.next({message: 'Error : No ready cages at this time', type: 'danger'});
            return false;
        }
    });
}
}

Can anybody please advise? If I remove the resolver the route works fine. It's a silly issue that is driving me nuts.

Body:
For anybody struggling the issue was caused by not closing the observable. I amended my code inside the resolver as follows:

cageResolverService

import 'rxjs/add/operator/first'
...
... ...

resolve(): any {

    let criteria = {
        "limit": 1,
        "orderBy": "createdAt",
        "state": "PICKED"
    }

    // Subscribe to the observable
    this.cage = this.cageService.load( this.appUtilityService.encode( criteria ) )
    .subscribe();

    var self = this;

    return self.cageService.cages$
    .map( cages => {

        if( cages && cages.length )
        {
            return cages.find( cage => cage.state === 'PICKED' );
        }
        else
        {
            self.flashService.command.next({message: 'Error : No ready cages at this time', type: 'danger'});
            return false;
        }
    })
    .first();
}

NOTE: The addition of "first();" at the end of the method which closes the observable and allows the route to render.

Thanks for the help.


问:
Training and Predicting with instance keys
I am able to train my model and use ML Engine for prediction but my results don't include any identifying information. This works fine when submitting one row at a time for prediction but when submitting multiple rows I have no way of connecting the prediction back to the original input data. The GCP documentation discusses using instance keys but I can't find any example code that trains and predicts using an instance key. Taking the GCP census example how would I update the input functions to pass a unique ID through the graph and ignore it during training yet return the unique ID with predictions? Or alternatively if anyone knows of a different example already using keys that would help as well.

From Census Estimator Sample

```<code>def serving_input_fn():
    feature_placeholders = {
      column.name: tf.placeholder(column.dtype, [None])
      for column in INPUT_COLUMNS
    }

    features = {
      key: tf.expand_dims(tensor, -1)
      for key, tensor in feature_placeholders.items()
    }

    return input_fn_utils.InputFnOps(
      features,
      None,
      feature_placeholders
    )

def generate_input_fn(filenames,
                  num_epochs=None,
                  shuffle=True,
                  skip_header_lines=0,
                  batch_size=40):

    def _input_fn():
        files = tf.concat([
          tf.train.match_filenames_once(filename)
          for filename in filenames
        ], axis=0)

        filename_queue = tf.train.string_input_producer(
          files, num_epochs=num_epochs, shuffle=shuffle)
        reader = tf.TextLineReader(skip_header_lines=skip_header_lines)

        _, rows = reader.read_up_to(filename_queue, num_records=batch_size)

        row_columns = tf.expand_dims(rows, -1)
        columns = tf.decode_csv(row_columns, record_defaults=CSV_COLUMN_DEFAULTS)
        features = dict(zip(CSV_COLUMNS, columns))

        # Remove unused columns
        for col in UNUSED_COLUMNS:
          features.pop(col)

        if shuffle:
           features = tf.train.shuffle_batch(
             features,
             batch_size,
             capacity=batch_size * 10,
             min_after_dequeue=batch_size*2 + 1,
             num_threads=multiprocessing.cpu_count(),
             enqueue_many=True,
             allow_smaller_final_batch=True
           )
        label_tensor = parse_label_column(features.pop(LABEL_COLUMN))
        return features, label_tensor

    return _input_fn
</code>```

Update:
I was able to use the suggested code from this answer below I just needed to alter it slightly to update the output alternatives in the model_fn_ops instead of just the prediction dict. However, this only works if my serving input function is coded for json inputs similar to this. My serving input function was previously modeled after the CSV serving input function in the Census Core Sample.

I think my problem is coming from the build_standardized_signature_def function and even more so the is_classification_problem function that it calls. The input dict length using the csv serving function is 1 so this logic ends up using the classification_signature_def which only ends up displaying the scores (which turns out are actually the probabilities) whereas the input dict length is greater than 1 with the json serving input function and instead the predict_signature_def is used which includes all of the outputs.

答:
Great question. The Cloud ML Engine flowers sample does this, by using the tf.identity operation to pass a string straight through from input to output.  Here are the relevant lines during graph construction.

```<code>keys_placeholder = tf.placeholder(tf.string, shape=[None])
inputs = {
    'key': keys_placeholder,
    'image_bytes': tensors.input_jpeg
}

# To extract the id, we need to add the identity function.
keys = tf.identity(keys_placeholder)
outputs = {
   'key': keys,
   'prediction': tensors.predictions[0],
   'scores': tensors.predictions[1]
}
</code>```

For batch prediction you need to insert "key": "some_key_value" into your instance records. For online prediction you would query the above graph with a JSON request like:

```<code>{'instances' : [
    {'key': 'first_key', 'image_bytes' : {'b64': ...}},
    {'key': 'second_key', 'image_bytes': {'b64': ...}}
    ]
}
</code>```

Body:
I am able to train my model and use ML Engine for prediction but my results don't include any identifying information. This works fine when submitting one row at a time for prediction but when submitting multiple rows I have no way of connecting the prediction back to the original input data. The GCP documentation discusses using instance keys but I can't find any example code that trains and predicts using an instance key. Taking the GCP census example how would I update the input functions to pass a unique ID through the graph and ignore it during training yet return the unique ID with predictions? Or alternatively if anyone knows of a different example already using keys that would help as well.

From Census Estimator Sample

def serving_input_fn():
    feature_placeholders = {
      column.name: tf.placeholder(column.dtype, [None])
      for column in INPUT_COLUMNS
    }

    features = {
      key: tf.expand_dims(tensor, -1)
      for key, tensor in feature_placeholders.items()
    }

    return input_fn_utils.InputFnOps(
      features,
      None,
      feature_placeholders
    )

def generate_input_fn(filenames,
                  num_epochs=None,
                  shuffle=True,
                  skip_header_lines=0,
                  batch_size=40):

    def _input_fn():
        files = tf.concat([
          tf.train.match_filenames_once(filename)
          for filename in filenames
        ], axis=0)

        filename_queue = tf.train.string_input_producer(
          files, num_epochs=num_epochs, shuffle=shuffle)
        reader = tf.TextLineReader(skip_header_lines=skip_header_lines)

        _, rows = reader.read_up_to(filename_queue, num_records=batch_size)

        row_columns = tf.expand_dims(rows, -1)
        columns = tf.decode_csv(row_columns, record_defaults=CSV_COLUMN_DEFAULTS)
        features = dict(zip(CSV_COLUMNS, columns))

        # Remove unused columns
        for col in UNUSED_COLUMNS:
          features.pop(col)

        if shuffle:
           features = tf.train.shuffle_batch(
             features,
             batch_size,
             capacity=batch_size * 10,
             min_after_dequeue=batch_size*2 + 1,
             num_threads=multiprocessing.cpu_count(),
             enqueue_many=True,
             allow_smaller_final_batch=True
           )
        label_tensor = parse_label_column(features.pop(LABEL_COLUMN))
        return features, label_tensor

    return _input_fn

Update:
I was able to use the suggested code from this answer below I just needed to alter it slightly to update the output alternatives in the model_fn_ops instead of just the prediction dict. However, this only works if my serving input function is coded for json inputs similar to this. My serving input function was previously modeled after the CSV serving input function in the Census Core Sample.

I think my problem is coming from the build_standardized_signature_def function and even more so the is_classification_problem function that it calls. The input dict length using the csv serving function is 1 so this logic ends up using the classification_signature_def which only ends up displaying the scores (which turns out are actually the probabilities) whereas the input dict length is greater than 1 with the json serving input function and instead the predict_signature_def is used which includes all of the outputs.

Body:
Great question. The Cloud ML Engine flowers sample does this, by using the tf.identity operation to pass a string straight through from input to output.  Here are the relevant lines during graph construction.

keys_placeholder = tf.placeholder(tf.string, shape=[None])
inputs = {
    'key': keys_placeholder,
    'image_bytes': tensors.input_jpeg
}

# To extract the id, we need to add the identity function.
keys = tf.identity(keys_placeholder)
outputs = {
   'key': keys,
   'prediction': tensors.predictions[0],
   'scores': tensors.predictions[1]
}

For batch prediction you need to insert "key": "some_key_value" into your instance records. For online prediction you would query the above graph with a JSON request like:

{'instances' : [
    {'key': 'first_key', 'image_bytes' : {'b64': ...}},
    {'key': 'second_key', 'image_bytes': {'b64': ...}}
    ]
}


问:
How capture part of string included delimiter?
Having a string so formed:

```<code>#foo1 foo2# foo3 foo4 #foo5# ##foo6# #foo7## #foo8 foo9#
</code>```

The expected should be an array so formed:

```<code>array (
  [0] => #foo1 foo2#
  [1] => foo3
  [2] => foo4
  [3] => #foo5#
  [4] => ##foo6# #foo7##
  [5] => #foo8 foo9#
);
</code>```

Or more simply splitting for space but capuring all which inside a delimiter, included it... in a array.

NOTE: The string can to have repeated it.

答:
You can use preg_match_all using this alternation regex:

```<code>/(#+).*?\1|\S+/
</code>```

RegEx Demo

RegEx Breakup:

(#+) - Match 1 or more # in captured group #1

.*? - Match 0 or more of any characters (non-greedy)

\1 - Back-reference to captured group #1 to make sure we have same #s on RHS

| - OR

\S+ - one or more non-white-space characters

Code:

```<code>$str = '#foo1 foo2# foo3 foo4 #foo5# ##foo6# #foo7## #foo8 foo9#';

preg_match_all('/(#+).*?\1|\S+/', $str, $matches);

print_r($matches[0]);
</code>```

Output:

```<code>Array
(
    [0] => #foo1 foo2#
    [1] => foo3
    [2] => foo4
    [3] => #foo5#
    [4] => ##foo6# #foo7##
    [5] => #foo8 foo9#
)
</code>```

Body:
Having a string so formed:

#foo1 foo2# foo3 foo4 #foo5# ##foo6# #foo7## #foo8 foo9#

The expected should be an array so formed:

array (
  [0] => #foo1 foo2#
  [1] => foo3
  [2] => foo4
  [3] => #foo5#
  [4] => ##foo6# #foo7##
  [5] => #foo8 foo9#
);

Or more simply splitting for space but capuring all which inside a delimiter, included it... in a array.

NOTE: The string can to have repeated it.

Body:
You can use preg_match_all using this alternation regex:

/(#+).*?\1|\S+/

RegEx Demo

RegEx Breakup:

(#+) - Match 1 or more # in captured group #1

.*? - Match 0 or more of any characters (non-greedy)

\1 - Back-reference to captured group #1 to make sure we have same #s on RHS

| - OR

\S+ - one or more non-white-space characters

Code:

$str = '#foo1 foo2# foo3 foo4 #foo5# ##foo6# #foo7## #foo8 foo9#';

preg_match_all('/(#+).*?\1|\S+/', $str, $matches);

print_r($matches[0]);

Output:

Array
(
    [0] => #foo1 foo2#
    [1] => foo3
    [2] => foo4
    [3] => #foo5#
    [4] => ##foo6# #foo7##
    [5] => #foo8 foo9#
)


问:
Constructor Injection: How many dependencies is too many?
I've been using manual constructor injection DI for a little bit now.  One thing that I notice is that my constructors are starting to get rather long.

I have a class that depends on a bunch of little objects - anywhere between 6 and 10 sometimes.  As I continue to break my application into smaller chunks, I could see this number increasing over time.  Is this a common problem?

Obviously this is going to depend a great deal on the project.  However, the basic question is this:

When do you start to get uncomfortable with the number of dependencies that a class has?  What are some strategies that you use to reduce these dependencies?

答:
A class with 6-10 dependencies is a code smell. It is an indication that the class is probably violating the Single Responsibility Principle.

What are some strategies that you use to reduce these dependencies?

Mark Seemann has made that task clear in his post Refactoring to Aggregate Services and moreso in his book Dependency Injection in .NET. The fact your class has so many dependencies indicates there are more than one responsibilities within the class. Often there is an implicit domain concept waiting to be made explicit by identifying it and making it into its own service. Generally speaking, most classes should never need more than 4-5 dependencies.

ContentLicense: CC BY-SA 4.0


问:
Find out where the error happened in Clojure
For the most part I understand what Clojure is telling me with it's error messages. But I am still clueless as to find out where the error happened.

Here is an example of what I mean

```<code>(defn extract [m]
  (keys m))

(defn multiple [xs]
  (map #(* 2 %) xs))

(defn process [xs]
  (-> xs
      (multiple)     ; seq -> seq
      (extract))) ; map -> seq ... fails

(process [1 2 3])
</code>```

Statically typed languages would now tell me that I tried to pass a sequence to a function that expects a map on line X. And Clojure does this in a way:

```<code>ClassCastException java.lang.Long cannot be cast to java.util.Map$Entry
</code>```

But I still have no idea where the error happened. Obviously for this instance it's easy because there are just 3 functions involved, you can easily just read through all of them but as programs grow bigger this gets old very quickly.

Is there a way find out where the errors happened other than just proof reading the code from top to bottom? (which is my current approach)

答:
Re-typing your example I have:

```<code>(defn extract [m]
  (keys m))

(defn multiply [xs]
  (mapv #(* 2 %) xs))

(defn process [xs]
  (-> xs
    (multiply)      ; seq -> seq
    (extract)))     ; map -> seq ... fails ***line 21***

(println (process [1 2 3]))
;=> java.lang.ClassCastException: java.lang.Long cannot be cast
to java.util.Map$Entry, compiling:(tst/clj/core.clj:21:21)
</code>```

So we get a good clue in the exception where is says the file and line/col number tst.clj.core.clj:21:21 that the extract method is the problem.

Another indispensible tool I use is Plumatic Schema to inject "gradual" type checking into clojure.  The code becomes:

```<code>(ns tst.clj.core
  (:use clj.core tupelo.test)
  (:require
    [tupelo.core :as t]
    [tupelo.schema :as tsk]
    [schema.core :as s]))
(t/refer-tupelo)
(t/print-versions)

(s/defn extract :- [s/Any]
  [m :- tsk/Map]
  (keys m))

(s/defn multiply :- [s/Num]
  [xs :- [s/Num]]
  (mapv #(* 2 %) xs))

(s/defn process :- s/Any
  [xs :- [s/Num]]
  (-> xs
    (multiply) ; seq -> seq
    (extract))) ; map -> seq ... fails

(println (process [1 2 3]))

clojure.lang.ExceptionInfo: Input to extract does not match schema:
[(named (not (map? [2 4 6])) m)] {:type :schema.core/error, :schema [#schema.core.One{:schema {Any Any},
:optional? false, :name m}],
:value [[2 4 6]], :error [(named (not (map? [2 4 6])) m)]},
compiling:(tst/clj/core.clj:23:17)
</code>```

So, while the format of the error message is a bit lengthy, it tells right away that we passed a parameter of the wrong type and/or shape into the method extract.

Note that you need a line like this:

```<code>(s/set-fn-validation! true) ; enforce fn schemas
</code>```

I create a special file test/tst/clj/_bootstrap.clj so it is always in the same place.

For more information on Plumatic Schema please see:

https://github.com/plumatic/schema

https://youtu.be/o_jtwIs2Ot8

https://github.com/plumatic/schema/wiki/Basics-Examples

https://github.com/plumatic/schema/wiki/Defining-New-Schema-Types-1.0

Body:
For the most part I understand what Clojure is telling me with it's error messages. But I am still clueless as to find out where the error happened.

Here is an example of what I mean

(defn extract [m]
  (keys m))

(defn multiple [xs]
  (map #(* 2 %) xs))

(defn process [xs]
  (-> xs
      (multiple)     ; seq -> seq
      (extract))) ; map -> seq ... fails

(process [1 2 3])

Statically typed languages would now tell me that I tried to pass a sequence to a function that expects a map on line X. And Clojure does this in a way:

ClassCastException java.lang.Long cannot be cast to java.util.Map$Entry

But I still have no idea where the error happened. Obviously for this instance it's easy because there are just 3 functions involved, you can easily just read through all of them but as programs grow bigger this gets old very quickly.

Is there a way find out where the errors happened other than just proof reading the code from top to bottom? (which is my current approach)

Body:
Re-typing your example I have:

(defn extract [m]
  (keys m))

(defn multiply [xs]
  (mapv #(* 2 %) xs))

(defn process [xs]
  (-> xs
    (multiply)      ; seq -> seq
    (extract)))     ; map -> seq ... fails ***line 21***

(println (process [1 2 3]))
;=> java.lang.ClassCastException: java.lang.Long cannot be cast
to java.util.Map$Entry, compiling:(tst/clj/core.clj:21:21)

So we get a good clue in the exception where is says the file and line/col number tst.clj.core.clj:21:21 that the extract method is the problem.

Another indispensible tool I use is Plumatic Schema to inject "gradual" type checking into clojure.  The code becomes:

(ns tst.clj.core
  (:use clj.core tupelo.test)
  (:require
    [tupelo.core :as t]
    [tupelo.schema :as tsk]
    [schema.core :as s]))
(t/refer-tupelo)
(t/print-versions)

(s/defn extract :- [s/Any]
  [m :- tsk/Map]
  (keys m))

(s/defn multiply :- [s/Num]
  [xs :- [s/Num]]
  (mapv #(* 2 %) xs))

(s/defn process :- s/Any
  [xs :- [s/Num]]
  (-> xs
    (multiply) ; seq -> seq
    (extract))) ; map -> seq ... fails

(println (process [1 2 3]))

clojure.lang.ExceptionInfo: Input to extract does not match schema:
[(named (not (map? [2 4 6])) m)] {:type :schema.core/error, :schema [#schema.core.One{:schema {Any Any},
:optional? false, :name m}],
:value [[2 4 6]], :error [(named (not (map? [2 4 6])) m)]},
compiling:(tst/clj/core.clj:23:17)

So, while the format of the error message is a bit lengthy, it tells right away that we passed a parameter of the wrong type and/or shape into the method extract.

Note that you need a line like this:

(s/set-fn-validation! true) ; enforce fn schemas

I create a special file test/tst/clj/_bootstrap.clj so it is always in the same place.

For more information on Plumatic Schema please see:

https://github.com/plumatic/schema

https://youtu.be/o_jtwIs2Ot8

https://github.com/plumatic/schema/wiki/Basics-Examples

https://github.com/plumatic/schema/wiki/Defining-New-Schema-Types-1.0


问:
ERROR 2006 (HY000) at line 1: MySQL server has gone away
ERROR 2006 (HY000) at line 1: MySQL server has gone away

I am facing the same problem.  I am trying to restore mysqldump file to my machine. The file have size of 2.7 MB. I am getting  "ERROR 2006 (HY000) at line 1: MySQL server has gone away" error. I increased size of max_allowed_packet and wait_timeout. But nothing worked.

Following are the content of my file (my-medium.ini), please suggest
me where I am wrong. My installation have various ini files, and I have
modified, my-large, my-medium, my-small, my-huge, my-innodb-heavy-4G. Thanks in advance!!

```<code># Example MySQL config file for medium systems.
#
# This is for a system with little memory (32M - 64M) where MySQL plays
# an important part, or systems up to 128M where MySQL is used together with
# other programs (such as a web server)
#
# You can copy this file to
# /etc/my.cnf to set global options,
# mysql-data-dir/my.cnf to set server-specific options (in this
# installation this directory is C:\mysql\data) or
# ~/.my.cnf to set user-specific options.
#
# In this file, you can use all long options that a program supports.
# If you want to know which options a program supports, run the program
# with the "--help" option.

# The following options will be passed to all MySQL clients
[client]
#password   = your_password
port        = 3306
socket      = /tmp/mysql.sock

# Here follows entries for some specific programs

# The MySQL server
[mysqld]
port        = 3306
socket      = /tmp/mysql.sock
skip-locking
key_buffer_size = 16M
max_allowed_packet = 512M
table_open_cache = 64
sort_buffer_size = 512K
net_buffer_length = 8K
read_buffer_size = 256K
read_rnd_buffer_size = 512K
myisam_sort_buffer_size = 8M
wait_timeout = 6000

# Don't listen on a TCP/IP port at all. This can be a security enhancement,
# if all processes that need to connect to mysqld run on the same host.
# All interaction with mysqld must be made via Unix sockets or named pipes.
# Note that using this option without enabling named pipes on Windows
# (via the "enable-named-pipe" option) will render mysqld useless!
#
#skip-networking

# Replication Master Server (default)
# binary logging is required for replication
log-bin=mysql-bin

# binary logging format - mixed recommended
binlog_format=mixed

# required unique id between 1 and 2^32 - 1
# defaults to 1 if master-host is not set
# but will not function as a master if omitted
server-id   = 1

# Replication Slave (comment out master section to use this)
#
# To configure this host as a replication slave, you can choose between
# two methods :
#
# 1) Use the CHANGE MASTER TO command (fully described in our manual) -
#    the syntax is:
#
#    CHANGE MASTER TO MASTER_HOST=<host>, MASTER_PORT=<port>,
#    MASTER_USER=<user>, MASTER_PASSWORD=<password> ;
#
#    where you replace <host>, <user>, <password> by quoted strings and
#    <port> by the master's port number (3306 by default).
#
#    Example:
#
#    CHANGE MASTER TO MASTER_HOST='125.564.12.1', MASTER_PORT=3306,
#    MASTER_USER='joe', MASTER_PASSWORD='secret';
#
# OR
#
# 2) Set the variables below. However, in case you choose this method, then
#    start replication for the first time (even unsuccessfully, for example
#    if you mistyped the password in master-password and the slave fails to
#    connect), the slave will create a master.info file, and any later
#    change in this file to the variables' values below will be ignored and
#    overridden by the content of the master.info file, unless you shutdown
#    the slave server, delete master.info and restart the slaver server.
#    For that reason, you may want to leave the lines below untouched
#    (commented) and instead use CHANGE MASTER TO (see above)
#
# required unique id between 2 and 2^32 - 1
# (and different from the master)
# defaults to 2 if master-host is set
# but will not function as a slave if omitted
#server-id       = 2
#
# The replication master for this slave - required
#master-host     =   <hostname>
#
# The username the slave will use for authentication when connecting
# to the master - required
#master-user     =   <username>
#
# The password the slave will authenticate with when connecting to
# the master - required
#master-password =   <password>
#
# The port the master is listening on.
# optional - defaults to 3306
#master-port     =  <port>
#
# binary logging - not required for slaves, but recommended
#log-bin=mysql-bin

# Point the following paths to different dedicated disks
#tmpdir     = /tmp/
#log-update     = /path-to-dedicated-directory/hostname

# Uncomment the following if you are using InnoDB tables
#innodb_data_home_dir = C:\mysql\data/
#innodb_data_file_path = ibdata1:10M:autoextend
#innodb_log_group_home_dir = C:\mysql\data/
# You can set .._buffer_pool_size up to 50 - 80 %
# of RAM but beware of setting memory usage too high
#innodb_buffer_pool_size = 16M
#innodb_additional_mem_pool_size = 2M
# Set .._log_file_size to 25 % of buffer pool size
#innodb_log_file_size = 5M
#innodb_log_buffer_size = 8M
#innodb_flush_log_at_trx_commit = 1
#innodb_lock_wait_timeout = 50

[mysqldump]
quick
max_allowed_packet = 512M

[mysql]
no-auto-rehash
# Remove the next comment character if you are not familiar with SQL
#safe-updates

[myisamchk]
key_buffer_size = 20M
sort_buffer_size = 20M
read_buffer = 2M
write_buffer = 2M

[mysqlhotcopy]
interactive-timeout
</code>```

答:
Under [mysqld] I have tried the following:

```<code>max_allowed_packet = 2096M
</code>```

restarted mysqld and it did not work, however what worked for me is to set max_allowed_packet globally from command line and then run the export from dump, it went through without any issues.

You can start from smaller packet size depending on database, I also did reimport my database with same size.

For Export:-

```<code>mysqldump --opt --user=confluenceUser --password='<passwd>' --max_allowed_packet=2147483648 confluencedb | gzip > confluencedb.sql.gz
</code>```

For Import:-

```<code>mysql> SET GLOBAL max_allowed_packet=2147483648;

Query OK, 0 rows affected, 1 warning (0.00 sec)

zcat confluence.sql.gz | mysql -uconfluence -p<passwd> confluencedb
</code>```

Body:
ERROR 2006 (HY000) at line 1: MySQL server has gone away

I am facing the same problem.  I am trying to restore mysqldump file to my machine. The file have size of 2.7 MB. I am getting  "ERROR 2006 (HY000) at line 1: MySQL server has gone away" error. I increased size of max_allowed_packet and wait_timeout. But nothing worked.

Following are the content of my file (my-medium.ini), please suggest
me where I am wrong. My installation have various ini files, and I have
modified, my-large, my-medium, my-small, my-huge, my-innodb-heavy-4G. Thanks in advance!!

# Example MySQL config file for medium systems.
#
# This is for a system with little memory (32M - 64M) where MySQL plays
# an important part, or systems up to 128M where MySQL is used together with
# other programs (such as a web server)
#
# You can copy this file to
# /etc/my.cnf to set global options,
# mysql-data-dir/my.cnf to set server-specific options (in this
# installation this directory is C:\mysql\data) or
# ~/.my.cnf to set user-specific options.
#
# In this file, you can use all long options that a program supports.
# If you want to know which options a program supports, run the program
# with the "--help" option.

# The following options will be passed to all MySQL clients
[client]
#password   = your_password
port        = 3306
socket      = /tmp/mysql.sock

# Here follows entries for some specific programs

# The MySQL server
[mysqld]
port        = 3306
socket      = /tmp/mysql.sock
skip-locking
key_buffer_size = 16M
max_allowed_packet = 512M
table_open_cache = 64
sort_buffer_size = 512K
net_buffer_length = 8K
read_buffer_size = 256K
read_rnd_buffer_size = 512K
myisam_sort_buffer_size = 8M
wait_timeout = 6000

# Don't listen on a TCP/IP port at all. This can be a security enhancement,
# if all processes that need to connect to mysqld run on the same host.
# All interaction with mysqld must be made via Unix sockets or named pipes.
# Note that using this option without enabling named pipes on Windows
# (via the "enable-named-pipe" option) will render mysqld useless!
#
#skip-networking

# Replication Master Server (default)
# binary logging is required for replication
log-bin=mysql-bin

# binary logging format - mixed recommended
binlog_format=mixed

# required unique id between 1 and 2^32 - 1
# defaults to 1 if master-host is not set
# but will not function as a master if omitted
server-id   = 1

# Replication Slave (comment out master section to use this)
#
# To configure this host as a replication slave, you can choose between
# two methods :
#
# 1) Use the CHANGE MASTER TO command (fully described in our manual) -
#    the syntax is:
#
#    CHANGE MASTER TO MASTER_HOST=<host>, MASTER_PORT=<port>,
#    MASTER_USER=<user>, MASTER_PASSWORD=<password> ;
#
#    where you replace <host>, <user>, <password> by quoted strings and
#    <port> by the master's port number (3306 by default).
#
#    Example:
#
#    CHANGE MASTER TO MASTER_HOST='125.564.12.1', MASTER_PORT=3306,
#    MASTER_USER='joe', MASTER_PASSWORD='secret';
#
# OR
#
# 2) Set the variables below. However, in case you choose this method, then
#    start replication for the first time (even unsuccessfully, for example
#    if you mistyped the password in master-password and the slave fails to
#    connect), the slave will create a master.info file, and any later
#    change in this file to the variables' values below will be ignored and
#    overridden by the content of the master.info file, unless you shutdown
#    the slave server, delete master.info and restart the slaver server.
#    For that reason, you may want to leave the lines below untouched
#    (commented) and instead use CHANGE MASTER TO (see above)
#
# required unique id between 2 and 2^32 - 1
# (and different from the master)
# defaults to 2 if master-host is set
# but will not function as a slave if omitted
#server-id       = 2
#
# The replication master for this slave - required
#master-host     =   <hostname>
#
# The username the slave will use for authentication when connecting
# to the master - required
#master-user     =   <username>
#
# The password the slave will authenticate with when connecting to
# the master - required
#master-password =   <password>
#
# The port the master is listening on.
# optional - defaults to 3306
#master-port     =  <port>
#
# binary logging - not required for slaves, but recommended
#log-bin=mysql-bin

# Point the following paths to different dedicated disks
#tmpdir     = /tmp/
#log-update     = /path-to-dedicated-directory/hostname

# Uncomment the following if you are using InnoDB tables
#innodb_data_home_dir = C:\mysql\data/
#innodb_data_file_path = ibdata1:10M:autoextend
#innodb_log_group_home_dir = C:\mysql\data/
# You can set .._buffer_pool_size up to 50 - 80 %
# of RAM but beware of setting memory usage too high
#innodb_buffer_pool_size = 16M
#innodb_additional_mem_pool_size = 2M
# Set .._log_file_size to 25 % of buffer pool size
#innodb_log_file_size = 5M
#innodb_log_buffer_size = 8M
#innodb_flush_log_at_trx_commit = 1
#innodb_lock_wait_timeout = 50

[mysqldump]
quick
max_allowed_packet = 512M

[mysql]
no-auto-rehash
# Remove the next comment character if you are not familiar with SQL
#safe-updates

[myisamchk]
key_buffer_size = 20M
sort_buffer_size = 20M
read_buffer = 2M
write_buffer = 2M

[mysqlhotcopy]
interactive-timeout

Body:
Under [mysqld] I have tried the following:

max_allowed_packet = 2096M

restarted mysqld and it did not work, however what worked for me is to set max_allowed_packet globally from command line and then run the export from dump, it went through without any issues.

You can start from smaller packet size depending on database, I also did reimport my database with same size.

For Export:-

mysqldump --opt --user=confluenceUser --password='<passwd>' --max_allowed_packet=2147483648 confluencedb | gzip > confluencedb.sql.gz

For Import:-

mysql> SET GLOBAL max_allowed_packet=2147483648;

Query OK, 0 rows affected, 1 warning (0.00 sec)

zcat confluence.sql.gz | mysql -uconfluence -p<passwd> confluencedb


问:
java regex- get specific index where not have a specific word before
Im trying to add the double quote on a xml string only on specific place.

Here an example of xml content

```<code>    <opr:sec name=display>
     <opr:fld name=fieldName>Value1</opr:fld>
     <opr:fld name=someName>value2</opr:fld>
</code>```

I need to add double quote like : name="fieldName" and the field names are different each line.

The first double quote are simple using the name= that need to be before

But for the closing double quote i think to use the > sign, but need to avoid the fld at end.

How i regex a letter that don't have a specific text before

答:
Here is a simpler way to do what you want.

Use this regex :

name=([^>]*)>

And replace it by :

name="$1">

Body:
Im trying to add the double quote on a xml string only on specific place.

Here an example of xml content

    <opr:sec name=display>
     <opr:fld name=fieldName>Value1</opr:fld>
     <opr:fld name=someName>value2</opr:fld>

I need to add double quote like : name="fieldName" and the field names are different each line.

The first double quote are simple using the name= that need to be before

But for the closing double quote i think to use the > sign, but need to avoid the fld at end.

How i regex a letter that don't have a specific text before


问:
Find all Java versions in the system path
I needed to know a command to find all of the versions of Java in the system path. I knew that which -a java would print all places that the java executable can be found in the system path, but I then wanted to get the version info for each of these executables.

答:
which -a java | xargs -I{} echo "echo {};{} -version;echo" | sh

This will print the path to each of the java executables found in the system path, as well as the version information of that executable, and separate entries with a newline. It works like so:

Pipe the output from which -a java into xargs

Use xargs -I{} echo to construct bash commands, with each line in the input from which replacing {}

Pipe the constructed bash commands into the system's default shell executor.

A sample output on my machine gives

```<code>/usr/bin/java
java version "1.8.0_131"
Java(TM) SE Runtime Environment (build 1.8.0_131-b11)
Java HotSpot(TM) 64-Bit Server VM (build 25.131-b11, mixed mode)

/usr/lib/jvm/java-8-oracle/bin/java
java version "1.8.0_131"
Java(TM) SE Runtime Environment (build 1.8.0_131-b11)
Java HotSpot(TM) 64-Bit Server VM (build 25.131-b11, mixed mode)
</code>```

Note that if you want to know the versions of a different executable, you can modify the bash command that gets constructed to appropriately print version info. E.G. if you want to know all the versions of python you can run

which -a python | xargs -I{} echo "echo {};{} --version;echo" | sh

Body:
which -a java | xargs -I{} echo "echo {};{} -version;echo" | sh

This will print the path to each of the java executables found in the system path, as well as the version information of that executable, and separate entries with a newline. It works like so:

Pipe the output from which -a java into xargs

Use xargs -I{} echo to construct bash commands, with each line in the input from which replacing {}

Pipe the constructed bash commands into the system's default shell executor.

A sample output on my machine gives

/usr/bin/java
java version "1.8.0_131"
Java(TM) SE Runtime Environment (build 1.8.0_131-b11)
Java HotSpot(TM) 64-Bit Server VM (build 25.131-b11, mixed mode)

/usr/lib/jvm/java-8-oracle/bin/java
java version "1.8.0_131"
Java(TM) SE Runtime Environment (build 1.8.0_131-b11)
Java HotSpot(TM) 64-Bit Server VM (build 25.131-b11, mixed mode)

Note that if you want to know the versions of a different executable, you can modify the bash command that gets constructed to appropriately print version info. E.G. if you want to know all the versions of python you can run

which -a python | xargs -I{} echo "echo {};{} --version;echo" | sh


问:
Python - how to use few times the same next iteration?
I would like to search a list:

```<code>[0, 0, 1, 0, 1, 1, 1, 0, 1, 1]
</code>```

and replace/edit items different from the previous item and next item. For xxample: I want to get rid of/edit 1 at index 2 in the list above.

Take a look at my code below and please continue reading my core question beneath my code:

!Update: Result should be: [0, 0, 0, 0, 1, 1, 1, 1, 1, 1]

```<code>x = [0, 0, 1, 0, 1, 1, 1, 0, 1, 1]
print(x)
hiter = iter(x)
next(hiter)
prev = None

for i in x:
    try:
        print('prev %s - CURRENT %s - next %s' % (prev, i, next(hiter)))
        prev = i

        #if i != prev and i != next(hiter):
        #   x[i] = prev

    except StopIteration:
        break

print(x)
</code>```

We know the previous item, the next item and the current item.

But everytime I use:

```
if i != prev and <b>i != next(hiter)</b>...
```

the next(hiter) destroys order. In other words, if I use next(hiter) more than 1 time in my loop, Python reads the next item as double, because I used next(hiter) two times in a loop.

I tried also declare seperate variable like y = next(hiter) - but still it didn't work (obviously won't work but I was desperate to check it anyway xD).

I have no clues, in addition, hiter.__next__() does the same as next(hiter).

答:
You could use a generator that keeps the previous item and looks one item ahead:

```<code>def gen(x):
    x = iter(x)
    # Get the first item and simply yield it
    first = next(x)
    yield first

    # create a list containing the previous element, the current element and the next element
    # and iterate over your input.
    three = [None, first, next(x)]
    for item in x:
        # Update the list of elements: Remove the previous previous item and
        # add the new next item.
        three = three[1:] + [item]
        prev, cur, nxt = three

        if cur != prev and cur != nxt:
            three[1] = prev  # replace the current item with the previous item
            yield prev

        else:
            yield cur

    # Simply yield the last item
    yield three[-1]

>>> list(gen([0, 0, 1, 0, 1, 1, 1, 0, 1, 1]))
[0, 0, 0, 0, 1, 1, 1, 1, 1, 1]
</code>```

In this approach I simply returned the first and last item without checks because the only have a next or previous item not both. You could put some checks there as well if you like.

As @MadPhysicist pointed out one doesn't need the list at all, you could simply use a variable for the previous, current and next item:

```<code>def gen(x):
    x = iter(x)
    # Get the first item and simply yield it
    first = next(x)
    yield first

    cur, nxt = first, next(x)  # Initial current and next item
    for item in x:
        prev, cur, nxt = cur, nxt, item  # Update the previous, current and next item

        if cur != prev and cur != nxt:
            cur = prev
            yield prev

        else:
            yield cur

    # Simply yield the last item
    yield nxt
</code>```

NB: Both approaches will create a new list and don't modify the original list.

Body:
I would like to search a list:

[0, 0, 1, 0, 1, 1, 1, 0, 1, 1]

and replace/edit items different from the previous item and next item. For xxample: I want to get rid of/edit 1 at index 2 in the list above.

Take a look at my code below and please continue reading my core question beneath my code:

!Update: Result should be: [0, 0, 0, 0, 1, 1, 1, 1, 1, 1]

x = [0, 0, 1, 0, 1, 1, 1, 0, 1, 1]
print(x)
hiter = iter(x)
next(hiter)
prev = None

for i in x:
    try:
        print('prev %s - CURRENT %s - next %s' % (prev, i, next(hiter)))
        prev = i

        #if i != prev and i != next(hiter):
        #   x[i] = prev

    except StopIteration:
        break

print(x)

We know the previous item, the next item and the current item.

But everytime I use:

if i != prev and i != next(hiter)...

the next(hiter) destroys order. In other words, if I use next(hiter) more than 1 time in my loop, Python reads the next item as double, because I used next(hiter) two times in a loop.

I tried also declare seperate variable like y = next(hiter) - but still it didn't work (obviously won't work but I was desperate to check it anyway xD).

I have no clues, in addition, hiter.__next__() does the same as next(hiter).

Body:
You could use a generator that keeps the previous item and looks one item ahead:

def gen(x):
    x = iter(x)
    # Get the first item and simply yield it
    first = next(x)
    yield first

    # create a list containing the previous element, the current element and the next element
    # and iterate over your input.
    three = [None, first, next(x)]
    for item in x:
        # Update the list of elements: Remove the previous previous item and
        # add the new next item.
        three = three[1:] + [item]
        prev, cur, nxt = three

        if cur != prev and cur != nxt:
            three[1] = prev  # replace the current item with the previous item
            yield prev

        else:
            yield cur

    # Simply yield the last item
    yield three[-1]

>>> list(gen([0, 0, 1, 0, 1, 1, 1, 0, 1, 1]))
[0, 0, 0, 0, 1, 1, 1, 1, 1, 1]

In this approach I simply returned the first and last item without checks because the only have a next or previous item not both. You could put some checks there as well if you like.

As @MadPhysicist pointed out one doesn't need the list at all, you could simply use a variable for the previous, current and next item:

def gen(x):
    x = iter(x)
    # Get the first item and simply yield it
    first = next(x)
    yield first

    cur, nxt = first, next(x)  # Initial current and next item
    for item in x:
        prev, cur, nxt = cur, nxt, item  # Update the previous, current and next item

        if cur != prev and cur != nxt:
            cur = prev
            yield prev

        else:
            yield cur

    # Simply yield the last item
    yield nxt

NB: Both approaches will create a new list and don't modify the original list.


问:
How I can detect window resize instantly in angular 2?
Some features in my component turn on or off depend on browser size, therefore I want to check browser width on resize event. However, I could do it using OnInit method. But I need to refresh browser when resize happened to update browser width

```<code> ngOnInit() {
     if (window.innerWidth <= 767){
       ---- do something
      }
   }
</code>```

I tried to use OnChanges method, but it does not work either.

```<code>OnChanges(changes:SimpleChanges){
console.log( 'width:====>' + changes[window.innerWidth].currentValue);
  if ( changes[window.innerWidth].currentValue <= 767 ){
      ---- do something
}
</code>```

}

is there any suggestions or alternative way to accomplish this?

答:
Use HostListener. You should probably debounce the resize event though before doing anything, it will fire everytime the size changes which could be dozens or hundreds of times in a few milliseconds as the user drags the window size.</p>

```<code>import { Component, HostListener } from '@angular/core';

@Component({...})
class TestComponent {
    @HostListener('window:resize')
    onWindowResize() {
        //debounce resize, wait for resize to finish before doing stuff
        if (this.resizeTimeout) {
            clearTimeout(this.resizeTimeout);
        }
        this.resizeTimeout = setTimeout((() => {
            console.log('Resize complete');
        }).bind(this), 500);
    }
}
</code>```

Body:
Some features in my component turn on or off depend on browser size, therefore I want to check browser width on resize event. However, I could do it using OnInit method. But I need to refresh browser when resize happened to update browser width

 ngOnInit() {
     if (window.innerWidth <= 767){
       ---- do something
      }
   }

I tried to use OnChanges method, but it does not work either.

OnChanges(changes:SimpleChanges){
console.log( 'width:====>' + changes[window.innerWidth].currentValue);
  if ( changes[window.innerWidth].currentValue <= 767 ){
      ---- do something
}

}

is there any suggestions or alternative way to accomplish this?

Body:
Use HostListener. You should probably debounce the resize event though before doing anything, it will fire everytime the size changes which could be dozens or hundreds of times in a few milliseconds as the user drags the window size.

import { Component, HostListener } from '@angular/core';

@Component({...})
class TestComponent {
    @HostListener('window:resize')
    onWindowResize() {
        //debounce resize, wait for resize to finish before doing stuff
        if (this.resizeTimeout) {
            clearTimeout(this.resizeTimeout);
        }
        this.resizeTimeout = setTimeout((() => {
            console.log('Resize complete');
        }).bind(this), 500);
    }
}


问:
trying to figure out N / S / E / W side of street w/ Google Maps API
Were using Google Maps API to figure out some GIS specific info but we're struggling to get the side of the street that an address or geocode is on. I've looked through stackoverflow and google maps api groups but not seeing too many other people who want/need this.

As an example, 40 St Marks Ave, Brooklyn, NY is on the S (South) side of the street, we can see this if we plot it using Google Maps, but I'm not seeing where this info is returned when we make an API call.

If it's something that the API really doesn't return, any of you folks have a clever way of figuring that out? Been scratching my head on this one and starting to think that I'm just not looking at it quite the right way.

btw, we definitely need the side of the street info returned as compass coordinates (aka N/S/W/E).

Thanks.

答: A simple solution that comes to mind is to use a timestamp on multiple pictures, while moving down the street. From there we can get to know the direction of movement and know whether the building was on the left or right of the street.


问:
GET the Page Source of desktop site not mobile Site
is it possible to get the desktop stie page source of an website instead of the mobile website ?
My Code:</p>

```<code> public void test() {
    ;
 // Instantiate the RequestQueue.
    RequestQueue queue = Volley.newRequestQueue(this);
    String url = "google.com";

  // Request a string response from the provided URL.
    button = (TextView) findViewById(R.id.buttoneins);

    StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
               button.setText("Response is: " + response.substring(0,5532));
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            button.setText("That didn't work!");
        }
    });
    // Add the request to the RequestQueue.
    queue.add(stringRequest);
  }
</code>```

答:
try to override public Map<String, String> getHeaders().

```<code> StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
        new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
           button.setText("Response is: " + response.substring(0,5532));
            }
        }, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        button.setText("That didn't work!");
    },
    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
            Map<String, String>  params = new HashMap<String, String>();
            params.put("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0");

            return params;
    }

});
</code>```

Body:
is it possible to get the desktop stie page source of an website instead of the mobile website ?
My Code:

 public void test() {
    ;
 // Instantiate the RequestQueue.
    RequestQueue queue = Volley.newRequestQueue(this);
    String url = "google.com";

  // Request a string response from the provided URL.
    button = (TextView) findViewById(R.id.buttoneins);

    StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
               button.setText("Response is: " + response.substring(0,5532));
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            button.setText("That didn't work!");
        }
    });
    // Add the request to the RequestQueue.
    queue.add(stringRequest);
  }

Body:
try to override public Map<String, String> getHeaders().

 StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
        new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
           button.setText("Response is: " + response.substring(0,5532));
            }
        }, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        button.setText("That didn't work!");
    },
    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
            Map<String, String>  params = new HashMap<String, String>();
            params.put("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0");

            return params;
    }

});


问:
SSRS Sum Expression for Adding Percent Column
I think I've exhausted my searches with Google.  Before it gets suggested, and I know it will, I cannot update my stored procedure to do this because of how the data is returned.  I have to do this calculation in the report.

My table is grouped by Service Month-Year and it's the only group.  I have a column in the table that calculates a percentage and that expression works great (see below).

    =Sum(Fields!POSTED_AFTER_SVC_MO.Value,"SvcMo_Yr") / Sum(Fields!POSTED_IN_SVC_MO.Value,"SvcMo_Yr") + Sum(Fields!POSTED_AFTER_SVC_MO.Value,"SvcMo_Yr"))

What I'm unable to do is calculate a future percentage based on the results from the expression above.

In the example below, in order to get the future percentage for April 2017 (bottom table in image), I need to add the percentages for March through October and divide by 6.  In Excel I use an Offset function to get those 6 rows but in SSRS I can't figure it out.

Example Data

One thing I have been able to do is calculate the average percentage for each month using an indicator I added to my stored procedure.  If there was a way that I could just sum these I would be home free.  Adding a total row and an extra Sum in the expression below did not work.

=Sum(Avg(IIF(Fields!FUTURE_MNTH_1_CALC_IND.Value = 1, CDbl(Sum(Fields!POSTED_AFTER_SVC_MO.Value) / (Sum(Fields!POSTED_IN_SVC_MO.Value) + Sum(Fields!POSTED_AFTER_SVC_MO.Value))),Cdbl(0))))/6

Thank you in advance for any advice you can throw my way!

John

答: I figured it out. I just recreated my stored procedure to do only the totaling because I only needed just those two totals. Then I added that new stored procedure as another dataset in my report and created at hidden table so I could use the Lookup function to retrieve the totals.  Worked like a charm!</p>


问:
How to remove one of the duplicate values that are next to each other in a list?
```<code>x1 = [5, 5]
x2 = [1, 5, 5, 2]
x3 = [5, 5, 1, 2, 5, 5]
x4 = [5, 5, 1, 5, 5, 2, 5, 5]
x5 = [5, -5]
x6 = [1, 2, 3, 4]
x7 = [5, 5, 5, 5, 5, 5]
</code>```

How do I remove one of the duplicate values that are next to each other on every list?

After all one of the duplicate values that are next to each other are removed, they should look like this:

```<code>x1 = [5]
x2 = [1, 5, 2]
x3 = [5, 1, 2, 5]
x4 = [5, 1, 5, 2, 5]
x5 = [5, -5]
x6 = [1, 2, 3, 4]
x7 = [5]
</code>```

答:
Simple list comprehension would do:

```<code>>>> x = [5, 5, 1, 5, 2, 5, 5]
>>> [a for a, b in zip(x, x[1:]) if a != b] + [x[-1]]
[5, 1, 5, 2, 5]
</code>```

You are basically taking each element if the next one differs, plus the last element.

Body:
x1 = [5, 5]
x2 = [1, 5, 5, 2]
x3 = [5, 5, 1, 2, 5, 5]
x4 = [5, 5, 1, 5, 5, 2, 5, 5]
x5 = [5, -5]
x6 = [1, 2, 3, 4]
x7 = [5, 5, 5, 5, 5, 5]

How do I remove one of the duplicate values that are next to each other on every list?

After all one of the duplicate values that are next to each other are removed, they should look like this:

x1 = [5]
x2 = [1, 5, 2]
x3 = [5, 1, 2, 5]
x4 = [5, 1, 5, 2, 5]
x5 = [5, -5]
x6 = [1, 2, 3, 4]
x7 = [5]

Body:
Simple list comprehension would do:

>>> x = [5, 5, 1, 5, 2, 5, 5]
>>> [a for a, b in zip(x, x[1:]) if a != b] + [x[-1]]
[5, 1, 5, 2, 5]

You are basically taking each element if the next one differs, plus the last element.


问:
In a multi-account AWS environment, how would I force a role assumption on a IAM user when he/she logs in?
I am managing a multi-account AWS environment with consolidated billing. At the same time, I centralize all IAM user creation under one alias (account) for effective management. But their resources reside in other AWS accounts which are created on project basis.

I have set up the delegated Access across AWS accounts using IAM roles and it works. However these users need to switch role manually every time they log on. It is cumbersome. How could I force these users to acquire such role automatically when they log on ?

答:
You can provide them with the link to directly log into that account that they consider "native". If they are not logged into the base account AWS will force a log into that account, then switch role automatically.

You can manually construct the link yourself by using the following format:
  https://signin.aws.amazon.com/switchrole?account=account_id_number&roleName=role_name&displayName=text_to_display
  Where your administrator provides the account_id_number and role_name to you. For text_to_display, see the explanation in step 5 in the following procedure.

http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_switch-role-console.html