问:
How can add borderColor and borderWidth to Column type - highchart?
I have tried to add border for selected series. Please adivise

```<code>    series: [{
        showInLegend: false,
        name: 'Twitter Trending',
        colorByPoint: true,
        data: dataArr,
        select: {
            borderWidth: 4,
            borderColor: '#e4b0b2'
        },
        allowPointSelect: true
    }]
</code>```

Reference Screenshot

答:
In order to get desired result, plotoptions will be

```<code>plotOptions: {
    series: {
      allowPointSelect: true,
      states: {
        select: {
          borderWidth: 4,
          borderColor: '#e4b0b2'
        }
      }
    }
  },
</code>```

Highcharts.chart('container', {
  chart: {
    type: 'column'
  },
  title: {
    text: 'Stacked bar chart'
  },
  xAxis: {
    categories: ['Apples', 'Oranges', 'Pears', 'Grapes', 'Bananas']
  },
  yAxis: {
    min: 0,
    title: {
      text: 'Total fruit consumption'
    }
  },
  legend: {
    reversed: true
  },
  plotOptions: {
    series: {
      allowPointSelect: true,
      states: {
        select: {
          borderWidth: 4,
          borderColor: '#e4b0b2'
        }
      }
    }
  },
  series: [{
    name: 'John',
    data: [3, 4, 4, 2, 5],
    showInLegend: false,
    name: 'Twitter Trending',
    colorByPoint: true,
  }]
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>

<div id="container" style="min-width: 310px; max-width: 800px; height: 400px; margin: 0 auto"></div></code>```

Body:
I have tried to add border for selected series. Please adivise

    series: [{
        showInLegend: false,
        name: 'Twitter Trending',
        colorByPoint: true,
        data: dataArr,
        select: {
            borderWidth: 4,
            borderColor: '#e4b0b2'
        },
        allowPointSelect: true
    }]

Reference Screenshot

Body:
In order to get desired result, plotoptions will be

plotOptions: {
    series: {
      allowPointSelect: true,
      states: {
        select: {
          borderWidth: 4,
          borderColor: '#e4b0b2'
        }
      }
    }
  },

Highcharts.chart('container', {
  chart: {
    type: 'column'
  },
  title: {
    text: 'Stacked bar chart'
  },
  xAxis: {
    categories: ['Apples', 'Oranges', 'Pears', 'Grapes', 'Bananas']
  },
  yAxis: {
    min: 0,
    title: {
      text: 'Total fruit consumption'
    }
  },
  legend: {
    reversed: true
  },
  plotOptions: {
    series: {
      allowPointSelect: true,
      states: {
        select: {
          borderWidth: 4,
          borderColor: '#e4b0b2'
        }
      }
    }
  },
  series: [{
    name: 'John',
    data: [3, 4, 4, 2, 5],
    showInLegend: false,
    name: 'Twitter Trending',
    colorByPoint: true,
  }]
});

<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>

<div id="container" style="min-width: 310px; max-width: 800px; height: 400px; margin: 0 auto"></div>


来源: stackexchange

问:
Ensuring availability in Kubernetes with high-variance memory / CPU load?
Problem: the code we're running on Kubernetes Pods have a very high variance across it's runtime; specifically, it has occasional CPU & Memory spikes when certain conditions are triggered. These triggers involve user queries with hard realtime requirements (system has to respond within <5 seconds).

Under conditions where the node serving the spiking pod doesn't have enough CPU/RAM, Kubernetes responds to these excessive requests by killing the pod altogether; which results in no output across any time whatsoever.

In what way can we ensure, that these spikes are being taken into account when pods are allocated; and more critically, that no pod shutdown happens for these reasons?

Thanks!

答:
High availability of pods with load can be achieved in two ways:

Configuring More CPU/Memory

As the applications requires more CPU/memory during the peak times configure in such a way that allocated resources for the POD will take care of extra load. Configure the POD something like this:

```<code>resources:
      requests:
        memory: "64Mi"
        cpu: "250m"
      limits:
        memory: "128Mi"
        cpu: "500m"
</code>```

You can increase the limits based on the usage. But this way of doing can cause two issues

1) Underutilized resources

As the resources are allocated in large number, these may go wasted unless there is a spike in the traffic.

2) Deployment failure

POD deployment may fail because of not having enough resources in the kubernetes node to cater the request.

For more info : https://kubernetes.io/docs/concepts/configuration/manage-compute-resources-container/

> Autoscaling

Ideal way of doing it is to autoscale the POD based on the traffic.

```<code>kubectl autoscale deployment <DEPLOY-APP-NAME> --cpu-percent=50 --min=1 --max=10
</code>```

Configure the cpu-percent based on the requirement, else 80% by default. Min and max are the number of PODS which can be configured accordingly.

So each time a POD hits the CPU percent with 50% a new pod will be launched and continues till it launches a max of 10 PODS and same applicable for vice-versa scenario.

For more info: https://kubernetes.io/docs/tasks/run-application/horizontal-pod-autoscale-walkthrough/

ContentLicense: CC BY-SA 3.0

Body:
High availability of pods with load can be achieved in two ways:

Configuring More CPU/Memory

As the applications requires more CPU/memory during the peak times configure in such a way that allocated resources for the POD will take care of extra load. Configure the POD something like this:

resources:
      requests:
        memory: "64Mi"
        cpu: "250m"
      limits:
        memory: "128Mi"
        cpu: "500m"

You can increase the limits based on the usage. But this way of doing can cause two issues

1) Underutilized resources

As the resources are allocated in large number, these may go wasted unless there is a spike in the traffic.

2) Deployment failure

POD deployment may fail because of not having enough resources in the kubernetes node to cater the request.

For more info : https://kubernetes.io/docs/concepts/configuration/manage-compute-resources-container/

> Autoscaling

Ideal way of doing it is to autoscale the POD based on the traffic.

kubectl autoscale deployment <DEPLOY-APP-NAME> --cpu-percent=50 --min=1 --max=10

Configure the cpu-percent based on the requirement, else 80% by default. Min and max are the number of PODS which can be configured accordingly.

So each time a POD hits the CPU percent with 50% a new pod will be launched and continues till it launches a max of 10 PODS and same applicable for vice-versa scenario.

For more info: https://kubernetes.io/docs/tasks/run-application/horizontal-pod-autoscale-walkthrough/


问:
Grouping numeric distribution in R
I have moved to R very recently and enjoying it ,so is there any way to group X values in R? I want to group by 10 and frequency would occur accordingly?

count(delivery_days)# delivery_days is the table X is delivery time taken for one product and freq I've gathered by the count code in R.

```<code>    x freq
1   3    1
2   4    1
3   5    1
4  10    1
5  12    2
6  25    3
7  32    1
8  45    1
9  65    1
10 78    1
</code>```

Is there any packages need installing to get it or else please let me know .

Title: Grouping numeric distribution in R

Body:
I have moved to R very recently and enjoying it ,so is there any way to group X values in R? I want to group by 10 and frequency would occur accordingly?

count(delivery_days)# delivery_days is the table X is delivery time taken for one product and freq I've gathered by the count code in R.

    x freq
1   3    1
2   4    1
3   5    1
4  10    1
5  12    2
6  25    3
7  32    1
8  45    1
9  65    1
10 78    1

Is there any packages need installing to get it or else please let me know .

Body:
delivery_day=c(2,20,21,22,58,41)
myseq<-seq(from=0,to=max(delivery_day)+10,by=10)
delivery_day_cut<-cut(delivery_day,breaks=myseq)

  >[1] (0,10]  (10,20] (20,30] (20,30] (50,60] (40,50]
  >Levels: (0,10] (10,20] (20,30] (30,40] (40,50] (50,60]

table(delivery_day_cut)

  >delivery_day_cut
   (0,10] (10,20] (20,30] (30,40] (40,50] (50,60]
       1       1       2       0       1       1


问:
How to set datepicker value to selected date after page load?
I have one datepicker having id="from_dt" and button with id="fromToDate".
When i select a date from the datepicker and click the button, the page will load and then i want to set that selected datepicker value to a textbox.

```<code><input class="form-control" id="from_dt" type="text" placeholder="From Date" value="" readonly>
<input type="submit" class="btn btn-outline btn-primary btn-xs" id='fromToDate' value="Search" onclick="getEventListWithDateTime()">
</code>```

and this is button click function :

```<code>function getEventListWithDateTime() {
$("#eventListDatePickerForm").attr( "action", "/eventList/" + $("#from_dt").val() + "/" + $("#to_dt").val());
</code>```

}

答:
Mike's answer helped me
https://stackoverflow.com/a/28061283/6517383

For using a dynamic variable just use:

```<code>var dateToBePrefilled = "10/12/2012";
$( ".selector" ).datepicker( "setDate", dateToBePrefilled );
</code>```

Body:
I have one datepicker having id="from_dt" and button with id="fromToDate".
When i select a date from the datepicker and click the button, the page will load and then i want to set that selected datepicker value to a textbox.

<input class="form-control" id="from_dt" type="text" placeholder="From Date" value="" readonly>
<input type="submit" class="btn btn-outline btn-primary btn-xs" id='fromToDate' value="Search" onclick="getEventListWithDateTime()">

and this is button click function :

function getEventListWithDateTime() {
$("#eventListDatePickerForm").attr( "action", "/eventList/" + $("#from_dt").val() + "/" + $("#to_dt").val());

}

Body:
Mike's answer helped me
https://stackoverflow.com/a/28061283/6517383

For using a dynamic variable just use:

var dateToBePrefilled = "10/12/2012";
$( ".selector" ).datepicker( "setDate", dateToBePrefilled );


问:
How can i trigger an Airflow Dag from nodeJS?
I have scenario where the AirFlow Dag updates snowflake tables, and we have a requirement where in i have to trigger the Dag remotely - in our case from NodeJS.
I would like to know if this is possible ?</p>

答: Airflow’s experimental API does have an endpoint to trigger a dag run, POST /api/experimental/dags//dag_runs. Otherwise, you could use the probably more stable CLI call to airflow trigger_dag, but that might not be possible for you depending on your requirements/setup.


问:
Linker command failed with exit code 1 after installing CocoaPods and firebase pod
I'm trying to use the firebase pod, however getting this (see image) error message when a run is attempted.

I followed this guide to install Cocoapods and added the firebase dependency to the Podfile.

p.s I tried to clean it a bunch of times.

答:
Sometimes its because of you might be declaring an object with same variable name.

Clear the repeating variable name change it. After that clean your project and build again.
Its worked for me....! Thanks.


问:
What are some software and techniques for extracting proper names from a text?
I have a large corpus of text-based documents (100,000+) from which I want to extract proper names (e.g. a person's name).

Could anyone recommend techniques and/or software that would be useful in accomplishing this goal. I'm not particularly interested in low-level text parsing, so much as I am in more high-level things such as recognizing and/or ranking.

答: Probably your best bet is to compare each word against a dictionary of proper names.</p>

ContentLicense: CC BY-SA 2.5


问:
Ansible SSH passwd authentication successful, but publickey authentication fails
When using ansible, I authenticate using the following parameters:

```<code>-u bob -k -K -b
</code>```

I get the output I want, but it turns out that Ansible fails publickey authentication on each system.

Selected output from /var/log/secure on one of the recipient systems:

```<code>Failed publickey for bob from $IP port $PORT ssh2

Accepted password for bob from $IP port $PORT ssh2
</code>```

I'm making my through the documentation, but I have yet to find a method to prevent Ansible from attempting to use anything other than just passwd authentication.

Any help is appreciated.

答:
Add SSH client option -o PreferredAuthentications=password where applicable (Ansible inventory, extra-variables, ssh-config, etc.).

For example, for hosts file:

```<code>[myhosts]
host1 ansible_host=X.X.X.X ansible_ssh_extra_args="-o PreferredAuthentications=password"
</code>```

Body:
When using ansible, I authenticate using the following parameters:

-u bob -k -K -b

I get the output I want, but it turns out that Ansible fails publickey authentication on each system.

Selected output from /var/log/secure on one of the recipient systems:

Failed publickey for bob from $IP port $PORT ssh2

Accepted password for bob from $IP port $PORT ssh2

I'm making my through the documentation, but I have yet to find a method to prevent Ansible from attempting to use anything other than just passwd authentication.

Any help is appreciated.

Body:
Add SSH client option -o PreferredAuthentications=password where applicable (Ansible inventory, extra-variables, ssh-config, etc.).

For example, for hosts file:

[myhosts]
host1 ansible_host=X.X.X.X ansible_ssh_extra_args="-o PreferredAuthentications=password"


问:
Email error -The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.57 SMTP;
I am trying to send email through my asp.net Application and it is throwing the error  "The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.57 SMTP; Client was not authenticated to send anonymous mail during MAIL FROM [SG2PR0601CA0003.apcprd06.prod.outlook.com]"</p>

```<code>       MailMessage message = new MailMessage();
        SmtpClient SmtpServer = new SmtpClient("smtp.live.com");
        message.From = new MailAddress("xxx@outlook.com");
        message.To.Add("xxx@gmail.com");
        message.Subject = "Test Email";
        message.Body = "Email Body";
        SmtpServer.Port = 587;
        SmtpServer.Credentials = new
         System.Net.NetworkCredential("xxx@outlook.com", "xxxxxxxx");
        //SmtpServer.EnableSsl = true;
        SmtpServer.Timeout = 60000; // 60 seconds
        SmtpServer.Send(message);
</code>```

答:
1) Check the account credentials by logging in on the owa (www.outlook.com)

2) please check the link below as this will be the solution to your question

https://www.codeproject.com/Articles/700211/Csharp-SMTP-Configuration-for-Outlook-Com-SMTP-Hos

The 2 differences I already see are below

- SmtpServer.EnableSsl = true;

- new SmtpClient("smtp-mail.outlook.com")

In the article is also a cool section 'Use the App Password Instead of Your Outlook.Com Account Password'

Body:
I am trying to send email through my asp.net Application and it is throwing the error  "The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.57 SMTP; Client was not authenticated to send anonymous mail during MAIL FROM [SG2PR0601CA0003.apcprd06.prod.outlook.com]"

       MailMessage message = new MailMessage();
        SmtpClient SmtpServer = new SmtpClient("smtp.live.com");
        message.From = new MailAddress("xxx@outlook.com");
        message.To.Add("xxx@gmail.com");
        message.Subject = "Test Email";
        message.Body = "Email Body";
        SmtpServer.Port = 587;
        SmtpServer.Credentials = new
         System.Net.NetworkCredential("xxx@outlook.com", "xxxxxxxx");
        //SmtpServer.EnableSsl = true;
        SmtpServer.Timeout = 60000; // 60 seconds
        SmtpServer.Send(message);


问:
Is it possible to include formatting (i.e. HTML) in the description of a Maven POM?
I'd like to have useful urls and a bit of tidiness in the description and other text fields of my Maven generated site.

Is there a way to do this?

答:
If we are talking about maven-site-plugin, you can customize your site by modifying the default template, which uses Velocity as template engine, by specifying something like this:

```<code>    <configuration>
      <templateFile>${basedir}/maven-site.vm</templateFile>
    </configuration>
</code>```

Reference documentation here.

Also, keep in mind from their documentation, this method has downsides.

Note: If you use this method then skins and the default templates, CSS
  and images are disabled. It is therefor highly recommended that you
  package this as a skin instead.

EDIT:
You can add CDATA tag to include more sofisticated description like so:

```<code><description>
    <![CDATA[
        <p>This is a description including html tags and whatnot</p>
    ]]>
</description>
</code>```

Body:
If we are talking about maven-site-plugin, you can customize your site by modifying the default template, which uses Velocity as template engine, by specifying something like this:

    <configuration>
      <templateFile>${basedir}/maven-site.vm</templateFile>
    </configuration>

Reference documentation here.

Also, keep in mind from their documentation, this method has downsides.

Note: If you use this method then skins and the default templates, CSS
  and images are disabled. It is therefor highly recommended that you
  package this as a skin instead.

EDIT:
You can add CDATA tag to include more sofisticated description like so:

<description>
    <![CDATA[
        <p>This is a description including html tags and whatnot</p>
    ]]>
</description>


问:
Disable WAL in OrientDB through Java API
We have an OrientDB graph database and a daily scheduler which performs massive insertions in the database using the Java API. For this reason, we would like to disable WAL from the Java code when performing these insertions, otherwise the size of the WAL file will be huge in a short amount of time.

We already know that is possible to disable WAL permanently by editing some OrientDB configurations, but we don't want to make this choice.

We have seen that there is a closed issue on the github repository of OrientDB, which suggests the following solution:

```<code>private void reopenWithWALSetTo(final boolean useWAL) {
    db.getStorage().close(true, false);
    db.close();
    OGlobalConfiguration.USE_WAL.setValue(useWAL);
    db = new ODatabaseDocumentTx(dbURL);
    db.open("admin", "admin");
}
</code>```

The problem is that we are not using an instance of ODatabaseDocumentTx when opening the connection with the database. In fact, since we are using a graph DB, we use OrientGraphFactory in the following way:

```<code>factory = new OrientGraphFactory("url", "username", "password");
graph = factory.getTx();
</code>```

It is possible to obtain an instance of ODatabaseDocumentTx in the following way:

```<code>db = graph.getRawGraph();
</code>```

But then, after having close the instance of ODatabaseDocumentTx, it is not possible to reopen the connection with our graph db.

Any suggestions?

答:
You could disable the journal (WAL) for some operations where reliability is not necessary, starting OrientDB with this Java option:

```<code>-Dstorage.useWAL=false
</code>```

https://orientdb.com/docs/last/Write-Ahead-Log.html

Body:
We have an OrientDB graph database and a daily scheduler which performs massive insertions in the database using the Java API. For this reason, we would like to disable WAL from the Java code when performing these insertions, otherwise the size of the WAL file will be huge in a short amount of time.

We already know that is possible to disable WAL permanently by editing some OrientDB configurations, but we don't want to make this choice.

We have seen that there is a closed issue on the github repository of OrientDB, which suggests the following solution:

private void reopenWithWALSetTo(final boolean useWAL) {
    db.getStorage().close(true, false);
    db.close();
    OGlobalConfiguration.USE_WAL.setValue(useWAL);
    db = new ODatabaseDocumentTx(dbURL);
    db.open("admin", "admin");
}

The problem is that we are not using an instance of ODatabaseDocumentTx when opening the connection with the database. In fact, since we are using a graph DB, we use OrientGraphFactory in the following way:

factory = new OrientGraphFactory("url", "username", "password");
graph = factory.getTx();

It is possible to obtain an instance of ODatabaseDocumentTx in the following way:

db = graph.getRawGraph();

But then, after having close the instance of ODatabaseDocumentTx, it is not possible to reopen the connection with our graph db.

Any suggestions?

Body:
You could disable the journal (WAL) for some operations where reliability is not necessary, starting OrientDB with this Java option:

-Dstorage.useWAL=false

https://orientdb.com/docs/last/Write-Ahead-Log.html


问:
Masking number at a particular position
I have a input field with a maximum length of 15 character.
i want to do something like this

original number :784198012345671
should be:  784********5671

答:
```<code>const original = "784198012345671",
 obfuscated = original.substr(0, 3) + "*".repeat(original.length - 7) + original.substr(-4);
</code>```

You may use substr to get the number groups at the beginning and the end out of the number and then use repeat to fill the asterisks inbetween.

Title: Masking number at a particular position

Body:
const original = "784198012345671",
 obfuscated = original.substr(0, 3) + "*".repeat(original.length - 7) + original.substr(-4);

You may use substr to get the number groups at the beginning and the end out of the number and then use repeat to fill the asterisks inbetween.


问:
Storing a list of functions
The code

```<code>for ( var i:int = 0; i < markers.length; i++ )
{
    markers[i].addEventListener( MapMouseEvent.CLICK, function( e:Event ):void
    {
        markers[i].openInfoWindow( infoWindows[i] );
    });
    map.addOverlay( markers[i] );
}
</code>```

I have a list of markers in markers array, and a list of associated InfoWindowOptions in the infoWindow array.

The Issue

By the time the marker is clicked and the anonymous function called, the for loop has already finished and i is now equal to markers.length. So I get an out of bounds error on markers[i] and infoWindows[i].

I would like to create a list of associated functions as well and store it in an array. So I can do something like this instead:

```<code>for ( var i:int = 0; i < markers.length; i++ )
{
    markers[i].addEventListener( MapMouseEvent.CLICK, markerListeners[i] );
}
</code>```

So what I need to know is either,

How can I can store a list of function references in an array?

Is there a better way of doing this?

答:
Is there a better way of doing this?

I'm going to attempt a better way of doing this. First of all, it's good to avoid every putting an anonymous function in an addEventListener because you won't be able to remove that listeners and it won't be garbage collected -- so your application will have memory leaks.

With that said, a Dictionary would be perfect for this purpose.

Instead of maintaing two separate arrays and trying to link them together the key:value syntax of a Dictionary will greatly simplify your workflow.

First you should setup your Dictionary:

```<code>var markersDictionary:Dictionary = new Dictionary(true);

//you didn't show how you create your arrays so I'm showing
//you how to create a dictionary manually.
//this can also be done in a loop
markersDictionary[marker] = new InfoWindow(); // This should be whatever is in your infoWindows array
markersDictionary[marker] = new InfoWindow();
markersDictionary[marker] = new InfoWindow();
</code>```

Now to add listeners:

```<code>for(var key:Object in markersDictionary)
{
  var marker:Marker = markersDictionary[key];
  marker.addEventListener(MouseMapEvent.CLICK, markerClickhandler, false, 0, true);
  //...false, 0, true is for weak event listeners, you should get in
  // the habit of always doing this unless you have a reason to otherwise.
{
</code>```

and of course you need to define markerClickhandler:

```<code>function markerClickhandler(event:MouseMapEvent):void
{
  var marker:Marker = event.target as Marker;

  marker.openInfoWindow(InfowWindow(markersDictionary[marker]);
}
</code>```

Title: Storing a list of functions

Body:
The code

for ( var i:int = 0; i < markers.length; i++ )
{
    markers[i].addEventListener( MapMouseEvent.CLICK, function( e:Event ):void
    {
        markers[i].openInfoWindow( infoWindows[i] );
    });
    map.addOverlay( markers[i] );
}

I have a list of markers in markers array, and a list of associated InfoWindowOptions in the infoWindow array.

The Issue

By the time the marker is clicked and the anonymous function called, the for loop has already finished and i is now equal to markers.length. So I get an out of bounds error on markers[i] and infoWindows[i].

I would like to create a list of associated functions as well and store it in an array. So I can do something like this instead:

for ( var i:int = 0; i < markers.length; i++ )
{
    markers[i].addEventListener( MapMouseEvent.CLICK, markerListeners[i] );
}

So what I need to know is either,

How can I can store a list of function references in an array?

Is there a better way of doing this?

Body:
Is there a better way of doing this?

I'm going to attempt a better way of doing this. First of all, it's good to avoid every putting an anonymous function in an addEventListener because you won't be able to remove that listeners and it won't be garbage collected -- so your application will have memory leaks.

With that said, a Dictionary would be perfect for this purpose.

Instead of maintaing two separate arrays and trying to link them together the key:value syntax of a Dictionary will greatly simplify your workflow.

First you should setup your Dictionary:

var markersDictionary:Dictionary = new Dictionary(true);

//you didn't show how you create your arrays so I'm showing
//you how to create a dictionary manually.
//this can also be done in a loop
markersDictionary[marker] = new InfoWindow(); // This should be whatever is in your infoWindows array
markersDictionary[marker] = new InfoWindow();
markersDictionary[marker] = new InfoWindow();

Now to add listeners:

for(var key:Object in markersDictionary)
{
  var marker:Marker = markersDictionary[key];
  marker.addEventListener(MouseMapEvent.CLICK, markerClickhandler, false, 0, true);
  //...false, 0, true is for weak event listeners, you should get in
  // the habit of always doing this unless you have a reason to otherwise.
{

and of course you need to define markerClickhandler:

function markerClickhandler(event:MouseMapEvent):void
{
  var marker:Marker = event.target as Marker;

  marker.openInfoWindow(InfowWindow(markersDictionary[marker]);
}


问:
onClick on li element are not passing target id properly?
I am working on a ReactJS project using MaterialUI. I have following code

```<code>{ this.state.categories.map((category, key) => (
      <List>
        <ListItem button id={key} onClick={this.handleClick}>
              <ListItemText primary={category.name} />
              {(category.id === Number(this.state.nestedOpenNum)) ?
<ExpandLess /> : <ExpandMore />}
        </ListItem>
      </List>
            )

      )}
</code>```

and state looks something like

```<code>this.state = {
  open: false,
  nestedOpen: false,
  nestedOpenNum: 0,
  result: [],
  categories: [{
      id: 0,
      name: "COMPUER SCIENCE",
    }, {
      id: 1,
      name: "BUSINESS",
    }, {
      id: 2,
      name: "ART & HUMANITIES",
    }, {
      id: 3,
      name: "MATH & LOGIC",
    },{
      id: 4,
      name: "SCIENCE",
    }]
};
</code>```

this is the handleClick function-

```<code>handleClick = (e) => {
this.setState({ nestedOpenNum: e.target.id });
this.setState({ nestedOpen: !this.state.nestedOpen });
console.log(e.target.id );
</code>```

};

PROBLEM

When I click in padding area of li element(green area), everything working perfectly. But e.target.id is not passing when I click on li element(blue area).

how can I solve this?

答: I believe you should use currentTarget not target. Look at this https://github.com/DefinitelyTyped/DefinitelyTyped/issues/11508#issuecomment-256045682

Body:
I am working on a ReactJS project using MaterialUI. I have following code

{ this.state.categories.map((category, key) => (
      <List>
        <ListItem button id={key} onClick={this.handleClick}>
              <ListItemText primary={category.name} />
              {(category.id === Number(this.state.nestedOpenNum)) ?
<ExpandLess /> : <ExpandMore />}
        </ListItem>
      </List>
            )

      )}

and state looks something like

this.state = {
  open: false,
  nestedOpen: false,
  nestedOpenNum: 0,
  result: [],
  categories: [{
      id: 0,
      name: "COMPUER SCIENCE",
    }, {
      id: 1,
      name: "BUSINESS",
    }, {
      id: 2,
      name: "ART & HUMANITIES",
    }, {
      id: 3,
      name: "MATH & LOGIC",
    },{
      id: 4,
      name: "SCIENCE",
    }]
};

this is the handleClick function-

handleClick = (e) => {
this.setState({ nestedOpenNum: e.target.id });
this.setState({ nestedOpen: !this.state.nestedOpen });
console.log(e.target.id );

};

PROBLEM

When I click in padding area of li element(green area), everything working perfectly. But e.target.id is not passing when I click on li element(blue area).

how can I solve this?


问:
Removing child node from html document jquery
```<code>var ff = "<div class='ofr-test'><h3>My test</h3><div class='ban--content'><strong>Only a Test</strong><p>Blah Blah</p><p id='first' class='red'>Blah2 Blah2 Blah2</p></div></div>"

$(ff).find('.first').remove().end().html();
</code>```

Works correctly, but the parent div(class=‘ofr-test’) is being removed, how can I fix it?

答:
Try this

var ff = ".ofr-test"

$(ff).find('#first').remove().end().html();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='ofr-test'>
  <h3>My test</h3>
  <div class='ban--content'>
  <strong>Only a Test</strong>
  <p>Blah Blah</p>
  <p id='first' class='red'>Blah2 Blah2 Blah2</p></div></div></code>```

You are having a id named first not a class more over use the above syntax to select a node its more readable.Although I'm not sure why whole div is being used in your case but its not a good option whatsoever

Body:
var ff = "

My test

Only a Test
Blah Blah

Blah2 Blah2 Blah2

"

$(ff).find('.first').remove().end().html();

Works correctly, but the parent div(class=‘ofr-test’) is being removed, how can I fix it?

Body:
Try this

var ff = ".ofr-test"

$(ff).find('#first').remove().end().html();

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='ofr-test'>
  <h3>My test</h3>
  <div class='ban--content'>
  <strong>Only a Test</strong>
  <p>Blah Blah</p>
  <p id='first' class='red'>Blah2 Blah2 Blah2</p></div></div>

You are having a id named first not a class more over use the above syntax to select a node its more readable.Although I'm not sure why whole div is being used in your case but its not a good option whatsoever


问:
PyGame Screen Returning Black when run
While trying to run a game in which is being developed for a project, the code would not work and causes the screen to be black. The Mycharacter is a character, enemy is for a enemy character, obstacle is for obstacles within the game. The design is supposed to be a character chasing the enemy while the enemy is chasing the character to gain points with obstructions in the way.
We are importing other classes into this function and main class.
All help will be appricated.
Heres how the code looks:</p>

```<code>import pygame
import time
import random
import Mycharacter
import enemy
import obstacle
import json

GREEN = (0, 255, 0)

class Controller:
    def __init__(self):
        pygame.init()
        self.screen = pygame.display.set_mode((800, 800))
        self.background = pygame.Surface(self.screen.get_size()).convert()
    #self.button_image = pygame.image.load("start_button.png").convert
    self.button = pygame.Rect(350, 50, 100, 100)
    #self.button_image.get_rect()
    self.font = pygame.font.Font("Shark_Soft_Bites.TTF", 60)
    self.text = pygame.font.Font.render(self.font,"Start", True, (255, 0, 0))
    #self.score_text = pygame.font.Font.render("Highscore: "+ str())
    self.file = open("highscores.json", "r")
    self.currentState = "Start"
    self.obstacles = []
    for i in range(5):
        x = random.randrange(50, 600)
        y = random.randrange(60, 700)
        self.obstacles.append(obstacle.Obstacle((x, y), 'rock.png' ))
    self.enemies = []
    for i in range(3) :
        if i == 0:
            x = 725
            y = 100
        elif i == 1:
            x = 75
            y = 700
        elif i == 2:
            x = 725
            y = 700
        self.enemies.append(enemy.Enemy((x, y), "enemy.png"))
    self.Mycharacter = Mycharacter.Mycharacter((75, 100), "head6.png")
    self.mysprites = pygame.sprite.Group((self.Mycharacter,) + tuple(self.enemies) + tuple(self.obstacles))
    self.mysprites2 = pygame.sprite.Group(tuple(self.enemies) + tuple(self.obstacles))
    self.score = 0
    self.end_time = 0
    self.start_time = 0
    self.time = (self.end_time-self.start_time) * 1000

def mainLoop(self):
    """
    This is the main loop for the game that calls the other functions in this class
    in order to create a start screen, run the game, and present the high score and player
    score at the end of the game.
    Param list: None
    Return list: None
    """
    self.done = False
    while not self.done:
        if self.currentState == "start":
            self.startGame(self)
        elif self.currentState == "running":
            self.start_time = pygame.time.get_ticks()
            self.runGame(self)
        elif self.currentState == "end":
            self.endGame(self)
    pygame.quit

def startGame(self):
    """
    This is the function for the start of the game.  It fills the screen
    with a different color background and creates the start button that the user
    can click on to begin running the game.
    Param list: None
    Returns: None
    """
    start = True
    while start:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                self.done = True
                start = False
            if event.type == pygame.MOUSEBUTTONDOWN:
                mouse_pos = pygame.mouse.get_pos()
                if self.button.collidepoint(mouse_pos):
                    self.currentState = "running"
                    start = False
        self.screen.fill((255, 0, 255))
        pygame.draw.rect(self.screen, (0, 0, 0), self.button)
        self.screen.blit(self.text, (350,50))
        pygame.display.flip()
    pygame.quit

def runGame(self):
    run = True
    clock = pygame.time.Clock
    while run:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                self.done = True
                run = False
            if event.type == pygame.KEYDOWN:
            #Under here is the game logic and i don't know if i should have the random enemy movement under here
                if(event.key == pygame.K_UP):
                    self.Mycharacter.move_up()
                elif(event.key == pygame.K_DOWN):
                    self.Mycharacter.move_down()
                elif(event.key == pygame.K_LEFT):
                    self.Mycharacter.move_left()
                elif(event.key == pygame.K_RIGHT):
                    self.Mycharacter.move_right()
            self.score += 1
            if self.score > 400:
                if self.score > 800:
                    if self.score > 1200:
                        self.enemy.speed(18)
                    else:
                        self.enemy.speed(16)
                else:
                    self.enemy.speed(14)
            else:
                self.enemy.speed(12)

            self.mysprites.update()
            #self.mysprites2.group_collide
            #possibly sprite.groupcollide to save myself these two loops but I like the loops
            #also idk if the dokill means it will .kill() or something else
            for i in range(len(self.obstacles)):
                if(pygame.sprite.collide_rect(self.Mycharacter, self.obstacle[i])):
                    self.Mycharacter.kill()
                    self.currentState = "end"
                    self.end_time = pygame.time.get_ticks()
                    run = False

            for i in range(len(self.enemies)):
                if(pygame.sprite.collide_rect(self.Mycharacter, self.enemies[i])):
                    self.Mycharacter.kill()
                    self.currentState = "end"
                    self.end_time = pygame.time.get_ticks()
                    run = False

            self.screen.fill(GREEN)
            #self.obstacles.draw(self.screen)
            #self.enemies.draw(self.screen)
            self.screen.blit(self.background, (0, 0))
            self.mysprites.draw()
            #self.screen.blit(self.Mycharacter,(self.Mycharacter.rect.x, self.Mycharacter.rect.y))
                    #drawing code
                    #update screen with what has been drawn
            pygame.display.flip()

            clock.tick(60)
    pygame.quit

def endGame(self):
    #self.screen = pygame.display.set_mode(800, 800)
    #self.background = pygame.Surface(self.screen.get_size()).convert()
    end = False
    while not end:
        for event in pygame.event.get():
            if event == pygame.QUIT:
                end = True
                self.done = True
            else:
                line = json.load(self.file.readline())
                num = line["one"]
                self.file.close()
                if self.time > int(num):
                    self.file = open("highscores.json", "w")
                    newstr = "highscore:"+str(num)
                    jsonstr = json.dump(newstr)
                    self.file.write(newstr)
                    self.file.close
                self.file = open("highscores.json", "r")
                newline = json.load(self.file.readline())
                score = newline["highscore"]
                self.file.close()
                self.screen.fill((0, 0, 255))
                #create text and rect to blit onto screen to display high score
                self.screen.blit("Highscore: " + str(score), (350, 50))
                self.screen.blit("Your Score: " + str(num), (350, 150))
                pygame.display.flip()
    pygame.quit

def main():
    the_game = Controller()
    the_game.mainLoop()

main()
</code>```

答:
The first problem that I can see is that you pass self as an argument to the different scene methods self.startGame(self) in the mainLoop. Just remove the self.

In the runGame method, you have indented a lot of your code incorrectly. The game logic and drawing code shouldn't be in the event loop but in the outer while loop. It should still draw everything, though, but only if events are in the queue (for example if the mouse gets moved).

Also, the self.background surface is just black because you never fill it with another color.

Side notes: You forgot some parentheses behind clock = pygame.time.Clock an pygame.quit.

In the endGame method, you load the json file every time an event occurs (f.e. mouse movements). You should better do that once per mouse click or something similar.

Here's a minimal example that works correctly:

```<code>import pygame

GREEN = pygame.Color('green')

class Controller:
    def __init__(self):
        pygame.init()
        self.screen = pygame.display.set_mode((800, 800))
        self.background = pygame.Surface(self.screen.get_size()).convert()
        self.background.fill(GREEN)  # Fill the background if it shouldn't be black.
        self.clock = pygame.time.Clock()
        self.currentState = "start"
        self.button = pygame.Rect(350, 50, 100, 100)

    def mainLoop(self):
        self.done = False
        while not self.done:
            if self.currentState == "start":
                self.startGame()
            elif self.currentState == "running":
                self.start_time = pygame.time.get_ticks()
                self.runGame()

    def startGame(self):
        start = True
        while start:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    self.done = True
                    start = False
                if event.type == pygame.MOUSEBUTTONDOWN:
                    mouse_pos = pygame.mouse.get_pos()
                    if self.button.collidepoint(mouse_pos):
                        self.currentState = "running"
                        return  # Back to the mainloop

            self.screen.fill((255, 0, 255))
            pygame.draw.rect(self.screen, (0, 0, 110), self.button)
            pygame.display.flip()
            self.clock.tick(60)

    def runGame(self):
        run = True
        while run:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    self.done = True
                    run = False

            self.screen.blit(self.background, (0, 0))
            pygame.draw.rect(self.screen, (200, 0, 0), [20, 30, 50, 90])
            pygame.display.flip()
            self.clock.tick(60)

def main():
    the_game = Controller()
    the_game.mainLoop()

main()
pygame.quit()
</code>```

Title: PyGame Screen Returning Black when run

Body:
While trying to run a game in which is being developed for a project, the code would not work and causes the screen to be black. The Mycharacter is a character, enemy is for a enemy character, obstacle is for obstacles within the game. The design is supposed to be a character chasing the enemy while the enemy is chasing the character to gain points with obstructions in the way.
We are importing other classes into this function and main class.
All help will be appricated.
Heres how the code looks:

import pygame
import time
import random
import Mycharacter
import enemy
import obstacle
import json

GREEN = (0, 255, 0)

class Controller:
    def __init__(self):
        pygame.init()
        self.screen = pygame.display.set_mode((800, 800))
        self.background = pygame.Surface(self.screen.get_size()).convert()
    #self.button_image = pygame.image.load("start_button.png").convert
    self.button = pygame.Rect(350, 50, 100, 100)
    #self.button_image.get_rect()
    self.font = pygame.font.Font("Shark_Soft_Bites.TTF", 60)
    self.text = pygame.font.Font.render(self.font,"Start", True, (255, 0, 0))
    #self.score_text = pygame.font.Font.render("Highscore: "+ str())
    self.file = open("highscores.json", "r")
    self.currentState = "Start"
    self.obstacles = []
    for i in range(5):
        x = random.randrange(50, 600)
        y = random.randrange(60, 700)
        self.obstacles.append(obstacle.Obstacle((x, y), 'rock.png' ))
    self.enemies = []
    for i in range(3) :
        if i == 0:
            x = 725
            y = 100
        elif i == 1:
            x = 75
            y = 700
        elif i == 2:
            x = 725
            y = 700
        self.enemies.append(enemy.Enemy((x, y), "enemy.png"))
    self.Mycharacter = Mycharacter.Mycharacter((75, 100), "head6.png")
    self.mysprites = pygame.sprite.Group((self.Mycharacter,) + tuple(self.enemies) + tuple(self.obstacles))
    self.mysprites2 = pygame.sprite.Group(tuple(self.enemies) + tuple(self.obstacles))
    self.score = 0
    self.end_time = 0
    self.start_time = 0
    self.time = (self.end_time-self.start_time) * 1000

def mainLoop(self):
    """
    This is the main loop for the game that calls the other functions in this class
    in order to create a start screen, run the game, and present the high score and player
    score at the end of the game.
    Param list: None
    Return list: None
    """
    self.done = False
    while not self.done:
        if self.currentState == "start":
            self.startGame(self)
        elif self.currentState == "running":
            self.start_time = pygame.time.get_ticks()
            self.runGame(self)
        elif self.currentState == "end":
            self.endGame(self)
    pygame.quit

def startGame(self):
    """
    This is the function for the start of the game.  It fills the screen
    with a different color background and creates the start button that the user
    can click on to begin running the game.
    Param list: None
    Returns: None
    """
    start = True
    while start:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                self.done = True
                start = False
            if event.type == pygame.MOUSEBUTTONDOWN:
                mouse_pos = pygame.mouse.get_pos()
                if self.button.collidepoint(mouse_pos):
                    self.currentState = "running"
                    start = False
        self.screen.fill((255, 0, 255))
        pygame.draw.rect(self.screen, (0, 0, 0), self.button)
        self.screen.blit(self.text, (350,50))
        pygame.display.flip()
    pygame.quit

def runGame(self):
    run = True
    clock = pygame.time.Clock
    while run:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                self.done = True
                run = False
            if event.type == pygame.KEYDOWN:
            #Under here is the game logic and i don't know if i should have the random enemy movement under here
                if(event.key == pygame.K_UP):
                    self.Mycharacter.move_up()
                elif(event.key == pygame.K_DOWN):
                    self.Mycharacter.move_down()
                elif(event.key == pygame.K_LEFT):
                    self.Mycharacter.move_left()
                elif(event.key == pygame.K_RIGHT):
                    self.Mycharacter.move_right()
            self.score += 1
            if self.score > 400:
                if self.score > 800:
                    if self.score > 1200:
                        self.enemy.speed(18)
                    else:
                        self.enemy.speed(16)
                else:
                    self.enemy.speed(14)
            else:
                self.enemy.speed(12)

            self.mysprites.update()
            #self.mysprites2.group_collide
            #possibly sprite.groupcollide to save myself these two loops but I like the loops
            #also idk if the dokill means it will .kill() or something else
            for i in range(len(self.obstacles)):
                if(pygame.sprite.collide_rect(self.Mycharacter, self.obstacle[i])):
                    self.Mycharacter.kill()
                    self.currentState = "end"
                    self.end_time = pygame.time.get_ticks()
                    run = False

            for i in range(len(self.enemies)):
                if(pygame.sprite.collide_rect(self.Mycharacter, self.enemies[i])):
                    self.Mycharacter.kill()
                    self.currentState = "end"
                    self.end_time = pygame.time.get_ticks()
                    run = False

            self.screen.fill(GREEN)
            #self.obstacles.draw(self.screen)
            #self.enemies.draw(self.screen)
            self.screen.blit(self.background, (0, 0))
            self.mysprites.draw()
            #self.screen.blit(self.Mycharacter,(self.Mycharacter.rect.x, self.Mycharacter.rect.y))
                    #drawing code
                    #update screen with what has been drawn
            pygame.display.flip()

            clock.tick(60)
    pygame.quit

def endGame(self):
    #self.screen = pygame.display.set_mode(800, 800)
    #self.background = pygame.Surface(self.screen.get_size()).convert()
    end = False
    while not end:
        for event in pygame.event.get():
            if event == pygame.QUIT:
                end = True
                self.done = True
            else:
                line = json.load(self.file.readline())
                num = line["one"]
                self.file.close()
                if self.time > int(num):
                    self.file = open("highscores.json", "w")
                    newstr = "highscore:"+str(num)
                    jsonstr = json.dump(newstr)
                    self.file.write(newstr)
                    self.file.close
                self.file = open("highscores.json", "r")
                newline = json.load(self.file.readline())
                score = newline["highscore"]
                self.file.close()
                self.screen.fill((0, 0, 255))
                #create text and rect to blit onto screen to display high score
                self.screen.blit("Highscore: " + str(score), (350, 50))
                self.screen.blit("Your Score: " + str(num), (350, 150))
                pygame.display.flip()
    pygame.quit

def main():
    the_game = Controller()
    the_game.mainLoop()

main()

Body:
The first problem that I can see is that you pass self as an argument to the different scene methods self.startGame(self) in the mainLoop. Just remove the self.

In the runGame method, you have indented a lot of your code incorrectly. The game logic and drawing code shouldn't be in the event loop but in the outer while loop. It should still draw everything, though, but only if events are in the queue (for example if the mouse gets moved).

Also, the self.background surface is just black because you never fill it with another color.

Side notes: You forgot some parentheses behind clock = pygame.time.Clock an pygame.quit.

In the endGame method, you load the json file every time an event occurs (f.e. mouse movements). You should better do that once per mouse click or something similar.

Here's a minimal example that works correctly:

import pygame

GREEN = pygame.Color('green')

class Controller:
    def __init__(self):
        pygame.init()
        self.screen = pygame.display.set_mode((800, 800))
        self.background = pygame.Surface(self.screen.get_size()).convert()
        self.background.fill(GREEN)  # Fill the background if it shouldn't be black.
        self.clock = pygame.time.Clock()
        self.currentState = "start"
        self.button = pygame.Rect(350, 50, 100, 100)

    def mainLoop(self):
        self.done = False
        while not self.done:
            if self.currentState == "start":
                self.startGame()
            elif self.currentState == "running":
                self.start_time = pygame.time.get_ticks()
                self.runGame()

    def startGame(self):
        start = True
        while start:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    self.done = True
                    start = False
                if event.type == pygame.MOUSEBUTTONDOWN:
                    mouse_pos = pygame.mouse.get_pos()
                    if self.button.collidepoint(mouse_pos):
                        self.currentState = "running"
                        return  # Back to the mainloop

            self.screen.fill((255, 0, 255))
            pygame.draw.rect(self.screen, (0, 0, 110), self.button)
            pygame.display.flip()
            self.clock.tick(60)

    def runGame(self):
        run = True
        while run:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    self.done = True
                    run = False

            self.screen.blit(self.background, (0, 0))
            pygame.draw.rect(self.screen, (200, 0, 0), [20, 30, 50, 90])
            pygame.display.flip()
            self.clock.tick(60)

def main():
    the_game = Controller()
    the_game.mainLoop()

main()
pygame.quit()


问:
Bash-shell grammar issue about Ternary operator and printf function
```<code>cat file
chenghuanghuijia jidianzhong 100 E20128
pannybudaqiu gujihuihenwan -1
shuijiao buxihuan 20 E20138
huijiakan babamama 10
</code>```

I want get the result that when the line contains E2[0-9]*$ , the end of the line will be printed, if the line not contain E2[0-9]*$, the end of the line will be printed NULL or \n.

Here is my code:

```<code>awk '{printf("%s\n",($NF~/E2[0-9]*$/? "E2.*$" : NULL))}' file
</code>```

The output as below:

```<code>E2.*$

E2.*$
</code>```

but I want to print E20128 & E20138, So I verified my code with deleting " "

```<code>awk '{printf("%s\n",($NF~/E2[0-9]*$/? E2.*$ : NULL))}' file
</code>```

Then it comes the error:

```<code>awk: cmd. line:1: {printf("%s\n",($NF~/E2[0-9]*$/? E2.*$ : NULL))}
awk: cmd. line:1:                                    ^ syntax error
awk: cmd. line:1: {printf("%s\n",($NF~/E2[0-9]*$/? E2.*$ : NULL))}
awk: cmd. line:1:                                               ^ syntax error
awk: cmd. line:1: {printf("%s\n",($NF~/E2[0-9]*$/? E2.*$ : NULL))}
awk: cmd. line:1:                                                ^ syntax error
</code>```

So I think is the grammar issue of Ternary operator( _?x:y) or printf function.
please support me .

答:
With GNU sed:

```<code>sed '/.*\(E2[0-9]*\)$/s//\1/;//!s/.*//' file
</code>```

/.*\(E2[0-9]*\)$: capture strings matching E2[0-9]* and output it using backreference (s//\1/)

//!: if there is no matching string, clear the line(s/.*//)

Body:
cat file
chenghuanghuijia jidianzhong 100 E20128
pannybudaqiu gujihuihenwan -1
shuijiao buxihuan 20 E20138
huijiakan babamama 10

I want get the result that when the line contains E2[0-9]*$ , the end of the line will be printed, if the line not contain E2[0-9]*$, the end of the line will be printed NULL or \n.

Here is my code:

awk '{printf("%s\n",($NF~/E2[0-9]*$/? "E2.*$" : NULL))}' file

The output as below:

E2.*$

E2.*$

but I want to print E20128 & E20138, So I verified my code with deleting " "

awk '{printf("%s\n",($NF~/E2[0-9]*$/? E2.*$ : NULL))}' file

Then it comes the error:

awk: cmd. line:1: {printf("%s\n",($NF~/E2[0-9]*$/? E2.*$ : NULL))}
awk: cmd. line:1:                                    ^ syntax error
awk: cmd. line:1: {printf("%s\n",($NF~/E2[0-9]*$/? E2.*$ : NULL))}
awk: cmd. line:1:                                               ^ syntax error
awk: cmd. line:1: {printf("%s\n",($NF~/E2[0-9]*$/? E2.*$ : NULL))}
awk: cmd. line:1:                                                ^ syntax error

So I think is the grammar issue of Ternary operator( _?x:y) or printf function.
please support me .

Body:
With GNU sed:

sed '/.*\(E2[0-9]*\)$/s//\1/;//!s/.*//' file

/.*\(E2[0-9]*\)$: capture strings matching E2[0-9]* and output it using backreference (s//\1/)

//!: if there is no matching string, clear the line(s/.*//)


问:
Symfony 3: How to redirect from within InteractiveLoginEvent listener
In Symfony 3.4.0, from an event listener that listens to the InteractiveLoginEvent I would like to redirect to another route, so I would like to respond a redirect.

But the InteractiveLoginEvent object has no "setResponse" method. So which is the preferred way to use the InteractiveLoginEvent to modify the response so that a redirect is sent to the user?

答:
To perform a redirect after successful login, you can add a custom success handler, that should implement the AuthenticationSuccessHandlerInterface.

AuthenticationSuccessHandler.php

```<code><?php

namespace AppBundle\Security\Authentication\Handler;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Http\Authentication\AuthenticationSuccessHandlerInterface;

class AuthenticationSuccessHandler implements AuthenticationSuccessHandlerInterface
{
    private $router;

    public function __construct(RouterInterface $router)
    {
        $this->router = $router;
    }

    public function onAuthenticationSuccess(Request $request, TokenInterface $token)
    {
        return new RedirectResponse($this->router->generate('homepage'));
    }
}
</code>```

services.yml

```<code>   services:
       AppBundle\Security\Authentication\Handler:
           arguments: ['@router']
</code>```

security.yml

```<code>security:
    # ...
    firewalls:
          form_login:
              # ...
              use_referer: false
              success_handler: AppBundle\Security\Authentication\Handler\AuthenticationSuccessHandler
</code>```

Body:
To perform a redirect after successful login, you can add a custom success handler, that should implement the AuthenticationSuccessHandlerInterface.

AuthenticationSuccessHandler.php

<?php

namespace AppBundle\Security\Authentication\Handler;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Http\Authentication\AuthenticationSuccessHandlerInterface;

class AuthenticationSuccessHandler implements AuthenticationSuccessHandlerInterface
{
    private $router;

    public function __construct(RouterInterface $router)
    {
        $this->router = $router;
    }

    public function onAuthenticationSuccess(Request $request, TokenInterface $token)
    {
        return new RedirectResponse($this->router->generate('homepage'));
    }
}

services.yml

   services:
       AppBundle\Security\Authentication\Handler:
           arguments: ['@router']

security.yml

security:
    # ...
    firewalls:
          form_login:
              # ...
              use_referer: false
              success_handler: AppBundle\Security\Authentication\Handler\AuthenticationSuccessHandler


问:
can i change the date 1510808400000 to a valid date format in android
I am working on some error like i am getting response of a date which is like 1510808400000 and i have to display this as a valid date format like dd-mm-yy Suggest me is there any way to convert that long value to valid date format. or guide me possible changes.</p>

答:
Use below code</p>

```<code>long millis = Long.parse("1510808400000 ");
Date date = new Date(millis);
String displayDate = new SimpleDateFormat("dd-mm-yy").format(date);
</code>```

Body:
Use below code

long millis = Long.parse("1510808400000 ");
Date date = new Date(millis);
String displayDate = new SimpleDateFormat("dd-mm-yy").format(date);


问:
How to get spread operator updating state with React
I've defined my initial state in a Component as follows:

```<code>constructor(props) {
    super(props);
    //this.state = {count: props.initialCount};
    this.state = {
        timeArray: [],
        metawords: '',
        description: '',
        currentTime: '',
        inputFieldsDisabled: true
    }
}
</code>```

I have an event that gets called and I want to just update the metawords property.  I was thinking that the following code should work but it does not.

```<code>updateInputValue1(evt) {
    const newMetawords = "abcd";
    this.setState(
        [...this.state,{
            metawords: evt.target.value
        }]
    );
</code>```

Thoughts?

答:
Why not simply:

```<code>this.setState({ metawords: evt.target.value })
</code>```

You don't need to pass all other state values, just pass the property and the new value, that you want to update. You don't need to bother about the other state values during setState, React will do the merging (merging of all other state values and the state that you wants to update).

For more details check DOC.

Body:
I've defined my initial state in a Component as follows:

constructor(props) {
    super(props);
    //this.state = {count: props.initialCount};
    this.state = {
        timeArray: [],
        metawords: '',
        description: '',
        currentTime: '',
        inputFieldsDisabled: true
    }
}

I have an event that gets called and I want to just update the metawords property.  I was thinking that the following code should work but it does not.

updateInputValue1(evt) {
    const newMetawords = "abcd";
    this.setState(
        [...this.state,{
            metawords: evt.target.value
        }]
    );

Thoughts?

Body:
Why not simply:

this.setState({ metawords: evt.target.value })

You don't need to pass all other state values, just pass the property and the new value, that you want to update. You don't need to bother about the other state values during setState, React will do the merging (merging of all other state values and the state that you wants to update).

For more details check DOC.


答:
You can use spread  operator like this to setState.

```<code>this.setState(
        {...this.state,
          metawords: evt.target.value
        })
</code>```

However since you only want to change a single property, this will also work in your case:

```<code>this.setState({metawords: evt.target.value})
</code>```

Title: How to get spread operator updating state with React

Body:
You can use spread  operator like this to setState.

this.setState(
        {...this.state,
          metawords: evt.target.value
        })

However since you only want to change a single property, this will also work in your case:

this.setState({metawords: evt.target.value})


问:
How can I update all except the max value in a group by
I have the table below:

```<code>+----+----------+-----+-------
| ID | animal| pets | age
+----+----------+-----+------
|  1 | pig   | y    | 19
|  2 | pig   | y    | 21
|  3 | horse | y    | 23
|  4 | dog   | y    | 45
|  5 | dog   | y    | 56
|  6 | cat   | n    | 34
|  7 | cat   | y    | 56
</code>```

I need help building a query that sets Pets to 'n' for the rows of that kind of animal that have an age thats less than the maximum value of age for that animal that is set to 'y'. So there could only be one row for each animal set to 'y' and it must be that with the max age so the resulting table should look like this:

```<code>+----+----------+-----+-------
| ID | animal| pets | age
+----+----------+-----+------
|  1 | pig   | n    | 19
|  2 | pig   | y    | 21
|  3 | horse | y    | 23
|  4 | dog   | n    | 45
|  5 | dog   | y    | 56
|  6 | cat   | n    | 34
|  7 | cat   | y    | 56
</code>```

答:
You can use this code,</p>

```<code> update your_table_name a
 inner join your_table_name b on a.animal = b.animal
 set a.pet='n'
 where a.age < (select max(b.age));
</code>```

Body:
I have the table below:

+----+----------+-----+-------
| ID | animal| pets | age
+----+----------+-----+------
|  1 | pig   | y    | 19
|  2 | pig   | y    | 21
|  3 | horse | y    | 23
|  4 | dog   | y    | 45
|  5 | dog   | y    | 56
|  6 | cat   | n    | 34
|  7 | cat   | y    | 56

I need help building a query that sets Pets to 'n' for the rows of that kind of animal that have an age thats less than the maximum value of age for that animal that is set to 'y'. So there could only be one row for each animal set to 'y' and it must be that with the max age so the resulting table should look like this:

+----+----------+-----+-------
| ID | animal| pets | age
+----+----------+-----+------
|  1 | pig   | n    | 19
|  2 | pig   | y    | 21
|  3 | horse | y    | 23
|  4 | dog   | n    | 45
|  5 | dog   | y    | 56
|  6 | cat   | n    | 34
|  7 | cat   | y    | 56

Body:
You can use this code,

 update your_table_name a
 inner join your_table_name b on a.animal = b.animal
 set a.pet='n'
 where a.age < (select max(b.age));


问:
Changing variables
I am sure this is just something simple but I am just getting into C# and this isn't clicking in my mind.

I basically need to assign to a button of mine the function of changing the variable offsets that my tool uses to write data to my 3DS.

I have both variables but I don't really know how to tell it to switch from using 1 set to the other when I press it and then waterfall back if I press it again.

This is my code here showing my variables that are called upon throughout my tool

```<code>public partial class MainForm : Form
{

    public delegate void LogDelegate(string l);
    public LogDelegate delLastLog;
    public string lastlog = "";
    public int pid = 0;
    public PKHeX dumpedPKHeX = new PKHeX();
    //Possibly Ultra box layout Offset? 0x33015AB0
    //Possibly Ultra Wondercard Offset? 0x33075BF4
    public uint boxOff = 0x330D9838;
    public uint wcOff = 0x331397E4;
    public uint partyOff = 0x34195E10;
</code>```

Then this is my button I have started.

```<code>private void btn_ConvertMode_Click(object sender, EventArgs e)
{
    MessageBox.Show("Ultra Support Mode Activated!", "WonderInjection", MessageBoxButtons.OK);
    return;
}
</code>```

Any idea guys? Basically the boxoff and wcoff offsets I need to be able to be switched to the ones I have commented out one the command of the button.

答:
```<code>public bool isDefaultOffset(uint boxOff,uint wcOff)
{
    if((boxOff==0x330D9838))&&(wcOff==0x331397E4))
     return true;
    else
     return false;
}

    public void ChangeOffSet(uint boxOff,uint wcOff)
{
if(isDefaultOffset(boxOff,wcOff))
   {
      boxOff= 0x33015AB0;
      boxOff= 0x33075BF4;
   }
   else
  {
    // set default values here
  }

}
</code>```

<p>and then call changeOffset() method on your event. </p>

Title: Changing variables

Body:
I am sure this is just something simple but I am just getting into C# and this isn't clicking in my mind.

I basically need to assign to a button of mine the function of changing the variable offsets that my tool uses to write data to my 3DS.

I have both variables but I don't really know how to tell it to switch from using 1 set to the other when I press it and then waterfall back if I press it again.

This is my code here showing my variables that are called upon throughout my tool

public partial class MainForm : Form
{

    public delegate void LogDelegate(string l);
    public LogDelegate delLastLog;
    public string lastlog = "";
    public int pid = 0;
    public PKHeX dumpedPKHeX = new PKHeX();
    //Possibly Ultra box layout Offset? 0x33015AB0
    //Possibly Ultra Wondercard Offset? 0x33075BF4
    public uint boxOff = 0x330D9838;
    public uint wcOff = 0x331397E4;
    public uint partyOff = 0x34195E10;

Then this is my button I have started.

private void btn_ConvertMode_Click(object sender, EventArgs e)
{
    MessageBox.Show("Ultra Support Mode Activated!", "WonderInjection", MessageBoxButtons.OK);
    return;
}

Any idea guys? Basically the boxoff and wcoff offsets I need to be able to be switched to the ones I have commented out one the command of the button.

Body:
public bool isDefaultOffset(uint boxOff,uint wcOff)
{
    if((boxOff==0x330D9838))&&(wcOff==0x331397E4))
     return true;
    else
     return false;
}

    public void ChangeOffSet(uint boxOff,uint wcOff)
{
if(isDefaultOffset(boxOff,wcOff))
   {
      boxOff= 0x33015AB0;
      boxOff= 0x33075BF4;
   }
   else
  {
    // set default values here
  }

}

and then call changeOffset() method on your event.


问:
Invalid Toolchain. Itunes store operation failed
As soon as I updated xcode to 9.2 , I cannot validate my archived builds. I get this error message every time:

Invalid Toolchain. New apps and app updates must be built with the public (GM) versions of Xcode 6 or later, macOS, and iOS SDK or later. Don't submit apps built with beta software including beta macOS builds.

Is this something wrong with Apple's new relase of xcode? Otherwise, I didn't change anything that would make this project using "Beta software".

答: I have faced this too. Apple has just released the Xcode 9.2 update and might not have updated iTunes connect to accept builds from it yet. It might be resolved soon in a couple of hours or days.</p>


答:
modify date format as required.</p>

```<code>  private String getDate(long timeStamp){

        try{
            SimpleDateFormat sdf = new SimpleDateFormat("MM dd, yyyy");
            Date netDate = (new Date(timeStamp));
            return sdf.format(netDate);
        }
        catch(Exception ex){
           ex.printStackTrace();
            return null;
        }
    }
</code>```

Title: can i change the date 1510808400000 to a valid date format in android

Body: I am working on some error like i am getting response of a date which is like 1510808400000 and i have to display this as a valid date format like dd-mm-yy Suggest me is there any way to convert that long value to valid date format. or guide me possible changes.

Body:
modify date format as required.

  private String getDate(long timeStamp){

        try{
            SimpleDateFormat sdf = new SimpleDateFormat("MM dd, yyyy");
            Date netDate = (new Date(timeStamp));
            return sdf.format(netDate);
        }
        catch(Exception ex){
           ex.printStackTrace();
            return null;
        }
    }


问:
Ansible - hide with_dict variables from playbook output
I have a playbook where I use a dictionary variable file and an includes_tasks play. My issue is the playbook displays the variables when it is run. I tried no_log: True and ignore_errors: True but makes no difference. I am using ansible version 2.4.1.0

Here is the playbook tasks:

```<code>tasks:
  - name: "Install License and Remove Default Identifier"
    include_tasks: includes/junos_license.yml
    with_dict: "{{ vsrx  }}"
</code>```

Here is the output from running the playbook:

```<code>TASK [Install License and Remove Default Identifier]

***************************************************************************
msg: All items completed

results: [
  {
    "item": {
      "key": "vsrx-02",
      "value": {
        "Hostname": "vsrx-02",
        "IP_Address": "192.168.1.211"
      }
    },
    "_ansible_item_result": true,
    "include": "includes/junos_license.yml",
    "include_variables": {}
  },
  {
    "item": {
      "key": "vsrx-01",
      "value": {
        "Hostname": "vsrx-01",
        "IP_Address": "192.168.1.209"
      }
    },
    "_ansible_item_result": true,
    "include": "includes/junos_license.yml",
    "include_variables": {}
  }
]
included: /home/ansible/junos_base_config/includes/junos_license.yml for
localhost
included: /home/ansible/junos_base_config/includes/junos_license.yml for
localhost
</code>```

答:
Use loop_control:</p>

```<code>tasks:
  - name: "Install License and Remove Default Identifier"
    include_tasks: includes/junos_license.yml
    with_dict: "{{ vsrx }}"
    loop_control:
      label: "{{ item.key }}"
</code>```

Body:
I have a playbook where I use a dictionary variable file and an includes_tasks play. My issue is the playbook displays the variables when it is run. I tried no_log: True and ignore_errors: True but makes no difference. I am using ansible version 2.4.1.0

Here is the playbook tasks:

tasks:
  - name: "Install License and Remove Default Identifier"
    include_tasks: includes/junos_license.yml
    with_dict: "{{ vsrx  }}"

Here is the output from running the playbook:

TASK [Install License and Remove Default Identifier]

***************************************************************************
msg: All items completed

results: [
  {
    "item": {
      "key": "vsrx-02",
      "value": {
        "Hostname": "vsrx-02",
        "IP_Address": "192.168.1.211"
      }
    },
    "_ansible_item_result": true,
    "include": "includes/junos_license.yml",
    "include_variables": {}
  },
  {
    "item": {
      "key": "vsrx-01",
      "value": {
        "Hostname": "vsrx-01",
        "IP_Address": "192.168.1.209"
      }
    },
    "_ansible_item_result": true,
    "include": "includes/junos_license.yml",
    "include_variables": {}
  }
]
included: /home/ansible/junos_base_config/includes/junos_license.yml for
localhost
included: /home/ansible/junos_base_config/includes/junos_license.yml for
localhost

Body:
Use loop_control:

tasks:
  - name: "Install License and Remove Default Identifier"
    include_tasks: includes/junos_license.yml
    with_dict: "{{ vsrx }}"
    loop_control:
      label: "{{ item.key }}"


问:
start eclipse error, start to "Loading org.eclipse.core.filebuffers"
today, i in the console execute end eclipse process. now run eclipse is not start. start in the "Loading org.eclipse.core.filebuffers" stop start alos tip "java heap space"

workspace logs file content is:

```<code>!ENTRY org.eclipse.osgi 4 0 2017-12-05 13:55:59.305
!MESSAGE Application error
!STACK 1
java.lang.OutOfMemoryError: Java heap space
    at org.eclipse.swt.custom.StyledTextRenderer.setStyleRanges(StyledTextRenderer.java:1228)
    at org.eclipse.swt.custom.StyledText.setStyleRanges(StyledText.java:9913)
    at org.eclipse.swt.custom.StyledText.setStyleRanges(StyledText.java:9976)
    at org.eclipse.jface.text.TextViewer.applyTextPresentation(TextViewer.java:4884)
    at org.eclipse.jface.text.TextViewer.changeTextPresentation(TextViewer.java:4936)
    at org.eclipse.jface.text.presentation.PresentationReconciler.applyTextRegionCollection(PresentationReconciler.java:582)
    at org.eclipse.jface.text.presentation.PresentationReconciler.processDamage(PresentationReconciler.java:571)
    at org.eclipse.jface.text.presentation.PresentationReconciler.access$3(PresentationReconciler.java:567)
    at org.eclipse.jface.text.presentation.PresentationReconciler$InternalListener.textChanged(PresentationReconciler.java:227)
    at org.eclipse.jface.text.TextViewer.updateTextListeners(TextViewer.java:2826)
    at org.eclipse.jface.text.TextViewer.invalidateTextPresentation(TextViewer.java:3478)
    at org.eclipse.ui.texteditor.AbstractTextEditor.handlePreferenceStoreChanged(AbstractTextEditor.java:4628)
    at org.eclipse.ui.texteditor.AbstractDecoratedTextEditor.handlePreferenceStoreChanged(AbstractDecoratedTextEditor.java:906)
    at org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor.handlePreferenceStoreChanged(JavaEditor.java:2519)
    at org.eclipse.wst.jsdt.internal.ui.javaeditor.CompilationUnitEditor.handlePreferenceStoreChanged(CompilationUnitEditor.java:1530)
    at org.eclipse.ui.texteditor.AbstractTextEditor$PropertyChangeListener.propertyChange(AbstractTextEditor.java:715)
    at org.eclipse.ui.texteditor.ChainedPreferenceStore.firePropertyChangeEvent(ChainedPreferenceStore.java:164)
    at org.eclipse.ui.texteditor.ChainedPreferenceStore.handlePropertyChangeEvent(ChainedPreferenceStore.java:431)
    at org.eclipse.ui.texteditor.ChainedPreferenceStore.access$0(ChainedPreferenceStore.java:408)
    at org.eclipse.ui.texteditor.ChainedPreferenceStore$PropertyChangeListener.propertyChange(ChainedPreferenceStore.java:69)
    at org.eclipse.ui.preferences.ScopedPreferenceStore$3.run(ScopedPreferenceStore.java:351)

!ENTRY org.eclipse.e4.ui.workbench 4 0 2017-12-05 13:59:31.266
!MESSAGE
!STACK 0
java.lang.NullPointerException
    at org.eclipse.jface.resource.JFaceResources.getResources(JFaceResources.java:209)
    at org.eclipse.jface.resource.JFaceResources.getResources(JFaceResources.java:230)
    at org.eclipse.ui.part.WorkbenchPart.dispose(WorkbenchPart.java:109)
    at org.eclipse.ui.internal.views.markers.ExtendedMarkersView.dispose(ExtendedMarkersView.java:634)
    at org.eclipse.ui.internal.e4.compatibility.CompatibilityPart.invalidate(CompatibilityPart.java:238)
    at org.eclipse.ui.internal.e4.compatibility.CompatibilityPart.destroy(CompatibilityPart.java:394)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.eclipse.e4.core.internal.di.MethodRequestor.execute(MethodRequestor.java:56)
    at org.eclipse.e4.core.internal.di.InjectorImpl.processAnnotated(InjectorImpl.java:898)at org.eclipse.e4.core.internal.contexts.osgi.EclipseContextOSGi.dispose(EclipseContextOSGi.java:106)
    at org.eclipse.e4.core.internal.contexts.osgi.EclipseContextOSGi.bundleChanged(EclipseContextOSGi.java:139)
    at org.eclipse.osgi.internal.framework.BundleContextImpl.dispatchEvent(BundleContextImpl.java:902)
    at org.eclipse.osgi.framework.eventmgr.EventManager.dispatchEvent(EventManager.java:230)
    at org.eclipse.osgi.framework.eventmgr.ListenerQueue.dispatchEventSynchronous(ListenerQueue.java:148)
    at org.eclipse.osgi.internal.framework.EquinoxEventPublisher.publishBundleEventPrivileged(EquinoxEventPublisher.java:165)
    at org.eclipse.osgi.internal.framework.EquinoxEventPublisher.publishBundleEvent(EquinoxEventPublisher.java:75)
    at org.eclipse.osgi.internal.framework.EquinoxEventPublisher.publishBundleEvent(EquinoxEventPublisher.java:67)
    at org.eclipse.osgi.internal.framework.EquinoxContainerAdaptor.publishModuleEvent(EquinoxContainerAdaptor.java:102)
    at org.eclipse.osgi.container.Module.publishEvent(Module.java:466)
    at org.eclipse.osgi.container.Module.doStop(Module.java:624)
    at org.eclipse.osgi.container.Module.stop(Module.java:488)
    at org.eclipse.osgi.container.SystemModule.stop(SystemModule.java:186)
    at org.eclipse.osgi.internal.framework.EquinoxBundle$SystemBundle$EquinoxSystemModule$1.run(EquinoxBundle.java:159)
    at java.lang.Thread.run(Unknown Source)

!ENTRY org.eclipse.e4.ui.workbench 4 0 2017-12-05 13:59:31.269
!MESSAGE FrameworkEvent ERROR
</code>```

if you konw ,place tell me .

                                                                 thanks

答:
Please try to increase heap size of the eclipse

Go to Eclipse Folder

Edit eclipse.ini

Set\increase the heap memory size like below

```<code>-startup
plugins/org.eclipse.equinox.launcher_1.3.0.v20120522-1813.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.gtk.linux.x86_64_1.1.200.v20120913-144807
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
256m
--launcher.defaultAction
openFile
-vmargs
-Xms512m
-Xmx1024m
-XX:+UseParallelGC
-XX:PermSize=256M
-XX:MaxPermSize=1024M
</code>```

Body:
today, i in the console execute end eclipse process. now run eclipse is not start. start in the "Loading org.eclipse.core.filebuffers" stop start alos tip "java heap space"

workspace logs file content is:

!ENTRY org.eclipse.osgi 4 0 2017-12-05 13:55:59.305
!MESSAGE Application error
!STACK 1
java.lang.OutOfMemoryError: Java heap space
    at org.eclipse.swt.custom.StyledTextRenderer.setStyleRanges(StyledTextRenderer.java:1228)
    at org.eclipse.swt.custom.StyledText.setStyleRanges(StyledText.java:9913)
    at org.eclipse.swt.custom.StyledText.setStyleRanges(StyledText.java:9976)
    at org.eclipse.jface.text.TextViewer.applyTextPresentation(TextViewer.java:4884)
    at org.eclipse.jface.text.TextViewer.changeTextPresentation(TextViewer.java:4936)
    at org.eclipse.jface.text.presentation.PresentationReconciler.applyTextRegionCollection(PresentationReconciler.java:582)
    at org.eclipse.jface.text.presentation.PresentationReconciler.processDamage(PresentationReconciler.java:571)
    at org.eclipse.jface.text.presentation.PresentationReconciler.access$3(PresentationReconciler.java:567)
    at org.eclipse.jface.text.presentation.PresentationReconciler$InternalListener.textChanged(PresentationReconciler.java:227)
    at org.eclipse.jface.text.TextViewer.updateTextListeners(TextViewer.java:2826)
    at org.eclipse.jface.text.TextViewer.invalidateTextPresentation(TextViewer.java:3478)
    at org.eclipse.ui.texteditor.AbstractTextEditor.handlePreferenceStoreChanged(AbstractTextEditor.java:4628)
    at org.eclipse.ui.texteditor.AbstractDecoratedTextEditor.handlePreferenceStoreChanged(AbstractDecoratedTextEditor.java:906)
    at org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor.handlePreferenceStoreChanged(JavaEditor.java:2519)
    at org.eclipse.wst.jsdt.internal.ui.javaeditor.CompilationUnitEditor.handlePreferenceStoreChanged(CompilationUnitEditor.java:1530)
    at org.eclipse.ui.texteditor.AbstractTextEditor$PropertyChangeListener.propertyChange(AbstractTextEditor.java:715)
    at org.eclipse.ui.texteditor.ChainedPreferenceStore.firePropertyChangeEvent(ChainedPreferenceStore.java:164)
    at org.eclipse.ui.texteditor.ChainedPreferenceStore.handlePropertyChangeEvent(ChainedPreferenceStore.java:431)
    at org.eclipse.ui.texteditor.ChainedPreferenceStore.access$0(ChainedPreferenceStore.java:408)
    at org.eclipse.ui.texteditor.ChainedPreferenceStore$PropertyChangeListener.propertyChange(ChainedPreferenceStore.java:69)
    at org.eclipse.ui.preferences.ScopedPreferenceStore$3.run(ScopedPreferenceStore.java:351)

!ENTRY org.eclipse.e4.ui.workbench 4 0 2017-12-05 13:59:31.266
!MESSAGE
!STACK 0
java.lang.NullPointerException
    at org.eclipse.jface.resource.JFaceResources.getResources(JFaceResources.java:209)
    at org.eclipse.jface.resource.JFaceResources.getResources(JFaceResources.java:230)
    at org.eclipse.ui.part.WorkbenchPart.dispose(WorkbenchPart.java:109)
    at org.eclipse.ui.internal.views.markers.ExtendedMarkersView.dispose(ExtendedMarkersView.java:634)
    at org.eclipse.ui.internal.e4.compatibility.CompatibilityPart.invalidate(CompatibilityPart.java:238)
    at org.eclipse.ui.internal.e4.compatibility.CompatibilityPart.destroy(CompatibilityPart.java:394)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.eclipse.e4.core.internal.di.MethodRequestor.execute(MethodRequestor.java:56)
    at org.eclipse.e4.core.internal.di.InjectorImpl.processAnnotated(InjectorImpl.java:898)at org.eclipse.e4.core.internal.contexts.osgi.EclipseContextOSGi.dispose(EclipseContextOSGi.java:106)
    at org.eclipse.e4.core.internal.contexts.osgi.EclipseContextOSGi.bundleChanged(EclipseContextOSGi.java:139)
    at org.eclipse.osgi.internal.framework.BundleContextImpl.dispatchEvent(BundleContextImpl.java:902)
    at org.eclipse.osgi.framework.eventmgr.EventManager.dispatchEvent(EventManager.java:230)
    at org.eclipse.osgi.framework.eventmgr.ListenerQueue.dispatchEventSynchronous(ListenerQueue.java:148)
    at org.eclipse.osgi.internal.framework.EquinoxEventPublisher.publishBundleEventPrivileged(EquinoxEventPublisher.java:165)
    at org.eclipse.osgi.internal.framework.EquinoxEventPublisher.publishBundleEvent(EquinoxEventPublisher.java:75)
    at org.eclipse.osgi.internal.framework.EquinoxEventPublisher.publishBundleEvent(EquinoxEventPublisher.java:67)
    at org.eclipse.osgi.internal.framework.EquinoxContainerAdaptor.publishModuleEvent(EquinoxContainerAdaptor.java:102)
    at org.eclipse.osgi.container.Module.publishEvent(Module.java:466)
    at org.eclipse.osgi.container.Module.doStop(Module.java:624)
    at org.eclipse.osgi.container.Module.stop(Module.java:488)
    at org.eclipse.osgi.container.SystemModule.stop(SystemModule.java:186)
    at org.eclipse.osgi.internal.framework.EquinoxBundle$SystemBundle$EquinoxSystemModule$1.run(EquinoxBundle.java:159)
    at java.lang.Thread.run(Unknown Source)

!ENTRY org.eclipse.e4.ui.workbench 4 0 2017-12-05 13:59:31.269
!MESSAGE FrameworkEvent ERROR

if you konw ,place tell me .

                                                                 thanks

Body:
Please try to increase heap size of the eclipse

Go to Eclipse Folder

Edit eclipse.ini

Set\increase the heap memory size like below

-startup
plugins/org.eclipse.equinox.launcher_1.3.0.v20120522-1813.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.gtk.linux.x86_64_1.1.200.v20120913-144807
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
256m
--launcher.defaultAction
openFile
-vmargs
-Xms512m
-Xmx1024m
-XX:+UseParallelGC
-XX:PermSize=256M
-XX:MaxPermSize=1024M


问:
why boost implement BOOST_CURRENT_FUNCTION in a function
boost implements a macro BOOST_CURRENT_FUNCTION in its current_function.hpp
, the macro is to provide the full name of the function, for exception throw, logging etc.

What is interesting is that the macro is implemented inside a function.

What's the special reason of doing so?

```<code>....

namespace boost
{

    namespace detail
    {

        inline void current_function_helper()
        {

            #if defined( BOOST_DISABLE_CURRENT_FUNCTION )

                # define BOOST_CURRENT_FUNCTION "(unknown)"

            #elif ...

            #elif defined(__FUNCSIG__)

                # define BOOST_CURRENT_FUNCTION __FUNCSIG__

            #elif ....

            #else

                # define BOOST_CURRENT_FUNCTION "(unknown)"

            #endif

        }

    } // namespace detail

} // namespace boost

....
</code>```

答:
Upon looking at the full implementation one sees that it makes use of several compiler specific "function signature" macros. Those macros are of course only valid inside a function.

The test #elif defined(__FUNCSIG__) is going to fail at file scope. And so must appear inside a function. Here the helper is introduced to supply a function scope for this check.

The documentation on MSDN confirms this:

__FUNCSIG__ Defined as a string literal that contains the signature of the enclosing function. The macro is defined only within
  a function.

Body:
boost implements a macro BOOST_CURRENT_FUNCTION in its current_function.hpp
, the macro is to provide the full name of the function, for exception throw, logging etc.

What is interesting is that the macro is implemented inside a function.

What's the special reason of doing so?

....

namespace boost
{

    namespace detail
    {

        inline void current_function_helper()
        {

            #if defined( BOOST_DISABLE_CURRENT_FUNCTION )

                # define BOOST_CURRENT_FUNCTION "(unknown)"

            #elif ...

            #elif defined(__FUNCSIG__)

                # define BOOST_CURRENT_FUNCTION __FUNCSIG__

            #elif ....

            #else

                # define BOOST_CURRENT_FUNCTION "(unknown)"

            #endif

        }

    } // namespace detail

} // namespace boost

....


问:
Perl IPC - FIFO and daemons & CPU Usage
I have a mail parser perl script which is called every time a mail arrives for a user (using .qmail). It extracts a calendar attachment out of the mail and places the "path" of the file in a FIFO queue implemented using the Directory::Queue module.

Another perl script which reads the path of the calendar attachment and performs certain file operations on the local system as well as on the remote CalDAV server, is being run as a daemon, as explained here. So basically this script looks like:

```<code>my $declarations

sub foo {
.
.
}

sub bar {
.
.
}

while ($keep_running) {
    for(keep-checking-the-queue-for-new-entries) {

        sub caldav_logic1 {
        .
        .
     }
        sub caldav_logic2 {
        .
        .
    }
  }
}
</code>```

I am using Proc::Daemon for running the script as a daemon. Now the problem is, this process has almost 100% CPU usage. What are the suggested ways to implement the daemon in a more standard, safer way ? I am using pretty much the same code as mentioned in the link mentioned for usage of Proc::Daemon.

答:
I bet it is your for loop and checking for new queue entries.

There are ways to watch a directory for file changes. These ways are OS dependent but there might be a Perl module that wraps them up for you. Use that instead of busy looping. Even with a sleep delay, the looping is inefficient when you can have your program told exactly when to wake up by an OS event.

File::ChangeNotify looks promising.

Title: Perl IPC - FIFO and daemons & CPU Usage

Body:
I have a mail parser perl script which is called every time a mail arrives for a user (using .qmail). It extracts a calendar attachment out of the mail and places the "path" of the file in a FIFO queue implemented using the Directory::Queue module.

Another perl script which reads the path of the calendar attachment and performs certain file operations on the local system as well as on the remote CalDAV server, is being run as a daemon, as explained here. So basically this script looks like:

my $declarations

sub foo {
.
.
}

sub bar {
.
.
}

while ($keep_running) {
    for(keep-checking-the-queue-for-new-entries) {

        sub caldav_logic1 {
        .
        .
     }
        sub caldav_logic2 {
        .
        .
    }
  }
}

I am using Proc::Daemon for running the script as a daemon. Now the problem is, this process has almost 100% CPU usage. What are the suggested ways to implement the daemon in a more standard, safer way ? I am using pretty much the same code as mentioned in the link mentioned for usage of Proc::Daemon.


问:
How can HTML <select/> prevent click through parent's div
I'm creating shopping cart page that there's a div have a click listener for redirecting to the product page, but you also can select qty on the div. How can I prevent the redirection when selecting from <select/>

I've tried event.stopPropagation() / e.preventDefault() on select but not working

Here's the sample code.

https://jsfiddle.net/hk7861es/2/

答:
Not exactly what you asked for, but definitely a simple solution:

Add 1 line to check for click target

```<code>if ($(event.target).is('#select')) return;
</code>```

This line checks whether what you click is #select, if yes, ignore the event.

$('#box').click(function(e) {
  if ($(e.target).is('#select')) return; // <--- ADD THIS LINE

  $('#text').append('You clicked');
})

$("#select").keypress(function () {
  $(this).val(valueToKeep);
});
$("#select").keydown(function () {
  valueToKeep = $(this).val();
});  ```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#box {
  height: 200px;
  width: 400px;
  background-color: lightgrey;
  display: flex;
  align-items: center;
  justify-content: center;
}</code>```

  Volvo: 200hp ; $3000

  QTY:
  <select id="select">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
  </select>

```

Body:
Not exactly what you asked for, but definitely a simple solution:

Add 1 line to check for click target

if ($(event.target).is('#select')) return;

This line checks whether what you click is #select, if yes, ignore the event.

$('#box').click(function(e) {
  if ($(e.target).is('#select')) return; // <--- ADD THIS LINE

  $('#text').append('You clicked');
})

$("#select").keypress(function () {
  $(this).val(valueToKeep);
});
$("#select").keydown(function () {
  valueToKeep = $(this).val();
});

#box {
  height: 200px;
  width: 400px;
  background-color: lightgrey;
  display: flex;
  align-items: center;
  justify-content: center;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="box">
  Volvo: 200hp ; $3000

  QTY:
  <select id="select">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
  </select>

</div>
<p id="text"></p>


问:
How to handle exceptions when reading files with buffered reader?
I have made code to read text (json, xml etc.) from a text file, and convert it into a strings which can then be used by other code to convert into plain old java objects or POJOS that are annotated by jackson.

I am not sure if my code handles the exceptions properly. So far, I have used the principles mentioned after my code (READ THIS DOWN VOTERS !!!), to develop the code. Note that I cannot use try with resources because I am stuck with Java 6 (even though my project JRE is 1.8).

```<code>package com.testing;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class JunkEx {

    public static void main(String[] args) {
        String filePath = ".\\src\\test\\resources\\text-files\\orders\\orders-2017.txt";
        String contents = fileToString(filePath);
        System.out.println(contents);
    }

    private static String fileToString(String filePath) {
        StringBuilder stringBuilder = null;
        BufferedReader br = null;

        try {
        br = new BufferedReader(new FileReader(filePath));
        stringBuilder = new StringBuilder();
        String currentLine;
        while ((currentLine = br.readLine()) != null) {
            stringBuilder.append(currentLine);
            stringBuilder.append("\n");
        }

        }catch (FileNotFoundException ex1) {
            ex1.printStackTrace();
        }catch (IOException ex2) {
            ex2.printStackTrace();
        }finally {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return stringBuilder.toString();
    }

}
</code>```

Principles:

1) Catch the most specific exception first, then the one above it in the exception hierarchy. I.e catch FileNotFoundException 1st and IOException later. Refer point 5 here

2) Do NOT return from inside a finally block, because finally is always executed as long as try "completes" fully or abruptly. Refer this SO answer.

3) Cleanup resources like buffered readers in the finally block. Refer point 1 here.

4) Do not make the callers of the "dangerous" method (i.e. which could throw exceptions), have to know/throw each of the exceptions inside it. I.e dangerous method should not "throws FileNotFoundException, IOException...etc". refer this link, specifically the last paragraph

Flaw in the code:
If any of the first two catch blocks are executed, then its likely that the entire file was not read. But, my method will return a string anyway. The string could be null or incomplete.

Questions -

1) I want to throw an exception when the text file is not successfully converted to a string, i.e. one of the three catch blocks is executed. Should I wrap the exception in each catch block inside a generic Exception object and throw that or do something else ?

2) How can I improve/fix the exception handling of this code?

Project structure:

答:
Simple answer: don't catch the exceptions at all. Let the caller catch them. He's the one who needs to know, and knows what to do about them. This method certainly doesn't.

4) Do not make the callers of the "dangerous" method (i.e. which could throw exceptions), have to know/throw each of the exceptions inside it. I.e dangerous method should not "throws FileNotFoundException, IOException...etc". refer this link, specifically the last paragraph.

I don't think much of this 'principle', and in any case it doesn't actually apply here. The only exceptions thrown are IOException and FileNotFoundException, which is derived from it. The caller doesn't have to deal with both if he doesn't wish to. However he may wish to do exactly that, if for example the file being missing constitutes a deployment error.

Body:
I have made code to read text (json, xml etc.) from a text file, and convert it into a strings which can then be used by other code to convert into plain old java objects or POJOS that are annotated by jackson.

I am not sure if my code handles the exceptions properly. So far, I have used the principles mentioned after my code (READ THIS DOWN VOTERS !!!), to develop the code. Note that I cannot use try with resources because I am stuck with Java 6 (even though my project JRE is 1.8).

package com.testing;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class JunkEx {

    public static void main(String[] args) {
        String filePath = ".\\src\\test\\resources\\text-files\\orders\\orders-2017.txt";
        String contents = fileToString(filePath);
        System.out.println(contents);
    }

    private static String fileToString(String filePath) {
        StringBuilder stringBuilder = null;
        BufferedReader br = null;

        try {
        br = new BufferedReader(new FileReader(filePath));
        stringBuilder = new StringBuilder();
        String currentLine;
        while ((currentLine = br.readLine()) != null) {
            stringBuilder.append(currentLine);
            stringBuilder.append("\n");
        }

        }catch (FileNotFoundException ex1) {
            ex1.printStackTrace();
        }catch (IOException ex2) {
            ex2.printStackTrace();
        }finally {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return stringBuilder.toString();
    }

}

Principles:

1) Catch the most specific exception first, then the one above it in the exception hierarchy. I.e catch FileNotFoundException 1st and IOException later. Refer point 5 here

2) Do NOT return from inside a finally block, because finally is always executed as long as try "completes" fully or abruptly. Refer this SO answer.

3) Cleanup resources like buffered readers in the finally block. Refer point 1 here.

4) Do not make the callers of the "dangerous" method (i.e. which could throw exceptions), have to know/throw each of the exceptions inside it. I.e dangerous method should not "throws FileNotFoundException, IOException...etc". refer this link, specifically the last paragraph

Flaw in the code:
If any of the first two catch blocks are executed, then its likely that the entire file was not read. But, my method will return a string anyway. The string could be null or incomplete.

Questions -

1) I want to throw an exception when the text file is not successfully converted to a string, i.e. one of the three catch blocks is executed. Should I wrap the exception in each catch block inside a generic Exception object and throw that or do something else ?

2) How can I improve/fix the exception handling of this code?

Project structure: