问:
How to dynamically choose the configurations based on the environment in JAVA?
I have a utility class which has common configurations related to email-sender, the configurations changes based on the environment like Staging and Production. Now how can I dynamically choose the configurations based on the environment?

here is my code,

EmailUtility.java

```<code>package com.housecar.common;

public class EmailUtility {

 //For staging
 public static final String FROM_EMAIL_ID = "xx12@xyz.com";
 public static final String FROM_NAME = "xyz";
 static final String SMTP_USERNAME = "xx12@xyz.com";
 static final String SMTP_PASSWORD = "15sss67$";
 public static final String REPLY_EMAIL_ID = "xx12@xyz.com";
 public static final String MAIL_SMTP_PORT = "587";
 public static final String MAIL_SMTP_SOCKET_FACTORY_PORT = "587";
 public static final String SMTP_HOST = "smtp.gmail.com";
 public static final String MAIL_SMTP_SOCKETFACTORY_CLASS = "javax.net.ssl.SSLSocketFactory";

 //for production

 /*public static final String FROM_EMAIL_ID = "admin@xyz.com";
 public static final String FROM_NAME = "xyz";
 static final String SMTP_USERNAME = "AKYeeeELEQAGAA"; // Replace with
                                                            // your SMTP
                                                            // username.
 static final String SMTP_PASSWORD = "gvwwwwwbgpGm/C/LmUYUK5HosQar7mTSwjl5MFeBRR";
 public static final String REPLY_EMAIL_ID = "admin@xyz.com";
 public static final String MAIL_SMTP_PORT = "587";
 public static final String MAIL_SMTP_SOCKET_FACTORY_PORT = "587";
 public static final String SMTP_HOST = "email-smtp.us-east-1.amazonaws.com";
 public static final String MAIL_SMTP_SOCKETFACTORY_CLASS = "javax.net.ssl.SSLSocketFactory";*/

}
</code>```

In my code I'm manually commenting out the configuration!

答:
The other answers here are a step in the right direction.

Some suggest to move the configuration values into a .properties file. This is a big step in the right direction, but ignores the fact that you're using Spring Boot.

Some suggest to move the configuration values into the Spring application.properties or application.yaml files. This is the better choice for a Spring application. application.properties is actually just a .properties file like first suggested, but is automatically loaded by the Spring Framework. This is all described in Chapter 24. Externalized Configuration of the Spring Boot Reference Guide.

But, your question actually said:

[...] common configurations related to email-sender, the configurations changes based on the environment like Staging and Production.

Spring has a very nice feature, where you can have one set of configuration files (or even a single .yaml file), and the framework will automatically load the appropriate configuration values, depending on where the application is running, in Staging or Production. This is all described in Chapter 25. Profiles.

Body:
I have a utility class which has common configurations related to email-sender, the configurations changes based on the environment like Staging and Production. Now how can I dynamically choose the configurations based on the environment?

here is my code,

EmailUtility.java

package com.housecar.common;

public class EmailUtility {

 //For staging
 public static final String FROM_EMAIL_ID = "xx12@xyz.com";
 public static final String FROM_NAME = "xyz";
 static final String SMTP_USERNAME = "xx12@xyz.com";
 static final String SMTP_PASSWORD = "15sss67$";
 public static final String REPLY_EMAIL_ID = "xx12@xyz.com";
 public static final String MAIL_SMTP_PORT = "587";
 public static final String MAIL_SMTP_SOCKET_FACTORY_PORT = "587";
 public static final String SMTP_HOST = "smtp.gmail.com";
 public static final String MAIL_SMTP_SOCKETFACTORY_CLASS = "javax.net.ssl.SSLSocketFactory";

 //for production

 /*public static final String FROM_EMAIL_ID = "admin@xyz.com";
 public static final String FROM_NAME = "xyz";
 static final String SMTP_USERNAME = "AKYeeeELEQAGAA"; // Replace with
                                                            // your SMTP
                                                            // username.
 static final String SMTP_PASSWORD = "gvwwwwwbgpGm/C/LmUYUK5HosQar7mTSwjl5MFeBRR";
 public static final String REPLY_EMAIL_ID = "admin@xyz.com";
 public static final String MAIL_SMTP_PORT = "587";
 public static final String MAIL_SMTP_SOCKET_FACTORY_PORT = "587";
 public static final String SMTP_HOST = "email-smtp.us-east-1.amazonaws.com";
 public static final String MAIL_SMTP_SOCKETFACTORY_CLASS = "javax.net.ssl.SSLSocketFactory";*/

}

In my code I'm manually commenting out the configuration!


来源: stackexchange

问:
Handling XML escape characters (e.g. quotes) using JAXB Marshaller
I need to serialize an XML java object to a XML file using the JAXB Marshaller (JAXB version 2.2). Now in the xml object, I have a tag which contains String value such that:

```<code>"<"tagA>
**"<"YYYYY>done"<"/YYYYY>**
"<"/tagA>
</code>```

Now as you can see that this string value again contains tags.
I want this to be written in the same way in the xml file.

But JAXB Marshaller converts these values such as:

"&"lt;YYYYY"&"gt;"&"#xD;done   ...& so on

I am not able to treat these escape characters separately using JAXB 2.2
Is it possible anyways?

Any help in this regard will be great..

Thanks in advance,
Abhinav Mishra

答:
You can leverage the CDATA structure.  Standard JAXB does not cover this structure.  There is an extension in EclipseLink JAXB (MOXy) for this (I'm the tech lead).  Check out my answer to a related question:

How to generate CDATA block using JAXB?

It describes the @XmlCDATA annotation in MOXy:

```<code>import javax.xml.bind.annotation.XmlRootElement;
import org.eclipse.persistence.oxm.annotations.XmlCDATA;

@XmlRootElement(name="c")
public class Customer {

   private String bio;

   @XmlCDATA
   public void setBio(String bio) {
      this.bio = bio;
   }

   public String getBio() {
      return bio;
   }

}
</code>```

For more information see:

http://bdoughan.blogspot.com/2010/07/cdata-cdata-run-run-data-run.html

ContentLicense: CC BY-SA 3.0

Body:
I need to serialize an XML java object to a XML file using the JAXB Marshaller (JAXB version 2.2). Now in the xml object, I have a tag which contains String value such that:

"<"tagA>
**"<"YYYYY>done"<"/YYYYY>**
"<"/tagA>

Now as you can see that this string value again contains tags.
I want this to be written in the same way in the xml file.

But JAXB Marshaller converts these values such as:

"&"lt;YYYYY"&"gt;"&"#xD;done   ...& so on

I am not able to treat these escape characters separately using JAXB 2.2
Is it possible anyways?

Any help in this regard will be great..

Thanks in advance,
Abhinav Mishra

Body:
You can leverage the CDATA structure.  Standard JAXB does not cover this structure.  There is an extension in EclipseLink JAXB (MOXy) for this (I'm the tech lead).  Check out my answer to a related question:

How to generate CDATA block using JAXB?

It describes the @XmlCDATA annotation in MOXy:

import javax.xml.bind.annotation.XmlRootElement;
import org.eclipse.persistence.oxm.annotations.XmlCDATA;

@XmlRootElement(name="c")
public class Customer {

   private String bio;

   @XmlCDATA
   public void setBio(String bio) {
      this.bio = bio;
   }

   public String getBio() {
      return bio;
   }

}

For more information see:

http://bdoughan.blogspot.com/2010/07/cdata-cdata-run-run-data-run.html

ContentLicense: CC BY-SA 2.5


问:
Upload file using AJAX with CodeIgniter
I've tried many example. This one ever succeed but sometimes it failed to upload. This is my code :

```<code><div class="fallback">
    <form method="POST" id="quiz_file" action="<?php echo site_url('home/upload_quiz/' . $kelas);?>" enctype="multipart/form-data">
        <input name="filequiz" id="filequiz" type="file" />
    </form>
</div>
</code>```

This is the ajax code :

```<code>$('#submitquiz').on('click', function(event) {
                var inputFile = $('input[name=filequiz]');
                var uploadURI = $('#quiz_file').attr('action');
                document.getElementById('submitquiz').disabled = true;
                var fileToUpload = inputFile[0].files[0];
                // make sure there is file to upload
                if (fileToUpload != 'undefined')
                {
                    // provide the form data
                    // that would be sent to sever through ajax
                    var formData = new FormData();
                    formData.append("file", fileToUpload);
                    console.log("Process");
                    // now upload the file using $.ajax
                    $.ajax({
                        url: uploadURI,
                        type: 'post',
                        data: formData,
                        processData: false,
                        contentType: false,
                        beforeSend: function ( xhr ) {
                           console.log("progress");
                           console.log(xhr);
                           console.log(formData);
                        },
                        success: function(data)
                        {
                           console.log("finish");
                           console.log(data);
                        }
</code>```

This is my controller :

```<code>function upload_quiz($kelas)
    {
        $temp = explode(".", $_FILES["filequiz"]["name"]);
        $extension = end($temp);
        $new_name = time() . "." . $extension;
        $config['upload_path']          = './assets/images/quiz_images/';
        $config['allowed_types']        = 'gif|jpg|png|jpeg';
        $config['max_size']             = 2000;
        $config['file_name']            = $new_name;
        $config['max_width']            = 1024;
        $config['max_height']           = 768;
        $this->load->library('upload', $config);

        $session_data = $this->session->userdata('logged_in');
        $data['user_name'] = $session_data['user_name'];
        $data['kelas'] = $kelas;
        if ( ! $this->upload->do_upload('filequiz'))
        {
            $data['error'] = array('error' => $this->upload->display_errors());
            $this->load->view('course', $data);
        }
        else
        {
            $data['status'] = array('upload_data' => $this->upload->data());
            $quiz_name = $this->input->post('quiz_name');
            $this->load->model('Model');
            if($this->Model->input_quiz($quiz_name,$new_name,$kelas) == TRUE)
            {
                $this->load->view('course', $data);
            }
            elseif($this->Model->input_quiz($quiz_name,$new_name,$kelas) == FALSE)
            {
                $this->load->view('course', $data);
            }
        }
    }
</code>```

After i submit using button, the AJAX response when im using console.log(data). And it says the first line in my controller function ($temp) is UNDIFEND INDEX : filequiz.

What could im missing about ?

答:
Change this

```<code>  $temp = explode(".", $_FILES["filequiz"]["name"]);
</code>```

as following

```<code> $temp = explode(".", $_FILES["file"]["name"]);
</code>```

and if ( ! $this->upload->do_upload('filequiz')) to if ( ! $this->upload->do_upload('file'))

as you sending filename as file by JS not filequiz

However if you want to use name filequiz then change ajax code from

```<code>formData.append("file", fileToUpload);
</code>```

to

```<code>formData.append("filequiz", fileToUpload);
</code>```

Title: Upload file using AJAX with CodeIgniter

Body:
I've tried many example. This one ever succeed but sometimes it failed to upload. This is my code :

    <form method="POST" id="quiz_file" action="<?php echo site_url('home/upload_quiz/' . $kelas);?>" enctype="multipart/form-data">
        <input name="filequiz" id="filequiz" type="file" />
    </form>

This is the ajax code :

$('#submitquiz').on('click', function(event) {
                var inputFile = $('input[name=filequiz]');
                var uploadURI = $('#quiz_file').attr('action');
                document.getElementById('submitquiz').disabled = true;
                var fileToUpload = inputFile[0].files[0];
                // make sure there is file to upload
                if (fileToUpload != 'undefined')
                {
                    // provide the form data
                    // that would be sent to sever through ajax
                    var formData = new FormData();
                    formData.append("file", fileToUpload);
                    console.log("Process");
                    // now upload the file using $.ajax
                    $.ajax({
                        url: uploadURI,
                        type: 'post',
                        data: formData,
                        processData: false,
                        contentType: false,
                        beforeSend: function ( xhr ) {
                           console.log("progress");
                           console.log(xhr);
                           console.log(formData);
                        },
                        success: function(data)
                        {
                           console.log("finish");
                           console.log(data);
                        }

This is my controller :

function upload_quiz($kelas)
    {
        $temp = explode(".", $_FILES["filequiz"]["name"]);
        $extension = end($temp);
        $new_name = time() . "." . $extension;
        $config['upload_path']          = './assets/images/quiz_images/';
        $config['allowed_types']        = 'gif|jpg|png|jpeg';
        $config['max_size']             = 2000;
        $config['file_name']            = $new_name;
        $config['max_width']            = 1024;
        $config['max_height']           = 768;
        $this->load->library('upload', $config);

        $session_data = $this->session->userdata('logged_in');
        $data['user_name'] = $session_data['user_name'];
        $data['kelas'] = $kelas;
        if ( ! $this->upload->do_upload('filequiz'))
        {
            $data['error'] = array('error' => $this->upload->display_errors());
            $this->load->view('course', $data);
        }
        else
        {
            $data['status'] = array('upload_data' => $this->upload->data());
            $quiz_name = $this->input->post('quiz_name');
            $this->load->model('Model');
            if($this->Model->input_quiz($quiz_name,$new_name,$kelas) == TRUE)
            {
                $this->load->view('course', $data);
            }
            elseif($this->Model->input_quiz($quiz_name,$new_name,$kelas) == FALSE)
            {
                $this->load->view('course', $data);
            }
        }
    }

After i submit using button, the AJAX response when im using console.log(data). And it says the first line in my controller function ($temp) is UNDIFEND INDEX : filequiz.

What could im missing about ?

Body:
Change this

  $temp = explode(".", $_FILES["filequiz"]["name"]);

as following

 $temp = explode(".", $_FILES["file"]["name"]);

and if ( ! $this->upload->do_upload('filequiz')) to if ( ! $this->upload->do_upload('file'))

as you sending filename as file by JS not filequiz

However if you want to use name filequiz then change ajax code from

formData.append("file", fileToUpload);

to

formData.append("filequiz", fileToUpload);


问:
how to summarise only numerical columns in R
I want to have summary of only numerical columns of R dataframe. I am doing following

```<code>numeric_var <- names(df)[which(sapply(df, is.numeric))]

summary(df[,.SD, .SDcols = numeric_var])
</code>```

But, I get following error

```<code>Error in `[.data.frame`(df, , .SD, .SDcols = numeric_var) :
unused argument (.SDcols = numeric_var)
</code>```

How can I do it in R?

答:
It seems, the OP is using data.table syntax (i.e., SDcols = ...) but according to the error message df is only of class data.frame.

To use data.table syntax, the data.tablepackage has to be loaded and df needs to be coerced to class data.table. Below is a complete example:

```<code>set.seed(1234L)
DF <- data.frame(a = LETTERS[1:5], b = rnorm(5), c = 1:5)
DF
#  a          b c
#1 A -1.2070657 1
#2 B  0.2774292 2
#3 C  1.0844412 3
#4 D -2.3456977 4
#5 E  0.4291247 5

numeric_var <- names(DF)[sapply(DF, is.numeric)]

library(data.table)
setDT(DF)[, summary(.SD), .SDcols = numeric_var]
#       b                 c
# Min.   :-2.3457   Min.   :1
# 1st Qu.:-1.2071   1st Qu.:2
# Median : 0.2774   Median :3
# Mean   :-0.3524   Mean   :3
# 3rd Qu.: 0.4291   3rd Qu.:4
# Max.   : 1.0844   Max.   :5
</code>```

Body:
I want to have summary of only numerical columns of R dataframe. I am doing following

numeric_var <- names(df)[which(sapply(df, is.numeric))]

summary(df[,.SD, .SDcols = numeric_var])

But, I get following error

Error in `[.data.frame`(df, , .SD, .SDcols = numeric_var) :
unused argument (.SDcols = numeric_var)

How can I do it in R?

Body:
It seems, the OP is using data.table syntax (i.e., SDcols = ...) but according to the error message df is only of class data.frame.

To use data.table syntax, the data.tablepackage has to be loaded and df needs to be coerced to class data.table. Below is a complete example:

set.seed(1234L)
DF <- data.frame(a = LETTERS[1:5], b = rnorm(5), c = 1:5)
DF
#  a          b c
#1 A -1.2070657 1
#2 B  0.2774292 2
#3 C  1.0844412 3
#4 D -2.3456977 4
#5 E  0.4291247 5

numeric_var <- names(DF)[sapply(DF, is.numeric)]

library(data.table)
setDT(DF)[, summary(.SD), .SDcols = numeric_var]
#       b                 c
# Min.   :-2.3457   Min.   :1
# 1st Qu.:-1.2071   1st Qu.:2
# Median : 0.2774   Median :3
# Mean   :-0.3524   Mean   :3
# 3rd Qu.: 0.4291   3rd Qu.:4
# Max.   : 1.0844   Max.   :5


问:
Replace array value with new one
I have array of array, where i want to change date format. I am trying to get it as below

```<code>foreach ($toReturn as $value) {

    $start_date = new DateTime($value['start_date']);
    $value['start_date'] = $start_date->format('m-d-Y');

    $end_date = new DateTime($value['end_date']);
    $value['end_date'] = $end_date->format('m-d-Y');
}
</code>```

here format gets changed but it is not replacing array value with new one?? Why??

答:
You have to change value by reference:</p>

```<code>foreach ($toReturn as &$value) {

    $start_date = new DateTime($value['start_date']);
    $value['start_date'] = $start_date->format('m-d-Y');

    $end_date = new DateTime($value['end_date']);
    $value['end_date'] = $end_date->format('m-d-Y');
}
</code>```

Title: Replace array value with new one

Body:
I have array of array, where i want to change date format. I am trying to get it as below

foreach ($toReturn as $value) {

    $start_date = new DateTime($value['start_date']);
    $value['start_date'] = $start_date->format('m-d-Y');

    $end_date = new DateTime($value['end_date']);
    $value['end_date'] = $end_date->format('m-d-Y');
}

here format gets changed but it is not replacing array value with new one?? Why??

Body:
You have to change value by reference:

foreach ($toReturn as &$value) {

    $start_date = new DateTime($value['start_date']);
    $value['start_date'] = $start_date->format('m-d-Y');

    $end_date = new DateTime($value['end_date']);
    $value['end_date'] = $end_date->format('m-d-Y');
}


问:
UITableView in Swift
I'm struggling to figure out what's wrong with this code snippet. This is currently working in Objective-C, but in Swift this just crashes on the first line of the method. It shows an error message in console log: Bad_Instruction.

```<code>func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell!  {
        var cell : UITableViewCell = tableView.dequeueReusableCellWithIdentifier("Cell") as UITableViewCell

        if (cell == nil) {
            cell = UITableViewCell(style: UITableViewCellStyle.Value1, reuseIdentifier: "Cell")
        }

        cell.textLabel.text = "TEXT"
        cell.detailTextLabel.text = "DETAIL TEXT"

        return cell
    }
</code>```

答:
I went through your codes and most probably the reason for the crash is you are trying to typecast an optional value  which is not assigned

Now consider the line of code below

```<code>var cell : UITableViewCell = tableView.dequeueReusableCellWithIdentifier("Cell") as UITableViewCell
</code>```

When there are no cells in the tableview you are still trying to typecast as UITableView.When the compiler tries to typecast nil value you face this issue

The correct statement should be

```<code>var cell : UITableViewCell = tableView.dequeueReusableCellWithIdentifier("Cell")
</code>```

You can use if else statement to typecast for values which holds

Title: UITableView in Swift

Body:
I'm struggling to figure out what's wrong with this code snippet. This is currently working in Objective-C, but in Swift this just crashes on the first line of the method. It shows an error message in console log: Bad_Instruction.

func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell!  {
        var cell : UITableViewCell = tableView.dequeueReusableCellWithIdentifier("Cell") as UITableViewCell

        if (cell == nil) {
            cell = UITableViewCell(style: UITableViewCellStyle.Value1, reuseIdentifier: "Cell")
        }

        cell.textLabel.text = "TEXT"
        cell.detailTextLabel.text = "DETAIL TEXT"

        return cell
    }

Body:
I went through your codes and most probably the reason for the crash is you are trying to typecast an optional value  which is not assigned

Now consider the line of code below

var cell : UITableViewCell = tableView.dequeueReusableCellWithIdentifier("Cell") as UITableViewCell

When there are no cells in the tableview you are still trying to typecast as UITableView.When the compiler tries to typecast nil value you face this issue

The correct statement should be

var cell : UITableViewCell = tableView.dequeueReusableCellWithIdentifier("Cell")

You can use if else statement to typecast for values which holds


问:
how to scale to fit the background image objective c
I am trying to set the image without any uiimageview,now I have the image but it is repeated horizontally twice I want to scale and fix it to screen size how do u do that??

I have tried some methods but nothing worked out

below is my code:

```<code>- (void)viewDidLoad {
[super viewDidLoad];
UIGraphicsBeginImageContext(self.view.frame.size);
[[UIImage imageNamed:@"background_themee.png"] drawInRect:self.view.bounds];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
// self.view.backgroundColor = [UIColor colorWithPatternImage:image];
// UIGraphicsBeginImageContext(self.view.frame.size);
// [[UIImage imageNamed:@"background_themee.png"]   drawInRect:self.view.bounds];
// UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
// UIGraphicsEndImageContext();
 self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage  imageNamed:@"background_themee"]];
 // Do any additional setup after loading the view.
}
</code>```

thanks in advance for your suggestions!!

答: you can select scale to fill or aspect fill/fit according to your need

Body:
I am trying to set the image without any uiimageview,now I have the image but it is repeated horizontally twice I want to scale and fix it to screen size how do u do that??

I have tried some methods but nothing worked out

below is my code:

- (void)viewDidLoad {
[super viewDidLoad];
UIGraphicsBeginImageContext(self.view.frame.size);
[[UIImage imageNamed:@"background_themee.png"] drawInRect:self.view.bounds];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
// self.view.backgroundColor = [UIColor colorWithPatternImage:image];
// UIGraphicsBeginImageContext(self.view.frame.size);
// [[UIImage imageNamed:@"background_themee.png"]   drawInRect:self.view.bounds];
// UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
// UIGraphicsEndImageContext();
 self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage  imageNamed:@"background_themee"]];
 // Do any additional setup after loading the view.
}

thanks in advance for your suggestions!!


问:
Initialize a new object from class in Enum
I have an Enum called Plugins:

```<code>public enum Plugins {

    ROTATING_LINE (plugin.rotatingline.RotatingLine.class),
    SNOW_SYSTEM (plugin.snow.SnowSystem.class);

    private Class<?> c;

    private Plugins (Class<?> c) {
        this.c = c;
    }

    public Class<?> getClassObject() {
        return c;
    }

}
</code>```

What I would like to do is to loop through all the enums in Plugins and create new objects from those using the variable c like this:

```<code>for (Plugins plugins : Plugins.values()) {
    Class<?> c = plugins.getClassObject();
    pluginList.add(new c(400, 400));
}
</code>```

Is there a way of accomplishing this with a similar method? The reason why I want to do this is to create a list of classes that should be added to the List plugins when I start my application.

答:
There are 2 ways:

use Enum.valueOf() static function, then cast it into your enum type.

```<code>Enum v = Enum.valueOf(TheEnumClass, valueInString);
</code>```

Use class.getEnumConstants() function to get the list of the enum constants, and loop this list and get.

```<code>Plugins[] plugins = Plugins.class.getEnumConstants();
for (Plugins plugin: plugins) {
    // use plugin.name() to get name and compare
}
</code>```

Body:
I have an Enum called Plugins:

public enum Plugins {

    ROTATING_LINE (plugin.rotatingline.RotatingLine.class),
    SNOW_SYSTEM (plugin.snow.SnowSystem.class);

    private Class<?> c;

    private Plugins (Class<?> c) {
        this.c = c;
    }

    public Class<?> getClassObject() {
        return c;
    }

}

What I would like to do is to loop through all the enums in Plugins and create new objects from those using the variable c like this:

for (Plugins plugins : Plugins.values()) {
    Class<?> c = plugins.getClassObject();
    pluginList.add(new c(400, 400));
}

Is there a way of accomplishing this with a similar method? The reason why I want to do this is to create a list of classes that should be added to the List plugins when I start my application.

Body:
There are 2 ways:

use Enum.valueOf() static function, then cast it into your enum type.

Enum v = Enum.valueOf(TheEnumClass, valueInString);

Use class.getEnumConstants() function to get the list of the enum constants, and loop this list and get.

Plugins[] plugins = Plugins.class.getEnumConstants();
for (Plugins plugin: plugins) {
    // use plugin.name() to get name and compare
}


问:
How can i ignore cases in react to filter data?
I have written a code which filters the data but it filters with Case of the alphabet, i want to ignore the case and filter.

Here is what i have written-

```<code>let filteredcontacts = this.props.contacts.filter(
     (contact) => {
         val= contact.name.indexOf(this.state.search)!==-1;
});
</code>```

答:
Before filtering the data first convert the text into lowercase by using toLocaleLowerCase() then use indexOf on that to check the index.

Write it like this:

```<code>let filteredcontacts = this.props.contacts.filter(contact => {
       return contact.name.toLocaleLowerCase().indexOf(this.state.search) !== -1;
});
</code>```

I think, inside filter it should be contact.name instead of friend.name.

Body:
I have written a code which filters the data but it filters with Case of the alphabet, i want to ignore the case and filter.

Here is what i have written-

let filteredcontacts = this.props.contacts.filter(
     (contact) => {
         val= contact.name.indexOf(this.state.search)!==-1;
});

Body:
Before filtering the data first convert the text into lowercase by using toLocaleLowerCase() then use indexOf on that to check the index.

Write it like this:

let filteredcontacts = this.props.contacts.filter(contact => {
       return contact.name.toLocaleLowerCase().indexOf(this.state.search) !== -1;
});

I think, inside filter it should be contact.name instead of friend.name.


问:
Parsing XML with REGEX in Java
Given the below XML snippet I need to get a list of name/value pairs for each child under DataElements. XPath or an XML parser cannot be used for reasons beyond my control so I am using regex.

```<code><?xml version="1.0"?>
<StandardDataObject xmlns="myns">
  <DataElements>
    <EmpStatus>2.0</EmpStatus>
    <Expenditure>95465.00</Expenditure>
    <StaffType>11.A</StaffType>
    <Industry>13</Industry>
  </DataElements>
  <InteractionElements>
    <TargetCenter>92f4-MPA</TargetCenter>
    <Trace>7.19879</Trace>
  </InteractionElements>
</StandardDataObject>
</code>```

The output I need is:
    [{EmpStatus:2.0},  {Expenditure:95465.00}, {StaffType:11.A}, {Industry:13}]

The tag names under DataElements are dynamic and so cannot be expressed literally in the regex. The tag names TargetCenter and Trace are static and could be in the regex but if there is a way to avoid hardcoding that would be preferable.

```<code>"<([A-Za-z0-9]+?)>([A-Za-z0-9.]*?)</"
</code>```

This is the regex I have constructed and it has the problem that it erroneously includes {Trace:719879} in the results.  Relying on new-lines within the XML or any other apparent formatting is not an option.

Below is an approximation of the Java code I am using:

```<code>private static final Pattern PATTERN_1 = Pattern.compile(..REGEX..);
private List<DataElement> listDataElements(CharSequence cs) {
    List<DataElement> list = new ArrayList<DataElement>();
    Matcher matcher = PATTERN_1.matcher(cs);
    while (matcher.find()) {
        list.add(new DataElement(matcher.group(1), matcher.group(2)));
    }
    return list;
}
</code>```

How can I change my regex to only include data elements and ignore the rest?

答:
Try to parse the Reg Ex via a property file and create then pattern object. I sorted out the same issue I faced while injecting Reg Ex via xml beans.

Ex :- I needed to parse the Reg Ex '(.)(D[0-9]{7}.D[0-9]{9}.D[A-Z]{3}[0-9]{4})(.)' by injecting in Spring. But it didn't work. Once tried to use the same Reg Ex hard coded in a Java class it worked.

Pattern pattern = Pattern.compile("(.)(D[0-9]{7}.D[0-9]{9}.D[A-Z]{2}[0-9]{4})(.)"); Matcher matcher = pattern.matcher(file.getName().trim());

```<code>Next I tried to load that Reg Ex via property file while injecting it. It worked fine.

  p:remoteDirectory="${rawDailyReport.remote.download.dir}"
  p:localDirectory="${rawDailyReport.local.valid.dir}"
  p:redEx="${rawDailyReport.download.regex}"
</code>```

And in the property file the property is defined as follows.

rawDailyReport.download.regex=(.)(D[0-9]{7}\.D[0-9]{9}\.D[A-Z]{2}[0-9]{4})(.)

This is because the values with place holders are loaded through org.springframework.beans.factory.config.PropertyPlaceholderConfigurer and it handles these xml sensitive characters internally.

Thanks,
Amith

OwnerDisplayName: Mocky

Title: Parsing XML with REGEX in Java

Body:
Given the below XML snippet I need to get a list of name/value pairs for each child under DataElements. XPath or an XML parser cannot be used for reasons beyond my control so I am using regex.

<?xml version="1.0"?>
<StandardDataObject xmlns="myns">
  <DataElements>
    <EmpStatus>2.0</EmpStatus>
    <Expenditure>95465.00</Expenditure>
    <StaffType>11.A</StaffType>
    <Industry>13</Industry>
  </DataElements>
  <InteractionElements>
    <TargetCenter>92f4-MPA</TargetCenter>
    <Trace>7.19879</Trace>
  </InteractionElements>
</StandardDataObject>

The output I need is:
    [{EmpStatus:2.0},  {Expenditure:95465.00}, {StaffType:11.A}, {Industry:13}]

The tag names under DataElements are dynamic and so cannot be expressed literally in the regex. The tag names TargetCenter and Trace are static and could be in the regex but if there is a way to avoid hardcoding that would be preferable.

"<([A-Za-z0-9]+?)>([A-Za-z0-9.]*?)</"

This is the regex I have constructed and it has the problem that it erroneously includes {Trace:719879} in the results.  Relying on new-lines within the XML or any other apparent formatting is not an option.

Below is an approximation of the Java code I am using:

private static final Pattern PATTERN_1 = Pattern.compile(..REGEX..);
private List<DataElement> listDataElements(CharSequence cs) {
    List<DataElement> list = new ArrayList<DataElement>();
    Matcher matcher = PATTERN_1.matcher(cs);
    while (matcher.find()) {
        list.add(new DataElement(matcher.group(1), matcher.group(2)));
    }
    return list;
}

How can I change my regex to only include data elements and ignore the rest?

LastEditorDisplayName: Steve McLeod

Body:
Try to parse the Reg Ex via a property file and create then pattern object. I sorted out the same issue I faced while injecting Reg Ex via xml beans.

Ex :- I needed to parse the Reg Ex '(.)(D[0-9]{7}.D[0-9]{9}.D[A-Z]{3}[0-9]{4})(.)' by injecting in Spring. But it didn't work. Once tried to use the same Reg Ex hard coded in a Java class it worked.

Pattern pattern = Pattern.compile("(.)(D[0-9]{7}.D[0-9]{9}.D[A-Z]{2}[0-9]{4})(.)"); Matcher matcher = pattern.matcher(file.getName().trim());

Next I tried to load that Reg Ex via property file while injecting it. It worked fine.

  p:remoteDirectory="${rawDailyReport.remote.download.dir}"
  p:localDirectory="${rawDailyReport.local.valid.dir}"
  p:redEx="${rawDailyReport.download.regex}"

And in the property file the property is defined as follows.

rawDailyReport.download.regex=(.)(D[0-9]{7}\.D[0-9]{9}\.D[A-Z]{2}[0-9]{4})(.)

This is because the values with place holders are loaded through org.springframework.beans.factory.config.PropertyPlaceholderConfigurer and it handles these xml sensitive characters internally.

Thanks,
Amith


问:
how to display image when image tag special?
I have a code:

```<code><div><img src=".../media/wysiwyg/ingresso-festa-retro-mix.jpg" >
</code>```

It is not display image. However, when I use <> then it display normally:

```<code><div><img src=".../media/wysiwyg/ingresso-festa-retro-mix.jpg">
</code>```

is someone know it?

答:
You can achieve this by using jquery without you wont. otherwise if its jade or pug means you can because they having compiler to compile it into HTML. but DOM may have some property for HTML to render.
even though < and > will render into < > but only after DOM.

Sample using jquery,

$('#demo').each(function(){
    var $this = $(this);
    var t = $this.text();
    $this.html(t.replace('&lt','<').replace('&gt', '>'));
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<div id="demo"><img src="http://i.stack.imgur.com/oURrw.png"></div></code>```

Body:
I have a code:

It is not display image. However, when I use <> then it display normally:

is someone know it?

Body:
You can achieve this by using jquery without you wont. otherwise if its jade or pug means you can because they having compiler to compile it into HTML. but DOM may have some property for HTML to render.
even though < and > will render into < > but only after DOM.

Sample using jquery,

$('#demo').each(function(){
    var $this = $(this);
    var t = $this.text();
    $this.html(t.replace('&lt','<').replace('&gt', '>'));
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<div id="demo">&lt;img src="http://i.stack.imgur.com/oURrw.png"&gt;</div>


问:
'Undefined' JSON data
This is my first time using JSON. I have an external json file and I am using the json file in my html file to create divs with every json data read. I can get the correct output for all of the values, except for one which is the 'descript' value. I have tried printing it to the cosole log but all I'm getting for that particular value is 'undefined' but the other values are alright. Any idea on why this happened?

JSON file:

```<code>[{"title":"3G","filePath":"https://example.com","descript":"hello world"}, {"title":"4G", "filePath":"https://example.com", "descript": "test"} ]
</code>```

HTML file:

```<code> $.ajax({
      url : "testJSON.json",
      type : "get", // whichever you like
      contentType:"json",
      success : function(list)
        {
          var divCol  = "<div class='col-sm-4 col-md-4'>";
          var divWell = "<div class='well'>";
          var divClose= "</div>";

          list.forEach(function(obj, index) {

            var title     = "<h5>"      + obj.title    + "</h5>";
            var desc      = "<p>"       + obj.descript + "</p>";
            var linkStart = "<a class='btn btn-default' style='float:left' href='" + obj.filePath + "' target='_blank'>";
            var linkEnd   = "CSV</a>";
            var div = divCol    +
            divWell     +
            title       +
            desc        +
            linkStart       +
           // image       +
            linkEnd +
            divClose +
            divClose;

              console.log(list)
           $("#imdaFiles").append(div); // insert the div you've just created

           })
        }
    });
</code>```

答: Just a short notice that might solve the issue.. you misplaced a double quote on the right side of the last descript key in your JSON.

Title: 'Undefined' JSON data

Body:
This is my first time using JSON. I have an external json file and I am using the json file in my html file to create divs with every json data read. I can get the correct output for all of the values, except for one which is the 'descript' value. I have tried printing it to the cosole log but all I'm getting for that particular value is 'undefined' but the other values are alright. Any idea on why this happened?

JSON file:

[{"title":"3G","filePath":"https://example.com","descript":"hello world"}, {"title":"4G", "filePath":"https://example.com", "descript": "test"} ]

HTML file:

 $.ajax({
      url : "testJSON.json",
      type : "get", // whichever you like
      contentType:"json",
      success : function(list)
        {
          var divCol  = "
";
          var divWell = "
";
          var divClose= "
";

          list.forEach(function(obj, index) {

            var title     = "
"      + obj.title    + "
";
            var desc      = "
"       + obj.descript + "
";
            var linkStart = "";
            var linkEnd   = "CSV";
            var div = divCol    +
            divWell     +
            title       +
            desc        +
            linkStart       +
           // image       +
            linkEnd +
            divClose +
            divClose;

              console.log(list)
           $("#imdaFiles").append(div); // insert the div you've just created

           })
        }
    });


问:
invalid result when using jinja2 within c++
I use this code for json templating using jinja2:

```<code>import json
from jinja2 import Template

def render_json(p_input_str, p_template_str, p_str):
    p_input = json.loads(p_input_str)
    t = Template(p_template_str)
    return t.render(input=p_input, str=p_str)
</code>```

temp.json :

```<code>{
    "id" : "{{ input["id"] }}",
    "data" : [
        {% for item in input["list"] %}
        {
        "id" : "{{ item["id"] }}",
        "value" : "{{ item["data"] }}"
        },
        {% endfor %}
        null
    ],
    "str" : "{{ str }}",
    "ext" : "{{ input["x"] }}"
}
</code>```

input.json:

```<code>{
    "id" : "1",
    "list" : [ { "id" : "2", "data" : "4" } ],
    "x" : "20"
}
</code>```

using python everything works fine:

```<code>input_str=open("test.json").read()
template_str=open("temp.json").read()
print render_json(input_str, template_str, "1234")
</code>```

output:

```<code>{
    "id" : "1",
    "data" : [

        {
        "id" : "2",
        "value" : "4"
        },

        null
    ],
    "str" : "1234",
    "ext" : "20"
}
</code>```

but when I try to call render_json from c++, input_str is prepended to output:

```<code>{
    "id" : "1",
    "list" : [ { "id" : "2", "data" : "4" } ],
    "x" : "20"
}
{
    "id" : "1",
    "data" : [

        {
        "id" : "2",
        "value" : "4"
        },

        null
    ],
    "str" : "1234",
    "ext" : "20"
}
</code>```

this is my c++ code for embeding python:
it's based on python documentation Embedding Python in Another Application

```<code>int main(int argc, char *argv[])
{
  std::stringstream buffer;
  std::ifstream t;

  t.open("test.json");
  buffer << t.rdbuf();
  std::string input_str = buffer.str();
  t.close();
  buffer.clear();

  t.open("temp.json");
  buffer << t.rdbuf();
  std::string template_str = buffer.str();

  std::vector<std::string> x = {input_str, template_str, "1234"};

  PyObject *pName, *pModule, *pDict, *pFunc;
  PyObject *pArgs, *pValue;

  if (argc < 3)
  {
    printf("Usage: exe_name python_source function_name\n");
    return 1;
  }

  Py_Initialize();
  pName = PyString_FromString(argv[1]);
  /* Error checking of pName left out */

  pModule = PyImport_Import(pName);
  Py_DECREF(pName);

  if (pModule != NULL)
  {
    pFunc = PyObject_GetAttrString(pModule, argv[2]);
    /* pFunc is a new reference */

    if (pFunc && PyCallable_Check(pFunc))
    {
      pArgs = PyTuple_New(3);
      for (int i = 0; i < 3; ++i)
      {
        pValue = PyString_FromString(x[i].c_str());
        if (!pValue)
        {
          Py_DECREF(pArgs);
          Py_DECREF(pModule);
          fprintf(stderr, "Cannot convert argument\n");
          return 1;
        }
        /* pValue reference stolen here: */
        PyTuple_SetItem(pArgs, i, pValue);
      }
      pValue = PyObject_CallObject(pFunc, pArgs);
      Py_DECREF(pArgs);
      if (pValue != NULL)
      {
        printf("Result of call: %s\n", PyString_AsString(pValue));
        Py_DECREF(pValue);
      }
      else
      {
        Py_DECREF(pFunc);
        Py_DECREF(pModule);
        PyErr_Print();
        fprintf(stderr,"Call failed\n");
        return 1;
      }
    }
    else
    {
      if (PyErr_Occurred())
        PyErr_Print();
      fprintf(stderr, "Cannot find function \"%s\"\n", argv[2]);
    }
    Py_XDECREF(pFunc);
    Py_DECREF(pModule);
  }
  else
  {
    PyErr_Print();
    fprintf(stderr, "Failed to load \"%s\"\n", argv[1]);
    return 1;
  }
  Py_Finalize();
  return 0;
}
</code>```

答:
Pretty sure this has something to do with your construction of input_str and template_str from the same std::stringstream and nothing to do with your python or bindings. That is, if you just print template_str before calling your python, you'll see it already has the contents of input_str at the beginning.

std::stringstream::clear doesn't do what you think it does -- it's just inherited from ios_base and it clears error flags.

Just use a second buffer.  (or call buffer.str(""), which i think does what you really want, but it's probably not worth the decrease in readability.)

Body:
I use this code for json templating using jinja2:

import json
from jinja2 import Template

def render_json(p_input_str, p_template_str, p_str):
    p_input = json.loads(p_input_str)
    t = Template(p_template_str)
    return t.render(input=p_input, str=p_str)

temp.json :

{
    "id" : "{{ input["id"] }}",
    "data" : [
        {% for item in input["list"] %}
        {
        "id" : "{{ item["id"] }}",
        "value" : "{{ item["data"] }}"
        },
        {% endfor %}
        null
    ],
    "str" : "{{ str }}",
    "ext" : "{{ input["x"] }}"
}

input.json:

{
    "id" : "1",
    "list" : [ { "id" : "2", "data" : "4" } ],
    "x" : "20"
}

using python everything works fine:

input_str=open("test.json").read()
template_str=open("temp.json").read()
print render_json(input_str, template_str, "1234")

output:

{
    "id" : "1",
    "data" : [

        {
        "id" : "2",
        "value" : "4"
        },

        null
    ],
    "str" : "1234",
    "ext" : "20"
}

but when I try to call render_json from c++, input_str is prepended to output:

{
    "id" : "1",
    "list" : [ { "id" : "2", "data" : "4" } ],
    "x" : "20"
}
{
    "id" : "1",
    "data" : [

        {
        "id" : "2",
        "value" : "4"
        },

        null
    ],
    "str" : "1234",
    "ext" : "20"
}

this is my c++ code for embeding python:
it's based on python documentation Embedding Python in Another Application

int main(int argc, char *argv[])
{
  std::stringstream buffer;
  std::ifstream t;

  t.open("test.json");
  buffer << t.rdbuf();
  std::string input_str = buffer.str();
  t.close();
  buffer.clear();

  t.open("temp.json");
  buffer << t.rdbuf();
  std::string template_str = buffer.str();

  std::vector<std::string> x = {input_str, template_str, "1234"};

  PyObject *pName, *pModule, *pDict, *pFunc;
  PyObject *pArgs, *pValue;

  if (argc < 3)
  {
    printf("Usage: exe_name python_source function_name\n");
    return 1;
  }

  Py_Initialize();
  pName = PyString_FromString(argv[1]);
  /* Error checking of pName left out */

  pModule = PyImport_Import(pName);
  Py_DECREF(pName);

  if (pModule != NULL)
  {
    pFunc = PyObject_GetAttrString(pModule, argv[2]);
    /* pFunc is a new reference */

    if (pFunc && PyCallable_Check(pFunc))
    {
      pArgs = PyTuple_New(3);
      for (int i = 0; i < 3; ++i)
      {
        pValue = PyString_FromString(x[i].c_str());
        if (!pValue)
        {
          Py_DECREF(pArgs);
          Py_DECREF(pModule);
          fprintf(stderr, "Cannot convert argument\n");
          return 1;
        }
        /* pValue reference stolen here: */
        PyTuple_SetItem(pArgs, i, pValue);
      }
      pValue = PyObject_CallObject(pFunc, pArgs);
      Py_DECREF(pArgs);
      if (pValue != NULL)
      {
        printf("Result of call: %s\n", PyString_AsString(pValue));
        Py_DECREF(pValue);
      }
      else
      {
        Py_DECREF(pFunc);
        Py_DECREF(pModule);
        PyErr_Print();
        fprintf(stderr,"Call failed\n");
        return 1;
      }
    }
    else
    {
      if (PyErr_Occurred())
        PyErr_Print();
      fprintf(stderr, "Cannot find function \"%s\"\n", argv[2]);
    }
    Py_XDECREF(pFunc);
    Py_DECREF(pModule);
  }
  else
  {
    PyErr_Print();
    fprintf(stderr, "Failed to load \"%s\"\n", argv[1]);
    return 1;
  }
  Py_Finalize();
  return 0;
}


问:
Bubble Sort Strings
This program is for listing 10 students and their marks. Then I want to sort it with Bubble sort. Here the problem occurs. The marks are getting sorted. But the name is still in the same place. After sorting, name stays in same place and marks get moved according to ascending order.</p>

```<code>public class StudentResult {
    public static void main(String [] args) {
        String names[] = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j" };
        int marks[] = { 100, 20, 30, 40, 50, 60, 32, 80, 90, 10 };
        System.out.println("Students              Marks");
        System.out.println("____________________________");
        for (int i = 0; i < names.length; i++)
            System.out.println(names[i] + "          -          " + marks[i]);
        bubbleSort(marks, names);
        System.out.println("\n\n\nSorted List\n\n");
        System.out.println("Students              Marks");
        System.out.println("____________________________");
        for(int i = 0; i < marks.length; i++)
            System.out.println(names[i] + "          -          " + marks[i]);
    }

    static void bubbleSort(int[] marks, String[] names) {
        int n = marks.length;
        int m = names.length;
        int temp = 0;
        for(int i=0; i < n; i++){
            for(int j=1; j < (n-i); j++){
                if(marks[j-1] > marks[j]){
                    //swap elements
                    temp = marks[j-1];
                    marks[j-1] = marks[j];
                    marks[j] = temp;
                }
            }
        }
    }
}
</code>```

答:
Just make a small change in your bubble sort method as shown below:

```<code>static void bubbleSort(int[] marks, String[] names) {
    int n = marks.length;
    int m = names.length;
    int temp = 0;
    String temp1 = null;
    for (int i = 0; i < n; i++) {
        for (int j = 1; j < (n - i); j++) {
            if (marks[j - 1] > marks[j]) {
                // swap elements
                temp = marks[j - 1];
                marks[j - 1] = marks[j];
                marks[j] = temp;
                temp1 = names[j - 1];
                names[j - 1] = names[j];
                names[j] = temp1;
            }
        }
    }
}
</code>```

This will give below output of your programme:

```<code>Students       Marks
______________________
a        -      100
b        -       20
c        -       30
d        -       40
e        -       50
f        -       60
g        -       32
h        -       80
i        -       90
j        -       10

Sorted List

Students       Marks
______________________
j        -       10
b        -       20
c        -       30
g        -       32
d        -       40
e        -       50
f        -       60
h        -       80
i        -       90
a        -      100
</code>```

Title: Bubble Sort Strings

Body:
This program is for listing 10 students and their marks. Then I want to sort it with Bubble sort. Here the problem occurs. The marks are getting sorted. But the name is still in the same place. After sorting, name stays in same place and marks get moved according to ascending order.

public class StudentResult {
    public static void main(String [] args) {
        String names[] = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j" };
        int marks[] = { 100, 20, 30, 40, 50, 60, 32, 80, 90, 10 };
        System.out.println("Students              Marks");
        System.out.println("____________________________");
        for (int i = 0; i < names.length; i++)
            System.out.println(names[i] + "          -          " + marks[i]);
        bubbleSort(marks, names);
        System.out.println("\n\n\nSorted List\n\n");
        System.out.println("Students              Marks");
        System.out.println("____________________________");
        for(int i = 0; i < marks.length; i++)
            System.out.println(names[i] + "          -          " + marks[i]);
    }

    static void bubbleSort(int[] marks, String[] names) {
        int n = marks.length;
        int m = names.length;
        int temp = 0;
        for(int i=0; i < n; i++){
            for(int j=1; j < (n-i); j++){
                if(marks[j-1] > marks[j]){
                    //swap elements
                    temp = marks[j-1];
                    marks[j-1] = marks[j];
                    marks[j] = temp;
                }
            }
        }
    }
}

Body:
Just make a small change in your bubble sort method as shown below:

static void bubbleSort(int[] marks, String[] names) {
    int n = marks.length;
    int m = names.length;
    int temp = 0;
    String temp1 = null;
    for (int i = 0; i < n; i++) {
        for (int j = 1; j < (n - i); j++) {
            if (marks[j - 1] > marks[j]) {
                // swap elements
                temp = marks[j - 1];
                marks[j - 1] = marks[j];
                marks[j] = temp;
                temp1 = names[j - 1];
                names[j - 1] = names[j];
                names[j] = temp1;
            }
        }
    }
}

This will give below output of your programme:

Students       Marks
______________________
a        -      100
b        -       20
c        -       30
d        -       40
e        -       50
f        -       60
g        -       32
h        -       80
i        -       90
j        -       10

Sorted List

Students       Marks
______________________
j        -       10
b        -       20
c        -       30
g        -       32
d        -       40
e        -       50
f        -       60
h        -       80
i        -       90
a        -      100


问:
Find the longest arithmetic progression from an array
I have an array of numbers ex.[5,1,2,4,6,8,12], and I want to find the length of longest arithmetic progression within the sequence and to print it. Longest arithmetic progression means an increasing sequence with common difference, in this case [2,4,6,8].</p>

```<code>#include <stdio.h>

void main()
{
    int array[100], i, num,diff;
    printf("Enter the size of an array \n");

    scanf("%d", &num);

    printf("Enter the elements of the array \n");

    for (i = 0; i < num; i++) {
        scanf("%d", &array[i]);
    }

    printf("\n Numbers in a.p: ");

    for (i = 0; i < num; i++) {
        diff = array[i+1]-array[i];
        if (array[i]-diff == array[i+1]-diff);
        {
            printf("%d, ", array[i]);
        }
    }
    printf("\n Common difference:%d", diff);
}
</code>```

答:
Following is the complete working code. You can see it working here:</p>

```<code>     #include <stdio.h>

 int main()
 {
     int array[100], i, num,diff, resDiff, startIndx, resStartIndx, countCur, countPre;
     printf("Enter the size of an array \n");
     scanf("%d", &num);

     printf("Enter the elements of the array \n");
     for (i = 0; i < num; i++) {
         scanf("%d", &array[i]);
     }

     //Now code changes
     startIndx =0, resStartIndx=0, countPre=0, resDiff=0;
     for (i = 0; i < num; /*No increment required here*/) {
         countCur =0;
         startIndx=i;
         countCur++;

         if(++i < num)
         {
             diff = array[i] - array[startIndx];
             countCur++;
             i++;
             while((i < num) && (diff == (array[i] - array[i-1])))
             {
                 countCur++;
                 i++;
             }

             if(countCur > countPre)
             {
                 resStartIndx = startIndx;
                 countPre = countCur;
                 resDiff = diff;
             }
         }
     }

     countPre += resStartIndx;
     printf("\n Numbers in a.p: ");
     for (i = resStartIndx; i < countPre; i++) {
         printf("%d, ", array[i]);
     }
     printf("\n Common difference:%d", resDiff);
     return 0;
 }
</code>```

Body:
I have an array of numbers ex.[5,1,2,4,6,8,12], and I want to find the length of longest arithmetic progression within the sequence and to print it. Longest arithmetic progression means an increasing sequence with common difference, in this case [2,4,6,8].

#include <stdio.h>

void main()
{
    int array[100], i, num,diff;
    printf("Enter the size of an array \n");

    scanf("%d", &num);

    printf("Enter the elements of the array \n");

    for (i = 0; i < num; i++) {
        scanf("%d", &array[i]);
    }

    printf("\n Numbers in a.p: ");

    for (i = 0; i < num; i++) {
        diff = array[i+1]-array[i];
        if (array[i]-diff == array[i+1]-diff);
        {
            printf("%d, ", array[i]);
        }
    }
    printf("\n Common difference:%d", diff);
}

Body:
Following is the complete working code. You can see it working here:

     #include <stdio.h>

 int main()
 {
     int array[100], i, num,diff, resDiff, startIndx, resStartIndx, countCur, countPre;
     printf("Enter the size of an array \n");
     scanf("%d", &num);

     printf("Enter the elements of the array \n");
     for (i = 0; i < num; i++) {
         scanf("%d", &array[i]);
     }

     //Now code changes
     startIndx =0, resStartIndx=0, countPre=0, resDiff=0;
     for (i = 0; i < num; /*No increment required here*/) {
         countCur =0;
         startIndx=i;
         countCur++;

         if(++i < num)
         {
             diff = array[i] - array[startIndx];
             countCur++;
             i++;
             while((i < num) && (diff == (array[i] - array[i-1])))
             {
                 countCur++;
                 i++;
             }

             if(countCur > countPre)
             {
                 resStartIndx = startIndx;
                 countPre = countCur;
                 resDiff = diff;
             }
         }
     }

     countPre += resStartIndx;
     printf("\n Numbers in a.p: ");
     for (i = resStartIndx; i < countPre; i++) {
         printf("%d, ", array[i]);
     }
     printf("\n Common difference:%d", resDiff);
     return 0;
 }


问:
Send Notification to ios app bundle id using FCM
I am building an api to upload video on youtube channel. One of the requirement is that whenever a video is uploaded successfully to youtube server a notification must be sent to the ios app bundle id using Firebase Cloud Messaging.
I have registered my application in fcm console with bundle id com.tbox.ygtp
I have tried to google on how to send notification to the ios app and i found following API

```<code> $url = 'https://fcm.googleapis.com/fcm/send';
    $server_key = 'AAAAylThdyA:APA91bGISSU********VTqHJqBnV81B3jfJzAice07E********HHLXTVylMU1OWSHvdyoZMVNlM8t9p9tXH_4OKm********fEOatp_alw9qMlQNT507lLWLt1N_FMHel1JCCWcuQjD';

    $fields = array();
    //$fields['data'] = $data;
    $fields['notification'] = array('body'=>$data);
    if(is_array($target)){
        $fields['registration_ids'] = $target;
    }else{
        $fields['to'] = $target;
    }
    //header with content_type and api key
    $headers = array(
        'Content-Type:application/json',
      'Authorization:key='.$server_key
    );

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
    $result = curl_exec($ch);
    if ($result === FALSE) {
        die('FCM Send Error: ' . curl_error($ch));
    }
    curl_close($ch);

    return $result;
</code>```

This Api sends notification to device tokens. But I need the notification to be sent on application bundle id.
Can someone guide me through how to send the notification to application bundle id using FCM.

答:
There is currently no API or parameter you could use to send a message only to a specific bundle id. This option is only available when sending the message through Firebase Notifications Console.

As a workaround, you could make use of Topic Messaging, by subscribing the users to the topic (where you could name as your bundle id, or a simpler alias), then simply use the topic name to send a message to the users.

Body:
I am building an api to upload video on youtube channel. One of the requirement is that whenever a video is uploaded successfully to youtube server a notification must be sent to the ios app bundle id using Firebase Cloud Messaging.
I have registered my application in fcm console with bundle id com.tbox.ygtp
I have tried to google on how to send notification to the ios app and i found following API

 $url = 'https://fcm.googleapis.com/fcm/send';
    $server_key = 'AAAAylThdyA:APA91bGISSU********VTqHJqBnV81B3jfJzAice07E********HHLXTVylMU1OWSHvdyoZMVNlM8t9p9tXH_4OKm********fEOatp_alw9qMlQNT507lLWLt1N_FMHel1JCCWcuQjD';

    $fields = array();
    //$fields['data'] = $data;
    $fields['notification'] = array('body'=>$data);
    if(is_array($target)){
        $fields['registration_ids'] = $target;
    }else{
        $fields['to'] = $target;
    }
    //header with content_type and api key
    $headers = array(
        'Content-Type:application/json',
      'Authorization:key='.$server_key
    );

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
    $result = curl_exec($ch);
    if ($result === FALSE) {
        die('FCM Send Error: ' . curl_error($ch));
    }
    curl_close($ch);

    return $result;

This Api sends notification to device tokens. But I need the notification to be sent on application bundle id.
Can someone guide me through how to send the notification to application bundle id using FCM.


问:
Can HTTPS POST data be read by third parties?
If I log a user in via a secure HTTPS AJAX POST, does this mean the body of the HTTP POST is encrypted and therefore secure? </p>

答:
It depends on what you want to protect against (what threats should be mitigated).

HTTPS is a secure channel between the client (browser in this case) and the server. This means anybody with sufficient privileges on the client, and also on the server can read the data, because those are the ends of the imaginary pipe that HTTPS is. Practically any admin on the client or on the server can read the transmitted data, but a man-in-the-middle attacker (somebody on the network inbetween) cannot, HTTPS is secure against that (and only that, albeit it's not just confidentiality that HTTPS provides, but that's a separate topic).

The more important question is, how will you put the username and password into the body of an ajax request? That would mean you had to store such username and password somewhere on the client, where it is most probably not very secure. For instance any single successful XSS attack can reveal such credentials to an attacker. That would probably be my primary concern in this case.


问:
How i can reload/restart service in angular?
How can I restart a service without reloading an app?

I do not want to use window.location.reload().

答:
You could use a factory instead of simple service and create a reset method on it which would set it to its "initial state".

For example, your factory could look something like this:

```<code>function MyFactory() {

    // generate the initial structure of the service
    let Factory = _getDefaultFactory();

    // expose the service properties and methods
    return Factory;

    /**
     * Reset the factory back to its default state
     */
    function reset() {
        // generate the initial structure again
        // and override the current structure of the service
        Factory = _getDefaultFactory();
    }

    /**
     * Generate a default service structure
     */
    function _getDefaultFactory() {

        return {

            // include the reset method so you can call it later
            // e.g. MyFactory.reset();
            reset: reset

            // include other factory properties and methods here

        };

    }

}
</code>```

Body:
You could use a factory instead of simple service and create a reset method on it which would set it to its "initial state".

For example, your factory could look something like this:

function MyFactory() {

    // generate the initial structure of the service
    let Factory = _getDefaultFactory();

    // expose the service properties and methods
    return Factory;

    /**
     * Reset the factory back to its default state
     */
    function reset() {
        // generate the initial structure again
        // and override the current structure of the service
        Factory = _getDefaultFactory();
    }

    /**
     * Generate a default service structure
     */
    function _getDefaultFactory() {

        return {

            // include the reset method so you can call it later
            // e.g. MyFactory.reset();
            reset: reset

            // include other factory properties and methods here

        };

    }

}


问:
[C++]Would this be a valid approach for a 'sleep' function in a thread?
I would like to implement a sleep() function in my thread class, but I don't know if this is a valid/proper way to do it.
This is my entire thread class (thread.h):

```<code>#include <process.h>

struct RUNNABLE{
    virtual void run() = 0;
};

class thread{
public:
    void start(void *ptr){
        DWORD thr_id;
        HANDLE thr_handl = (HANDLE)_beginthreadex(NULL, 0, thread_proc, ptr, 0, (unsigned int*)&thr_id);
    }

    void sleep(int sleep_time, bool alertable){
        SleepEx(sleep_time, alertable);
    }
private:
    static unsigned int __stdcall thread_proc(void *param){
        ((RUNNABLE*)param)->run();
        _endthreadex(0);
        return 0;
    }
};
</code>```

And as you're probably able to sort out, this is my sleep() function:

```<code>void sleep(int sleep_time, bool alertable){
    SleepEx(sleep_time, alertable);
}
</code>```

But will this make the actual thread contained inside this thread instance sleep for the specified amount of milliseconds?

Best regards,
Benjamin :).

EDIT:

So according to atzz, I could define the sleep function as a static member function, and have that call ::SleepEx(), and that would allow me to call it like this:

```<code>class test : RUNNABLE{
    virtual void run(){
        printf("hi");
        thread::sleep(1000, false);
    }
};
</code>```

and then that'll cause the thread executing the 'test' runnable to sleep 1000 milliseonds?

答: No, this will put the original thread to sleep, not the one you start.</p>

Body:
I would like to implement a sleep() function in my thread class, but I don't know if this is a valid/proper way to do it.
This is my entire thread class (thread.h):

#include <process.h>

struct RUNNABLE{
    virtual void run() = 0;
};

class thread{
public:
    void start(void *ptr){
        DWORD thr_id;
        HANDLE thr_handl = (HANDLE)_beginthreadex(NULL, 0, thread_proc, ptr, 0, (unsigned int*)&thr_id);
    }

    void sleep(int sleep_time, bool alertable){
        SleepEx(sleep_time, alertable);
    }
private:
    static unsigned int __stdcall thread_proc(void *param){
        ((RUNNABLE*)param)->run();
        _endthreadex(0);
        return 0;
    }
};

And as you're probably able to sort out, this is my sleep() function:

void sleep(int sleep_time, bool alertable){
    SleepEx(sleep_time, alertable);
}

But will this make the actual thread contained inside this thread instance sleep for the specified amount of milliseconds?

Best regards,
Benjamin :).

EDIT:

So according to atzz, I could define the sleep function as a static member function, and have that call ::SleepEx(), and that would allow me to call it like this:

class test : RUNNABLE{
    virtual void run(){
        printf("hi");
        thread::sleep(1000, false);
    }
};

and then that'll cause the thread executing the 'test' runnable to sleep 1000 milliseonds?


问:
Convert one date format into another in PHP
Is there a simple way to convert one date format into another date format in PHP?

I have this:

```<code>$old_date = date('y-m-d-h-i-s');            // works

$middle = strtotime($old_date);             // returns bool(false)

$new_date = date('Y-m-d H:i:s', $middle);   // returns 1970-01-01 00:00:00
</code>```

But I'd of course like it to return a current date rather than the crack 'o dawn. What am I doing wrong?

答:
This is the other way you can convert date format</p>

```<code> <?php
$pastDate = "Tuesday 11th October, 2016";
$pastDate = str_replace(",","",$pastDate);

$date = new DateTime($pastDate);
$new_date_format = $date->format('Y-m-d');

echo $new_date_format.' 23:59:59'; ?>
</code>```

Body:
Is there a simple way to convert one date format into another date format in PHP?

I have this:

$old_date = date('y-m-d-h-i-s');            // works

$middle = strtotime($old_date);             // returns bool(false)

$new_date = date('Y-m-d H:i:s', $middle);   // returns 1970-01-01 00:00:00

But I'd of course like it to return a current date rather than the crack 'o dawn. What am I doing wrong?

Body:
This is the other way you can convert date format

 <?php
$pastDate = "Tuesday 11th October, 2016";
$pastDate = str_replace(",","",$pastDate);

$date = new DateTime($pastDate);
$new_date_format = $date->format('Y-m-d');

echo $new_date_format.' 23:59:59'; ?>


问:
DYGRAPHS: Show warning when disable small graph in range selector
I disabled the small graph in range selector using:
showInRangeSelector: false,
but I'm getting warning sign like this:
I can't seem to find where is the bug.

Updated with code:

```<code><html>
<head>
<link href="http://dygraphs.com/2.0.0/dygraph.css" rel="stylesheet"/>
<script src="http://dygraphs.com/2.0.0/dygraph.js"></script>
<div id="hello" class="chart"></div>
</head>
<body>
<script type = "text/javascript">

var hello = [
            [new Date("2016-03-06"),[10,20,30],[11,11,11]],
            [new Date("2016-03-07"),[10,20,30],[15,15,15]],
            [new Date("2016-03-08"),[10,20,30],[32,32,32]],
            [new Date("2016-03-09"),[10,20,30],[18,18,18]],
            [new Date("2016-03-10"),[10,20,30],[26,26,26]],
            [new Date("2016-03-11"),[10,20,30],[31,31,31]],
            [new Date("2016-03-12"),[10,20,30],[9,9,9]],
        ],

a = new Dygraph(
    document.getElementById("hello"),hello,
    {
        labels: [ "Date", "Mean" , "Scatter"],
        customBars: true,
        showRangeSelector: true,
        showInRangeSelector : false,
        interactionModel: Dygraph.defaultInteractionModel,
        series: {
            "Mean" : {
                drawPoints: false,
                color: "#585858",
            },
            "Scatter" : {
                drawPoints: true,
                pointSize: 3,
                strokeWidth: 0,
            }
        },
    }
);
</script>
</code>```

Thank you :)

I have to add extra wording because the post is mostly codes and I can't post it :P

答:
This is the workaround I am thinking. Tell me if it is useful for you.

The idea is that you can create another serie only for the rangeselector.

The data for this serie does not matter as it is not going to be shown. But it depends on the way you want to see the range selector. If you want to see the typical line in the rangeselector you can use this first solution.

https://jsfiddle.net/b8sz6m36/4/

```<code>var hello = [
        [new Date("2016-03-06"),[10,20,30],[11,11,11],[1,1,1]],
        [new Date("2016-03-07"),[10,20,30],[15,15,15],[1,1,1]],
        [new Date("2016-03-08"),[10,20,30],[32,32,32],[1,1,1]],
        [new Date("2016-03-09"),[10,20,30],[18,18,18],[1,1,1]],
        [new Date("2016-03-10"),[10,20,30],[26,26,26],[1,1,1]],
        [new Date("2016-03-11"),[10,20,30],[31,31,31],[1,1,1]],
        [new Date("2016-03-12"),[10,20,30],[9,9,9],[1,1,1]],
    ],

a = new Dygraph(
document.getElementById("hello"),hello,
{
    labels: [ "Date", "Mean" , "Scatter", "RangeSelector"],
    customBars: true,
    showRangeSelector: true,
    interactionModel: Dygraph.defaultInteractionModel,
    series: {
        "Mean" : {
            drawPoints: false,
            color: "#585858",
                    showInRangeSelector : false,
        },
        "Scatter" : {
            drawPoints: true,
            pointSize: 3,
            strokeWidth: 0,
                    showInRangeSelector : false,
        },
        "RangeSelector" : {
            showInRangeSelector : true,
        }
    },
  }
);
</code>```

If it does not matter to you to have the range selector completely empty, you can use this second solution where the data in the serie for the rangeselector is simpler

https://jsfiddle.net/b8sz6m36/5/

```<code>var hello = [
        [new Date("2016-03-06"),[10,20,30],[11,11,11],0],
        [new Date("2016-03-07"),[10,20,30],[15,15,15],0],
        [new Date("2016-03-08"),[10,20,30],[32,32,32],0],
        [new Date("2016-03-09"),[10,20,30],[18,18,18],0],
        [new Date("2016-03-10"),[10,20,30],[26,26,26],0],
        [new Date("2016-03-11"),[10,20,30],[31,31,31],0],
        [new Date("2016-03-12"),[10,20,30],[9,9,9],0],
    ],

a = new Dygraph(
document.getElementById("hello"),hello,
{
    labels: [ "Date", "Mean" , "Scatter", "RangeSelector"],
    customBars: true,
    showRangeSelector: true,
    interactionModel: Dygraph.defaultInteractionModel,
    series: {
        "Mean" : {
            drawPoints: false,
            color: "#585858",
                    showInRangeSelector : false,
        },
        "Scatter" : {
            drawPoints: true,
            pointSize: 3,
            strokeWidth: 0,
                    showInRangeSelector : false,
        },
        "RangeSelector" : {
            showInRangeSelector : true,
        }
    },
  }
);
</code>```

Body:
I disabled the small graph in range selector using:
showInRangeSelector: false,
but I'm getting warning sign like this:
I can't seem to find where is the bug.

Updated with code:

<link href="http://dygraphs.com/2.0.0/dygraph.css" rel="stylesheet"/>

Thank you :)

I have to add extra wording because the post is mostly codes and I can't post it :P

Body:
This is the workaround I am thinking. Tell me if it is useful for you.

The idea is that you can create another serie only for the rangeselector.

The data for this serie does not matter as it is not going to be shown. But it depends on the way you want to see the range selector. If you want to see the typical line in the rangeselector you can use this first solution.

https://jsfiddle.net/b8sz6m36/4/

var hello = [
        [new Date("2016-03-06"),[10,20,30],[11,11,11],[1,1,1]],
        [new Date("2016-03-07"),[10,20,30],[15,15,15],[1,1,1]],
        [new Date("2016-03-08"),[10,20,30],[32,32,32],[1,1,1]],
        [new Date("2016-03-09"),[10,20,30],[18,18,18],[1,1,1]],
        [new Date("2016-03-10"),[10,20,30],[26,26,26],[1,1,1]],
        [new Date("2016-03-11"),[10,20,30],[31,31,31],[1,1,1]],
        [new Date("2016-03-12"),[10,20,30],[9,9,9],[1,1,1]],
    ],

a = new Dygraph(
document.getElementById("hello"),hello,
{
    labels: [ "Date", "Mean" , "Scatter", "RangeSelector"],
    customBars: true,
    showRangeSelector: true,
    interactionModel: Dygraph.defaultInteractionModel,
    series: {
        "Mean" : {
            drawPoints: false,
            color: "#585858",
                    showInRangeSelector : false,
        },
        "Scatter" : {
            drawPoints: true,
            pointSize: 3,
            strokeWidth: 0,
                    showInRangeSelector : false,
        },
        "RangeSelector" : {
            showInRangeSelector : true,
        }
    },
  }
);

If it does not matter to you to have the range selector completely empty, you can use this second solution where the data in the serie for the rangeselector is simpler

https://jsfiddle.net/b8sz6m36/5/

var hello = [
        [new Date("2016-03-06"),[10,20,30],[11,11,11],0],
        [new Date("2016-03-07"),[10,20,30],[15,15,15],0],
        [new Date("2016-03-08"),[10,20,30],[32,32,32],0],
        [new Date("2016-03-09"),[10,20,30],[18,18,18],0],
        [new Date("2016-03-10"),[10,20,30],[26,26,26],0],
        [new Date("2016-03-11"),[10,20,30],[31,31,31],0],
        [new Date("2016-03-12"),[10,20,30],[9,9,9],0],
    ],

a = new Dygraph(
document.getElementById("hello"),hello,
{
    labels: [ "Date", "Mean" , "Scatter", "RangeSelector"],
    customBars: true,
    showRangeSelector: true,
    interactionModel: Dygraph.defaultInteractionModel,
    series: {
        "Mean" : {
            drawPoints: false,
            color: "#585858",
                    showInRangeSelector : false,
        },
        "Scatter" : {
            drawPoints: true,
            pointSize: 3,
            strokeWidth: 0,
                    showInRangeSelector : false,
        },
        "RangeSelector" : {
            showInRangeSelector : true,
        }
    },
  }
);


问:
Using sqlplus to programmatically check connection
Is it possible to use sqlplus to programmatically check a database connection (in particular, the SYS account)?

I'm thinking something along this line

Run sql plus (using Process.Start) with some parameter, giving the sys username and password

Check the exit code (or even the stdout), whether it is successful or not. The best way I can come up so far is to check the stdout string whether the substring "ERROR" exist, but I don't think this is very clean

Is this something possible? What parameter do you suggest I use?
The reason I want to do this is because System.Data.OracleClient doesn't support connection as SYSDBA

答:
I had similar question. I discovered we could specify what failure code could be sent depending on the case:

```<code>sqlplus /nolog << EOF
 WHENEVER SQLERROR EXIT 50
 WHENEVER OSERROR EXIT 66
 connect /@${MISTERY_DB}
 exit;
EOF
</code>```

Then to check the return code:

```<code>RET_CODE=$?
if [ ${RET_CODE} -eq 50 ] ; then
  echo "it was an SQLERROR"
fi
</code>```

Body:
I had similar question. I discovered we could specify what failure code could be sent depending on the case:

sqlplus /nolog << EOF
 WHENEVER SQLERROR EXIT 50
 WHENEVER OSERROR EXIT 66
 connect /@${MISTERY_DB}
 exit;
EOF

Then to check the return code:

RET_CODE=$?
if [ ${RET_CODE} -eq 50 ] ; then
  echo "it was an SQLERROR"
fi


问:
PHP rand from list
What is the best way of doing this ?

```<code>rand('Helloworld','Hi world');
</code>```

I know this is not working as rand needs a min and max number, but what is the solution for this ?

答: Use array_rand.</p>

Title: PHP rand from list

Body:
What is the best way of doing this ?

rand('Helloworld','Hi world');

I know this is not working as rand needs a min and max number, but what is the solution for this ?

Body: Use array_rand.


问:
NLTK single-word part-of-speech tagging
Is there a way to use NLTK to get a set of possible parts of speech of a single string of letters, taking into account that different words might have homonyms?

For example: report -> {Noun, Verb}  ,  kind -> {Adjective, Noun}

I have not been able to find a POS-tokenizer that tags part-of-speech for words outside of the context of a full sentence. This seems like a very basic request of NLTK, so I'm confused as to why I've had so much trouble finding it.

答:
Because POS models are trained on sentence/document based data, so the expected input to the pre-trained model is a sentence/document. When there's only a single word, it treats it as a single word sentence, hence there should only be one tag in that single word sentence context.

If you're trying to find all possible POS tags per English words, you would need a corpus of many different use of the words and then tag the corpus and count/extract the no. of tags per word. E.g.

```<code>>>> from nltk import pos_tag
>>> sent1 = 'The coaches are going from Singapore to Frankfurt'
>>> sent2 = 'He coaches the football team'
>>> pos_tag(sent1.split())
[('The', 'DT'), ('coaches', 'NNS'), ('are', 'VBP'), ('going', 'VBG'), ('from', 'IN'), ('Singapore', 'NNP'), ('to', 'TO'), ('Frankfurt', 'NNP')]
>>> pos_tag(sent2.split())
[('He', 'PRP'), ('coaches', 'VBZ'), ('the', 'DT'), ('football', 'NN'), ('team', 'NN')]

>>> from collections import defaultdict, Counter
>>> counts = defaultdict(Counter)
>>> tagged_sents = [pos_tag(sent) for sent in [sent1.split(), sent2.split()]]

>>> for word, pos in chain(*tagged_sents):
...     counts[word][pos] += 1
...

>>> counts
defaultdict(<class 'collections.Counter'>, {'from': Counter({'IN': 1}), 'to': Counter({'TO': 1}), 'Singapore': Counter({'NNP': 1}), 'football': Counter({'NN': 1}), 'coaches': Counter({'VBZ': 1, 'NNS': 1}), 'going': Counter({'VBG': 1}), 'are': Counter({'VBP': 1}), 'team': Counter({'NN': 1}), 'The': Counter({'DT': 1}), 'Frankfurt': Counter({'NNP': 1}), 'the': Counter({'DT': 1}), 'He': Counter({'PRP': 1})})

>>> counts['coaches']
Counter({'VBZ': 1, 'NNS': 1})
</code>```

Alternatively, there's WordNet:

```<code>>>> from nltk.corpus import wordnet as wn
>>> wn.synsets('coaches')
[Synset('coach.n.01'), Synset('coach.n.02'), Synset('passenger_car.n.01'), Synset('coach.n.04'), Synset('bus.n.01'), Synset('coach.v.01'), Synset('coach.v.02')]
>>> [ss.pos() for ss in wn.synsets('coaches')]
[u'n', u'n', u'n', u'n', u'n', u'v', u'v']
>>> Counter([ss.pos() for ss in wn.synsets('coaches')])
Counter({u'n': 5, u'v': 2})
</code>```

But note that WordNet is a manually crafted resource, so you cannot expect every English word to be in it.

Title: NLTK single-word part-of-speech tagging

Body:
Because POS models are trained on sentence/document based data, so the expected input to the pre-trained model is a sentence/document. When there's only a single word, it treats it as a single word sentence, hence there should only be one tag in that single word sentence context.

If you're trying to find all possible POS tags per English words, you would need a corpus of many different use of the words and then tag the corpus and count/extract the no. of tags per word. E.g.

>>> from nltk import pos_tag
>>> sent1 = 'The coaches are going from Singapore to Frankfurt'
>>> sent2 = 'He coaches the football team'
>>> pos_tag(sent1.split())
[('The', 'DT'), ('coaches', 'NNS'), ('are', 'VBP'), ('going', 'VBG'), ('from', 'IN'), ('Singapore', 'NNP'), ('to', 'TO'), ('Frankfurt', 'NNP')]
>>> pos_tag(sent2.split())
[('He', 'PRP'), ('coaches', 'VBZ'), ('the', 'DT'), ('football', 'NN'), ('team', 'NN')]

>>> from collections import defaultdict, Counter
>>> counts = defaultdict(Counter)
>>> tagged_sents = [pos_tag(sent) for sent in [sent1.split(), sent2.split()]]

>>> for word, pos in chain(*tagged_sents):
...     counts[word][pos] += 1
...

>>> counts
defaultdict(<class 'collections.Counter'>, {'from': Counter({'IN': 1}), 'to': Counter({'TO': 1}), 'Singapore': Counter({'NNP': 1}), 'football': Counter({'NN': 1}), 'coaches': Counter({'VBZ': 1, 'NNS': 1}), 'going': Counter({'VBG': 1}), 'are': Counter({'VBP': 1}), 'team': Counter({'NN': 1}), 'The': Counter({'DT': 1}), 'Frankfurt': Counter({'NNP': 1}), 'the': Counter({'DT': 1}), 'He': Counter({'PRP': 1})})

>>> counts['coaches']
Counter({'VBZ': 1, 'NNS': 1})

Alternatively, there's WordNet:

>>> from nltk.corpus import wordnet as wn
>>> wn.synsets('coaches')
[Synset('coach.n.01'), Synset('coach.n.02'), Synset('passenger_car.n.01'), Synset('coach.n.04'), Synset('bus.n.01'), Synset('coach.v.01'), Synset('coach.v.02')]
>>> [ss.pos() for ss in wn.synsets('coaches')]
[u'n', u'n', u'n', u'n', u'n', u'v', u'v']
>>> Counter([ss.pos() for ss in wn.synsets('coaches')])
Counter({u'n': 5, u'v': 2})

But note that WordNet is a manually crafted resource, so you cannot expect every English word to be in it.


问:
How to access user objects within req in node express?
I'm using passport to authenticate user but having a hard time accessing it. I see the user object when I log the req object but I get undefined when I log or try to access req.user. I even tried to set the user object manually but I still get undefined. Is there a trick to access things within req or I'm missing a concept here? Here is what I have in my controller:</p>

```<code>passport.authenticate('local', function(err, user, info) {
  if (err) {
    return next(err);
  }
  if (!user) {
    return res.status(401).json({
       err: info
    });
  }
 req.logIn(user, function(err) {

  if (err) {
    return res.status(500).json({
      err: 'Could not log in user'
    });
   }
   req.user = user;
   console.log(req.user);
   res.status(200).json(req.user);
 });
})(req, res, next);
</code>```

答:
Please try this ,

```<code>app.post("/url" , function( req , res , next){
  passport.authenticate('local', function(err, user, info) {
      if (err) {
        return next(err);
      }
      if (!user) {
        return res.status(401).json({
           err: info
        });
      }

      console.log(  req.user );

      req.logIn(user, function(err) {

              if (err) {
                return res.status(500).json({
                  err: 'Could not log in user'
                });
               }
        req.user = user;
        console.log(req.user);
        res.status(200).json(req.user);
        });
    })(req, res, next);

})
</code>```

In this example, note that authenticate() is called from within the route handler, rather than being used as route middleware. This gives the callback access to the req and res objects through closure.

Body:
I'm using passport to authenticate user but having a hard time accessing it. I see the user object when I log the req object but I get undefined when I log or try to access req.user. I even tried to set the user object manually but I still get undefined. Is there a trick to access things within req or I'm missing a concept here? Here is what I have in my controller:

passport.authenticate('local', function(err, user, info) {
  if (err) {
    return next(err);
  }
  if (!user) {
    return res.status(401).json({
       err: info
    });
  }
 req.logIn(user, function(err) {

  if (err) {
    return res.status(500).json({
      err: 'Could not log in user'
    });
   }
   req.user = user;
   console.log(req.user);
   res.status(200).json(req.user);
 });
})(req, res, next);

Body:
Please try this ,

app.post("/url" , function( req , res , next){
  passport.authenticate('local', function(err, user, info) {
      if (err) {
        return next(err);
      }
      if (!user) {
        return res.status(401).json({
           err: info
        });
      }

      console.log(  req.user );

      req.logIn(user, function(err) {

              if (err) {
                return res.status(500).json({
                  err: 'Could not log in user'
                });
               }
        req.user = user;
        console.log(req.user);
        res.status(200).json(req.user);
        });
    })(req, res, next);

})

In this example, note that authenticate() is called from within the route handler, rather than being used as route middleware. This gives the callback access to the req and res objects through closure.


问:
My Scannerclass doesn't scan the String - but why?
We received an exercise at college about unicode and ASCII and chars and so on. One part of the exercise is to find a way to read the users input in console that have to be a char and give back the ASCII and Unicode.

Quite easy I think, but my scanner won't scan. Because there's no .nextChar method for the scanner. I was used to use the String method (scanner.nextLine). In the next step, I turned the singlechar-String to a char with char ... = s.charAt and from there I wanted to get the hex and ASCII. Whatever I do my Scanner wont scan the String. Here's the code:

```<code>do{

    System.out.println("Geben Sie ein Zeichen ein um den dazugehoerigen ASCII- und Unicode anzuzeigen");
    input = scan.nextLine();

} while(input.length() >= 2 & input.length() < 1);

zeichen = input.charAt(0);

i = (int) zeichen;

System.out.println("Sie haben " + zeichen + " gewählt.\nDer dazugehoerige ASCII-Code ist " + i + "\nDer dazugehoerige Unicode ist " + (buffer.toString()+ Integer.toHexString(i)));
</code>```

答:
your condition here is wrong:

```<code>(input.length() >= 2) & (input.length() < 1)
</code>```

and boolean condition can be done as && and not &

on the other hand there is no string ever whose length can be bigger than 2 and less than 1 at the same time! so that condition will never meet!

Body:
We received an exercise at college about unicode and ASCII and chars and so on. One part of the exercise is to find a way to read the users input in console that have to be a char and give back the ASCII and Unicode.

Quite easy I think, but my scanner won't scan. Because there's no .nextChar method for the scanner. I was used to use the String method (scanner.nextLine). In the next step, I turned the singlechar-String to a char with char ... = s.charAt and from there I wanted to get the hex and ASCII. Whatever I do my Scanner wont scan the String. Here's the code:

do{

    System.out.println("Geben Sie ein Zeichen ein um den dazugehoerigen ASCII- und Unicode anzuzeigen");
    input = scan.nextLine();

} while(input.length() >= 2 & input.length() < 1);

zeichen = input.charAt(0);

i = (int) zeichen;

System.out.println("Sie haben " + zeichen + " gewählt.\nDer dazugehoerige ASCII-Code ist " + i + "\nDer dazugehoerige Unicode ist " + (buffer.toString()+ Integer.toHexString(i)));

Body:
your condition here is wrong:

(input.length() >= 2) & (input.length() < 1)

and boolean condition can be done as && and not &

on the other hand there is no string ever whose length can be bigger than 2 and less than 1 at the same time! so that condition will never meet!


问:
Multiple condition in JMeter if controller
Following condition in if controller is not working

(${__threadNum} =="1" || ${__threadNum} % 5 == "0")  && ("${__iterationNum}"=="1")

答:
You have types mismatch in your expression, you should amend it to:

```<code>(${__threadNum} ==1 || ${__threadNum} % 5 == 0) && ${__iterationNum} == 1
</code>```

Also make sure you have Custom JMeter Functions bundle installed, it can be done using JMeter Plugins Manager

In case of any problems take a look at jmeter.log file, it should contain all necessary troubleshooting information.

Body:
You have types mismatch in your expression, you should amend it to:

(${__threadNum} ==1 || ${__threadNum} % 5 == 0) && ${__iterationNum} == 1

Also make sure you have Custom JMeter Functions bundle installed, it can be done using JMeter Plugins Manager

In case of any problems take a look at jmeter.log file, it should contain all necessary troubleshooting information.


问:
Copying CSV File to Excel Using Recorded Macro
Below code is not working and throwing error

Invalid Procedure call or argument.

This is the recorded macro code for importing CSV file data into Excel file.

```<code>Sub CopyCSVtoExcel()
'
' CopyCSVtoExcel Macro
'
'
    With ActiveSheet.QueryTables.Add(Connection:= _
        "TEXT;C:\Users\hkum29\Desktop\New folder\data.csv", Destination:=Range("$A$1" _
        ))
        .CommandType = 0
        .Name = "data"
        .FieldNames = True
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .RefreshStyle = xlInsertDeleteCells
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .TextFilePromptOnRefresh = False
        .TextFilePlatform = 437
        .TextFileStartRow = 1
        .TextFileParseType = xlDelimited
        .TextFileTextQualifier = xlTextQualifierSingleQuote
        .TextFileConsecutiveDelimiter = False
        .TextFileTabDelimiter = False
        .TextFileSemicolonDelimiter = False
        .TextFileCommaDelimiter = True
        .TextFileSpaceDelimiter = False
        .TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, _
        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 _
        , 1, 1, 1, 1, 1, 1, 1)
        .TextFileTrailingMinusNumbers = True
        .Refresh BackgroundQuery:=True
    End With
End Sub
</code>```

答:
As per the MSDN KB QueryTable.CommandType Property (Excel),

You can set the CommandType property only if the value of the QueryType property for the query table or PivotTable cache is xlOLEDBQuery.

And since it is neither, simply comment the line .CommandType = 0 or delete that line.

Body:
Below code is not working and throwing error

Invalid Procedure call or argument.

This is the recorded macro code for importing CSV file data into Excel file.

Sub CopyCSVtoExcel()
'
' CopyCSVtoExcel Macro
'
'
    With ActiveSheet.QueryTables.Add(Connection:= _
        "TEXT;C:\Users\hkum29\Desktop\New folder\data.csv", Destination:=Range("$A$1" _
        ))
        .CommandType = 0
        .Name = "data"
        .FieldNames = True
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .RefreshStyle = xlInsertDeleteCells
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .TextFilePromptOnRefresh = False
        .TextFilePlatform = 437
        .TextFileStartRow = 1
        .TextFileParseType = xlDelimited
        .TextFileTextQualifier = xlTextQualifierSingleQuote
        .TextFileConsecutiveDelimiter = False
        .TextFileTabDelimiter = False
        .TextFileSemicolonDelimiter = False
        .TextFileCommaDelimiter = True
        .TextFileSpaceDelimiter = False
        .TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, _
        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 _
        , 1, 1, 1, 1, 1, 1, 1)
        .TextFileTrailingMinusNumbers = True
        .Refresh BackgroundQuery:=True
    End With
End Sub


问:
Instantiate enum class
Consider I am having the following enum class,

```<code>public enum Sample {
    READ,
    WRITE
}
</code>```

and in the following class I am trying to test the enum class,

```<code>public class SampleTest {
    public static void main(String[] args) {
        testEnumSample(Sample.READ);
    }

    public static void testEnumSample(Sample sample) {
        System.out.println(sample);
    }
}
</code>```

Here I am specifying Sample.READ then passing it as the parameter to the method testEnumSample.
 Instead if we want to instantiate the enum class and pass it as parameter what we need to do?

答:
Check my answer in another post.

There are 2 ways:

Use Enum.valueOf() static function, then cast it into your enum type.

```<code>Enum v = Enum.valueOf(TheEnumClass, valueInString);
</code>```

Use class.getEnumConstants() function to get the list of the enum constants, and loop this list and get.

```<code>Plugins[] plugins = Plugins.class.getEnumConstants();
for (Plugins plugin: plugins) {
    // use plugin.name() to get name and compare
}
</code>```

Title: Instantiate enum class

Body:
Consider I am having the following enum class,

public enum Sample {
    READ,
    WRITE
}

and in the following class I am trying to test the enum class,

public class SampleTest {
    public static void main(String[] args) {
        testEnumSample(Sample.READ);
    }

    public static void testEnumSample(Sample sample) {
        System.out.println(sample);
    }
}

Here I am specifying Sample.READ then passing it as the parameter to the method testEnumSample.
 Instead if we want to instantiate the enum class and pass it as parameter what we need to do?

Body:
Check my answer in another post.

There are 2 ways:

Use Enum.valueOf() static function, then cast it into your enum type.

Enum v = Enum.valueOf(TheEnumClass, valueInString);

Use class.getEnumConstants() function to get the list of the enum constants, and loop this list and get.

Plugins[] plugins = Plugins.class.getEnumConstants();
for (Plugins plugin: plugins) {
    // use plugin.name() to get name and compare
}