问:
CoordinatedShutdown timeout on Akka cluster application
We've an akka cluster application (sharding some actors). Sometimes, when we deploy and our application should be turned off we see some logs like that:

Coordinated shutdown phase [cluster-sharding-shutdown-region] timed
  out after 10000 milliseconds

This happens on the first deploy after more than 2 days since last deploy (on mondays for example). We ask the akka node to quit the cluster with the JMX helper and we have the following code too:

```<code>actorSystem.registerOnTermination {
  logger.error("Gracefully shutdown of node")
  System.exit(0)
}
</code>```

So when this error happens, eventually node leaves the cluster (or at least it closes the JMX entry point to manage akka cluster) but process don't finish and the log "Gracefully shutdown of node" doesn't appear. So when this happen we need to shutdown the java process manually (we handle this with supervisor) and redeploy.

I know the timeout can be tunned through config but what are the implications of increasing this timeout? Why sometimes coordinated shutdown throws a timeout? What happens when coordinated shutdown timeout?

Any clue would be appreciated :D

Thank you

答:
What happens after timeout? Quoting from Akka documentation:

If tasks are not completed within a configured timeout (see reference.conf) the next phase will be started anyway. It is possible to configure recover=off for a phase to abort the rest of the shutdown process if a task fails or is not completed within the timeout.

Why the shutdown may time out? Quite possible you have a deadlock somewhere. In that case, increasing the timeout wouldn't help. It may also very well be that you need more time for shutdown. Then, you must increase the timeout.

But more related to your problem, could be the following:

By default, the JVM is not forcefully stopped (it will be stopped if all non-daemon threads have been terminated). To enable a hard System.exit as a final action you can configure:

```<code>akka.coordinated-shutdown.exit-jvm = on
</code>```

So you can turn this on, which should solve the "shutdown the java process manually" step.

Nevertheless, the hard question is to find out why the shutdown times out in the first place. I guess with the above trick you can survive for some time, but you'd better spend some time to find the actual cause.

Body:
We've an akka cluster application (sharding some actors). Sometimes, when we deploy and our application should be turned off we see some logs like that:

Coordinated shutdown phase [cluster-sharding-shutdown-region] timed
  out after 10000 milliseconds

This happens on the first deploy after more than 2 days since last deploy (on mondays for example). We ask the akka node to quit the cluster with the JMX helper and we have the following code too:

actorSystem.registerOnTermination {
  logger.error("Gracefully shutdown of node")
  System.exit(0)
}

So when this error happens, eventually node leaves the cluster (or at least it closes the JMX entry point to manage akka cluster) but process don't finish and the log "Gracefully shutdown of node" doesn't appear. So when this happen we need to shutdown the java process manually (we handle this with supervisor) and redeploy.

I know the timeout can be tunned through config but what are the implications of increasing this timeout? Why sometimes coordinated shutdown throws a timeout? What happens when coordinated shutdown timeout?

Any clue would be appreciated :D

Thank you

Body:
What happens after timeout? Quoting from Akka documentation:

If tasks are not completed within a configured timeout (see reference.conf) the next phase will be started anyway. It is possible to configure recover=off for a phase to abort the rest of the shutdown process if a task fails or is not completed within the timeout.

Why the shutdown may time out? Quite possible you have a deadlock somewhere. In that case, increasing the timeout wouldn't help. It may also very well be that you need more time for shutdown. Then, you must increase the timeout.

But more related to your problem, could be the following:

By default, the JVM is not forcefully stopped (it will be stopped if all non-daemon threads have been terminated). To enable a hard System.exit as a final action you can configure:

akka.coordinated-shutdown.exit-jvm = on

So you can turn this on, which should solve the "shutdown the java process manually" step.

Nevertheless, the hard question is to find out why the shutdown times out in the first place. I guess with the above trick you can survive for some time, but you'd better spend some time to find the actual cause.


来源: stackexchange

问:
Delete words from text but only those whom contains all the different letters
For example "apple" should be deleted while "dog" shouldn't.

For example: "Dog ate my apple,so i am sad wow."

Result would be: "Dog ate my ,so i am sad."

```<code>char[] skyrikliai = { ' ', '.', ',', '!', '?', ':', ';', '(', ')', '\t' };

 string[] parts = line.Split(skyrikliai, StringSplitOptions.RemoveEmptyEntries);
   foreach (string word in parts)
</code>```

答:
I assume you want to remove any given word that ends with one of the named special characters.

Therefore you could use Regular Expressions: (using System.Text.RegularExpressions;)

```<code>string str = "Dog ate my apple, so I am sad wow.";
var reg = new Regex(@"\w+[.|,|!|?|:|;|(|)|\t]");
var matches = reg.Matches(str);

// access the current match with 'i'
// keep track of how many characters were removed with 'j'
for (int i = 0, j = 0; i < matches.Count; i++)
{
    str = str.Remove(matches[i].Index - j - 1, matches[i].Length);
    j += matches[i].Length;
}
</code>```

Output would be: Dog ate my, so I am sad.

ContentLicense: CC BY-SA 3.0

Body:
For example "apple" should be deleted while "dog" shouldn't.

For example: "Dog ate my apple,so i am sad wow."

Result would be: "Dog ate my ,so i am sad."

char[] skyrikliai = { ' ', '.', ',', '!', '?', ':', ';', '(', ')', '\t' };

 string[] parts = line.Split(skyrikliai, StringSplitOptions.RemoveEmptyEntries);
   foreach (string word in parts)

Body:
I assume you want to remove any given word that ends with one of the named special characters.

Therefore you could use Regular Expressions: (using System.Text.RegularExpressions;)

string str = "Dog ate my apple, so I am sad wow.";
var reg = new Regex(@"\w+[.|,|!|?|:|;|(|)|\t]");
var matches = reg.Matches(str);

// access the current match with 'i'
// keep track of how many characters were removed with 'j'
for (int i = 0, j = 0; i < matches.Count; i++)
{
    str = str.Remove(matches[i].Index - j - 1, matches[i].Length);
    j += matches[i].Length;
}

Output would be: Dog ate my, so I am sad.


问:
Can I load hierarchical data with Entity Framework 4 using ".Include" and filter a Navigation Property based on some criteria
Hello I am using entity framework 4 and I am trying to query Customers and their Orders
as navigation property, but I only want to load the orders of a specific date.

When using this:

```<code>List<Customer> CustomerResults = ctx.Customers
.Include("Orders")
.Where(
       c =>
       c.Orders.Any(od =>(od.DateTimeIn >= this.StartDateComboBox.DateTime &&
       od.DateTimeIn <= this.EndDateComboBox.DateTime))
      );
</code>```

I get all Orders, if any of the Orders meet the criteria.

Is It possible to filter the navigation property to return only rows that meet specific criteria?

答:
No, there isn't.

In short, eager-loading with Include automatically loads all related records (think a LEFT OUTER JOIN without a filter).

Anytime you want to filter associated records, don't use Include - use an anonymous type projection and EF will just "work out" what needs to be retrieved:

```<code>var CustomerResults = ctx.Customers
                         .Select(x => new
                         {
                            Customer = x,
                            Orders = x.Orders.Where(y => y.DateTimeIn > value)
                         }).ToList();
</code>```

If you want to return a Customer entity, then just do another projection at the end, just make sure you materialize the query first (.ToList()).

EDIT - To put back into a customer object, example:

```<code>var Customers = new List<Customer>();
foreach (var anonType in CustomerResults)
{
   Customer c = anonType.Customer;
   c.Orders = anonType.Orders;
   Customers.Add(c);
}
</code>```

I'm sure you can do that with a LINQ expression, but i can't remember the syntax.

ContentLicense: CC BY-SA 2.5

Body:
Hello I am using entity framework 4 and I am trying to query Customers and their Orders
as navigation property, but I only want to load the orders of a specific date.

When using this:

List<Customer> CustomerResults = ctx.Customers
.Include("Orders")
.Where(
       c =>
       c.Orders.Any(od =>(od.DateTimeIn >= this.StartDateComboBox.DateTime &&
       od.DateTimeIn <= this.EndDateComboBox.DateTime))
      );

I get all Orders, if any of the Orders meet the criteria.

Is It possible to filter the navigation property to return only rows that meet specific criteria?

Body:
No, there isn't.

In short, eager-loading with Include automatically loads all related records (think a LEFT OUTER JOIN without a filter).

Anytime you want to filter associated records, don't use Include - use an anonymous type projection and EF will just "work out" what needs to be retrieved:

var CustomerResults = ctx.Customers
                         .Select(x => new
                         {
                            Customer = x,
                            Orders = x.Orders.Where(y => y.DateTimeIn > value)
                         }).ToList();

If you want to return a Customer entity, then just do another projection at the end, just make sure you materialize the query first (.ToList()).

EDIT - To put back into a customer object, example:

var Customers = new List<Customer>();
foreach (var anonType in CustomerResults)
{
   Customer c = anonType.Customer;
   c.Orders = anonType.Orders;
   Customers.Add(c);
}

I'm sure you can do that with a LINQ expression, but i can't remember the syntax.


问:
Sort by date in React data grid
Is there a sort by date in the React data grid? If so, how can this be called? In the examples, all sorting works only on the line:

Example 1

Example 2

In example 2, there are columns with dates, but they are sorted as strings.

答:
i have a solution that is really good but not great.  really good in that it sorts perfectly but it isn't good if you also want to filter on the column as well.

Basically you are displaying the formated date with a custom formatter and the value you are passing to sort on is the the number of seconds from 1/1/1970 for each date so it will sort right.

And yes, i use functions instead of components for the formatter and headerRenderer values all the time and it works fine.

i work an an intranet so i can't just copy/paste my code so this is just hand typed but hopefully you get the idea.

```<code>class GridUtil {

  static basicTextCell = (props)=>{
    return (<span>{props.value? props.value : ""}</span>)
   }
}

class AGridWrapper extends React.Component {

   ///////////////
   constructor(props){
     super(props);
     this.state={...}

     this.columnHeaderData = [
       {
         key: "dateCompleted",
         name: "Date Completed",
         formatter: (data)=>GridUtil.basicTextCell({value: data.dependentValues.dateCompletedFormatted}),
         getRowMetaData: (data)=>(data),
         sortable: true
       }
     ];

    }//end constructor

    ///////////////////////////////////
    //Note that DateUtil.getDisplayableDate() is our own class to format to MM/DD/YYYY
    formatGridData = !props.inData? "Loading..." : props.inData.map(function(obj,index){
      return {
       dateCompleted: rowData.compDate? new Date(rowData.compDate).getTime() : "";
       dateCompletedFormatted: rowData.compDate? DateUtil.getDisplayableDate(rowData.compDate) : "";
     }

   });

   //////////
   rowGetter = rowNumber=>formatGridData[rowNumber];

   /////////
   render(){

    return (
      <ReactDataGrid
       columns={this.columnHeaderData}
       rowGetter={this.rowGetter}
       rowsCount={this.formatGridData.length}
       ...
      />

}
</code>```

Title: Sort by date in React data grid

Body:
i have a solution that is really good but not great.  really good in that it sorts perfectly but it isn't good if you also want to filter on the column as well.

Basically you are displaying the formated date with a custom formatter and the value you are passing to sort on is the the number of seconds from 1/1/1970 for each date so it will sort right.

And yes, i use functions instead of components for the formatter and headerRenderer values all the time and it works fine.

i work an an intranet so i can't just copy/paste my code so this is just hand typed but hopefully you get the idea.

class GridUtil {

  static basicTextCell = (props)=>{
    return (<span>{props.value? props.value : ""}</span>)
   }
}

class AGridWrapper extends React.Component {

   ///////////////
   constructor(props){
     super(props);
     this.state={...}

     this.columnHeaderData = [
       {
         key: "dateCompleted",
         name: "Date Completed",
         formatter: (data)=>GridUtil.basicTextCell({value: data.dependentValues.dateCompletedFormatted}),
         getRowMetaData: (data)=>(data),
         sortable: true
       }
     ];

    }//end constructor

    ///////////////////////////////////
    //Note that DateUtil.getDisplayableDate() is our own class to format to MM/DD/YYYY
    formatGridData = !props.inData? "Loading..." : props.inData.map(function(obj,index){
      return {
       dateCompleted: rowData.compDate? new Date(rowData.compDate).getTime() : "";
       dateCompletedFormatted: rowData.compDate? DateUtil.getDisplayableDate(rowData.compDate) : "";
     }

   });

   //////////
   rowGetter = rowNumber=>formatGridData[rowNumber];

   /////////
   render(){

    return (
      <ReactDataGrid
       columns={this.columnHeaderData}
       rowGetter={this.rowGetter}
       rowsCount={this.formatGridData.length}
       ...
      />

}


问:
how can I print UID, GID for specific user?
I want to print the GID and UID for specific user to be printed  for examples the user is student , I want GID and UID to be printed only for them using terminal linux </p>

答: cat /etc/passwd | grep username | cut -d: -f3 -f4</p>


问:
ngfor in ngfor angularfire2 angular5
Before I begin, I need to stress that I am new to both angular and angularfire (constantly learning) -

My firebase database looks like this:

I can access the order details and bind them in the html, but I am not entirely sure how to convert the Items into an iterable array that I can then use a second ngfor.

My html file looks something like:

```<code>       <ng-container *ngFor="let order of orders$ | async ">
        <ng-container *ngFor="let item of order.Items">
         <ng-container *ngIf="order['Order Status'] == 0 ">

         ... Display stuff using {{ item.Item }} {{ item.Quantity }}
</code>```

My constructor in .ts file looks something like:

```<code>  constructor(afDb: AngularFireDatabase) {

   this.orders$ = afDb.list<any>('data/shop', ref => ref.orderByChild('ETA')).snapshotChanges().map(
    changes => {
      return changes.map(
        c => ({ key: c.payload.key, ...c.payload.val() })
      );
    }
  );
 }
</code>```

I have looked at others' questions and answers such as here:
AngularFire2 nested *ngFor Array within Array... but Firebase doesn't have arrays...?

but I haven't got a clue what the solution would look like for me as I already am using .map() to return the key of the orders. I user order.key as an input to a method that updates the order status, so I would need to this work as is.

I know I have to do something to the portion of my .ts code that I have pasted here but not sure where to begin.

As much as I would like a copy paste solution I would very much appreciate an explanation as to why a proposed solution would work, more so that I can learn the why rather than the what.

I am using AngularFire 2.3.0 and Angular 5.0.0

答:
I have a solution but may not be the best or most efficient.

I added the following to my .ts file

```<code>  generateArray(obj){
    return Object.keys(obj).map((key)=>{ return obj[key]});
  }
</code>```

and changed the item of order.Items in my .html to:

```<code>  *ngFor="let item of generateArray(order.Items)"
</code>```

Title: ngfor in ngfor angularfire2 angular5

Body:
Before I begin, I need to stress that I am new to both angular and angularfire (constantly learning) -

My firebase database looks like this:

I can access the order details and bind them in the html, but I am not entirely sure how to convert the Items into an iterable array that I can then use a second ngfor.

My html file looks something like:

       <ng-container *ngFor="let order of orders$ | async ">
        <ng-container *ngFor="let item of order.Items">
         <ng-container *ngIf="order['Order Status'] == 0 ">

         ... Display stuff using {{ item.Item }} {{ item.Quantity }}

My constructor in .ts file looks something like:

  constructor(afDb: AngularFireDatabase) {

   this.orders$ = afDb.list<any>('data/shop', ref => ref.orderByChild('ETA')).snapshotChanges().map(
    changes => {
      return changes.map(
        c => ({ key: c.payload.key, ...c.payload.val() })
      );
    }
  );
 }

I have looked at others' questions and answers such as here:
AngularFire2 nested *ngFor Array within Array... but Firebase doesn't have arrays...?

but I haven't got a clue what the solution would look like for me as I already am using .map() to return the key of the orders. I user order.key as an input to a method that updates the order status, so I would need to this work as is.

I know I have to do something to the portion of my .ts code that I have pasted here but not sure where to begin.

As much as I would like a copy paste solution I would very much appreciate an explanation as to why a proposed solution would work, more so that I can learn the why rather than the what.

I am using AngularFire 2.3.0 and Angular 5.0.0

Body:
I have a solution but may not be the best or most efficient.

I added the following to my .ts file

  generateArray(obj){
    return Object.keys(obj).map((key)=>{ return obj[key]});
  }

and changed the item of order.Items in my .html to:

  *ngFor="let item of generateArray(order.Items)"


问:
Node.js spawn child process and get terminal output live
I have a script that outputs 'hi', sleeps for a second, outputs 'hi', sleeps for 1 second, and so on and so forth. Now I thought I would be able to tackle this problem with this model.

```<code>var spawn = require('child_process').spawn,
temp    = spawn('PATH TO SCRIPT WITH THE ABOVE BEHAVIOUR');

temp.stdout.pipe(process.stdout);
</code>```

Now the problem is that the task needs to be finished in order for the output to be displayed. As I am understanding it, this is due to the fact that the newly spawned process takes execution control. Obviously node.js does not support threads so any solutions? My idea was to possibly run two instances, first one for the specific purpose of creating the task and have it pipe the output to process of the second instance, considering this can be achieved.

答:
Here is the cleanest approach I've found:</p>

```<code>require("child_process").spawn('bash', ['./script.sh'], {
  cwd: process.cwd(),
  detached: true,
  stdio: "inherit"
});
</code>```

Body:
I have a script that outputs 'hi', sleeps for a second, outputs 'hi', sleeps for 1 second, and so on and so forth. Now I thought I would be able to tackle this problem with this model.

var spawn = require('child_process').spawn,
temp    = spawn('PATH TO SCRIPT WITH THE ABOVE BEHAVIOUR');

temp.stdout.pipe(process.stdout);

Now the problem is that the task needs to be finished in order for the output to be displayed. As I am understanding it, this is due to the fact that the newly spawned process takes execution control. Obviously node.js does not support threads so any solutions? My idea was to possibly run two instances, first one for the specific purpose of creating the task and have it pipe the output to process of the second instance, considering this can be achieved.

Body:
Here is the cleanest approach I've found:

require("child_process").spawn('bash', ['./script.sh'], {
  cwd: process.cwd(),
  detached: true,
  stdio: "inherit"
});

ContentLicense: CC BY-SA 4.0


问:
change some tinymce behaviour (javascript)
Hi everybody
I am using the tinymce format dropdown to apply custom styles to html elements. This is for users without html knowledge
One annoying thing for me is that when a user klicks at different styles they all get added and something like this may happen

```<code><div class="floatleft floatright positionup positiondown">
</code>```

In order to prevent this I searched for the responsible code which is in editor_template.js (compressed) but visible in editor_template_src.js

Is there maybe a way to rewrite this piece of javascript so that each applied style replaces the former?

```<code>_createStyleSelect : function(n) {
            var t = this, ed = t.editor, ctrlMan = ed.controlManager, ctrl;

            // Setup style select box
            ctrl = ctrlMan.createListBox('styleselect', {
                title : 'advanced.style_select',
                onselect : function(name) {
                    var matches, formatNames = [];

                    each(ctrl.items, function(item) {
                        formatNames.push(item.value);
                    });

                    ed.focus();
                    ed.undoManager.add();

                    // Toggle off the current format
                    matches = ed.formatter.matchAll(formatNames);
                    if (!name || matches[0] == name)
                        ed.formatter.remove(matches[0]);
                    else
                        ed.formatter.apply(name);

                    ed.undoManager.add();
                    ed.nodeChanged();

                    return false; // No auto select
                }
            });
</code>```

答:
This a lot of work to do, but it can be done.
I solved this issue writing a custom plugin and using a custom FormatterClass.
I suggest you try developing with tiny_mce_dev.js - this way you are able to track down problems to js classes.
Then you should have a look at the js-class Formatter.js and try to modify this one in order to fullfill your wishes.
The next step will be to save the mofied Formatter.js and make it part of your plugin, so that you can reset the real Formatter.js, cause i suggest not to change the tinymce core files.

Body:
Hi everybody
I am using the tinymce format dropdown to apply custom styles to html elements. This is for users without html knowledge
One annoying thing for me is that when a user klicks at different styles they all get added and something like this may happen

In order to prevent this I searched for the responsible code which is in editor_template.js (compressed) but visible in editor_template_src.js

Is there maybe a way to rewrite this piece of javascript so that each applied style replaces the former?

_createStyleSelect : function(n) {
            var t = this, ed = t.editor, ctrlMan = ed.controlManager, ctrl;

            // Setup style select box
            ctrl = ctrlMan.createListBox('styleselect', {
                title : 'advanced.style_select',
                onselect : function(name) {
                    var matches, formatNames = [];

                    each(ctrl.items, function(item) {
                        formatNames.push(item.value);
                    });

                    ed.focus();
                    ed.undoManager.add();

                    // Toggle off the current format
                    matches = ed.formatter.matchAll(formatNames);
                    if (!name || matches[0] == name)
                        ed.formatter.remove(matches[0]);
                    else
                        ed.formatter.apply(name);

                    ed.undoManager.add();
                    ed.nodeChanged();

                    return false; // No auto select
                }
            });


问:
Nodejs server with Express not sending responses to HTTP requests from javascript file, but is receiving the requests and processing them
So I have a node-js server and an apache server on the same machine, and one of the javascript files is sending an HTTP request to the node-js server. The node-js server receives the file, reads the data, puts it in the database, as it should, but it isn't sending back any status codes or data.

Here is the XHTMLRequest send code snippet,

```<code>// creates a new http request to be sent to the nodejs server
function createNewUser(username, password, email) {

    // The url is the URL of our local nodejs server
    var userCreateRequest = new XMLHttpRequest();
    userCreateRequest.open( "POST", "http://<machine's IP>:8080/api/users" );

    // Create json object for user data
    var user = "name="+username+"&password="+password+"&email="+email;
    alert(user);

    // set content type for http request
    userCreateRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

    // Event listern for server response
    // userCreateRequest.addEventListener("readystatechange", processRequest, false);

    // Call process request whenever state changes
    userCreateRequest.onreadystatechange = function() {
            alert(this.readyState + ", " + this.status);
            if (this.readyState == 4 && this.status == 200) {

                    var response = this.response;
                    alert(response.name);

            }

    }

    // Send user data to server
    userCreateRequest.send(user);

}
</code>```

And here is the code for the node-js server (with express)

```<code>router.route('/users')

    .post(function(req, res) { //create a new user

            var user = new User();

            user.name = req.body.name;
            user.password = req.body.password;
            user.email = req.body.email;

            user.save(function(err) { //add user object to database

                    if(err)
                            res.send(err);

                    res.status(200).json(user);

            });

    });
</code>```

As I said above, the code works fine in terms of putting the body of the request in the database and what-not, but the server is not sending back the 200 OK response (or I'm failing to receive it for some reason). The only times I get an alert from onreadystatechange is when it's state 2, status 0, and state 4, status 0.

答:
It did end up being a CORS issue. I'm still a little iffy on exactly why, but after configuring the express/CORS package to allow requests from the IP and port of my apache server, it started working.

My understanding is that cross origin implies a different domain, where-as both of my servers are (as I understand it) on different ports on the same domain.

Either way, enabling CORS fixed the issue. Thank you to Jaromanda X for pointing it out and getting me on the right track.

Body:
So I have a node-js server and an apache server on the same machine, and one of the javascript files is sending an HTTP request to the node-js server. The node-js server receives the file, reads the data, puts it in the database, as it should, but it isn't sending back any status codes or data.

Here is the XHTMLRequest send code snippet,

// creates a new http request to be sent to the nodejs server
function createNewUser(username, password, email) {

    // The url is the URL of our local nodejs server
    var userCreateRequest = new XMLHttpRequest();
    userCreateRequest.open( "POST", "http://<machine's IP>:8080/api/users" );

    // Create json object for user data
    var user = "name="+username+"&password="+password+"&email="+email;
    alert(user);

    // set content type for http request
    userCreateRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

    // Event listern for server response
    // userCreateRequest.addEventListener("readystatechange", processRequest, false);

    // Call process request whenever state changes
    userCreateRequest.onreadystatechange = function() {
            alert(this.readyState + ", " + this.status);
            if (this.readyState == 4 && this.status == 200) {

                    var response = this.response;
                    alert(response.name);

            }

    }

    // Send user data to server
    userCreateRequest.send(user);

}

And here is the code for the node-js server (with express)

router.route('/users')

    .post(function(req, res) { //create a new user

            var user = new User();

            user.name = req.body.name;
            user.password = req.body.password;
            user.email = req.body.email;

            user.save(function(err) { //add user object to database

                    if(err)
                            res.send(err);

                    res.status(200).json(user);

            });

    });

As I said above, the code works fine in terms of putting the body of the request in the database and what-not, but the server is not sending back the 200 OK response (or I'm failing to receive it for some reason). The only times I get an alert from onreadystatechange is when it's state 2, status 0, and state 4, status 0.


问:
Most efficient way of combining two big lists
I have two lists that each contain 2500 values.

```<code>List<String> headers = new ArrayList<String>();
List<String> data = new ArrayList<String>();
</code>```

I need to combine these two lists into a two dimensional list or any other appropriate data structure that allows me to only iterate through once rather than doing the operation below which is very slow when dealing with big lists:

```<code> for (int i = 0; i < headers.size(); i++) {
    for (int in = 0; in < data.size(); in++) {

       }
 }
</code>```

It's critical the index of each list match each other when combining these two lists. So headers.get(9); must match data.get(9);.

I need a new list or other data structure that will allow me to store each value in the two lists as pairs. So headers.get(0); would be paired with data.get(0);.

Any help would be appreciated.

答:
I'm not really sure if the loop you presented is what what you really wanted to archieve, but if you wanted every element of the first list correspond to exactly one element of the second list I would suggest using Map<String, String>. This allows you to map every element of the first list of strings to one elements of the second list. Each pair is then stored as an Map.Entry<Key,Value>.

That way you are able to iterate only once through the map using for example loop like this:

```<code>for(Map.Entry<String,String> entry : map.entrySet()) {...}
</code>```

Body:
I have two lists that each contain 2500 values.

List<String> headers = new ArrayList<String>();
List<String> data = new ArrayList<String>();

I need to combine these two lists into a two dimensional list or any other appropriate data structure that allows me to only iterate through once rather than doing the operation below which is very slow when dealing with big lists:

 for (int i = 0; i < headers.size(); i++) {
    for (int in = 0; in < data.size(); in++) {

       }
 }

It's critical the index of each list match each other when combining these two lists. So headers.get(9); must match data.get(9);.

I need a new list or other data structure that will allow me to store each value in the two lists as pairs. So headers.get(0); would be paired with data.get(0);.

Any help would be appreciated.

Body:
I'm not really sure if the loop you presented is what what you really wanted to archieve, but if you wanted every element of the first list correspond to exactly one element of the second list I would suggest using Map<String, String>. This allows you to map every element of the first list of strings to one elements of the second list. Each pair is then stored as an Map.Entry<Key,Value>.

That way you are able to iterate only once through the map using for example loop like this:

for(Map.Entry<String,String> entry : map.entrySet()) {...}


问:
Changing src of dynamically loaded images with jquery
I have a div that is loaded dynamically with one or more images. Initially, all these images are crops.  The aim is, when a when a user clicks on a cropped image, its src is replaced by the full sized version.  Click the full sized version to return to the cropped image.  I have no knowledge of the file names of the image, other than that they are all numbers, except the full version has a "L" as the first character in the file name.

This code works, but I'm sure there must be a simpler way:

```<code>$('#class').on('click', '> img', function() {
var src = $(this).attr('src');
var test_src = src.match(/L/g);
var img_id = src.replace(/L/g, '');
var big_img = src.replace('/images/', '/images/L');
if (test_src == undefined) {
  $(this).attr('src', big_img)
    } else {
  $(this).attr('src', img_id);
   }
});
</code>```

The problem I only managed to overcome with this code was, if I simply got the img src and added an 'L', after the first click, the img src was changed to something like '/images/L123345.jpg', and so, clicking it again with the aim of returning to the original src ('/images/12345.jpg') just added a second L.

I'm sure I've missed something really obvious.  Thanks for any suggestions.

答:
This might work...</p>

```<code>var $img = $("<img>");

$img.on('load', function (e) {
    this.$photoImageManager.attr('src', e.target.src);
}.bind(this));

$img.attr('src', "../../users/" + userId + "/" + userId + "-photo.png");
</code>```

Body:
I have a div that is loaded dynamically with one or more images. Initially, all these images are crops.  The aim is, when a when a user clicks on a cropped image, its src is replaced by the full sized version.  Click the full sized version to return to the cropped image.  I have no knowledge of the file names of the image, other than that they are all numbers, except the full version has a "L" as the first character in the file name.

This code works, but I'm sure there must be a simpler way:

$('#class').on('click', '> img', function() {
var src = $(this).attr('src');
var test_src = src.match(/L/g);
var img_id = src.replace(/L/g, '');
var big_img = src.replace('/images/', '/images/L');
if (test_src == undefined) {
  $(this).attr('src', big_img)
    } else {
  $(this).attr('src', img_id);
   }
});

The problem I only managed to overcome with this code was, if I simply got the img src and added an 'L', after the first click, the img src was changed to something like '/images/L123345.jpg', and so, clicking it again with the aim of returning to the original src ('/images/12345.jpg') just added a second L.

I'm sure I've missed something really obvious.  Thanks for any suggestions.

Body:
This might work...

var $img = $("<img>");

$img.on('load', function (e) {
    this.$photoImageManager.attr('src', e.target.src);
}.bind(this));

$img.attr('src', "../../users/" + userId + "/" + userId + "-photo.png");


问:
Android Activity findviewbyid() is null
```<code>import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;

public class FileExplorerActivity extends Activity
{
    public static final String TAG="ricky";
    Button button;
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        button = (Button) findViewById(R.id.but);<<<------------------
        if(button == null)
        Log.d(TAG, "FileExplorerActivity: button is null");
    }
    public FileExplorerActivity()
    {
       Log.d(TAG, "FileExplorer: constructor()");
    }
}
</code>```

This is a simple Activity which is brought in front by another activity using Intent

```<code>Intent openFileBrowser = new Intent(this, FileExplorerActivity.class);
try
{
    startActivity(openFileBrowser);
}
</code>```

After running the code my LogCat file says "button is null" Why ???

答:
Next code solves the issue (Xamarin Android)</p>

```<code>public class MainActivity : WearableActivity
{
    ...

    OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);

        **SetContentView(Resource.Layout.RoundMain);**

        // Does not return null anymore:

        FindViewById<Button>(Resource.Id.ButtonVgOk).LongClick += (s, e) => ButtonVgOkOnLongClick();

        ...
   }
</code>```

Title: Android Activity findviewbyid() is null

Body:
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;

public class FileExplorerActivity extends Activity
{
    public static final String TAG="ricky";
    Button button;
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        button = (Button) findViewById(R.id.but);<<<------------------
        if(button == null)
        Log.d(TAG, "FileExplorerActivity: button is null");
    }
    public FileExplorerActivity()
    {
       Log.d(TAG, "FileExplorer: constructor()");
    }
}

This is a simple Activity which is brought in front by another activity using Intent

Intent openFileBrowser = new Intent(this, FileExplorerActivity.class);
try
{
    startActivity(openFileBrowser);
}

After running the code my LogCat file says "button is null" Why ???

Body:
Next code solves the issue (Xamarin Android)

public class MainActivity : WearableActivity
{
    ...

    OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);

        **SetContentView(Resource.Layout.RoundMain);**

        // Does not return null anymore:

        FindViewById<Button>(Resource.Id.ButtonVgOk).LongClick += (s, e) => ButtonVgOkOnLongClick();

        ...
   }


问:
OpenCL : error -9999 on NVIDIA K20m
I usually always find a solution on google (80% here), but this time this is unfortunately not the case. That's why I decided to create an account.

I have written an OpenCL code which runs on different Intel and AMD CPU. It runs on an AMD RADEON HD7970 and NVIDIA Quadro FX 1800M too. However when I try to launch the code on an NVIDIA K20m I get the error -9999 with "clEnqueueNDRangeKernel".

The most troubling is that the error occurs after 512 iterations (I guess 512 is a coincidence).

I believe (but maybe it was just error -11) I have already seen this error but it was an error during building program and due to "clGetEventProfilingInfo". This time all profiling is comment.

I'm looking for information about this error.

Thank you in advance for your answers.

Platform info:

OpenCL version: 1.1

CUDA version: 7.0.18

P.S.: It may be useful to precise that I'm not an administrator of this system.

答:
For the sake of future visitors from Google (on which this now has a very high ranking for this error code,) this is a vendor-specific error code from NVidia.

On Stream HPC's list of OpenCL error codes, code -9999 is listed for function clEnqueueNDRangeKernel with the description:

Illegal read or write to a buffer

Title: OpenCL : error -9999 on NVIDIA K20m


问:
Dojo Toolbox: Closing the dialog Box
Is there a way to set a button inside the dojo dialog box and have it close the dialog box it is residing in?

Putting dijits inside of dijits doesn't work, and I can't beleive there isn't a way to do that.

答:
Sure you can put a dijit widget inside another widget. And in a standard Dojo release there's even a test case Dijit Dialog focus & destroy included that demonstrates closing dialog with a button inside of it. Here's the relevant part:</p>

```<code>var btn = new dijit.form.Button({ label: "Close" });
dlg.containerNode.appendChild(btn.domNode);

dojo.connect(btn, "onClick", function(){
    console.log("destroying, while visible");
    dlg.destroy();
});
</code>```

Title: Dojo Toolbox: Closing the dialog Box

Body:
Sure you can put a dijit widget inside another widget. And in a standard Dojo release there's even a test case Dijit Dialog focus & destroy included that demonstrates closing dialog with a button inside of it. Here's the relevant part:

var btn = new dijit.form.Button({ label: "Close" });
dlg.containerNode.appendChild(btn.domNode);

dojo.connect(btn, "onClick", function(){
    console.log("destroying, while visible");
    dlg.destroy();
});

OwnerDisplayName: Maine


问:
How to use Grails Spring Security Plugin to require logging in before access an action?
I know that I can use annotation or Request mapping to restrict access to an ACTION by some specific ROLES. But now I have a different circumstance.

My scenario is: every user of my site can create posts, and they can make their own post public, private, or only share to some other users. I implement sharing post by a database table PERMISSION, which specify if a user have the right to view a post or not.

The problem arises here is that when a customer access a post through a direct link, how can I determine he/she have the privilege to view it? There's 3 circumstances:

The post is public, so it can be viewed by anyone (include not-login
  user)

The post is private, so only the login-owner can view it

The post is sharing, it means only the login-user that is shared and the
  owner can view it.

I want to process like this:

If the requested post is public: ok.

If the requested post is private/sharing: I want to redirect
  the customer to the login page; after
  logging in, the user will be re-direct
  to the page he wants to see.

The problem here is that I can redirect the user to login controller/ auth action, but after that I don't know how to redirect it back. The link to every post is different by post_id, so I can't use SpringSecurityUtils.securityConfig.successHandler.defaultTargetUrl

Could anyone know a way to do this?

答:
Have you looked at the Grails Spring Security ACL plugin? I don't know it very well, but it's designed to restrict access to particular instances:

http://grails.org/plugin/spring-security-acl


问:
How to add multiple key constraints for ORM eager loading in Laravel?
Suppose I have three relations:

```<code> 1. departments
        - id (primary)
        - name
 2. quotas
        - id (primary)
        - name
 3. department_quota
        - id (primary)
        - department_id (foreign)
        - quota_id (foreign)
        - number_of_seats
        - unique(department_id, quota_id)
</code>```

Now, I want to access number_of_seats per department grouped by quota, again I want to access number_of_seats per quota grouped by department. I need to do this task using laravel ORM eager loading.

I can access all quotas with departments using :

```<code>\App\Quota::with('departments')->get();
</code>```

and also the opposite thing using by:

```<code>\App\Department::with('quotas')->get();
</code>```

Yes, this is a many-to-many relation.
But how can I access the number_of_seats as stated above ?

I need this because I am to serve the relation as JSON serialized data for REST.

答:
If both models are belongsToMany you can add withPivot() to your departments() method.

```<code>public function departments(){
    return $this->belongsToMany('App\Department')->withPivot('number_of_seats');
}
</code>```

it will be included in the json collection and it can be reached via code with

```<code>foreach(Quota::with('departments')->get() as $quota){
       foreach($quota->departments as $department){
           echo $department->pivot->number_of_seats;
       }
    }
</code>```

Body:
Suppose I have three relations:

 1. departments
        - id (primary)
        - name
 2. quotas
        - id (primary)
        - name
 3. department_quota
        - id (primary)
        - department_id (foreign)
        - quota_id (foreign)
        - number_of_seats
        - unique(department_id, quota_id)

Now, I want to access number_of_seats per department grouped by quota, again I want to access number_of_seats per quota grouped by department. I need to do this task using laravel ORM eager loading.

I can access all quotas with departments using :

\App\Quota::with('departments')->get();

and also the opposite thing using by:

\App\Department::with('quotas')->get();

Yes, this is a many-to-many relation.
But how can I access the number_of_seats as stated above ?

I need this because I am to serve the relation as JSON serialized data for REST.

Body:
If both models are belongsToMany you can add withPivot() to your departments() method.

public function departments(){
    return $this->belongsToMany('App\Department')->withPivot('number_of_seats');
}

it will be included in the json collection and it can be reached via code with

foreach(Quota::with('departments')->get() as $quota){
       foreach($quota->departments as $department){
           echo $department->pivot->number_of_seats;
       }
    }


答:
About

It's critical the index of each list match each other when combining these two lists.

Create a simple class to hold both value

```<code>class MyData{
    String header;
    String data;
}
</code>```

Then use a single List<MyData>. You will only have one List of 2500 items.

Based on what you do with those data, other collection could be more efficient to read, but not to update.

Title: Most efficient way of combining two big lists

Body:
About

It's critical the index of each list match each other when combining these two lists.

Create a simple class to hold both value

class MyData{
    String header;
    String data;
}

Then use a single List<MyData>. You will only have one List of 2500 items.

Based on what you do with those data, other collection could be more efficient to read, but not to update.


问:
Firebase google auth (swift)
Following the firebase docs i added the authentication with google account and this is part of the code that i have in my app delegate

```<code> func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error?) {

        if let error = error {
            print("Failed to log into Google: ", error)
            return
        }
            print("Successfully logged into Google", user)
        guard let idToken = user.authentication.idToken else { return }
        guard let accessToken = user.authentication.accessToken else { return }
        let credentials = GoogleAuthProvider.credential(withIDToken: idToken, accessToken: accessToken)

        Auth.auth().signIn(with: credentials, completion: { (user, error) in
            if let err = error {
                print("Failed to create a Firebase User with Google account: ", err)
                return
            }

            guard let uid = user?.uid else { return }

            print("Successfully logged into Firebase with Google", uid)

        })
    }

    func sign(_ signIn: GIDSignIn!, didDisconnectWith user: GIDGoogleUser!, withError error: Error!) {
        // Perform any operations when the user disconnects from app here.
        // ...
    }
</code>```

but the google button

```<code> fileprivate func setupGoogleButtons() {

        googleButton.frame = CGRect(x: 189, y: 532, width: 118, height: 41)
        view.addSubview(googleButton)

        GIDSignIn.sharedInstance().uiDelegate = self
}
</code>```

is obviously in a viewController, what i would like to do is an automatically self.performSegue(withIdentifier: "goToHome1", sender: self) as soon as the user logs in with his google account, because at the moment after login the user always finds on the same VC. How can i do this?

UPDATE

I solve my problem following this question Google and Facebook Firebase Auth using swift 3

答:
If there is no error then the user signed in successfully so you should segue. The button itself just calls the sign in function. Depending on whether the sign in fails or succeeds you alert or segue.</p>

```<code>func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error?) {
    if let error = error {
        print("Failed to log into Google: ", error)
        return
    }

    print("Successfully logged into Google", user)
    guard let idToken = user.authentication.idToken else { return }
    guard let accessToken = user.authentication.accessToken else { return }
    let credentials = GoogleAuthProvider.credential(withIDToken: idToken, accessToken: accessToken)

    Auth.auth().signIn(with: credentials, completion: { (user, error) in
        if let err = error {
            print("Failed to create a Firebase User with Google account: ", err)
            return
        }

        guard let uid = user?.uid else { return }
        print("Successfully logged into Firebase with Google", uid)
        // segue here
        DispatchQueue.main.async {
            self.performSegue(withIdentifier: "goToHome1", sender: self)
        }
    })
}
</code>```

Title: Firebase google auth (swift)

Body:
Following the firebase docs i added the authentication with google account and this is part of the code that i have in my app delegate

 func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error?) {

        if let error = error {
            print("Failed to log into Google: ", error)
            return
        }
            print("Successfully logged into Google", user)
        guard let idToken = user.authentication.idToken else { return }
        guard let accessToken = user.authentication.accessToken else { return }
        let credentials = GoogleAuthProvider.credential(withIDToken: idToken, accessToken: accessToken)

        Auth.auth().signIn(with: credentials, completion: { (user, error) in
            if let err = error {
                print("Failed to create a Firebase User with Google account: ", err)
                return
            }

            guard let uid = user?.uid else { return }

            print("Successfully logged into Firebase with Google", uid)

        })
    }

    func sign(_ signIn: GIDSignIn!, didDisconnectWith user: GIDGoogleUser!, withError error: Error!) {
        // Perform any operations when the user disconnects from app here.
        // ...
    }

but the google button

 fileprivate func setupGoogleButtons() {

        googleButton.frame = CGRect(x: 189, y: 532, width: 118, height: 41)
        view.addSubview(googleButton)

        GIDSignIn.sharedInstance().uiDelegate = self
}

is obviously in a viewController, what i would like to do is an automatically self.performSegue(withIdentifier: "goToHome1", sender: self) as soon as the user logs in with his google account, because at the moment after login the user always finds on the same VC. How can i do this?

UPDATE

I solve my problem following this question Google and Facebook Firebase Auth using swift 3

Body:
If there is no error then the user signed in successfully so you should segue. The button itself just calls the sign in function. Depending on whether the sign in fails or succeeds you alert or segue.

func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error?) {
    if let error = error {
        print("Failed to log into Google: ", error)
        return
    }

    print("Successfully logged into Google", user)
    guard let idToken = user.authentication.idToken else { return }
    guard let accessToken = user.authentication.accessToken else { return }
    let credentials = GoogleAuthProvider.credential(withIDToken: idToken, accessToken: accessToken)

    Auth.auth().signIn(with: credentials, completion: { (user, error) in
        if let err = error {
            print("Failed to create a Firebase User with Google account: ", err)
            return
        }

        guard let uid = user?.uid else { return }
        print("Successfully logged into Firebase with Google", uid)
        // segue here
        DispatchQueue.main.async {
            self.performSegue(withIdentifier: "goToHome1", sender: self)
        }
    })
}


问:
topic distristribution in gensim ldamodel trained with countvectorizer
I have an assignment that's something like this:

```<code>import gensim
from sklearn.feature_extraction.text import CountVectorizer

newsgroup_data = ["Human machine interface for lab abc computer applications",
             "A survey of user opinion of computer system response time",
              "The EPS user interface management system",
              "System and human system engineering testing of EPS",
              "Relation of user perceived response time to error measurement",
              "The generation of random binary unordered trees",
              "The intersection graph of paths in trees",
              "Graph minors IV Widths of trees and well quasi ordering",
              "Graph minors A survey"]

vect = CountVectorizer(stop_words='english',
                       token_pattern='(?u)\\b\\w\\w\\w+\\b')
X = vect.fit_transform(newsgroup_data)
corpus = gensim.matutils.Sparse2Corpus(X, documents_columns=False)
id_map = dict((v, k) for k, v in vect.vocabulary_.items())
</code>```

My task is to estimate LDA model parameters on the corpus, find a list of the 10 topics and the most significant 10 words in each topic, which I do as such:

```<code>top10 = ldamodel.print_topics(num_topics=10, num_words=10)
ldamodel = gensim.models.ldamodel.LdaModel(corpus=corpus,
              id2word=id_map, num_topics=10, minimum_probability=0)
</code>```

Which passes the autograder fine.  The next task is to find the topic distribution of a new doc which I attempt to do as follows:

```<code>new_doc = ["\n\nIt's my understanding that the freezing will start to occur because \
of the\ngrowing distance of Pluto and Charon from the Sun, due to it's\nelliptical orbit. \
It is not due to shadowing effects. \n\n\nPluto can shadow Charon, and vice-versa.\n\nGeorge \
Krumins\n-- "]
newX = vect.transform(new_doc)
newC = gensim.matutils.Sparse2Corpus(newX, documents_columns=False)
print(ldamodel.get_document_topics(newC))
</code>```

This however simply returns

gensim.interfaces.TransformedCorpus

I also see from the docs the statement: "You can then infer topic distributions on new, unseen documents, with >>> doc_lda = lda[doc_bow]" but have no success here either.  Any help appreciated.

答:
Continued digging into this, specifically for the interface gensim.interfaces.TransformedCorpus.  As I understand it, the interface points to the topic/distribution I've asked for but I need to iterated through it to see the values.

```<code>topic_dist = ldamodel.get_document_topics(newC)
td=[]
for topic in topic_dis:
   td.append(topic)
td = td[0]
</code>```

does the trick.  Could also use

```<code>topic_dist = ldamodel[newC]
</code>```

Body:
I have an assignment that's something like this:

import gensim
from sklearn.feature_extraction.text import CountVectorizer

newsgroup_data = ["Human machine interface for lab abc computer applications",
             "A survey of user opinion of computer system response time",
              "The EPS user interface management system",
              "System and human system engineering testing of EPS",
              "Relation of user perceived response time to error measurement",
              "The generation of random binary unordered trees",
              "The intersection graph of paths in trees",
              "Graph minors IV Widths of trees and well quasi ordering",
              "Graph minors A survey"]

vect = CountVectorizer(stop_words='english',
                       token_pattern='(?u)\\b\\w\\w\\w+\\b')
X = vect.fit_transform(newsgroup_data)
corpus = gensim.matutils.Sparse2Corpus(X, documents_columns=False)
id_map = dict((v, k) for k, v in vect.vocabulary_.items())

My task is to estimate LDA model parameters on the corpus, find a list of the 10 topics and the most significant 10 words in each topic, which I do as such:

top10 = ldamodel.print_topics(num_topics=10, num_words=10)
ldamodel = gensim.models.ldamodel.LdaModel(corpus=corpus,
              id2word=id_map, num_topics=10, minimum_probability=0)

Which passes the autograder fine.  The next task is to find the topic distribution of a new doc which I attempt to do as follows:

new_doc = ["\n\nIt's my understanding that the freezing will start to occur because \
of the\ngrowing distance of Pluto and Charon from the Sun, due to it's\nelliptical orbit. \
It is not due to shadowing effects. \n\n\nPluto can shadow Charon, and vice-versa.\n\nGeorge \
Krumins\n-- "]
newX = vect.transform(new_doc)
newC = gensim.matutils.Sparse2Corpus(newX, documents_columns=False)
print(ldamodel.get_document_topics(newC))

This however simply returns

gensim.interfaces.TransformedCorpus

I also see from the docs the statement: "You can then infer topic distributions on new, unseen documents, with >>> doc_lda = lda[doc_bow]" but have no success here either.  Any help appreciated.

Body:
Continued digging into this, specifically for the interface gensim.interfaces.TransformedCorpus.  As I understand it, the interface points to the topic/distribution I've asked for but I need to iterated through it to see the values.

topic_dist = ldamodel.get_document_topics(newC)
td=[]
for topic in topic_dis:
   td.append(topic)
td = td[0]

does the trick.  Could also use

topic_dist = ldamodel[newC]


问:
Why isEmpty not working here ?
i made a structure here
struct dicStruct<T,U>{}

anad here is my instance of its

var instanceOfDicStruct:dicStruct<Int,String> = dicStruct()

isEmpty is not working here can anyone explain of send me some reference ?

instanceOfDicStruct.isEmpty

答:
A struct with two generic placeholder types ≠ dictionary.

If you need a dictionary, then create an instance of a dictionary like so:

```<code>var dictionaryInstance = [Int: String]()
</code>```

isEmpty works now:

```<code>print(dictionaryInstance.isEmpty) // true
</code>```

You can also create a typealias:

```<code>typealias MyDictionary = [Int: String]

var myDictionaryInstance = MyDictionary()
</code>```

Title: Why isEmpty not working here ?

Body:
A struct with two generic placeholder types ≠ dictionary.

If you need a dictionary, then create an instance of a dictionary like so:

var dictionaryInstance = [Int: String]()

isEmpty works now:

print(dictionaryInstance.isEmpty) // true

You can also create a typealias:

typealias MyDictionary = [Int: String]

var myDictionaryInstance = MyDictionary()


问:
Upload file to servlet behind proxy with packet limit
I have an application in which file uploads are pretty common, but now we have a new scenario behind a proxy we can't control.

The proxy has a max-packet-size of 5 MB, meaning that we can only upload at most 5MB per request; and that breaks our usual 10-250 MB normal uploads.

Is there a standard Java-based (or Spring) way to upload files on configurable chunks/parts?

Note: From the client side (web) we planned to use jQuery-File-Upload

答:
A combination of compression and chunking should work thus:

Chunk your file upload: This requires the server to understand/support request chunking. This will support your general need for reducing a single large packet

Compress the request: This also requires the server to support your compression encoding

Together, both mechanisms can significantly reduce your transmission size


问:
Pandas: append row to DataFrame with multiindex in columns
I have a DataFrame with a multiindex in the columns and would like to use dictionaries to append new rows.

Let's say that each row in the DataFrame is a city. The columns contains "distance" and "vehicle". And each cell would be the percentage of the population that chooses this vehicle for this distance.

I'm constructing an index like this:

```<code>index_tuples=[]

for distance in ["near", "far"]:
    for vehicle in ["bike", "car"]:
        index_tuples.append([distance, vehicle])

index = pd.MultiIndex.from_tuples(index_tuples, names=["distance", "vehicle"])
</code>```

Then I'm creating a dataframe:

```<code>dataframe = pd.DataFrame(index=["city"], columns = index)
</code>```

The structure of the dataframe looks good. Although pandas has added Nans as default values ?

Now I would like to set up a dictionary for the new city and add it:

```<code>my_home_city = {"near":{"bike":1, "car":0},"far":{"bike":0, "car":1}}
dataframe["my_home_city"] = my_home_city
</code>```

But this fails:

ValueError: Length of values does not match length of index

Here is the complete error message (pastebin)

UPDATE:

Thank you for all the good answers. I'm afraid I've oversimplified the problem in my example. Actually my index is nested with 3 levels (and it could become more).

So I've accepted the universal answer of converting my dictionary into a list of tuples. This might not be as clean as the other approaches but works for any multiindex setup.

答:
Multi index is a list of tuple , we just need to modify your dict ,then we could directly assign the value

```<code>d = {(x,y):my_home_city[x][y] for x in my_home_city for y in my_home_city[x]}
df.loc['my_home_city',:]=d
df
Out[994]:
distance     near       far
vehicle      bike  car bike  car
city          NaN  NaN  NaN  NaN
my_home_city    1    0    0    1
</code>```

More Info

```<code>d
Out[995]:
{('far', 'bike'): 0,
 ('far', 'car'): 1,
 ('near', 'bike'): 1,
 ('near', 'car'): 0}

df.columns.values
Out[996]: array([('near', 'bike'), ('near', 'car'), ('far', 'bike'), ('far', 'car')], dtype=object)
</code>```

Body:
I have a DataFrame with a multiindex in the columns and would like to use dictionaries to append new rows.

Let's say that each row in the DataFrame is a city. The columns contains "distance" and "vehicle". And each cell would be the percentage of the population that chooses this vehicle for this distance.

I'm constructing an index like this:

index_tuples=[]

for distance in ["near", "far"]:
    for vehicle in ["bike", "car"]:
        index_tuples.append([distance, vehicle])

index = pd.MultiIndex.from_tuples(index_tuples, names=["distance", "vehicle"])

Then I'm creating a dataframe:

dataframe = pd.DataFrame(index=["city"], columns = index)

The structure of the dataframe looks good. Although pandas has added Nans as default values ?

Now I would like to set up a dictionary for the new city and add it:

my_home_city = {"near":{"bike":1, "car":0},"far":{"bike":0, "car":1}}
dataframe["my_home_city"] = my_home_city

But this fails:

ValueError: Length of values does not match length of index

Here is the complete error message (pastebin)

UPDATE:

Thank you for all the good answers. I'm afraid I've oversimplified the problem in my example. Actually my index is nested with 3 levels (and it could become more).

So I've accepted the universal answer of converting my dictionary into a list of tuples. This might not be as clean as the other approaches but works for any multiindex setup.

Body:
Multi index is a list of tuple , we just need to modify your dict ,then we could directly assign the value

d = {(x,y):my_home_city[x][y] for x in my_home_city for y in my_home_city[x]}
df.loc['my_home_city',:]=d
df
Out[994]:
distance     near       far
vehicle      bike  car bike  car
city          NaN  NaN  NaN  NaN
my_home_city    1    0    0    1

More Info

d
Out[995]:
{('far', 'bike'): 0,
 ('far', 'car'): 1,
 ('near', 'bike'): 1,
 ('near', 'car'): 0}

df.columns.values
Out[996]: array([('near', 'bike'), ('near', 'car'), ('far', 'bike'), ('far', 'car')], dtype=object)


问:
PHP DOMDocument getElementsByTagName return raw XML
Is the getElementsByTagName function capable of returning the children as a XML blob?

答:
DOMDocument::getElementsByTagName() return a DOMNodeList instance. You can iterate through the DOMNodes contained in it, using DOMDocument::saveXML() to keep concatenating the raw XML to a string.

```<code><?php
$a = '<root>
    <prueba>
        <testtag value="1"/>
    </prueba>
    <notprueba>
        <testtag value="1"/>
    </notprueba>
    <prueba>
        <testtag value="2"/>
    </prueba>
</root>';
$doc = new DOMDocument;
$doc->loadXML($a);
$x = new DOMXPath($doc);
$nodes = $doc->getElementsByTagName("prueba");
$xml = "";
foreach ($nodes as $node) {
    $xml .= $doc->saveXML($node);
}
var_dump(htmlentities($xml));
</code>```

Demo

Body:
DOMDocument::getElementsByTagName() return a DOMNodeList instance. You can iterate through the DOMNodes contained in it, using DOMDocument::saveXML() to keep concatenating the raw XML to a string.

<?php
$a = '<root>
    <prueba>
        <testtag value="1"/>
    </prueba>
    <notprueba>
        <testtag value="1"/>
    </notprueba>
    <prueba>
        <testtag value="2"/>
    </prueba>
</root>';
$doc = new DOMDocument;
$doc->loadXML($a);
$x = new DOMXPath($doc);
$nodes = $doc->getElementsByTagName("prueba");
$xml = "";
foreach ($nodes as $node) {
    $xml .= $doc->saveXML($node);
}
var_dump(htmlentities($xml));

Demo


答:
Make a new class:

```<code>class HeadersWithData{
    String header;
    String data;

    HeadersWithData(String header, String data){
        this.header = header;
        this.data = data;
    }
}
</code>```

Declare your list:

```<code>List<HeadersWithData> combinedList = new ArrayList<>();
</code>```

And fill the list:

```<code>for (int i = 0; i < headers.size(); i++){
    combinedList.add(new HeadersWithData(headers.get(i), data.get(i)));
}
</code>```

Note: This is a one-dimensional list. A two-dimensional list would not make any sense in your case.

Body:
I have two lists that each contain 2500 values.

List<String> headers = new ArrayList<String>();
List<String> data = new ArrayList<String>();

I need to combine these two lists into a two dimensional list or any other appropriate data structure that allows me to only iterate through once rather than doing the operation below which is very slow when dealing with big lists:

 for (int i = 0; i < headers.size(); i++) {
    for (int in = 0; in < data.size(); in++) {

       }
 }

It's critical the index of each list match each other when combining these two lists. So headers.get(9); must match data.get(9);.

I need a new list or other data structure that will allow me to store each value in the two lists as pairs. So headers.get(0); would be paired with data.get(0);.

Any help would be appreciated.

Body:
Make a new class:

class HeadersWithData{
    String header;
    String data;

    HeadersWithData(String header, String data){
        this.header = header;
        this.data = data;
    }
}

Declare your list:

List<HeadersWithData> combinedList = new ArrayList<>();

And fill the list:

for (int i = 0; i < headers.size(); i++){
    combinedList.add(new HeadersWithData(headers.get(i), data.get(i)));
}

Note: This is a one-dimensional list. A two-dimensional list would not make any sense in your case.


问:
How to use Code Contracts with query?
I am fairly new to Code Contracts...and I ran into a problem.

I have in a method LINQ query that go something like this:

```<code>MyClass[] fields =
            (from p in rType.GetProperties()
             where p.CanRead
             let fAttr = p.GetCustomAttributes(typeof(MyClassAttribute), true).SingleOrDefault() as MyClassAttribute
             where fAttr != null
             select new MyClass(p, fAttr)).ToArray();
</code>```

And I want to implement Code Contracts in my project. I have done everything OK, until I got to this point. When I run static checker, it suggest to me that I need to add a couple of preconditions (Contract.Requires) regarding variables p and fAttr which are defined in the query. And also, I have a couple of unproven requires.

How can I solve this? Any ideas?

MyClass also contains two preconditions:

```<code>internal MyClass(PropertyInfo p, MyClassAttribute att)
    {
        Contract.Requires(p != null);
        Contract.Requires(att != null);
        ...
    }
</code>```

Thanks in advance :)

答:
I can't seem to reproduce this. Are you using the latest version of Code Contracts?

My entire code looks like this... is this close enough to your version?

```<code>using System;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Reflection;

namespace ConsoleApplication10
{
    class Program
    {
        class MyClassAttribute : Attribute{}
        class MyClass
        {
            internal MyClass(PropertyInfo p, MyClassAttribute a)
            {
                Contract.Requires(p != null);
                Contract.Requires(a != null);
            }
        }

        static void Main(string[] args)
        {
            var rType = typeof (DateTime);

            MyClass[] result = (from p in rType.GetProperties()
             where p.CanRead
             let fAttr = p.GetCustomAttributes(typeof(MyClassAttribute), true).SingleOrDefault() as MyClassAttribute
             where fAttr != null
             select new MyClass(p, fAttr)).ToArray();

        }
    }
}
</code>```

Title: How to use Code Contracts with query?

Body:
I am fairly new to Code Contracts...and I ran into a problem.

I have in a method LINQ query that go something like this:

MyClass[] fields =
            (from p in rType.GetProperties()
             where p.CanRead
             let fAttr = p.GetCustomAttributes(typeof(MyClassAttribute), true).SingleOrDefault() as MyClassAttribute
             where fAttr != null
             select new MyClass(p, fAttr)).ToArray();

And I want to implement Code Contracts in my project. I have done everything OK, until I got to this point. When I run static checker, it suggest to me that I need to add a couple of preconditions (Contract.Requires) regarding variables p and fAttr which are defined in the query. And also, I have a couple of unproven requires.

How can I solve this? Any ideas?

MyClass also contains two preconditions:

internal MyClass(PropertyInfo p, MyClassAttribute att)
    {
        Contract.Requires(p != null);
        Contract.Requires(att != null);
        ...
    }

Thanks in advance :)

Body:
I can't seem to reproduce this. Are you using the latest version of Code Contracts?

My entire code looks like this... is this close enough to your version?

using System;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Reflection;

namespace ConsoleApplication10
{
    class Program
    {
        class MyClassAttribute : Attribute{}
        class MyClass
        {
            internal MyClass(PropertyInfo p, MyClassAttribute a)
            {
                Contract.Requires(p != null);
                Contract.Requires(a != null);
            }
        }

        static void Main(string[] args)
        {
            var rType = typeof (DateTime);

            MyClass[] result = (from p in rType.GetProperties()
             where p.CanRead
             let fAttr = p.GetCustomAttributes(typeof(MyClassAttribute), true).SingleOrDefault() as MyClassAttribute
             where fAttr != null
             select new MyClass(p, fAttr)).ToArray();

        }
    }
}


问:
Counting rows iterativly that have a column correlation?
Given the table containing the columns: custID, startDate, endDate, etc.

How would one go about counting the highest number of rows that a customer generated existing within the same time period.

My thinking is that if you do a recursive JOIN and eliminate the rows that are identical you could compare A.startDate with B start and end dates.

I simply don't understand how to do this iterative process to find the highest number possible.

What I have right now look like this but it doesn't seem to work as intended.

```<code>SELECT DISTINCT A.custID, COUNT(A.custID) AS Concurrently
FROM T_Loan A JOIN T_Loan B
WHERE A.custID = B.custID AND NOT (A.endDate = B.endDate AND A.loanDate = B.startDate) AND A.startDate<= B.endDate AND A.startDate>= B.startDate
GROUP BY custID
HAVING Concurrently > 0;
</code>```

Any advice or suggestions would be much appreciated

答:
I'm a little confused by the comparison of loanDate to startDate in the query, and checking for a date range overlap seems to be referencing a wrong column.

Assuming that (custid,startdate,enddate) is a unique identifier for a row in T_Loan...  (ideally, we'd have a single column as a unique identifier for example, an id column as a surrogate primary key) and assuming that we're only interested in rows where all three of the columns are non-NULL...

Those are some big assumptions, but all we have to go on is the information provided in the question.

As a start, I'd figure out how to get a count of the number of rows in T_Loan that are for the same custid and are concurrent (that is, there's any amount of overlap in the start/end date ranges.)

For simplicity, I'd go ahead and include the current row in that count, so a row with no other concurrent rows would be reported with a count of 1 (the row itself). Here's how I'd do that:

```<code>SELECT a.custid
     , a.startdate
     , a.enddate
     , COUNT(b.custid)  AS cnt_concurrent
  FROM T_Loan a
  JOIN T_Loan b
    ON b.custid     = a.custid
   AND b.enddate   >= a.startdate
   AND b.startdate <= a.enddate
 GROUP
    BY a.custid
     , a.startdate
     , a.enddate
</code>```

That gives us, for each row in T_Loan a count of the number of rows in T_Loan that are for the same custid and there's some overlap in the date range with the current row.

We can use the resultset returned by that query as a rowsource in another query.

For example, to get the maximum number of concurrent rows for each custid, we could do something like this:

```<code>SELECT c.custid
     , MAX(c.cnt_concurrent) AS max_cnt_concurrent
  FROM (
         SELECT a.custid
              , a.startdate
              , a.enddate
              , COUNT(b.custid)  AS cnt_concurrent
           FROM T_Loan a
           JOIN T_Loan b
             ON b.custid     = a.custid
            AND b.enddate   >= a.startdate
            AND b.startdate <= a.enddate
          GROUP
             BY a.custid
              , a.startdate
              , a.enddate
       ) c
 GROUP BY c.custid
</code>```

This is going to include custid that have only one row in T_Loan, as well as custid where there are multiple rows, but no overlap in the date ranges. If we want to eliminate those rows (with a maximum concurrent count equal to 1), we can add a HAVING clause...

```<code>HAVING MAX(c.cnt_concurrent) > 1
</code>```

This query is an example of just one approach; there are other approaches we can use.

Body:
Given the table containing the columns: custID, startDate, endDate, etc.

How would one go about counting the highest number of rows that a customer generated existing within the same time period.

My thinking is that if you do a recursive JOIN and eliminate the rows that are identical you could compare A.startDate with B start and end dates.

I simply don't understand how to do this iterative process to find the highest number possible.

What I have right now look like this but it doesn't seem to work as intended.

SELECT DISTINCT A.custID, COUNT(A.custID) AS Concurrently
FROM T_Loan A JOIN T_Loan B
WHERE A.custID = B.custID AND NOT (A.endDate = B.endDate AND A.loanDate = B.startDate) AND A.startDate<= B.endDate AND A.startDate>= B.startDate
GROUP BY custID
HAVING Concurrently > 0;

Any advice or suggestions would be much appreciated

Body:
I'm a little confused by the comparison of loanDate to startDate in the query, and checking for a date range overlap seems to be referencing a wrong column.

Assuming that (custid,startdate,enddate) is a unique identifier for a row in T_Loan...  (ideally, we'd have a single column as a unique identifier for example, an id column as a surrogate primary key) and assuming that we're only interested in rows where all three of the columns are non-NULL...

Those are some big assumptions, but all we have to go on is the information provided in the question.

As a start, I'd figure out how to get a count of the number of rows in T_Loan that are for the same custid and are concurrent (that is, there's any amount of overlap in the start/end date ranges.)

For simplicity, I'd go ahead and include the current row in that count, so a row with no other concurrent rows would be reported with a count of 1 (the row itself). Here's how I'd do that:

SELECT a.custid
     , a.startdate
     , a.enddate
     , COUNT(b.custid)  AS cnt_concurrent
  FROM T_Loan a
  JOIN T_Loan b
    ON b.custid     = a.custid
   AND b.enddate   >= a.startdate
   AND b.startdate <= a.enddate
 GROUP
    BY a.custid
     , a.startdate
     , a.enddate

That gives us, for each row in T_Loan a count of the number of rows in T_Loan that are for the same custid and there's some overlap in the date range with the current row.

We can use the resultset returned by that query as a rowsource in another query.

For example, to get the maximum number of concurrent rows for each custid, we could do something like this:

SELECT c.custid
     , MAX(c.cnt_concurrent) AS max_cnt_concurrent
  FROM (
         SELECT a.custid
              , a.startdate
              , a.enddate
              , COUNT(b.custid)  AS cnt_concurrent
           FROM T_Loan a
           JOIN T_Loan b
             ON b.custid     = a.custid
            AND b.enddate   >= a.startdate
            AND b.startdate <= a.enddate
          GROUP
             BY a.custid
              , a.startdate
              , a.enddate
       ) c
 GROUP BY c.custid

This is going to include custid that have only one row in T_Loan, as well as custid where there are multiple rows, but no overlap in the date ranges. If we want to eliminate those rows (with a maximum concurrent count equal to 1), we can add a HAVING clause...

HAVING MAX(c.cnt_concurrent) > 1

This query is an example of just one approach; there are other approaches we can use.


问:
Create Border around image when clicked in JavaScript?
I'm working on an assignment for school and have been trying to get the code to run as it is supposed to. At this point all I need is for the Onclick to work. I try to put a border around each thumbnail image that is clicked and then have the border removed once another image is clicked. I have looked at multiple resources, but can't seem to get this to work at all. If anyone can provide assistance it would be really appreciated. I am extremely new to JavaScript and am pretty lost with the resources I've been given. My resolution needs to be purely in JavaScript without any JQuery.

// JavaScript Document //
var imgArray = new Array(
  //list of slides
  'chestnutp.jpg',
  'chestnuts.jpg',
  'elephant.jpg',
  'fall.jpg',
  'leaves.jpg'
);
var imgPath = "img/";

function swapImage(imgID) { //pulls image to larger area..
  var theImage = document.getElementById('largeImage');
  var newImg;
  newImg = imgArray[imgID];
  theImage.src = imgPath + newImg;
  var element = document.getElementById("id20");
  element.innerHTML = "New Fall Photo Gallery"; //Additional change to DOM; changes original name
}
var captionArray = [
  //list of captions
  'A chestnut coming out of a plant on a fall day.',
  'A bundle of chestnuts on the ground on a fall day.',
  'An Elephant walking on an African Fall evening.',
  'A fall display with flowers and pumpkins.',
  'Looking up at the leaves on a fall day.'
];

function swapCaption(ID) { //creates caption when larger image is shown
  var theCaption = document.getElementById('caption');
  var newCaption;
  newCaption = captionArray[ID];
  theCaption.innerHTML = newCaption;
}

function mark(ID) { //creates border
  document.getElementById(ID).style.border = "2px solid orange";
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>@charset "utf-8";

/* CSS Document */

body {
  background-color: #322F2F;
  font-family: Gotham, "Helvetica Neue", Helvetica, Arial, sans-serif;
}

* {
  box-sizing: border-box;
}

.col-1 {
  width: 8.33%;
}

.col-2 {
  width: 16.66%;
}

.col-3 {
  width: 25%;
}

.col-4 {
  width: 33.33%;
}

.col-5 {
  width: 41.66%;
}

.col-6 {
  width: 50%;
}

.col-7 {
  width: 58.33%;
}

.col-8 {
  width: 66.66%;
}

.col-9 {
  width: 75%;
}

.col-10 {
  width: 83.33%;
}

.col-11 {
  width: 91.66%;
}

.col-12 {
  width: 100%;
}

[class*="col-"] {
  float: left;
}

.row:after {
  content: "";
  clear: both;
  display: block;
}

#wrapper {
  height: auto;
  width: 60%;
  margin: auto;
}

h1 {
  font-size: 1.6em;
  color: #fff;
  text-align: center;
}

#thumbnails {
  height: 20%;
  width: 100%;
}

#thumbnails>img:hover {
  border: 1px #9D9C9C solid;
}

.thumbDown {
  border: none;
}

.thumbUp {
  border: 1px #9D9C9C solid;
}

.largeImage {
  height: 100%;
  width: 100%;
}

.caption {
  font-size: .9em;
  height: 25px;
  width: 100%;
  color: #fff;
}</code>```

<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Fall Air Photo Gallery</title>

  <link rel="stylesheet" type="text/css" href="css/style.css" />

Fall Air Photo Gallery

```

答:
$(document).ready(function() {
$(document).on("click","#thumbnails img",function(){
 $(this).css("border","5px solid orange");
 $("#thumbnails img").not($(this)).css("border","none");
});
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#thumbnails > img{
 border-radius:50%;
}</code>```

```

Body:
I'm working on an assignment for school and have been trying to get the code to run as it is supposed to. At this point all I need is for the Onclick to work. I try to put a border around each thumbnail image that is clicked and then have the border removed once another image is clicked. I have looked at multiple resources, but can't seem to get this to work at all. If anyone can provide assistance it would be really appreciated. I am extremely new to JavaScript and am pretty lost with the resources I've been given. My resolution needs to be purely in JavaScript without any JQuery.

// JavaScript Document //
var imgArray = new Array(
  //list of slides
  'chestnutp.jpg',
  'chestnuts.jpg',
  'elephant.jpg',
  'fall.jpg',
  'leaves.jpg'
);
var imgPath = "img/";

function swapImage(imgID) { //pulls image to larger area..
  var theImage = document.getElementById('largeImage');
  var newImg;
  newImg = imgArray[imgID];
  theImage.src = imgPath + newImg;
  var element = document.getElementById("id20");
  element.innerHTML = "New Fall Photo Gallery"; //Additional change to DOM; changes original name
}
var captionArray = [
  //list of captions
  'A chestnut coming out of a plant on a fall day.',
  'A bundle of chestnuts on the ground on a fall day.',
  'An Elephant walking on an African Fall evening.',
  'A fall display with flowers and pumpkins.',
  'Looking up at the leaves on a fall day.'
];

function swapCaption(ID) { //creates caption when larger image is shown
  var theCaption = document.getElementById('caption');
  var newCaption;
  newCaption = captionArray[ID];
  theCaption.innerHTML = newCaption;
}

function mark(ID) { //creates border
  document.getElementById(ID).style.border = "2px solid orange";
}

@charset "utf-8";

/* CSS Document */

body {
  background-color: #322F2F;
  font-family: Gotham, "Helvetica Neue", Helvetica, Arial, sans-serif;
}

* {
  box-sizing: border-box;
}

.col-1 {
  width: 8.33%;
}

.col-2 {
  width: 16.66%;
}

.col-3 {
  width: 25%;
}

.col-4 {
  width: 33.33%;
}

.col-5 {
  width: 41.66%;
}

.col-6 {
  width: 50%;
}

.col-7 {
  width: 58.33%;
}

.col-8 {
  width: 66.66%;
}

.col-9 {
  width: 75%;
}

.col-10 {
  width: 83.33%;
}

.col-11 {
  width: 91.66%;
}

.col-12 {
  width: 100%;
}

[class*="col-"] {
  float: left;
}

.row:after {
  content: "";
  clear: both;
  display: block;
}

#wrapper {
  height: auto;
  width: 60%;
  margin: auto;
}

h1 {
  font-size: 1.6em;
  color: #fff;
  text-align: center;
}

#thumbnails {
  height: 20%;
  width: 100%;
}

#thumbnails>img:hover {
  border: 1px #9D9C9C solid;
}

.thumbDown {
  border: none;
}

.thumbUp {
  border: 1px #9D9C9C solid;
}

.largeImage {
  height: 100%;
  width: 100%;
}

.caption {
  font-size: .9em;
  height: 25px;
  width: 100%;
  color: #fff;
}

<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Fall Air Photo Gallery</title>

  <link rel="stylesheet" type="text/css" href="css/style.css" />

Fall Air Photo Gallery

