问:
Javascript - Check numeric range overlapping in array
I have an array of time ranges with start & end values.

```<code>var timeRanges = [{
    start: 120,
    end: 140
},{
    start: 180,
    end: 220
},{
    start: 250,
    end: 300
}]
</code>```

Need to check whether the selected range overlap the time range or not. And also the selected range should be in between the timeRange intervals. (Ex: 140-180, 220-250)

```<code>var selected = {
    start: 150,
    end: 170
}
</code>```

答:
```<code> const overlaps = timeRanges.some( range =>
  (range.start < selected.start && range.end > selected.start) ||
  (range.start < selected.end && range.end > selected.end) ||
  (range.start > selected.start && range.end < selected.end)
 );
</code>```

Body:
I have an array of time ranges with start & end values.

var timeRanges = [{
    start: 120,
    end: 140
},{
    start: 180,
    end: 220
},{
    start: 250,
    end: 300
}]

Need to check whether the selected range overlap the time range or not. And also the selected range should be in between the timeRange intervals. (Ex: 140-180, 220-250)

var selected = {
    start: 150,
    end: 170
}

ContentLicense: CC BY-SA 4.0


来源: stackexchange

问:
Cookies resetting on page refresh but only certain user
I knocked together an advent calendar for a friend of mine and I use cookies to store whether or not she has "opened" a door - if she has, it shows a thumbnail of the contents. If she hasn't, it shows the "unopened" background. Now, I've had this working fine on my computer and in Chrome, FF and IE for over a month now.

Unfortunately, my friend isn't having the same result. When she loads the page, it shows as pristine and unopened every time. The thing is, when she clicks on it to "open" the door, it updates to show the thumbnail and if I get her to click on the padlock at the top of the address bar in Chrome, it shows that the cookies have been created and the correct one has been updated. Unfortunately as soon as the page is refreshed, it's somehow overwriting the cookie value.

Before clicking on Door 1 - cookie value is 0

After clicking on Door 1 - cookie value is 1

And yet when she refreshes the page, the cookie value is set back to 0 again.

I have NO idea what would make it do that. There IS a piece of code that checks if a specific cookie exists and if not, creates the list the cookies, but even disabling that script call doesn't stop the problem. If anyone has any ideas, I'd appreciate it because I've tried everything I can think of to make sure the cookies are being set properly and I'm not sure why they aren't persisting for her. I've asked her to check setting for storing cookies, extensions, ad blocking/script blocking stuff, antivirus, etc.

We're both using Chrome on Win 10 - it works for me, but not her.

Thanks in advance, I'm sure its something really simple and I'm just being slow-witted.

The website is here.

答: Started working spontaneously. </p>

ContentLicense: CC BY-SA 3.0

Body: Started working spontaneously.


问:
how to adjust vector objects in small size with same appearance
I have little problem here.

I want to make vector icon in 16*16 pixel.

this what i face:

vector image in 600% zoom display

vector image in 100 % display

this is .png icon 16*16 is perfect display and this what I want to make

any suggestions ?

答:
I was searching and found the solution.

Just go to from menu.

View -> Pixel Preview

will show me how it appears then I can adjust the design

Thanks.


问:
JavaScript time convert
I am very new to JavaScript. My guess is that there is a very easy answer.
I need to convert time in the format hh:mm:ss to Seconds.

答:
You can do something like this:</p>

```<code>var s = "1:01:01";
var a = s.split(":");

var sec = parseInt(a[0], 10)*60*60;
sec += parseInt(a[1], 10)*60;
sec += parseInt(a[2], 10);

alert(sec);
</code>```

ContentLicense: CC BY-SA 2.5

Title: JavaScript time convert

Body:
You can do something like this:

var s = "1:01:01";
var a = s.split(":");

var sec = parseInt(a[0], 10)*60*60;
sec += parseInt(a[1], 10)*60;
sec += parseInt(a[2], 10);

alert(sec);


问:
How to ignore last row in filter suggestion in MS Excel?

Here Two columns filter contain its data, Data1 column filter contain 2,2,3,4 and 11. but 11 is a sum of that column using formula. How can i ignore it from filter suggestion?

答:
You have basically two options:

Format each column as one table and make a total row:

2.Use the Subtotal Function. For example:

```<code>=SUBTOTAL(9;I5:I8)
</code>```

Though I might have missed some other options.

Body:
You have basically two options:

Format each column as one table and make a total row:

2.Use the Subtotal Function. For example:

=SUBTOTAL(9;I5:I8)

Though I might have missed some other options.


答:
Why don't you run your selection through the array and calculate what you need?</p>

```<code>timeRanges.forEach(function(aRange, index)) {

   if (selected.start > aRange.start && selected.end < aRange.end)
      console.log('Selection falls within the item ' + index):

}
</code>```

Title: Javascript - Check numeric range overlapping in array

Body:
Why don't you run your selection through the array and calculate what you need?

timeRanges.forEach(function(aRange, index)) {

   if (selected.start > aRange.start && selected.end < aRange.end)
      console.log('Selection falls within the item ' + index):

}


问:
TFS 2017 web application not displaying well
We installed TFS 2017 update 3 and we are having issues when displaying the icons in the web application. We are having issues with the "Files" section inside "Code" for each one of our projects, the contents of the files aren't displaying. In the browser console, we can see these issues. Our Bowtie.woff file has 39KB.

CSS3111: @font-face encountered unknown error. bowtie.eot

CSS3111: @font-face encountered unknown error. bowtie.woff

CSS3111: @font-face encountered unknown error. fabricmdl2icons.woff

CSS3114: @font-face failed OpenType embedding permission check.
  Permission must be Installable. fabricmdl2icons.ttf

CSS3111: @font-face encountered unknown error. fabricmdl2icons.woff

CSS3114: @font-face failed OpenType embedding permission check.
  Permission must be Installable. fabricmdl2icons.ttf

The request are showing errors:

_content/Fonts/Icons/bowtie.eot?iefix                500 internal server error

_content/Fonts/Icons/bowtie.woff                      500 internal server error

_content/Fonts/Icons/bowtie.eot?iefix                500 internal server error

/_scripts/TFS/min/VersionControl/scenarios/Shared/HookSplitterResizeEventToNativeEvent.js
  500 internal server error

_content/Extensions/CodeEditor/0.8.3/vs/Editor/editor.main.css 500 internal server error

_scripts/Extensions/min/TFS.extension.js     500 internal server error

答:
I checked the Bowtie.woff file on my side, it's also 39KB. Seems it's not caused by the file.

Seems it's related to the privilege of the service account.

If you are seeing HTTP 500 when servicing static content, most likely
  your service account does not have "Impersonate a client after
  authentication" privilege.

Refer to Vladimir's answer in this thread : TFS 2017 Missing Icons

To check/add permission you can do the following:

Windows Start > Administrative Tools

Open "Local Security Policy" editor.

Navigate to Security Settings  Local Policies > User
Rights Assignment

Double click on "Impersonate a client after authentication"

Another possibility is the web.config file issue which under below path:

```<code> C:\Program Files\Microsoft Team Foundation Server 15.0\Application Tier\Web Services\_static\tfs\Dev15.M125.1\_content\Fonts
</code>```

Refer to this thred for details : TFS 2015 Update 2 Missing Icons

Body:
I checked the Bowtie.woff file on my side, it's also 39KB. Seems it's not caused by the file.

Seems it's related to the privilege of the service account.

If you are seeing HTTP 500 when servicing static content, most likely
  your service account does not have "Impersonate a client after
  authentication" privilege.

Refer to Vladimir's answer in this thread : TFS 2017 Missing Icons

To check/add permission you can do the following:

Windows Start > Administrative Tools

Open "Local Security Policy" editor.

Navigate to Security Settings  Local Policies > User
Rights Assignment

Double click on "Impersonate a client after authentication"

Another possibility is the web.config file issue which under below path:

 C:\Program Files\Microsoft Team Foundation Server 15.0\Application Tier\Web Services\_static\tfs\Dev15.M125.1\_content\Fonts

Refer to this thred for details : TFS 2015 Update 2 Missing Icons


问:
Seperator in laravel
I am trying to use seperator inside my join statement but it keep on doesn't work. I tried following some website and question to do but still doesn't work. Can someone guide me on where did I go wrong? Could it be because of the way I use it?

Here is the code:

```<code>$data = PersonalInfo::join('evaluations','evaluations.user_id', '=', 'personal_infos.id')
-> join('qualifications', 'personal_infos.id', '=', 'qualifications.user_id')
-> join( 'language_proficiencies', 'personal_infos.id', '=', 'language_proficiencies.user_id')
-> join( 'families', 'personal_infos.id', '=', 'families.user_id')

    ->select(
      'language_proficiencies.meta_value as Language',
      'qualifications.meta_value as Education',
      'families.meta_value as Immediate Family',
      'personal_infos.name as Name',
      'personal_infos.created_at as Date')
    ->whereDate('personal_infos.created_at', '=', date('Y-m-d'))
    ->where('evaluations.Evaluation_Status', '=', 'Yes')
    ->where('language_proficiencies.meta_key' , '=', 'Language_Name')
    ->where('qualifications.meta_key' , '=', 'qualification_list')
    ->where('families.meta_key' , '=', 'relationshiplist')
    ->get()
    ->sortByDesc('created_at');
</code>```

I did something like this but it doesn't work

```<code>   // DB::raw("(GROUP_CONCAT(language_proficiencies.meta_value SEPARATOR ', ')) as 'Language'",
     // DB::raw("(GROUP_CONCAT(qualifications.meta_value SEPARATOR ', ')) as 'Education'",
       // DB::raw("(GROUP_CONCAT(families.meta_value SEPARATOR ', ')) as 'Immediate Family'",

     // GROUP_CONCAT(language_proficiencies.meta_value SEPARATOR ', ') as 'Language',
      //GROUP_CONCAT(qualifications.meta_value SEPARATOR ', ') as 'Education',
      //GROUP_CONCAT(families.meta_value  SEPARATOR ', ') as 'Immediate Family',
</code>```

EDIT:
Just want to do separator on qualification, language_proficiencies and families, I removed some codes to prevent it from being too messy.

答:
To use GROUP_CONCAT you should use GROUP BY clause because its an aggregate function, with grouping criteria your whole table will be considered as a single group and the values of all rows concatenated as comma separated list or a list with your defined separator

```<code>$data = PersonalInfo::join('evaluations','evaluations.user_id', '=', 'personal_infos.id')
    -> join('qualifications', 'personal_infos.id', '=', 'qualifications.user_id')
    -> join( 'language_proficiencies', 'personal_infos.id', '=', 'language_proficiencies.user_id')
    -> join( 'families', 'personal_infos.id', '=', 'families.user_id')
    ->select(
      DB::raw("(GROUP_CONCAT(language_proficiencies.meta_value SEPARATOR ', ')) as Language"),
      DB::raw("(GROUP_CONCAT(qualifications.meta_value SEPARATOR ', ')) as Education"),
      DB::raw("(GROUP_CONCAT(families.meta_value SEPARATOR ', ')) as ImmediateFamily"),
      'personal_infos.name as Name',
      'personal_infos.created_at as Date')
    ->whereDate('personal_infos.created_at', '=', date('Y-m-d'))
    ->where('evaluations.Evaluation_Status', '=', 'Yes')
    ->where('language_proficiencies.meta_key' , '=', 'Language_Name')
    ->where('qualifications.meta_key' , '=', 'qualification_list')
    ->where('families.meta_key' , '=', 'relationshiplist')
    ->groupBy('personal_infos.name')
    ->groupBy('personal_infos.created_at')
    ->get()
    ->sortByDesc('created_at');
</code>```

Also note there is a limitation on character limit using GROUP_CONCAT as per docs The result is truncated to the maximum length that is given by the group_concat_max_len system variable, which has a default value of 1024. The value can be set higher, although the effective maximum length of the return value is constrained by the value of max_allowed_packet

Title: Seperator in laravel

Body:
I am trying to use seperator inside my join statement but it keep on doesn't work. I tried following some website and question to do but still doesn't work. Can someone guide me on where did I go wrong? Could it be because of the way I use it?

Here is the code:

$data = PersonalInfo::join('evaluations','evaluations.user_id', '=', 'personal_infos.id')
-> join('qualifications', 'personal_infos.id', '=', 'qualifications.user_id')
-> join( 'language_proficiencies', 'personal_infos.id', '=', 'language_proficiencies.user_id')
-> join( 'families', 'personal_infos.id', '=', 'families.user_id')

    ->select(
      'language_proficiencies.meta_value as Language',
      'qualifications.meta_value as Education',
      'families.meta_value as Immediate Family',
      'personal_infos.name as Name',
      'personal_infos.created_at as Date')
    ->whereDate('personal_infos.created_at', '=', date('Y-m-d'))
    ->where('evaluations.Evaluation_Status', '=', 'Yes')
    ->where('language_proficiencies.meta_key' , '=', 'Language_Name')
    ->where('qualifications.meta_key' , '=', 'qualification_list')
    ->where('families.meta_key' , '=', 'relationshiplist')
    ->get()
    ->sortByDesc('created_at');

I did something like this but it doesn't work

   // DB::raw("(GROUP_CONCAT(language_proficiencies.meta_value SEPARATOR ', ')) as 'Language'",
     // DB::raw("(GROUP_CONCAT(qualifications.meta_value SEPARATOR ', ')) as 'Education'",
       // DB::raw("(GROUP_CONCAT(families.meta_value SEPARATOR ', ')) as 'Immediate Family'",

     // GROUP_CONCAT(language_proficiencies.meta_value SEPARATOR ', ') as 'Language',
      //GROUP_CONCAT(qualifications.meta_value SEPARATOR ', ') as 'Education',
      //GROUP_CONCAT(families.meta_value  SEPARATOR ', ') as 'Immediate Family',

EDIT:
Just want to do separator on qualification, language_proficiencies and families, I removed some codes to prevent it from being too messy.

Body:
To use GROUP_CONCAT you should use GROUP BY clause because its an aggregate function, with grouping criteria your whole table will be considered as a single group and the values of all rows concatenated as comma separated list or a list with your defined separator

$data = PersonalInfo::join('evaluations','evaluations.user_id', '=', 'personal_infos.id')
    -> join('qualifications', 'personal_infos.id', '=', 'qualifications.user_id')
    -> join( 'language_proficiencies', 'personal_infos.id', '=', 'language_proficiencies.user_id')
    -> join( 'families', 'personal_infos.id', '=', 'families.user_id')
    ->select(
      DB::raw("(GROUP_CONCAT(language_proficiencies.meta_value SEPARATOR ', ')) as Language"),
      DB::raw("(GROUP_CONCAT(qualifications.meta_value SEPARATOR ', ')) as Education"),
      DB::raw("(GROUP_CONCAT(families.meta_value SEPARATOR ', ')) as ImmediateFamily"),
      'personal_infos.name as Name',
      'personal_infos.created_at as Date')
    ->whereDate('personal_infos.created_at', '=', date('Y-m-d'))
    ->where('evaluations.Evaluation_Status', '=', 'Yes')
    ->where('language_proficiencies.meta_key' , '=', 'Language_Name')
    ->where('qualifications.meta_key' , '=', 'qualification_list')
    ->where('families.meta_key' , '=', 'relationshiplist')
    ->groupBy('personal_infos.name')
    ->groupBy('personal_infos.created_at')
    ->get()
    ->sortByDesc('created_at');

Also note there is a limitation on character limit using GROUP_CONCAT as per docs The result is truncated to the maximum length that is given by the group_concat_max_len system variable, which has a default value of 1024. The value can be set higher, although the effective maximum length of the return value is constrained by the value of max_allowed_packet


问:
How to run Multiple external commands from Python Script
I have a requirement where I have to run these few commands in the terminal using a python script.The requirement is as such:

ssh abc.xyz.com

After ssh to that machine, ssh to the environment

ssh qa

and then run few commands in the environment

I have tried achieving this using os.system() and using subprocess.call() but no luck.

Specifically, I tried doing this :

```<code>import subprocess
from time import sleep
subprocess.call("ssh abc.def.com", shell=True)
subprocess.call("python", shell=True)
sleep(0.3)
subprocess.call("ssh qa", shell=True)
</code>```

答:
i am not sure about your approach of connecting to remote server and executing command there with subprocess.

Instead You can use paramiko module to connect with remote server and execute command

```<code>import paramiko
ssh=paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('192.168.1.26',port=22,username='root',password='default')

# you can use your own commands in exec_command()

stdin,stdout,stderr=ssh.exec_command('echo 123')
output=stdout.readlines()
print '\n'.join(output)
</code>```

Body:
I have a requirement where I have to run these few commands in the terminal using a python script.The requirement is as such:

ssh abc.xyz.com

After ssh to that machine, ssh to the environment

ssh qa

and then run few commands in the environment

I have tried achieving this using os.system() and using subprocess.call() but no luck.

Specifically, I tried doing this :

import subprocess
from time import sleep
subprocess.call("ssh abc.def.com", shell=True)
subprocess.call("python", shell=True)
sleep(0.3)
subprocess.call("ssh qa", shell=True)

Body:
i am not sure about your approach of connecting to remote server and executing command there with subprocess.

Instead You can use paramiko module to connect with remote server and execute command

import paramiko
ssh=paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('192.168.1.26',port=22,username='root',password='default')

# you can use your own commands in exec_command()

stdin,stdout,stderr=ssh.exec_command('echo 123')
output=stdout.readlines()
print '\n'.join(output)


问:
Thread-safe C++ wrapper around a lex/yacc parser
I am trying to write a JSON parser (instead of using one of the freely available ones, because of certain project constraints) and have written lex+yacc based version with a simple wrapper C++ class. I have redefined the YY_INPUT macro for lex to read from a memory buffer. Now the deal is to ensure that the parser is thread-safe and I am not sure how easy it is to ensure that. There are two concerns:

Ultimately YY_INPUT is reading from a global object. I could not think of another way of doing this.

I have no idea how many globals does the generated lex/yacc code end up using.

Would be great if folks can share their experience of doing something similar.

Cheers.

PS. We don' t use STL/string or any templates for that matter. We use our own variant-based containers. We use lex+yacc rather than flex+bison, on four major Unices.

答: I don't have much experience working directly with yacc, but I know that bison supports reentrant parsers that are thread-safe.  It also looks like lex supports a reentrant lexer as well, and I'd guess that if you put the two together it should work out just fine.


问:
tableview not filling up entire screen in storyboard with a navigation bar
Hi I am new to iOS app development, xcode and swift. Im not sure if this is a problem or what is causing this but when designing my tableview in storyboards and adding constraints all the way round (0,0,0,0) and then segue from my navigation bar to my view controller. My Top constraint drops right under the navigation bar. Initially it does not do this but happens randomly. (Don't want any navigation issues or views being hidden down the line) Link to storyboard problem. I do not know whats causing this please help. can't upload photos provided a link. Thank you

答: Select viewcontroller in storyboard and uncheck Adjust scroll view insects box in property inspector.


问:
cannot sort an ArrayList of objects in java--Not allowed to use Comparator
I'm new to programming and I'm having some difficulties sorting an ArrayList of objects with a date and time attribute into chronological order. I have run many tests on my isBefore method, which determines which Tweet object is before the other, and have determined it to be fine. This means that my issue is probably in the algorithm I use to sort my ArrayList.

```<code> private void sortTwitter(){
  ArrayList<Tweet> temp = new ArrayList<Tweet>();

   while(getSizeTwitter()>1){

     int indexOfEarliest = 0;

     for(int i = 0; i<getSizeTwitter(); i++){ //finds the index of the earliest tweet in the tweets ArrayList

       //The Tweet object at [0] is tweets.get(0).
       //The Tweet object we want to compare it to initially is tweets.get(1). Specifically, we want tweets.get(1).getDate() and .getTime()
       Tweet tweet1 = this.tweets.get(indexOfEarliest);
       Tweet tweet2 = this.tweets.get(i);
       boolean tweet1Earlier = tweet1.isBefore(tweet2.getDate(), tweet2.getTime());

       if(tweet1Earlier == false){ //Supposed to update the value of indexOfEarliest to the index of tweet2 is tweet2 is earlier.
         indexOfEarliest = i;
       }

     }

     temp.add(this.tweets.get(indexOfEarliest));
     this.tweets.remove(indexOfEarliest);
   }

   //Now tweets is an array of 1 element, the largest.
   temp.add(this.tweets.get(0));
   this.tweets.clear();
   this.tweets = temp;

  }
</code>```

If I run the full program without the sorting method, I get this as output:

Without "sorting"

If I use the "sorting" algorithm, I get this:

With "sorting"

If anyone could please explain to me what I am doing wrong or point me in the right direction, I would be very grateful. Thanks!

Update: isBefore

```<code>public boolean isBefore(String sTestDate, String sTestTime){

    String[] splitTweetDate = this.date.split("-"); //Reconfigures the format of Tweet instance date and time
    String[] splitTweetTime = this.time.split(":");
    int[] tweetDate = stringToInt(splitTweetDate);
    int[] tweetTime = stringToInt(splitTweetTime);

    String[] splitTestDate = sTestDate.split("-"); //Reconfigures the format of query parameters
    String[] splitTestTime = sTestTime.split(":");
    int[] testDate = stringToInt(splitTestDate);
    int[] testTime = stringToInt(splitTestTime);

    for(int i = 0; i<3; i++){ //Tests the date year first, then month, then day. Returns true if tweetDate is earlier than testDate.
      if(tweetDate[i]<testDate[i]){
        return true;
      }
    }

    for(int i = 0; i<3; i++){ //If on the same day, tests hour first, then minutes, then seconds. Returns true if tweetTime is earlier than testDate.
      if(tweetTime[i]<testTime[i]){
        return true;
      }
    }

    return false; //If method returns nothing, message was posted at the same time or later.

  }

  //HELPER 2
  private int[] stringToInt(String[] arrString){ //converts an array of strings into an array of integers.
    int[] arrInt = new int[arrString.length];

    for(int i = 0; i<arrInt.length; i++){ //parseing the elements of the string array to integers.
      arrInt[i] = Integer.parseInt(arrString[i]);
    }

    return arrInt;
  }
</code>```

Someone has suggested that I use compares and I will if no-other solution is presented to me but I don't think I am technically allowed to (this is for an assignment).

答: Create separate sorting mechanism by using java.util.Comparator and provide criteria by comparing java.util.Date and simply call Collection.sort(<customList>, Comparator<>); thats it, no need to loop manually. please check examples how to implement Comparator using java.util.Date, you will get an idea. it will reduce your number of lines of code as well.

Body:
I'm new to programming and I'm having some difficulties sorting an ArrayList of objects with a date and time attribute into chronological order. I have run many tests on my isBefore method, which determines which Tweet object is before the other, and have determined it to be fine. This means that my issue is probably in the algorithm I use to sort my ArrayList.

 private void sortTwitter(){
  ArrayList<Tweet> temp = new ArrayList<Tweet>();

   while(getSizeTwitter()>1){

     int indexOfEarliest = 0;

     for(int i = 0; i<getSizeTwitter(); i++){ //finds the index of the earliest tweet in the tweets ArrayList

       //The Tweet object at [0] is tweets.get(0).
       //The Tweet object we want to compare it to initially is tweets.get(1). Specifically, we want tweets.get(1).getDate() and .getTime()
       Tweet tweet1 = this.tweets.get(indexOfEarliest);
       Tweet tweet2 = this.tweets.get(i);
       boolean tweet1Earlier = tweet1.isBefore(tweet2.getDate(), tweet2.getTime());

       if(tweet1Earlier == false){ //Supposed to update the value of indexOfEarliest to the index of tweet2 is tweet2 is earlier.
         indexOfEarliest = i;
       }

     }

     temp.add(this.tweets.get(indexOfEarliest));
     this.tweets.remove(indexOfEarliest);
   }

   //Now tweets is an array of 1 element, the largest.
   temp.add(this.tweets.get(0));
   this.tweets.clear();
   this.tweets = temp;

  }

If I run the full program without the sorting method, I get this as output:

Without "sorting"

If I use the "sorting" algorithm, I get this:

With "sorting"

If anyone could please explain to me what I am doing wrong or point me in the right direction, I would be very grateful. Thanks!

Update: isBefore

public boolean isBefore(String sTestDate, String sTestTime){

    String[] splitTweetDate = this.date.split("-"); //Reconfigures the format of Tweet instance date and time
    String[] splitTweetTime = this.time.split(":");
    int[] tweetDate = stringToInt(splitTweetDate);
    int[] tweetTime = stringToInt(splitTweetTime);

    String[] splitTestDate = sTestDate.split("-"); //Reconfigures the format of query parameters
    String[] splitTestTime = sTestTime.split(":");
    int[] testDate = stringToInt(splitTestDate);
    int[] testTime = stringToInt(splitTestTime);

    for(int i = 0; i<3; i++){ //Tests the date year first, then month, then day. Returns true if tweetDate is earlier than testDate.
      if(tweetDate[i]<testDate[i]){
        return true;
      }
    }

    for(int i = 0; i<3; i++){ //If on the same day, tests hour first, then minutes, then seconds. Returns true if tweetTime is earlier than testDate.
      if(tweetTime[i]<testTime[i]){
        return true;
      }
    }

    return false; //If method returns nothing, message was posted at the same time or later.

  }

  //HELPER 2
  private int[] stringToInt(String[] arrString){ //converts an array of strings into an array of integers.
    int[] arrInt = new int[arrString.length];

    for(int i = 0; i<arrInt.length; i++){ //parseing the elements of the string array to integers.
      arrInt[i] = Integer.parseInt(arrString[i]);
    }

    return arrInt;
  }

Someone has suggested that I use compares and I will if no-other solution is presented to me but I don't think I am technically allowed to (this is for an assignment).


问:
how to add role with same name and some customize column using asp.net identity?
```<code>IdentityResult result = _roleManager.Create(new Role("TestRole", 6, "Test Role Description"));
db.Roles.Add(new Role() {
             Id = Guid.NewGuid().ToString(),
             Name = "TestRole", companyId = 6,
             description = "Test Role Description"});
db.SaveChanges();
</code>```

when i try to do it apart from RoleManager it shows entity validation error.

答:
I've met the same issue .

First:
I changed Role Name Index by the code in :

```<code>protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
            rolesTable.Property(x => x.Name)
                .HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute("RoleNameIndex") { IsUnique = false }));
}
</code>```

when i save the roles twice like this:

```<code> db.roles.add(role);
 db.savechanges();
 db.roles.add(role2);//role.name == role2.name && role.companyid != role2.companyid
 db.savechanges();
</code>```

the code show error but it works fine this way:

```<code>     db.roles.add(role);
     db.roles.add(role2);//role.name == role2.name && role.companyid != role2.companyid
     db.savechanges();
</code>```

it is not very good so.

Last I recommend:
      use unique role name with a companyid in it like this:

```<code> AnyRoleName#CompanyId//example:'Admin#1'
</code>```

Hope it's helpful.

Body:
IdentityResult result = _roleManager.Create(new Role("TestRole", 6, "Test Role Description"));
db.Roles.Add(new Role() {
             Id = Guid.NewGuid().ToString(),
             Name = "TestRole", companyId = 6,
             description = "Test Role Description"});
db.SaveChanges();

when i try to do it apart from RoleManager it shows entity validation error.

Body:
I've met the same issue .

First:
I changed Role Name Index by the code in :

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
            rolesTable.Property(x => x.Name)
                .HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute("RoleNameIndex") { IsUnique = false }));
}

when i save the roles twice like this:

 db.roles.add(role);
 db.savechanges();
 db.roles.add(role2);//role.name == role2.name && role.companyid != role2.companyid
 db.savechanges();

the code show error but it works fine this way:

     db.roles.add(role);
     db.roles.add(role2);//role.name == role2.name && role.companyid != role2.companyid
     db.savechanges();

it is not very good so.

Last I recommend:
      use unique role name with a companyid in it like this:

 AnyRoleName#CompanyId//example:'Admin#1'

Hope it's helpful.


问:
Change color of span upon click
https://codepen.io/SmileySteven/pen/pdBYdv?editors=1111

```<code>function test(){
  var span = document.querySelectorAll('span');
  for(var i = 0 ; i <= span.length ;i++){
    span.addEventListener('click', function(){
    this.style.backgroundColor === '#ffffff'? this.style.backgroundColor = 'yellow'
         : this.style.backgroundColor="#000000";
   })
 }
}
test();
</code>```

Hello guys, I am trying to change the background color of my spans upon click but it does not seem to work - care to guide me as to what I am doing wrong?  I have set all span to background color of #ffffff

答:
```<code>span.addEventListener('click', function(){
</code>```

You are setting the event to whole collection of spans. You should set to the individual element

```<code>span[i].addEventListener('click', function(){
</code>```

https://codepen.io/anon/pen/LOvamO?editors=1111

Title: Change color of span upon click

Body:
https://codepen.io/SmileySteven/pen/pdBYdv?editors=1111

function test(){
  var span = document.querySelectorAll('span');
  for(var i = 0 ; i <= span.length ;i++){
    span.addEventListener('click', function(){
    this.style.backgroundColor === '#ffffff'? this.style.backgroundColor = 'yellow'
         : this.style.backgroundColor="#000000";
   })
 }
}
test();

Hello guys, I am trying to change the background color of my spans upon click but it does not seem to work - care to guide me as to what I am doing wrong?  I have set all span to background color of #ffffff