Body:
$(document).ready(function() {
$(document).on("click","#thumbnails img",function(){
 $(this).css("border","5px solid orange");
 $("#thumbnails img").not($(this)).css("border","none");
});
});

#thumbnails > img{
 border-radius:50%;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="thumbnails">
<img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTMZPrNzLxySwT9GuHbz33ZyNXFJtBrqg_ruleaepzXq2zf3NOewA"/>
<img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTMZPrNzLxySwT9GuHbz33ZyNXFJtBrqg_ruleaepzXq2zf3NOewA"/>
<img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTMZPrNzLxySwT9GuHbz33ZyNXFJtBrqg_ruleaepzXq2zf3NOewA"/>
</div>


问:
Trouble controlling the loops
If pressed delet , All images are deleted ,I do not want that.
I just want to delete one image.</p>

```<code>$get_img = "SELECT * FROM img";
$run_img = mysqli_query($db,$get_img);

while ($row_img= mysqli_fetch_array($run_img)){
    if (isset($_POST['delete'])){
        $delete= "DELETE FROM img WHERE id = {$row_img['id']} ";
        $query = mysqli_query ($db , $delete);
    }

    echo '
        <div style="width:200px; height:200px;  border: 5px solid red; margin:10px; float: right;">
            <img src="images/'.$row_pro['c_img'].'" width="200" height="200" /><br />
            <form action="get.php" method="POST">
                <input type="submit" name="delet" value="delet" />
            </form>
        </div>
    ';
}
</code>```

答:
Just a little explain, we start talking Arabic because Mostafa is not good in english, so i wrote a little explain in English and Arabic below to help to help both languages users.

```<code>while($row_img = mysqli_fetch_array($run_img)){

//explain [1]
    echo '
    <div style="width:200px; height:200px;  border: 5px solid red; margin:10px; float: right;">
        <img src="images/'.$row_img['c_img'].'" width="200" height="200" /><br />
        <form action="?" method="POST">
        <input name="id" value="'.$row_img['id'].'" hidden><!-- //explain [2] -->
        <input type="submit" name="delet" value="delet" />
        </form>
    </div>
    ';
}
if(isset($_POST['delet'])){
    $id = intval($_POST['id']);//explain [3]
    $delete= "DELETE FROM img WHERE id = '$id'";
    $query = mysqli_query($db, $delete);
    if($query){
        echo 'Deleted Successfully!';
    }
}
</code>```

explain [1] Remove the query from inside while its bad to put it there

explain [2] Then i made a hidden input called id to get the id from it

explain [3] Make the hidden sent id to $id variable and intval it for more security, you can read about it

.

explain [1] اول حاجة شلت الكويري إلي انت كاتبها جوا ال while

explain [2] بعدين سويت زر مخفي مع كل صورة إسمه أي دي يعطينا الاي دي الخاص فيها

explain [3] بعدين بستقبل الاي دي إلى بالزر المخفي على متغير جديد وبسويله شوية حماية.

I hope this helps you :)

Title: Trouble controlling the loops

Body:
If pressed delet , All images are deleted ,I do not want that.
I just want to delete one image.

$get_img = "SELECT * FROM img";
$run_img = mysqli_query($db,$get_img);

while ($row_img= mysqli_fetch_array($run_img)){
    if (isset($_POST['delete'])){
        $delete= "DELETE FROM img WHERE id = {$row_img['id']} ";
        $query = mysqli_query ($db , $delete);
    }

    echo '

            <form action="get.php" method="POST">
                <input type="submit" name="delet" value="delet" />
            </form>

    ';
}

Body:
Just a little explain, we start talking Arabic because Mostafa is not good in english, so i wrote a little explain in English and Arabic below to help to help both languages users.

while($row_img = mysqli_fetch_array($run_img)){

//explain [1]
    echo '
    <div style="width:200px; height:200px;  border: 5px solid red; margin:10px; float: right;">
        <img src="images/'.$row_img['c_img'].'" width="200" height="200" /><br />
        <form action="?" method="POST">
        <input name="id" value="'.$row_img['id'].'" hidden><!-- //explain [2] -->
        <input type="submit" name="delet" value="delet" />
        </form>
    </div>
    ';
}
if(isset($_POST['delet'])){
    $id = intval($_POST['id']);//explain [3]
    $delete= "DELETE FROM img WHERE id = '$id'";
    $query = mysqli_query($db, $delete);
    if($query){
        echo 'Deleted Successfully!';
    }
}

explain [1] Remove the query from inside while its bad to put it there

explain [2] Then i made a hidden input called id to get the id from it

explain [3] Make the hidden sent id to $id variable and intval it for more security, you can read about it

.

explain [1] اول حاجة شلت الكويري إلي انت كاتبها جوا ال while

explain [2] بعدين سويت زر مخفي مع كل صورة إسمه أي دي يعطينا الاي دي الخاص فيها

explain [3] بعدين بستقبل الاي دي إلى بالزر المخفي على متغير جديد وبسويله شوية حماية.

I hope this helps you :)


问:
what `extends (() => Unit)` mean?
What does following syntax mean? What is being extended, Function1?

```<code>trait AlarmHandler extends (() => Unit)
</code>```

答:
In general (T1, ..., TN) => T is syntactic sugar for FunctionN[T1, ..., TN, T], so () => Unit is syntactic sugar for Function0[Unit].

So in your code AlarmHandler extends Function0[Unit].

Title: what `extends (() => Unit)` mean?

Body:
What does following syntax mean? What is being extended, Function1?

trait AlarmHandler extends (() => Unit)


问:
Block spam from "tell a friend" forms
You have to have a form on your website for people to send an email to a friend if they found something interesting. You can force people to be logged in (which is not a good option in my case). You can make time delay (this is not really urgent email, so it can wait for 5 minutes). Do you have this problem? How would you solve it?

Edit: I am mostly interested in stopping manual spam

答:
The best solution is to use an all-purpose bot filtering solution. I know this is an old post, but a new botnet was discovered that uses these send to a friend modules to send spam (not a new technique but some interesting new advancements).

According to one security vendor (good tips), “At a minimum, they should include a rate-limiting mechanism that will prevent an IP address from issuing unreasonable numbers of requests over a specific period of time. Other DIY solutions are to have all users fill in CAPTCHAs and to enforce registration as a prerequisite to sending out an email message.”

Title: Block spam from "tell a friend" forms


问:
Current date time in specific timezone with and without DST offset with NodaTime
I need to sync a device internal clock on a device according to which timezone the users has selected.
I'm using the following code to get the current time for that zone with respect to the system clock:

```<code>var currentInstant = SystemClock.Instance.GetCurrentInstant().InZone(userTimezone);
</code>```

But I also need to be able to toggle a flag that enables/disables DST for the zone, meaning if the zone currently has DST active I need to be able to subtract the offset it adds, and only set the internal clock to the zone time with the standard offset.

I found the standard offset with (not 100% this is correct though):

```<code>currentInstant.GetZoneInterval().StandardOffset;
</code>```

But I'm not sure how to get the zone time using it?

答:
It sounds like you're nearly there. You presumably want the OffsetDateTime or LocalDateTime, which you'd get like this:

```<code>var now = SystemClock.Instance.GetCurrentInstant();
var zoneInterval = zone.GetZoneInterval(now);
var offset = zoneInterval.StandardOffset; // Ignore any savings
OffsetDateTime offsetNow = now.WithOffset(offset);
</code>```

You can get the LocalDateTime with offsetNow.LocalDateTime if you need that.

At that point, you don't have a ZonedDateTime, because you don't really have a time zone as such - your "zone without DST" isn't a regular time zone. But it sounds like it's what you need.

As Matt said, this is a fundamentally bad idea - I know you've tried to convince your client of that already, but it's probably worth thinking ahead and working out what you'll do when your client understands that it's a bad idea too...

Body:
I need to sync a device internal clock on a device according to which timezone the users has selected.
I'm using the following code to get the current time for that zone with respect to the system clock:

var currentInstant = SystemClock.Instance.GetCurrentInstant().InZone(userTimezone);

But I also need to be able to toggle a flag that enables/disables DST for the zone, meaning if the zone currently has DST active I need to be able to subtract the offset it adds, and only set the internal clock to the zone time with the standard offset.

I found the standard offset with (not 100% this is correct though):

currentInstant.GetZoneInterval().StandardOffset;

But I'm not sure how to get the zone time using it?

Body:
It sounds like you're nearly there. You presumably want the OffsetDateTime or LocalDateTime, which you'd get like this:

var now = SystemClock.Instance.GetCurrentInstant();
var zoneInterval = zone.GetZoneInterval(now);
var offset = zoneInterval.StandardOffset; // Ignore any savings
OffsetDateTime offsetNow = now.WithOffset(offset);

You can get the LocalDateTime with offsetNow.LocalDateTime if you need that.

At that point, you don't have a ZonedDateTime, because you don't really have a time zone as such - your "zone without DST" isn't a regular time zone. But it sounds like it's what you need.

As Matt said, this is a fundamentally bad idea - I know you've tried to convince your client of that already, but it's probably worth thinking ahead and working out what you'll do when your client understands that it's a bad idea too...


问:
iPhone - content won't scroll while image is loaded from URL
I'm trying to do something in my iPhone app where it downloads an image from a URL. The image downloads fine on the page, but I can't scroll through content or interact with it in any other way until the images download, making the app feels like it's frozen at first.

I've just used this code to load the image:

```<code>- (void)viewDidAppear:(BOOL)animated
{
    *photo1.image = [UIImage imageWithData:
        [NSData dataWithContentsOfURL:
            [NSURL URLWithString:@"http://www.ikipond.com/wp-includes/images/cosplayipn/will_1.png"]
         ]
    ];
}
</code>```

I'd really appreciate a suggestion of how to make it so users can interact with the page while the images are still downloading. Thanks a lot,

Chris

答: The dataWithContentsOfURL: method blocks until the download is complete, and is thus blocking the main (GUI) thread. You need to download the image asynchronously  (using NSURLConnection) or in a background thread.

Body:
I'm trying to do something in my iPhone app where it downloads an image from a URL. The image downloads fine on the page, but I can't scroll through content or interact with it in any other way until the images download, making the app feels like it's frozen at first.

I've just used this code to load the image:

- (void)viewDidAppear:(BOOL)animated
{
    *photo1.image = [UIImage imageWithData:
        [NSData dataWithContentsOfURL:
            [NSURL URLWithString:@"http://www.ikipond.com/wp-includes/images/cosplayipn/will_1.png"]
         ]
    ];
}

I'd really appreciate a suggestion of how to make it so users can interact with the page while the images are still downloading. Thanks a lot,

Chris