Body:
span.addEventListener('click', function(){

You are setting the event to whole collection of spans. You should set to the individual element

span[i].addEventListener('click', function(){

https://codepen.io/anon/pen/LOvamO?editors=1111


答:
Time interval B 'overlaps' A if:

B starts after A starts but before A finishes.

B starts before A starts and finishes after A starts.

So you can write a function which decides exactly that.

```<code>function areOverlapping(A, B) {
    if(B.start < A.start) {
        return B.finish > A.start;
    }
    else {
        return B.start < A.finish;
    }
}
</code>```

Body:
Time interval B 'overlaps' A if:

B starts after A starts but before A finishes.

B starts before A starts and finishes after A starts.

So you can write a function which decides exactly that.

function areOverlapping(A, B) {
    if(B.start < A.start) {
        return B.finish > A.start;
    }
    else {
        return B.start < A.finish;
    }
}


问:
Cutting a UIImageView according to UIBezier?
I have a UIImageView, with a certain image.
I also have a UIBezierPath in some strange shape.
I would like to cut the image to that shape and return a new image in that shape.

In the form of :

```<code>func getCut(bezier:UIBezierPath, image:UIImageView)->UIImageView
</code>```

答:
You can use CAShapeLayer for shaping the image... & then to get Image from that shape ...

```<code>UIGraphicsBeginImageContext(imgView.bounds.size);
[imgView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *mainImg = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
</code>```

Thank You...

Referenced from here..

Body:
I have a UIImageView, with a certain image.
I also have a UIBezierPath in some strange shape.
I would like to cut the image to that shape and return a new image in that shape.

In the form of :

func getCut(bezier:UIBezierPath, image:UIImageView)->UIImageView

Body:
You can use CAShapeLayer for shaping the image... & then to get Image from that shape ...

UIGraphicsBeginImageContext(imgView.bounds.size);
[imgView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *mainImg = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

Thank You...

Referenced from here..


问:
Wordpress REST API get full sitemap
I am trying to statically generate a WordPress site, which means having a list of every url in the site e.g.

```<code>routes = [
  '/about-us',
  '/sample-page',
  '/category/uncategorized',
  '/uncategorized/hello-world'
];
</code>```

I am currently loading three API endpoints I found in the documentation at:
https://developer.wordpress.org/rest-api/reference/

```<code>/wp-json/wp/v2/pages
/wp-json/wp/v2/categories
/wp-json/wp/v2/posts
</code>```

But this still doesn't cover all pages in the site... how can I get all pages of the site including tags etc, through the REST API? (without using plugins!)

Bonus points: If you have a recommendation how to resolve the conflict of:

```<code>/category/uncategorized
/uncategorized/hello-world
</code>```

Should really be:

```<code>/uncategorized
/uncategorized/hello-world
</code>```

So that static generation doesn't have missing pages!

答:
I think you are manually going to have to create the URLS for each category that comes back in your categories query. Surely you can get a list, and the create them each on the fly. I know it's not desirable, but what you're trying to do is not exactly cut-and-dry.

EDIT

Maybe look into WP CLI if the REST API isn't working out.

Title: Wordpress REST API get full sitemap

Body:
I am trying to statically generate a WordPress site, which means having a list of every url in the site e.g.

routes = [
  '/about-us',
  '/sample-page',
  '/category/uncategorized',
  '/uncategorized/hello-world'
];

I am currently loading three API endpoints I found in the documentation at:
https://developer.wordpress.org/rest-api/reference/

/wp-json/wp/v2/pages
/wp-json/wp/v2/categories
/wp-json/wp/v2/posts

But this still doesn't cover all pages in the site... how can I get all pages of the site including tags etc, through the REST API? (without using plugins!)

Bonus points: If you have a recommendation how to resolve the conflict of:

/category/uncategorized
/uncategorized/hello-world

Should really be:

/uncategorized
/uncategorized/hello-world

So that static generation doesn't have missing pages!


问:
How do I load font-awesome using SCSS (SASS) in Webpack using relative paths?
I have font-awesome in my node_modules folder so I try to import it in my main .scss file like so:

```<code>@import "../../node_modules/font-awesome/scss/font-awesome.scss";
</code>```

But Webpack bundling compilation fails, telling me

```<code>Error: Cannot resolve 'file' or 'directory' ../fonts/fontawesome-webfont.eot
</code>```

because the font-awesome.scss file refers to a relative path, '../fonts/'.

How can I tell scss \ webpack to @import another file, and use that file's folder as the home folder so that its relative paths work as it expects?

答:
I just set the path in my main scss file and it works :</p>

```<code>$fa-font-path: "../node_modules/font-awesome/fonts";
@import '~font-awesome/scss/font-awesome.scss';
</code>```

Body:
I have font-awesome in my node_modules folder so I try to import it in my main .scss file like so:

@import "../../node_modules/font-awesome/scss/font-awesome.scss";

But Webpack bundling compilation fails, telling me

Error: Cannot resolve 'file' or 'directory' ../fonts/fontawesome-webfont.eot

because the font-awesome.scss file refers to a relative path, '../fonts/'.

How can I tell scss \ webpack to @import another file, and use that file's folder as the home folder so that its relative paths work as it expects?

Body:
I just set the path in my main scss file and it works :

$fa-font-path: "../node_modules/font-awesome/fonts";
@import '~font-awesome/scss/font-awesome.scss';


问:
How to get the name of the item that is being checked by the user in next activity in android?
I'm working on an android app where user will select the food quantity and move to the checkout screen to purchase that similar to what foodpanda, swiggy does.

But I'm unable to fetch the content of the item being selected using the quantity. It is showing the package name instead of the item name.

Code -

```<code>public class Food implements Parcelable,Serializable {
    String Foodname;
    int CartQuantity = 0;
    double FoodPrice;

    public Food(String Foodname, int cartQuantity, double FoodPrice) {
        this.Foodname = Foodname;
        this.CartQuantity = cartQuantity;
        this.FoodPrice = FoodPrice;
    }

    protected Food(Parcel in) {
        Foodname = in.readString();
        CartQuantity = in.readInt();
        FoodPrice = in.readDouble();
    }

    public static final Creator<Food> CREATOR = new Creator<Food>() {
        @Override
        public Food createFromParcel(Parcel in) {
            return new Food(in);
        }

        @Override
        public Food[] newArray(int size) {
            return new Food[size];
        }
    };

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
            dest.writeString(this.Foodname);
            dest.writeInt(this.CartQuantity);
            dest.writeDouble(this.FoodPrice);
    }
}
</code>```

ListAdapter.class -

```<code>public class ListAdapter extends BaseAdapter {
    public ArrayList<Food> listproducts;
    private Context context;

    public ListAdapter(Context context,ArrayList<Food> listproducts){
        this.context=context;
        this.listproducts=listproducts;
    }
    @Override
    public int getCount() {
        return listproducts.size();
    }

    @Override
    public Food getItem(int position) {
        return listproducts.get(position);
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        View row;
        final ListViewHolder listViewHolder;
        if(convertView == null)
        {
            LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            row = layoutInflater.inflate(R.layout.list_item,parent,false);
            listViewHolder = new ListViewHolder();
            listViewHolder.foodName = row.findViewById(R.id.lblListItem);
            listViewHolder.foodPrice = row.findViewById(R.id.lblListItem1);
            listViewHolder.cartQuantity = row.findViewById(R.id.integer_number);
            listViewHolder.increment = row.findViewById(R.id.increase);
            listViewHolder.decrement = row.findViewById(R.id.decrease);
            row.setTag(listViewHolder);
        }
        else
        {
            row=convertView;
            listViewHolder= (ListViewHolder) row.getTag();
        }
        final Food food=getItem(position);

        listViewHolder.foodName.setText(food.Foodname);
        listViewHolder.foodPrice.setText(food.FoodPrice+" $");
        listViewHolder.cartQuantity.setText(food.CartQuantity+"");
        listViewHolder.increment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v)
            {
                updateQuantity(position,listViewHolder.cartQuantity,1);
            }
        });
        //listViewHolder.edTextQuantity.setText("0");
        listViewHolder.decrement.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updateQuantity(position,listViewHolder.cartQuantity,-1);

            }
        });

        return row;
    }

    private void updateQuantity(int position, TextView edTextQuantity, int value) {

        Food food = getItem(position);
        if(value > 0&&food.CartQuantity<10)
        {
            food.CartQuantity = food.CartQuantity + 1;
        }
        else
        {
            if(food.CartQuantity > 0)
            {
                food.CartQuantity = food.CartQuantity - 1;
            }

        }
        edTextQuantity.setText(food.CartQuantity+"");
    }
}
</code>```

This is what I've tried and this is what I'm getting from this code.

Activity where the user will select the items to order

Activity which displays the selected items by the user

Instead of showing the item name, price and quantity, it is displaying the package name.
How can I get the required values by changing the code?

答:
You must be using the object reference to setText . Something like

Food f = getFood(); //Did some logic

//Setting text like below.

textView.setText(f);//Wrong

Try using something like this.

textView.setText(f.FoodName));// Get Proper attribute from object to show the exact name.

Body:
I'm working on an android app where user will select the food quantity and move to the checkout screen to purchase that similar to what foodpanda, swiggy does.

But I'm unable to fetch the content of the item being selected using the quantity. It is showing the package name instead of the item name.

Code -

public class Food implements Parcelable,Serializable {
    String Foodname;
    int CartQuantity = 0;
    double FoodPrice;

    public Food(String Foodname, int cartQuantity, double FoodPrice) {
        this.Foodname = Foodname;
        this.CartQuantity = cartQuantity;
        this.FoodPrice = FoodPrice;
    }

    protected Food(Parcel in) {
        Foodname = in.readString();
        CartQuantity = in.readInt();
        FoodPrice = in.readDouble();
    }

    public static final Creator<Food> CREATOR = new Creator<Food>() {
        @Override
        public Food createFromParcel(Parcel in) {
            return new Food(in);
        }

        @Override
        public Food[] newArray(int size) {
            return new Food[size];
        }
    };

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
            dest.writeString(this.Foodname);
            dest.writeInt(this.CartQuantity);
            dest.writeDouble(this.FoodPrice);
    }
}

ListAdapter.class -

public class ListAdapter extends BaseAdapter {
    public ArrayList<Food> listproducts;
    private Context context;

    public ListAdapter(Context context,ArrayList<Food> listproducts){
        this.context=context;
        this.listproducts=listproducts;
    }
    @Override
    public int getCount() {
        return listproducts.size();
    }

    @Override
    public Food getItem(int position) {
        return listproducts.get(position);
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        View row;
        final ListViewHolder listViewHolder;
        if(convertView == null)
        {
            LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            row = layoutInflater.inflate(R.layout.list_item,parent,false);
            listViewHolder = new ListViewHolder();
            listViewHolder.foodName = row.findViewById(R.id.lblListItem);
            listViewHolder.foodPrice = row.findViewById(R.id.lblListItem1);
            listViewHolder.cartQuantity = row.findViewById(R.id.integer_number);
            listViewHolder.increment = row.findViewById(R.id.increase);
            listViewHolder.decrement = row.findViewById(R.id.decrease);
            row.setTag(listViewHolder);
        }
        else
        {
            row=convertView;
            listViewHolder= (ListViewHolder) row.getTag();
        }
        final Food food=getItem(position);

        listViewHolder.foodName.setText(food.Foodname);
        listViewHolder.foodPrice.setText(food.FoodPrice+" $");
        listViewHolder.cartQuantity.setText(food.CartQuantity+"");
        listViewHolder.increment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v)
            {
                updateQuantity(position,listViewHolder.cartQuantity,1);
            }
        });
        //listViewHolder.edTextQuantity.setText("0");
        listViewHolder.decrement.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updateQuantity(position,listViewHolder.cartQuantity,-1);

            }
        });

        return row;
    }

    private void updateQuantity(int position, TextView edTextQuantity, int value) {

        Food food = getItem(position);
        if(value > 0&&food.CartQuantity<10)
        {
            food.CartQuantity = food.CartQuantity + 1;
        }
        else
        {
            if(food.CartQuantity > 0)
            {
                food.CartQuantity = food.CartQuantity - 1;
            }

        }
        edTextQuantity.setText(food.CartQuantity+"");
    }
}

This is what I've tried and this is what I'm getting from this code.

Activity where the user will select the items to order

Activity which displays the selected items by the user

Instead of showing the item name, price and quantity, it is displaying the package name.
How can I get the required values by changing the code?


问:
How do I align elements in adjacent columns of a UL?
How do I align elements in adjacent columns of a ?

How it is not working:

Have tried specifying a fixed height to ul li {} which does the aligning; however, when the height needed is very small, this leaves huge white space.

HTML = standard

CSS =

```<code>ul {
    -webkit-column-count: 2;   /* Chrome, Safari, Opera */
    -moz-column-count:    2;   /* Firefox */
    column-count:         2;
}

ul li {
    color:         red;     /* bullet color */
    padding-right: 2.0em;   /* not too close */
}
</code>```

答: you haven't written your html code but try to put ul tag in a div tag. you can play with div's height and width</p>

Body:
How do I align elements in adjacent columns of a ?

How it is not working:

Have tried specifying a fixed height to ul li {} which does the aligning; however, when the height needed is very small, this leaves huge white space.

HTML = standard

CSS =

ul {
    -webkit-column-count: 2;   /* Chrome, Safari, Opera */
    -moz-column-count:    2;   /* Firefox */
    column-count:         2;
}

ul li {
    color:         red;     /* bullet color */
    padding-right: 2.0em;   /* not too close */
}


问:
Why does Forever for Node.JS not work in rc.local?
I am deploying a node.js app to a Ubuntu server on EC2, and I am using Forever to keep it running ... forever.

The problem is, if I type in following in a console:

```forever start ~/path/myapp.js```

It works just fine. But I want the app automatically starts when on startup, so I appended the line to /etc/rc.local, and it stopped working. Everything else in rc.local still works.

I am not familiar with Linux so my best guess is some important component hasn't initialized when running rc.local. Is there somewhere else I can append the line?

Thanks,

答:
This is a very late reply, but I just ran into this. For me, using forever list says that nothing is running, but doing sudo forever list will show that the server is in fact running.

This is because rc.local is run as root, so your forever command is run as root, and only root can see it in the list.

I don't know the best practices, but I got around it by calling my forever start script from rc.local like this, where "pi" is the user I want to launch the forever process:

su pi -c './start'

If it helps, this is my abridged ./start script, yours may differ, or you can possibly put its contents directly in rc.local:

#!/bin/sh
forever start --append -l forever.log -o server.log -e error.log server.js

Body:
I am deploying a node.js app to a Ubuntu server on EC2, and I am using Forever to keep it running ... forever.

The problem is, if I type in following in a console:

forever start ~/path/myapp.js

It works just fine. But I want the app automatically starts when on startup, so I appended the line to /etc/rc.local, and it stopped working. Everything else in rc.local still works.

I am not familiar with Linux so my best guess is some important component hasn't initialized when running rc.local. Is there somewhere else I can append the line?

Thanks,


问:
Show Duplicate Values
I Have a table (#tempX) below.

```<code>BoxNumber | Location
----------|----------
ABC123    |Nowra
ABC123    |Sydney
KLM222    |Melbourne
XYZ444    |Karatha
XYZ444    |Mirabooka
XYZ444    |Logan
PQR888    |Brisbane
</code>```

I need to find the duplicate and display them.

```<code>BoxNumber | Location
----------|----------
ABC123    |Nowra
ABC123    |Sydney
XYZ444    |Karatha
XYZ444    |Mirabooka
XYZ444    |Logan
</code>```

I used the query below (you can copy and paste it to your SQL server) however it doesn't give me what I'm looking for. It gives me blank table as a result.

```<code>If(OBJECT_ID('tempdb..#tempX') Is Not Null)

Drop Table #tempX

create table #tempX (box varchar(max) ,location varchar(max))

insert into #tempX (box,location)
values ('ABC123','Nowra'),('ABC123','Sydney'),('KLM222', 'Melbourne'),('XYZ444','Karatha'),('XYZ444','Mirabooka'),('XYZ444','Logan'),('PQR888','Brisbane')

--select * from #tempx

select distinct Box, Location, count(*) from #tempX
group by Box, Location
having count(*) > 1
</code>```

I'm using SQL Server 2012. Thanks all.

答:
You could do it this way:</p>

```<code>   select *
      from #tempX
     where  Box in
           ( select Box
               from #tempX
              group by Box
             having count(*) > 1 )
</code>```

Title: Show Duplicate Values

Body:
I Have a table (#tempX) below.

BoxNumber | Location
----------|----------
ABC123    |Nowra
ABC123    |Sydney
KLM222    |Melbourne
XYZ444    |Karatha
XYZ444    |Mirabooka
XYZ444    |Logan
PQR888    |Brisbane

I need to find the duplicate and display them.

BoxNumber | Location
----------|----------
ABC123    |Nowra
ABC123    |Sydney
XYZ444    |Karatha
XYZ444    |Mirabooka
XYZ444    |Logan

I used the query below (you can copy and paste it to your SQL server) however it doesn't give me what I'm looking for. It gives me blank table as a result.

If(OBJECT_ID('tempdb..#tempX') Is Not Null)

Drop Table #tempX

create table #tempX (box varchar(max) ,location varchar(max))

insert into #tempX (box,location)
values ('ABC123','Nowra'),('ABC123','Sydney'),('KLM222', 'Melbourne'),('XYZ444','Karatha'),('XYZ444','Mirabooka'),('XYZ444','Logan'),('PQR888','Brisbane')

--select * from #tempx

select distinct Box, Location, count(*) from #tempX
group by Box, Location
having count(*) > 1

I'm using SQL Server 2012. Thanks all.

Body:
You could do it this way:

   select *
      from #tempX
     where  Box in
           ( select Box
               from #tempX
              group by Box
             having count(*) > 1 )


问:
Django query passing parameters into values()
I have a Django query like this and I want to be able to pass the "values" param from a variable. Reason for this I can standardize all my list values otherwise it will be hardcoded on every values.

So for example, this works:

```<code>employee_list = Employee.objects.all().values("id", "username").order_by('id')
</code>```

But I cannot do this. It doesnt work:

```<code>val_params = ["id", "username"]
employee_list = Employee.objects.all().values(val_params).order_by('id')
</code>```

what kind of val_params can i use to pass into values() ? Is there a way to do this ?

答:
You could do</p>

```<code>employee_list = Employee.objects.all().values(*val_params).order_by('id')
</code>```

Body:
I have a Django query like this and I want to be able to pass the "values" param from a variable. Reason for this I can standardize all my list values otherwise it will be hardcoded on every values.

So for example, this works:

employee_list = Employee.objects.all().values("id", "username").order_by('id')

But I cannot do this. It doesnt work:

val_params = ["id", "username"]
employee_list = Employee.objects.all().values(val_params).order_by('id')

what kind of val_params can i use to pass into values() ? Is there a way to do this ?

Body:
You could do

employee_list = Employee.objects.all().values(*val_params).order_by('id')


问:
Read content image and store it into a file with `PHP` and `CURL` and executable commands
I have a dynamic image as PHP file:

```<code><?php
header('Content-type: image/png');
echo file_get_contents('image.png');
</code>```

Now I want to read content image and store it into a file with PHP and CURL and executable commands.

First for sure, I test this command in cmd:

```<code># curl -s http://localhost/image.php > output.png
</code>```

This works good.

Now I use of same command in the php code with shell_exec function:

```<code><?php
$cmd = 'curl -s http://localhost/image.php';
$out = shell_exec($cmd);
file_put_contents('output.png', $out);
</code>```

But the output incomplete:

```<code>‰PNG
</code>```

And this may be binary in the photo because of NULL characters.

Another test I try with exec function.

```<code><?php
$cmd = 'curl -s http://localhost/image.php';
exec($cmd, $out);
file_put_contents('output.png', $out);
</code>```

Seem the output file contain real binary image:

```<code>‰PNG
IHDR   ً   P   Z'ï      PLTEےےے   –––¹¸vٍ       pHYs  ؤ  ؤ•+  tIDATX…¥کQ®©„Mdٍl"ْ®"کgˆ`ض“Hة{"e61«¼_u–0™(sخك
کr¹\يكےًا~¶’¼ïk¥‘’¥½ZKأb¬Zkّ‰¶»¯½|إj–|ظ.nضـ²¯آ‡y*üµàٌب›g–Z²'¹چضِê¶طج£µث5³kjںىkoُ
</code>```

But the image will not be shown.

I diff real image and new generated image:

Apparently, because the content of the $out is an array. Not well written in the new file.

Now, Where are my forms of work and how can I get to my goal?

EDIT: seem this problem is just on windows.

答:
The shell_exec doesn't work on my computer either.
For exec, the problem may be introduced by the additional characters in the exec results which may contain different characters than the picture.

To solve this, you can simply try these codes. It works on my computer.

```<code><?php
$cmd = 'curl http://localhost/image.php > output.png';
exec($cmd);
</code>```

Body:
I have a dynamic image as PHP file:

<?php
header('Content-type: image/png');
echo file_get_contents('image.png');

Now I want to read content image and store it into a file with PHP and CURL and executable commands.

First for sure, I test this command in cmd:

# curl -s http://localhost/image.php > output.png

This works good.

Now I use of same command in the php code with shell_exec function:

<?php
$cmd = 'curl -s http://localhost/image.php';
$out = shell_exec($cmd);
file_put_contents('output.png', $out);

But the output incomplete:

‰PNG

And this may be binary in the photo because of NULL characters.

Another test I try with exec function.

<?php
$cmd = 'curl -s http://localhost/image.php';
exec($cmd, $out);
file_put_contents('output.png', $out);

Seem the output file contain real binary image:

‰PNG
IHDR   ً   P   Z'ï      PLTEےےے   –––¹¸vٍ       pHYs  ؤ  ؤ•+  tIDATX…¥کQ®©„Mdٍl"ْ®"کgˆ`ض“Hة{"e61«¼_u–0™(sخك
کr¹\يكےًا~¶’¼ïk¥‘’¥½ZKأb¬Zkّ‰¶»¯½|إj–|ظ.nضـ²¯آ‡y*üµàٌب›g–Z²'¹چضِê¶طج£µث5³kjںىkoُ

But the image will not be shown.

I diff real image and new generated image:

Apparently, because the content of the $out is an array. Not well written in the new file.

Now, Where are my forms of work and how can I get to my goal?

EDIT: seem this problem is just on windows.

Body:
The shell_exec doesn't work on my computer either.
For exec, the problem may be introduced by the additional characters in the exec results which may contain different characters than the picture.

To solve this, you can simply try these codes. It works on my computer.

<?php
$cmd = 'curl http://localhost/image.php > output.png';
exec($cmd);


问:
Class with Object as a parameter
I'm trying to translate some python code to scala code. So I'm a total noob in Python.

But why do some classes have object as a parameter but never explicitly use it? What's the reasoning for having it as a parameter in the first place?

Example:

```<code>class Table(object)
</code>```

Thank you for your time.

答:
object is the most base type of class object defined in python.
Attributes of object can be seen as below

**>>> dir(object)

['class', 'delattr', 'doc', 'format', 'getattribute', 'hash', 'init', 'new', 'reduce', 'reduce_ex', 'repr', 'setattr', 'sizeof', 'str', 'subclasshook']**

So Table(object)  is just inheritance.!

Title: Class with Object as a parameter

Body:
I'm trying to translate some python code to scala code. So I'm a total noob in Python.

But why do some classes have object as a parameter but never explicitly use it? What's the reasoning for having it as a parameter in the first place?

Example:

class Table(object)

Thank you for your time.


问:
Location Services not working in iOS 11
I just rebuilt my app with the iOS 11 SDK in an attempt to remove the blue banner that is now always appearing. I thought - "Brilliant, that worked", only to discover that location services are now not working at all.

The application used to work with iOS 10 - Has anybody heard anything?

答:
Better safe than sorry ..
In iOS 11 : Add the below and you are good.

```<code><key>NSLocationWhenInUseUsageDescription</key>
<string>Description</string>

<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>Description</string>

<key>NSLocationAlwaysUsageDescription</key>
<string>Description</string>
</code>```

Title: Location Services not working in iOS 11

Body:
Better safe than sorry ..
In iOS 11 : Add the below and you are good.

<key>NSLocationWhenInUseUsageDescription</key>
<string>Description</string>

<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>Description</string>

<key>NSLocationAlwaysUsageDescription</key>
<string>Description</string>


问:
Angular Typescript map array into class
I have data that comes from a web api that looks like below. How do I map the product array into the Products, the reason for me doing that is that I need to transform the eating_time to javascript datetime.

My code below for the class where this.products = product will only store the array and the the list of product.

//Data from API

```<code>[ {datetime: "2017-06-25T07:45:00+08:00", name: "Apple", unit: 1, product: [{eating_time: "2017-06-25T07:45:00+08:00", qtytaken: 1, chart_bar=1 },
{eating_time: "2017-06-25T17:45:00+08:00", qtytaken: 1, chart_bar=1 },
{eating_time: "2017-06-25T23:55:00+08:00", qtytaken: 1, chart_bar=1 } ]
]
</code>```

// Class

```<code>class Product {
    eating_time: Date;
    qtytaken: number;
    chart_bar = 1;

    constructor({eating_time, qtytaken, chart_bar })  {
            this.eating_time = new Date(eating_time);
            this.qtytaken = dosage;
            this.chart_bar = chart_bar;
    }
}

export class ProductTaken {
    datetime: Date;
    name: string;
    unit: number;
    products: Product[];

    constructor({datetime, name, unit, product} )  {
        this.datetime = new Date(datetime) ;
        this.name = name;
        this.unit = unit;
        this.products = product ;
        }
}
</code>```

答:
Use interface or class without a constructor and map function

```<code>export interface ProductTaken {
    datetime: Date;
    name: string;
    unit: number;
    products: Product[];

}
</code>```

Your service should have the map function

```<code>return this.http.get(...)
      .map(res => <ProductTaken>res.json())
</code>```

LIVE DEMO

Title: Angular Typescript map array into class

Body:
I have data that comes from a web api that looks like below. How do I map the product array into the Products, the reason for me doing that is that I need to transform the eating_time to javascript datetime.

My code below for the class where this.products = product will only store the array and the the list of product.

//Data from API

[ {datetime: "2017-06-25T07:45:00+08:00", name: "Apple", unit: 1, product: [{eating_time: "2017-06-25T07:45:00+08:00", qtytaken: 1, chart_bar=1 },
{eating_time: "2017-06-25T17:45:00+08:00", qtytaken: 1, chart_bar=1 },
{eating_time: "2017-06-25T23:55:00+08:00", qtytaken: 1, chart_bar=1 } ]
]

// Class

class Product {
    eating_time: Date;
    qtytaken: number;
    chart_bar = 1;

    constructor({eating_time, qtytaken, chart_bar })  {
            this.eating_time = new Date(eating_time);
            this.qtytaken = dosage;
            this.chart_bar = chart_bar;
    }
}

export class ProductTaken {
    datetime: Date;
    name: string;
    unit: number;
    products: Product[];

    constructor({datetime, name, unit, product} )  {
        this.datetime = new Date(datetime) ;
        this.name = name;
        this.unit = unit;
        this.products = product ;
        }
}

Body:
Use interface or class without a constructor and map function

export interface ProductTaken {
    datetime: Date;
    name: string;
    unit: number;
    products: Product[];

}

Your service should have the map function

return this.http.get(...)
      .map(res => <ProductTaken>res.json())

LIVE DEMO


问:
If not disabled, then disable it and again enable with selection
I have a shell script which run my model after modifying another file. e.g.,

```<code>$cat myscript.sh
 cp myfile DELHI
 ./mymodel.exe (This will execute with DELHI information)
$cat DELHI
 ! If you enable an input below, then the information
 ! of the corresponding city will be passed to the model
   x = 150
   y = 150
 ! input = 'KOLKATA'
 ! input = 'MUMBAI'
  input = 'DELHI'
 ! input = 'CHENNAI'
 ......
 ......
 so on to 100 Cities
</code>```

All the inputs (KOLKATA, MUMBAI, ... ) are actually different files that contains many other information

So I need to enable few cities upon my interest one by one and execute the model. Manually it takes a lot time. So if can put it into a script, then it would save many times.

My script/algorithm is

```<code>  for city in KOLKATA MUMBAI DELHI CHENNAI;do
     cp myfile $city
     check all cities in '$city file' are disabled except one (that is to be executed)
     ./mymodel.exe
  done
</code>```

I am helpless how to give the check command.

答:
You an use sed:

For all lines start with some space and then "input", insert a !

For all lines start with ! input = 'YOURCITY', remove the !

Like this:

```<code>sed -i -e 's/^ *input/ ! input/' -e '/^ ! input = '"'$city'"'/s/ !/ /' "$city"
</code>```

You can call this in a loop for each city.

Body:
I have a shell script which run my model after modifying another file. e.g.,

$cat myscript.sh
 cp myfile DELHI
 ./mymodel.exe (This will execute with DELHI information)
$cat DELHI
 ! If you enable an input below, then the information
 ! of the corresponding city will be passed to the model
   x = 150
   y = 150
 ! input = 'KOLKATA'
 ! input = 'MUMBAI'
  input = 'DELHI'
 ! input = 'CHENNAI'
 ......
 ......
 so on to 100 Cities

All the inputs (KOLKATA, MUMBAI, ... ) are actually different files that contains many other information

So I need to enable few cities upon my interest one by one and execute the model. Manually it takes a lot time. So if can put it into a script, then it would save many times.

My script/algorithm is

  for city in KOLKATA MUMBAI DELHI CHENNAI;do
     cp myfile $city
     check all cities in '$city file' are disabled except one (that is to be executed)
     ./mymodel.exe
  done

I am helpless how to give the check command.

Body:
You an use sed:

For all lines start with some space and then "input", insert a !

For all lines start with ! input = 'YOURCITY', remove the !

Like this:

sed -i -e 's/^ *input/ ! input/' -e '/^ ! input = '"'$city'"'/s/ !/ /' "$city"

You can call this in a loop for each city.


问:
Url.Action fails to call controller method
I am trying to display some images on a page with this view

Details.cshtml

```<code>@foreach (var imagePath in Model.Images)
{
    <img src="@Url.Action("GetImage", "Receiving", new { @imagePath = imagePath })" />
}
</code>```

ReceivingController.cs

```<code>public ActionResult GetImage(string imagePath)
{
    var folder = ConfigurationManager.AppSettings["ImagesPath"];
    var path = Path.Combine(folder, imagePath);
    byte[] image = System.IO.File.ReadAllBytes(path);
    return File(image, "image/jpg");
}
</code>```

But when I set a breakpoint in the controller, it never gets hit and of course the images fail to load.

I can see the value being passed from the view is a path e.g. "C:\\inetpub\\wwwroot\\SiteName\\Images\\3000\\1\\1\\2.jpg"

I tried changing @Url.Action' to@Html.Action` just because I have no idea what else to try, but I got an error

OutputStream is not available when a custom TextWriter is used

I don't understand why the controller is not being called.

I noticed if I just navigate to the url Receiving\GetImage\whyareyounotworking, the controller action is fired.

I tried adding a route as below, but with no change

```<code>routes.MapRoute(
    name: "GetImage",
    url: "receiving/GetImage/{imagePath}",
    defaults: new { controller = "Receiving", action = "GetImage" }
);
</code>```

答:
remove this:

```<code>@imagePath
</code>```

So you will have an url.action like this:

```<code><img src="@Url.Action("GetImage", "Receiving", new { imagePath = imagePath })" />
</code>```

Body:
I am trying to display some images on a page with this view

Details.cshtml

@foreach (var imagePath in Model.Images)
{

}

ReceivingController.cs

public ActionResult GetImage(string imagePath)
{
    var folder = ConfigurationManager.AppSettings["ImagesPath"];
    var path = Path.Combine(folder, imagePath);
    byte[] image = System.IO.File.ReadAllBytes(path);
    return File(image, "image/jpg");
}

But when I set a breakpoint in the controller, it never gets hit and of course the images fail to load.

I can see the value being passed from the view is a path e.g. "C:\\inetpub\\wwwroot\\SiteName\\Images\\3000\\1\\1\\2.jpg"

I tried changing @Url.Action' to@Html.Action` just because I have no idea what else to try, but I got an error

OutputStream is not available when a custom TextWriter is used

I don't understand why the controller is not being called.

I noticed if I just navigate to the url Receiving\GetImage\whyareyounotworking, the controller action is fired.

I tried adding a route as below, but with no change

routes.MapRoute(
    name: "GetImage",
    url: "receiving/GetImage/{imagePath}",
    defaults: new { controller = "Receiving", action = "GetImage" }
);

Body:
remove this:

@imagePath

So you will have an url.action like this:

<img src="@Url.Action("GetImage", "Receiving", new { imagePath = imagePath })" />


问:
Incorrect touch location on 4k screen
I've been having some problems with touch detection on my current project, the problem is the higher the touch is on either axis the further off the touch point the touch registers.

In the image below you can see the issue i am talking about. The dot starts by rendering to the left of the mouse but by the time the mouse reaches the right side of the screen the dot is to the right of the mouse. The issue is much more obvious on the y axis.

The code running to create the above test is just the LibGDX SimpleTouchTest from https://github.com/libgdx/libgdx/wiki/Mouse%2C-touch-%26-keyboard so it is the absolute bare minimum.

The weird thing is, this only appears to be an issue on my laptop, on my desktop the dot sits under the mouse at all times. Both computers are running windows 10 so the only difference I can see is my laptop has a 4k display.

Has anyone found a solution to this issue?

Thanks
Adrian

答: So for some reason this is now working. Nothing has changed in the code so I can only assume something was out of wack within windows or the graphics driver that has some how sorted itself out over the last few weeks. Thanks to those that took the time to read my question.</p>

Title: Incorrect touch location on 4k screen


问:
Preloading images with jQuery
I'm looking for a quick and easy way to preload images with JavaScript. I'm using jQuery if that's important.

I saw this here (http://nettuts.com...):

```<code>function complexLoad(config, fileNames) {
  for (var x = 0; x < fileNames.length; x++) {
    $("<img>").attr({
      id: fileNames[x],
      src: config.imgDir + fileNames[x] + config.imgFormat,
      title: "The " + fileNames[x] + " nebula"
    }).appendTo("#" + config.imgContainer).css({ display: "none" });
  }
};
</code>```

But, it looks a bit over-the-top for what I want!

I know there are jQuery plugins out there that do this but they all seem a bit big (in size); I just need a quick, easy and short way of preloading images!

答:
Quick and easy:

```<code>function preload(arrayOfImages) {
    $(arrayOfImages).each(function(){
        $('<img/>')[0].src = this;
        // Alternatively you could use:
        // (new Image()).src = this;
    });
}

// Usage:

preload([
    'img/imageName.jpg',
    'img/anotherOne.jpg',
    'img/blahblahblah.jpg'
]);
</code>```

Or, if you want a jQuery plugin:

```<code>$.fn.preload = function() {
    this.each(function(){
        $('<img/>')[0].src = this;
    });
}

// Usage:

$(['img1.jpg','img2.jpg','img3.jpg']).preload();
</code>```

Title: Preloading images with jQuery

Body:
I'm looking for a quick and easy way to preload images with JavaScript. I'm using jQuery if that's important.

I saw this here (http://nettuts.com...):

function complexLoad(config, fileNames) {
  for (var x = 0; x < fileNames.length; x++) {
    $("").attr({
      id: fileNames[x],
      src: config.imgDir + fileNames[x] + config.imgFormat,
      title: "The " + fileNames[x] + " nebula"
    }).appendTo("#" + config.imgContainer).css({ display: "none" });
  }
};

But, it looks a bit over-the-top for what I want!

I know there are jQuery plugins out there that do this but they all seem a bit big (in size); I just need a quick, easy and short way of preloading images!

Body:
Quick and easy:

function preload(arrayOfImages) {
    $(arrayOfImages).each(function(){
        $('<img/>')[0].src = this;
        // Alternatively you could use:
        // (new Image()).src = this;
    });
}

// Usage:

preload([
    'img/imageName.jpg',
    'img/anotherOne.jpg',
    'img/blahblahblah.jpg'
]);

Or, if you want a jQuery plugin:

$.fn.preload = function() {
    this.each(function(){
        $('<img/>')[0].src = this;
    });
}

// Usage:

$(['img1.jpg','img2.jpg','img3.jpg']).preload();

OwnerDisplayName: JimmyP


问:
Making large text box for ajax search
I am making an AJAX application where the user can input the name of a movie and the results from the database will be loaded through jquery from a PHP API, However I am unsure how to implement a text box that will:

(a) Be the focus of attention on the page (i.e. quite large with a glow around it)

(b) automatically execute a function that uses jquery to make an ajax request on every time a letter is entered (kind of like google instant)

Any suggestions would be very greatly appreciated,
thanks, RayQuang

答:
If your using jQuery use the .keyup function and then put your code that gets something from your php script inside that function or do what I do and have your getting done by another function and call that from inside the .keyup function like this:

```<code> function getData(){
            data=$('#textareaid').val();
            $.post('http://example.come/ajaxcontroller.php', {data: data},
            function(data) {// Proccess returned ajax here, you could also use one of the ajax functions instead of .post});
          }

$(document).ready(function() {
$('#textareaid').keyup(function(e) { getData();}
}
</code>```

As for the glow, either use css to make a larger 3d border around your textarea (http://www.w3schools.com/css/css_border.asp) or wrap it in a div and make a background that accomplishes the specific effect your looking for.

Title: Making large text box for ajax search

Body:
If your using jQuery use the .keyup function and then put your code that gets something from your php script inside that function or do what I do and have your getting done by another function and call that from inside the .keyup function like this:

 function getData(){
            data=$('#textareaid').val();
            $.post('http://example.come/ajaxcontroller.php', {data: data},
            function(data) {// Proccess returned ajax here, you could also use one of the ajax functions instead of .post});
          }

$(document).ready(function() {
$('#textareaid').keyup(function(e) { getData();}
}

As for the glow, either use css to make a larger 3d border around your textarea (http://www.w3schools.com/css/css_border.asp) or wrap it in a div and make a background that accomplishes the specific effect your looking for.


问:
Send email from gmail using Telnet
I am working on windows and I have enabled telnet client

In cmd prompt:

```<code>$telnet smtp.gmail.com 587
220 mx.google.com ESMTP dk3sm50678627pbc.32 - gsmtp
$Helo
250 mx.google.com at your service
$ mail from: <myuser@gmail.com>
530 5.7.0 Must issue a STARTTLS command first. dk3sm50678627pbc.32 - gsmtp
$ STARTTLS
220 2.0.0 Ready to start TLS
$ mail from:
C:\Users\{myuser}>
Connection to host lost.
</code>```

Don't know What is the problem ?

Can anyone help me out , how i can send emails from gmail server using telnet from command line >

答:
Put into a VBS file, ie sendmail.vbs.

```<code>Set emailObj      = CreateObject("CDO.Message")
emailObj.From     = "cat@gmail.com"

emailObj.To       = "cat@gmail.com"

emailObj.Subject  = "Test CDO"
emailObj.TextBody = "Test CDO"

emailObj.AddAttachment "c:\windows\win.ini"

Set emailConfig = emailObj.Configuration

emailConfig.Fields("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "smtp.gmail.com"
emailConfig.Fields("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 465
emailConfig.Fields("http://schemas.microsoft.com/cdo/configuration/sendusing")    = 2
emailConfig.Fields("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1
emailConfig.Fields("http://schemas.microsoft.com/cdo/configuration/smtpusessl")      = true
emailConfig.Fields("http://schemas.microsoft.com/cdo/configuration/sendusername")    = "cat"
emailConfig.Fields("http://schemas.microsoft.com/cdo/configuration/sendpassword")    = "Ccat1"
emailConfig.Fields.Update

emailObj.Send

If err.number = 0 then Msgbox "Done"
</code>```

At Google's web site for GMail you have to turn this feature on for CDO to work.

At your Gmail page click Settings - Accounts and Import - Other Google Account Settings - [At very bottom of page] Allow less secure apps.

Also from memory you also have to click a link in an email the first time you use it (it's been a few years).

Title: Send email from gmail using Telnet

Body:
I am working on windows and I have enabled telnet client

In cmd prompt:

$telnet smtp.gmail.com 587
220 mx.google.com ESMTP dk3sm50678627pbc.32 - gsmtp
$Helo
250 mx.google.com at your service
$ mail from: <myuser@gmail.com>
530 5.7.0 Must issue a STARTTLS command first. dk3sm50678627pbc.32 - gsmtp
$ STARTTLS
220 2.0.0 Ready to start TLS
$ mail from:
C:\Users\{myuser}>
Connection to host lost.

Don't know What is the problem ?

Can anyone help me out , how i can send emails from gmail server using telnet from command line >

Body:
Put into a VBS file, ie sendmail.vbs.

Set emailObj      = CreateObject("CDO.Message")
emailObj.From     = "cat@gmail.com"

emailObj.To       = "cat@gmail.com"

emailObj.Subject  = "Test CDO"
emailObj.TextBody = "Test CDO"

emailObj.AddAttachment "c:\windows\win.ini"

Set emailConfig = emailObj.Configuration

emailConfig.Fields("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "smtp.gmail.com"
emailConfig.Fields("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 465
emailConfig.Fields("http://schemas.microsoft.com/cdo/configuration/sendusing")    = 2
emailConfig.Fields("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1
emailConfig.Fields("http://schemas.microsoft.com/cdo/configuration/smtpusessl")      = true
emailConfig.Fields("http://schemas.microsoft.com/cdo/configuration/sendusername")    = "cat"
emailConfig.Fields("http://schemas.microsoft.com/cdo/configuration/sendpassword")    = "Ccat1"
emailConfig.Fields.Update

emailObj.Send

If err.number = 0 then Msgbox "Done"

At Google's web site for GMail you have to turn this feature on for CDO to work.

At your Gmail page click Settings - Accounts and Import - Other Google Account Settings - [At very bottom of page] Allow less secure apps.

Also from memory you also have to click a link in an email the first time you use it (it's been a few years).


问:
JavaScript associative array behaving strangely
I have two objects. When I pass these as key to an associative array, and assign a value, all the values are stored wrong ( except for the last one ).

Can anyone please tell me what I'm doing wrong ??

var usrMrid = {name: "mrid"};
var usrXYZZ = {name: "xyzz"};

var comm = {};

comm[usrMrid] = "ONE";
comm[usrXYZZ] = "TWO";

console.log("usrMrid: " + comm[usrMrid]); // this gives TWO, when it should give ONE
console.log("usrXYZZ: " + comm[usrXYZZ]); // this works fine```

答:
When you use [] syntax with object and you pass an object as a property name, property name is going to be the string representation of the given expression, which will be in your case [object Object]. So when you use different objects, they create the same property with name [object Object] and override the previous ones.

You can see it in the example. Here I print the properties of the object and you can see that there is just one property with name [object Object].

var usrMrid = {name: "mrid"};
var usrXYZZ = {name: "xyzz"};

var comm = {};

comm[usrMrid] = "ONE";
comm[usrXYZZ] = "TWO";

console.log(comm);```
</div>
</div>
</p>

<p>You can use <code>Map</code> for that case</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var usrMrid = {name: "mrid"};
var usrXYZZ = {name: "xyzz"};

var comm = new Map([
  [usrMrid, "ONE"],
  [usrXYZZ, "TWO"]
]);

console.log(comm.get(usrMrid));</code>```

Body:
When you use [] syntax with object and you pass an object as a property name, property name is going to be the string representation of the given expression, which will be in your case [object Object]. So when you use different objects, they create the same property with name [object Object] and override the previous ones.

You can see it in the example. Here I print the properties of the object and you can see that there is just one property with name [object Object].

var usrMrid = {name: "mrid"};
var usrXYZZ = {name: "xyzz"};

var comm = {};

comm[usrMrid] = "ONE";
comm[usrXYZZ] = "TWO";

console.log(comm);

You can use Map for that case

var usrMrid = {name: "mrid"};
var usrXYZZ = {name: "xyzz"};

var comm = new Map([
  [usrMrid, "ONE"],
  [usrXYZZ, "TWO"]
]);

console.log(comm.get(usrMrid));


问:
Get latest data for all people in a table and then filter based on some criteria
I am attempting to return the row of the highest value for timestamp (an integer) for each person (that has multiple entries) in a table. Additionally, I am only interested in rows with the field containing ABCD, but this should be done after filtering to return the latest (max timestamp) entry for each person.

```<code>SELECT table."person", max(table."timestamp")
FROM table
WHERE table."type" = 1
HAVING table."field" LIKE '%ABCD%'
GROUP BY table."person"
</code>```

For some reason, I am not receiving the data I expect. The returned table is nearly twice the size of expectation. Is there some step here that I am not getting correct?

答:
Direct answer: as I understand your end goal, just move the HAVING clause to the WHERE section:

```<code>SELECT
  table."person", MAX(table."timestamp")
FROM table
WHERE
    table."type" = 1
AND table."field" LIKE '%ABCD%'
GROUP BY table."person";
</code>```

This should return no more than 1 row per table."person", with their associated maximum timestamp.

As an aside, I surprised your query worked at all.  Your HAVING clause referenced a column not in your query.  From the documentation (and my experience):

The fundamental difference between WHERE and HAVING is this: WHERE selects input rows before groups and aggregates are computed (thus, it controls which rows go into the aggregate computation), whereas HAVING selects group rows after groups and aggregates are computed.

Body:
I am attempting to return the row of the highest value for timestamp (an integer) for each person (that has multiple entries) in a table. Additionally, I am only interested in rows with the field containing ABCD, but this should be done after filtering to return the latest (max timestamp) entry for each person.

SELECT table."person", max(table."timestamp")
FROM table
WHERE table."type" = 1
HAVING table."field" LIKE '%ABCD%'
GROUP BY table."person"

For some reason, I am not receiving the data I expect. The returned table is nearly twice the size of expectation. Is there some step here that I am not getting correct?

Body:
Direct answer: as I understand your end goal, just move the HAVING clause to the WHERE section:

SELECT
  table."person", MAX(table."timestamp")
FROM table
WHERE
    table."type" = 1
AND table."field" LIKE '%ABCD%'
GROUP BY table."person";

This should return no more than 1 row per table."person", with their associated maximum timestamp.

As an aside, I surprised your query worked at all.  Your HAVING clause referenced a column not in your query.  From the documentation (and my experience):

The fundamental difference between WHERE and HAVING is this: WHERE selects input rows before groups and aggregates are computed (thus, it controls which rows go into the aggregate computation), whereas HAVING selects group rows after groups and aggregates are computed.


问:
Optimal bcrypt work factor
What would be an ideal bcrypt work factor for password hashing.

If I use a factor of 10, it takes approx .1s to hash a password on my laptop. If we end up with a very busy site, that turns into a good deal of work just checking people's passwords.

Perhaps it would be better to use a work factor of 7, reducing the total password hash work to about .01s per laptop-login?

How do you decide the tradeoff between brute force safety and operational cost?

答:
Remember that the value is stored in the password: $2a$(2 chars work)$(22 chars salt)(31 chars hash). It is not a fixed value.

If you find the load is too high, just make it so the next time they log in, you crypt to something faster to compute. Similarly, as time goes on and you get better servers, if load isn't an issue, you can upgrade the strength of their hash when they log in.

The trick is to keep it taking roughly the same amount of time forever into the future along with Moore's Law. The number is log2, so every time computers double in speed, add 1 to the default number.

Decide how long you want it to take to brute force a user's password. For some common dictionary word, for instance, your account creation probably already warned them their password was weak. If it's one of 1000 common words, say, and it takes an attacker 0.1s to test each, that buys them 100s (well, some words are more common...). If a user chose 'common dictionary word' + 2 numbers, that's over two hours. If your password database is compromised, and the attacker can only get a few hundred passwords a day, you've bought most of your users hours or days to safely change their passwords. It's a matter of buying them time.

http://www.postgresql.org/docs/8.3/static/pgcrypto.html has some times for cracking passwords for you to consider. Of course, the passwords they list there are random letters. Dictionary words... Practically speaking you can't save the guy whose password is 12345.

Title: Optimal bcrypt work factor


问:
Direct Arithmetic Operations on Small-sized Numbers in RISC Architectures
Are there any RISC architectures which allow arithmetic operations to be applied individually to bytes, half-words and other data cells, whose size is less than the size of the CPU general purpose registers?

In Intel x86 (IA-32) and x86-64 (known as EM64T or AMD64) processors not only the whole register is available, but its smaller parts are operable as well. Intel ISA allows to perform all the arithmetic operations on the whole register, it's half, quarter and a byte (to be more precise, two bytes in the register are available, for example AL and AH in RAX). After the operation is performed, we can make an overflow check, and if an overflow has occurred during the previous operation, it can be easily handled. No matter whether we've operated on the whole word (32-bit wide for IA-32 and 64-bit wide for EM64T) or the arithmetic instruction was executed over the data of smaller size (half-word, quarter-word or a byte), if the result exceeds the size of the chosen data cell, the corresponding flag (OF or CF) will be set to 1. So in Intel architecture there is no need to emulate processing such errors, which occur in operations with small-sized data, with a chain of instructions analyzing higher bits of the result.

The question is are there any RISC architectures in which direct arithmetic operations on small data are possible, these operations are implemented by means of the processor hardware (no software emulation is required to perform them), and overflows, carries and borrows occurring in such operations with bytes, half-words etc. are traced by the processor equipment, they should not be checked in a software manner. Or perhaps this approach contradicts the whole RISC philosophy and no RISC processor neither in the present nor in the past has ever implemented it?

答:
TL:DR: no, AFAIK there are no RISC ISAs with flag-setting partial-register ops narrower than 32 bits.  But many 64-bit RISC ISAs (like AArch64) that have FLAGS at all can set them from the result of a 32-bit op.

See the last section: this is because of a general lack of demand for software integer overflow checking, or a chicken/egg problem.  Usually you just need to compare/branch on 16-bit values, and you can do that just fine with them zero or sign extended to 32 or 64 bit.

Only a RISC where the register width is 8 or 16 bits can set flags from that operand-size.  e.g. AVR 8-bit RISC with 32 registers and 16-bit instruction words.  It needs extended-precision add/adc just to implement 16-bit int.

This is mostly a historical thing: x86 has 16-bit operand-size for everything because of the way it evolved from 16-bit-only 286.  When 80386 was designed, it was important that it be able to run 16-bit-only code at full speed, and they provided ways to incrementally add 32-bit ops to 16-bit code.  And used the same mechanism to allow 16-bit ops in 32-bit code.

The x86 8-bit low/high register stuff (AX=AH:AL) is again partly due to how 8086 was designed as a successor to 8080 and to make porting easy (and even possible to automate)  See Why are first four x86 GPRs named in such unintuitive order?.  (And also because it was just plain useful to have eight 1-byte registers and four 2-byte registers at the same time.)

Related: Which 2's complement integer operations can be used without zeroing high bits in the inputs, if only the low part of the result is wanted?  For many calculations, you don't have to re-zero the high bits after each operation to get the same result.  So lack of 8-bit / 16-bit operand size is not an obstacle to efficient implementation of most code that logically wraps its results to 8 or 16 bits.

64-bit RISC machines often have a 32-bit version of at least some important instructions like add, so you can get a zero-extended add result for free without having to separately truncate it, e.g. to make code like array[i++] efficient with uint32_t i and 64-bit pointers.  But never partial-register operand sizes narrower than 32-bit, on any RISC I've heard of.

DEC Alpha is interesting because it was a new design, 64-bit from the ground up, not a 64-bit extension to an existing ISA the way MIPS64 is.  This table of Alpha mnemonics shows that add/sub/mul/div were all available in 32 and 64-bit forms, but shifts and compares weren't.  (There are also byte-manipulation instructions that are basically SIMD shuffle/mask/insert/extract inside 64-bit integer registers, and a SIMD packged-compare for efficient string stuff.)

According to this official MIPS64 ISA doc (section 4.3 CPU Registers).

A MIPS64 processor always produces a 64-bit result, even for those
  instructions that are architecturally defined to operate on 32 bits.
  Such instructions typically sign-extend their 32-bit result into 64
  bits. In so doing, 32-bit programs work as expected, though the
  registers are actually 64 bits wide rather than 32 bits.

(You use special instructions for full 64-bit registers, like DADDU (doubleword-add unsigned) instead of ADDU.  Note that the non-U versions of add and dadd trap on 2's complement signed overflow (with 32-bit or 64-bit operand size), so you have to use the U version for wrapping signed math.  (ISA reference links on mips.com).  Anyway, MIPS doesn't have a special mode for 32-bit, but an OS would need to care about 32-bit programs vs. 64-bit, because 32-bit will assume all pointers are in the low 32 of virtual address space.

On a RISC load/store machine, you'd usually just use zero-extending (or sign-extending) byte/halfword loads.  When you're done, you'd use a byte / halfword store to get the truncated result.  (With for unsigned base2, or 2's complement signed, is typically what you want.)  This is how a compiler (or human) would implement C source that used short or uint8_t.

Semi-related: C's integer promotion rules automatically promote everything narrower than int up to int when used as an operand to a binary operator like +, so it mostly maps nicely to this way of computing.  (i.e. unsigned result = (a+b) * c in C doesn't have to truncate the a+b result back to uint8_t before the multiply, if a, b, and c are all uint8_t.  But it's pretty bad that uint16_t promotes to signed int, so uint16_t a,b;  unsigned c = a * b risks signed-overflow UB from promoting to signed int for the multiply.)  Anyway, C's promotion rules sort of look like they're designed for machines without full support for narrow operand sizes, because that's common for a lot of hardware.

But you're asking about overflow checking / flag-setting from narrow ops.

Not all RISC machines even have a FLAGS register.  ARM does, but for example MIPS and Alpha don't.  ARM doesn't set flags on every instruction: you have to explicitly use the flag-setting form of an instruction.

CPUs without FLAGS typically have some simple compare-and-branch instructions (often against zero, like MIPS bltz), and others that compare two inputs and write a 0 / 1 result to another integer register (e.g. MIPS SLTIU -- Set on less than immediate unsigned).  You can use the Set instructions + a bne with zero to create more complex branch conditions.

Hardware and software support for efficient overflow-checking is a problem in general.  Putting a jcc after every x86 instruction sucks quite a lot, too.

But partly because most languages don't make it easy to write code that needs overflow checking after every instruction, CPU architects don't provide it in hardware, especially not for narrow operand sizes.

MIPS is interesting with trapping add for signed overflow.

Ways to implement it efficiently might include having a "sticky" flag, the way FPU exception flags are sticky: the Invalid flag stays set after dividing by zero (and producing NaN); other FP instructions don't clear it.  So you can check for exception flags at the end of a series of computations, or after a loop.  This makes it cheap enough to actually use in practice, if there was a software framework for it.

With FP code, usually you don't need to look at flags because NaN itself is "sticky" or "infectious".  Most binary operators produce NaN if either input is NaN.  But unsigned and 2's complement integer representations don't have any spare bit patterns: they all represent specific numbers.  (1's complement has negative zero...)

For more about ISA design that would make overflow checking possible, have a look at discussion on Agner Fog's proposal for a new ISA that combines the best features of x86 (code density, lots of work per instruction) and RISC (easy to decode) for a high performance paper architecture.  Some interesting SIMD ideas, including making future extensions to vector width transparent, so you don't have to recompile to run faster with wider vectors.


问:
Sending a hex string to a remote via netcat
I've got some binary commands (which I'm representing as hex) that I need to send to a remote device (it's an embedded data collection device) and observe the reply.

It's easy to connect to it with netcat

```<code>nc -v 192.168.200.34 19000
</code>```

and it sits there happy as a clam.

The hex string I need to type in terminal and then send is something like:

02:45:31:38:03:34:43:0d:0a

Where 02 is STX, 03 is ETX and so on.

But when I type this into my netcat window (with or without spaces , with or without the colons) netcat transmits it as ascii.

All the literature is happy to tell me how to capture a hexdump from the remote device, but not how to transmit binary/hex data to the remote device.

Is this an easy thing to do, or am I missing something?

答:
You can do it with command: echo -n -e "\x02\x45\x31\x38\x03\x34\x43\x0d\x0a" | nc [-u] <-ip-addr-> <-port-no->

The -n supresses outputting the trailing newline.

The -e enables the interpretation of backslash escapes -> allowing us
to send hex codes.

'x' before each character specifies that the byte is in hexadecimal form.

-u switch to UDP traffic (optional)

Body:
I've got some binary commands (which I'm representing as hex) that I need to send to a remote device (it's an embedded data collection device) and observe the reply.

It's easy to connect to it with netcat

nc -v 192.168.200.34 19000

and it sits there happy as a clam.

The hex string I need to type in terminal and then send is something like:

02:45:31:38:03:34:43:0d:0a

Where 02 is STX, 03 is ETX and so on.

But when I type this into my netcat window (with or without spaces , with or without the colons) netcat transmits it as ascii.

All the literature is happy to tell me how to capture a hexdump from the remote device, but not how to transmit binary/hex data to the remote device.

Is this an easy thing to do, or am I missing something?