问:
Prime number, need a little assistance

Background Information:

So am trying to calculate all the prime numbers inside a number, and then sum them up. sumPrimes(10) should return 17 because 2 + 3 + 5 + 7 = 17.

The challenge is here --> https://www.freecodecamp.org/challenges/sum-all-primes

I added some console.log's in just to show whats happening.

My Approach:

My approach to doing this was trying to replicate this tutorial here but in code: https://youtu.be/FBbHzy7v2Kg?t=67

What i tried with my code was to separate the number into a array from 2, to what ever your number is (1 isn't prime). 10 would look like [ 2, 3, 4, 5, 6, 7, 8, 9, 10 ]. Then i use another for loop with i to pick a number out of that previous array arr, add it to prime, and then remove every multiple of that number from the array (arr) using a separate loop. When i go back to go get another number, we already know its a prime.

The rest of this is if you don't understand.

Example:

The first number of that array is 2. So i add 2 to prime.

prime's current value: 2

And then filter out any multiple. Since i am counting by the number itself in my j loop, i already know any number is a multiple. It also removes my already prime number from the array along with all its multiple's so it would never be undefined.

arr's current value (hopefully): [ 3, 5, 7, 9]

etc (continues on with 3, 5, and then 7).

Whats going wrong?

Its not removing all the multiples. I am using splice, and i don't think its cutting out that number correctly. Help?

Please don't just give me some ES6 answer and walk away. I want to stick with my (well the video's) idea. I don't care how short your answer is, just whats wrong with mine.

The repl --> https://repl.it/@John_Nicole/prime

```<code>function sumPrimes(num) {

    var prime = 0;
    var arr = [];

    for (let i = 2; i <= num; i++) {
        arr.push(i);
    } // turns into array
    console.log(arr)

    for (let i = 0; i < arr.length; i++) {
        var number = arr[i];
        console.log("Prime: "+prime+"+"+number)
        prime+=number

        for (var j = number; j <= arr.length; j+=number) {
          arr.splice(j)
        } // j

    } // i

   return "Final result: "+prime;
}

sumPrimes(10);
</code>```

Thanks in advance :D

答:
As everyone has already pointed out, your expectation of splice() seems incorrect. Check out the MDN docs here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

```<code>>>> [1,2,3].splice() # Input
>>> []               # Output
</code>```

There are two problems:

The function is not removing the value (from arr) correctly

The looping logic for the filter doesn't take into account the changing length of the array when you remove a value

This is how you could use splice to remove a value:

This creates a copy of the array starting at the index right after the one you want to take out

```<code>arrayTail = arr.slice(j + 1);
</code>```

This extracts all the elements in the array from the start till the index just before the one you want to take out

```<code>arrayHead = arr.splice(0,j);
</code>```

Finally merge the two pieces together to get your filtered array

```<code>arr = arrayHead.concat(arrayTail);
</code>```

Alternatively, you could also use the Array.filter function:

```<code>arr = arr.filter(function(value){
    // Filter all values that are divisible by the prime
    return value % number != 0;
});
</code>```

For part two, consider:

```<code>arr = [1,2,3,4,5,6,7,8,9];
// You filter for multiples of 2
// And that's okay because all the values are indices offset by 2
arr = [1,2,3,5,9];
// You filter for multiples of 3
arr[2] == 3
arr[4] == 9
// But the multiples of 3 are no longer offset by 3
</code>```

So instead of being clever about indices, simply loop through the rest of the array as normal, and just check whether the current value is a multiple of the prime number or not.

```<code>if (arr[j] % number == 0) {
    ... your splice code
}
</code>```

Now, this might be unsolicited, it sounds like you are just learning to program. I highly recommend developing a habit of using full variable names so it is easy to read. And also including a lot of comments to highlight the logic you are trying to accomplish by that coding block.

Hopefully you find this a good example:

```<code>function sumPrimes(num) {

    var currentPrime = 0;
    var arr = [];
    var sumOfPrimes = 0;

    // Create an array of potential primes
    for (let i = 2; i <= num; i++) {
        arr.push(i);
    }
    console.log("Prime array", arr);

    // For every value in the array, remove any future multiples of it
    for (let i = 0; i < arr.length; i++) {
        var currentPrime = arr[i];
        console.log("Prime: " + currentPrime);

        sumOfPrimes += currentPrime;
        console.log("Sum of Primes: " + sumOfPrimes);

        // Remove multiples of prime
        // Start at the next value in the array
        // And loop till the end
        for (let j = i + 1; j < arr.length; j++) {
            // If the current value is a multiple of
            // the prime, then remove it
            if (arr[j] % currentPrime == 0) {
                arrayTail = arr.slice(j + 1);
                arr = arr.splice(0,j).concat(arrayTail);
                j -= 1;
                // Since you removed an element, you need to
                // move the index back so it doesn't skip
                // any checks
            }
        }

        console.log("Filtered array for ", currentPrime, arr);

    }

   return "Final result: " + sumOfPrimes;
}
</code>```

Title: Prime number, need a little assistance

Body:
Background Information:

So am trying to calculate all the prime numbers inside a number, and then sum them up. sumPrimes(10) should return 17 because 2 + 3 + 5 + 7 = 17.

The challenge is here --> https://www.freecodecamp.org/challenges/sum-all-primes

I added some console.log's in just to show whats happening.

My Approach:

My approach to doing this was trying to replicate this tutorial here but in code: https://youtu.be/FBbHzy7v2Kg?t=67

What i tried with my code was to separate the number into a array from 2, to what ever your number is (1 isn't prime). 10 would look like [ 2, 3, 4, 5, 6, 7, 8, 9, 10 ]. Then i use another for loop with i to pick a number out of that previous array arr, add it to prime, and then remove every multiple of that number from the array (arr) using a separate loop. When i go back to go get another number, we already know its a prime.

The rest of this is if you don't understand.

Example:

The first number of that array is 2. So i add 2 to prime.

prime's current value: 2

And then filter out any multiple. Since i am counting by the number itself in my j loop, i already know any number is a multiple. It also removes my already prime number from the array along with all its multiple's so it would never be undefined.

arr's current value (hopefully): [ 3, 5, 7, 9]

etc (continues on with 3, 5, and then 7).

Whats going wrong?

Its not removing all the multiples. I am using splice, and i don't think its cutting out that number correctly. Help?

Please don't just give me some ES6 answer and walk away. I want to stick with my (well the video's) idea. I don't care how short your answer is, just whats wrong with mine.

The repl --> https://repl.it/@John_Nicole/prime

function sumPrimes(num) {

    var prime = 0;
    var arr = [];

    for (let i = 2; i <= num; i++) {
        arr.push(i);
    } // turns into array
    console.log(arr)

    for (let i = 0; i < arr.length; i++) {
        var number = arr[i];
        console.log("Prime: "+prime+"+"+number)
        prime+=number

        for (var j = number; j <= arr.length; j+=number) {
          arr.splice(j)
        } // j

    } // i

   return "Final result: "+prime;
}

sumPrimes(10);

Thanks in advance :D

Body:
As everyone has already pointed out, your expectation of splice() seems incorrect. Check out the MDN docs here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

>>> [1,2,3].splice() # Input
>>> []               # Output

There are two problems:

The function is not removing the value (from arr) correctly

The looping logic for the filter doesn't take into account the changing length of the array when you remove a value

This is how you could use splice to remove a value:

This creates a copy of the array starting at the index right after the one you want to take out

arrayTail = arr.slice(j + 1);

This extracts all the elements in the array from the start till the index just before the one you want to take out

arrayHead = arr.splice(0,j);

Finally merge the two pieces together to get your filtered array

arr = arrayHead.concat(arrayTail);

Alternatively, you could also use the Array.filter function:

arr = arr.filter(function(value){
    // Filter all values that are divisible by the prime
    return value % number != 0;
});

For part two, consider:

arr = [1,2,3,4,5,6,7,8,9];
// You filter for multiples of 2
// And that's okay because all the values are indices offset by 2
arr = [1,2,3,5,9];
// You filter for multiples of 3
arr[2] == 3
arr[4] == 9
// But the multiples of 3 are no longer offset by 3

So instead of being clever about indices, simply loop through the rest of the array as normal, and just check whether the current value is a multiple of the prime number or not.

if (arr[j] % number == 0) {
    ... your splice code
}

Now, this might be unsolicited, it sounds like you are just learning to program. I highly recommend developing a habit of using full variable names so it is easy to read. And also including a lot of comments to highlight the logic you are trying to accomplish by that coding block.

Hopefully you find this a good example:

function sumPrimes(num) {

    var currentPrime = 0;
    var arr = [];
    var sumOfPrimes = 0;

    // Create an array of potential primes
    for (let i = 2; i <= num; i++) {
        arr.push(i);
    }
    console.log("Prime array", arr);

    // For every value in the array, remove any future multiples of it
    for (let i = 0; i < arr.length; i++) {
        var currentPrime = arr[i];
        console.log("Prime: " + currentPrime);

        sumOfPrimes += currentPrime;
        console.log("Sum of Primes: " + sumOfPrimes);

        // Remove multiples of prime
        // Start at the next value in the array
        // And loop till the end
        for (let j = i + 1; j < arr.length; j++) {
            // If the current value is a multiple of
            // the prime, then remove it
            if (arr[j] % currentPrime == 0) {
                arrayTail = arr.slice(j + 1);
                arr = arr.splice(0,j).concat(arrayTail);
                j -= 1;
                // Since you removed an element, you need to
                // move the index back so it doesn't skip
                // any checks
            }
        }

        console.log("Filtered array for ", currentPrime, arr);

    }

   return "Final result: " + sumOfPrimes;
}


来源: stackexchange

问:
Twitter-style time-ago formatting ("2h") with Javascript
Timeago.js does a great job of formatting time stamps relative to the current time ("about 2 hours ago").

Are there any solutions that accomplish the same thing, but abbreviated? IE "2h", like Twitter uses.

答:
In timeago.js, you can simply replace the "strings" hash with the "strings" hash here: https://github.com/rmm5t/jquery-timeago/blob/master/locales/jquery.timeago.en-short.js</p>

```<code>  jQuery.timeago.settings.strings = {
    prefixAgo: null,
    prefixFromNow: null,
    suffixAgo: "",
    suffixFromNow: "",
    seconds: "1m",
    minute: "1m",
    minutes: "%dm",
    hour: "1h",
    hours: "%dh",
    day: "1d",
    days: "%dd",
    month: "1mo",
    months: "%dmo",
    year: "1yr",
    years: "%dyr",
    wordSeparator: " ",
    numbers: []
  };
</code>```

ContentLicense: CC BY-SA 3.0

Body:
In timeago.js, you can simply replace the "strings" hash with the "strings" hash here: https://github.com/rmm5t/jquery-timeago/blob/master/locales/jquery.timeago.en-short.js

  jQuery.timeago.settings.strings = {
    prefixAgo: null,
    prefixFromNow: null,
    suffixAgo: "",
    suffixFromNow: "",
    seconds: "1m",
    minute: "1m",
    minutes: "%dm",
    hour: "1h",
    hours: "%dh",
    day: "1d",
    days: "%dd",
    month: "1mo",
    months: "%dmo",
    year: "1yr",
    years: "%dyr",
    wordSeparator: " ",
    numbers: []
  };


问:
Angular 4. How to add item to an array according to sorting
I use Angular 4.4.6 in my project. Having a list of events I want this list to be sorted by date. I achieved this by adding ng2-order-pipe

```<code>// customers.html

<tr *ngFor="let event of customer.events | orderBy: order : reverse">
</code>```

The sorting works but my problem is that if I add an event, it is placed at the end of the list, ignoring sorting.

```<code>// customers.ts

this.order               = 'date';
this.reverse             = true;

.........................................

addEvent(new_date, new_state, new_description) {

    var new_event = {
        date:        new_date,
        state:       new_state,
        description: new_description,
        customer_id: this.customer['id']
    };
this.customer['events'].push(new_event);
}
</code>```

How to add an event so that it appears in its place according to sorting?

答:
From : https://angular.io/guide/pipes#pure-and-impure-pipes

Angular ignores changes within (composite) objects. It won't call a pure pipe if you change an input month, add to an input array, or update an input object property.

Fix

Reassign the array e.g.

```<code>this.customer['events'] = this.customer['events'].concat(new_event);
</code>```

Body:
I use Angular 4.4.6 in my project. Having a list of events I want this list to be sorted by date. I achieved this by adding ng2-order-pipe

// customers.html

The sorting works but my problem is that if I add an event, it is placed at the end of the list, ignoring sorting.

// customers.ts

this.order               = 'date';
this.reverse             = true;

.........................................

addEvent(new_date, new_state, new_description) {

    var new_event = {
        date:        new_date,
        state:       new_state,
        description: new_description,
        customer_id: this.customer['id']
    };
this.customer['events'].push(new_event);
}

How to add an event so that it appears in its place according to sorting?

Body:
From : https://angular.io/guide/pipes#pure-and-impure-pipes

Angular ignores changes within (composite) objects. It won't call a pure pipe if you change an input month, add to an input array, or update an input object property.

Fix

Reassign the array e.g.

this.customer['events'] = this.customer['events'].concat(new_event);


问:
R: extracting values from summary object and turning it into a list
I am running the command summary() on a dataset in the following way:

```<code>d = summary(dataset)
</code>```

and printing d gives me this result:

```<code>7/4/2015   8/27/2015   7/4/2012   8/29/2015   7/5/2015   8/7/2015
     754         738        736        725         733       345
</code>```

I'd like to remove the incidents of dates and obtain the counts (754, 738, 736, 725, 733, 345) in a list. I've tried looking at other questions and sites, but I can't seem to find a general helpful answer.

Thanks

答:
Assuming that 'dataset' object is a vector with class as factor, the output of summary will be a named vector.  We can remove the names attribute by using as.vector or with unname

```<code>as.vector(d)
</code>```

Or

```<code>unname(d)
</code>```

Body:
I am running the command summary() on a dataset in the following way:

d = summary(dataset)

and printing d gives me this result:

7/4/2015   8/27/2015   7/4/2012   8/29/2015   7/5/2015   8/7/2015
     754         738        736        725         733       345

I'd like to remove the incidents of dates and obtain the counts (754, 738, 736, 725, 733, 345) in a list. I've tried looking at other questions and sites, but I can't seem to find a general helpful answer.

Thanks

Body:
Assuming that 'dataset' object is a vector with class as factor, the output of summary will be a named vector.  We can remove the names attribute by using as.vector or with unname

as.vector(d)

Or

unname(d)


问:
notification expiry product in vb.net with ms access
I just wanted to ask on how to notify a product on or before its expiry date in vb.net. I tried a lot of codes about it but still i am not able to solved this problem. I will really appreciate your help. Thank you</p>

答:
Since you didnt provide the table structure, I will try to help you understand the logic, which you can easily apply to your table.

```<code>SELECT Count(*)
FROM   tbproducts
WHERE  Datediff(d, now, tbproducts.expiarydate) > 0
</code>```

Here you are simply saying, "please count for me how many products (rows) that passed their expiration day, when compared with right now"

Datediff(d, now, tbproducts.expiarydate) Will subtract today's date Now from the product's expiry date, and return the difference (in days d). This will return a long number.

So the difference between 12/7/2017 (now) and 12/5/2017 (expired 2 days ago), will be 7 (7th) - (minus) 5 (5th) = 2

And the difference between 12/7/2017 (now) and 12/10/2017 (not yet expired), will be 7 (7th) - (minus) 10 (10th) = -3

So as long as Datediff(d, now, tbproducts.expiarydate) returns a number over 0 then the product is expired

Body:
Since you didnt provide the table structure, I will try to help you understand the logic, which you can easily apply to your table.

SELECT Count(*)
FROM   tbproducts
WHERE  Datediff(d, now, tbproducts.expiarydate) > 0

Here you are simply saying, "please count for me how many products (rows) that passed their expiration day, when compared with right now"

Datediff(d, now, tbproducts.expiarydate) Will subtract today's date Now from the product's expiry date, and return the difference (in days d). This will return a long number.

So the difference between 12/7/2017 (now) and 12/5/2017 (expired 2 days ago), will be 7 (7th) - (minus) 5 (5th) = 2

And the difference between 12/7/2017 (now) and 12/10/2017 (not yet expired), will be 7 (7th) - (minus) 10 (10th) = -3

So as long as Datediff(d, now, tbproducts.expiarydate) returns a number over 0 then the product is expired


问:
Best way to upgrade an Angular 2.0.0-rc.4 application
I have recently started on a project that is on Angular 2.0.0-rc.4 For some reason it was not upgraded in time. I don't find enough help online.

What would be the best approach to upgrade this kind of project.
I was think of doing it in increments RC4 to RC5 (because there is some help on this), then 2 final and then 4.

Ultimate goal is to upgrade to latest Angular version.
Any links or docs would be highly appreciated.

答:
I'm unaware of a painless way to do this. Incrementing RC4, RC5, 2 and 4 would take a lot of wasted time, I think, because the same thing may have changed twice.

I've faced situations like this a couple times (in fact I am right now, migrating an old project from old C++ to C++17), so the only honest advice I can give is what I do. For your Angular project, it would be:

Start a fresh new project which works, be comfortable with any new stuff you see;

Create the first module;

Put the first component from old project into the new. Start with the component that has less dependencies;

Go to step 3 until you have a minimally functional project, eventually creating the other modules for other components.

Unless you have unusual component interactions, this process should be fairly manageable, but potentially tedious if you have many components.

Also, to keep it up to latest version, you should go to Angular 5, not 4.


问:
Primefaces fileUpload working locally but not on server
I have developed an application which allows the user to upload a file.

I am using Primefaces 2.2RC2 / JSF 2.0 / Tomcat 6 / Firefox

Everything works great when I am running it through my local server. When I push it to my live server the entire application freezes when I attempt to upload. An authentication window appears which causes it to freeze.

The upload works fine in IE which seems ridiculous.

I am not very savy when it comes to server configuration and permissions but I am assuming that this issue is probably a permissions problem.

EDIT More information

I am not storing the file locally or anything, I am just using the FileUploadEvent and then getting the contents of the file and storing it to a database like so:

```<code>public void upload(FileUploadEvent event) {
       byte[] file = event.getFile().getContents();
       ...
       myDao.uploadFile(file);
}
</code>```

There are no errors in the error logs so I can't even start to track down what is going on, it just locks up.

From doing some research it looks like this Flash bug is causing the problem.

https://bugs.adobe.com/jira/browse/FP-1044

Does anyone know a work around?

On a side note: Can anyone recommend another way of uploading files using Tomcat 6, JSF 2.0 ? Using primefaces was one of the only solutions that I have found for my configuration. Thank you.

答:
@BalusC

I you are correct in that it is a Firefox issue. Anyway what is primefaces file upload is using the SWFupload flash component. For some reason the cred's are not POSTed when the SWFupload component posts back to the page. I have not found much of a work around other than to not use SWFupload. Since primefaces does not offer another option for fileUpload I will have to wait for Primefaces 3 I guess.

ContentLicense: CC BY-SA 2.5

Body:
I have developed an application which allows the user to upload a file.

I am using Primefaces 2.2RC2 / JSF 2.0 / Tomcat 6 / Firefox

Everything works great when I am running it through my local server. When I push it to my live server the entire application freezes when I attempt to upload. An authentication window appears which causes it to freeze.

The upload works fine in IE which seems ridiculous.

I am not very savy when it comes to server configuration and permissions but I am assuming that this issue is probably a permissions problem.

EDIT More information

I am not storing the file locally or anything, I am just using the FileUploadEvent and then getting the contents of the file and storing it to a database like so:

public void upload(FileUploadEvent event) {
       byte[] file = event.getFile().getContents();
       ...
       myDao.uploadFile(file);
}

There are no errors in the error logs so I can't even start to track down what is going on, it just locks up.

From doing some research it looks like this Flash bug is causing the problem.

https://bugs.adobe.com/jira/browse/FP-1044

Does anyone know a work around?

On a side note: Can anyone recommend another way of uploading files using Tomcat 6, JSF 2.0 ? Using primefaces was one of the only solutions that I have found for my configuration. Thank you.


问:
How to eliminate if-else with same condition but different actions inside another if-else?
Suppose I have the code like following:

```<code>int age=(from user input);
int weight=(from user input);

if(age>60){
    if(weight>100){
        function1();
    }else if(weight<40){
        function2();
    }else{
        function3();
    }
}else if(age<20){
    if(weight>100){
        function4();
    }else if(weight<40){
        function5();
    }else{
        function6();
    }
}else{
    if(weight>100){
        function7();
    }else if(weight<40){
        function8();
    }else{
        function9();
    }
}
</code>```

the problem is that the code pattern:

```<code>if(weight>100){
    //do something different
}else if(weight<40){
    //do something different
}else{
    //do something different
}
</code>```

repeats as there are different ranges of age. And I can't enclose the inner if-else into a single function, because the things to do is different even through the condition is the same. Is there any way to modify this code so that the code pattern:

```<code>if(age>60){
    //do something different
}else if(age<20){
    //do something different
}else{
    //do something different
}
</code>```

and

```<code>if(weight>100){
    //do something different
}else if(weight<40){
    //do something different
}else{
    //do something different
}
</code>```

would appear once only?

答:
Not particularly elegant.  In brief, make up a method that do that inner-condition-check, and allow the "action" for different case to be passed in</p>

```<code>// Change to use other proper functional interface.  Using Runnable
// just to align with your sample code.
doOnWeight(int weight,
           Runnable overWeightAction,
           Runnable normalWeightAction,
           Runnable underWeightAction) {
    if(weight>100){
        overWeightAction.apply();
    }else if(weight<40){
        underWeightAction.apply();
    }else{
        normalWeightAction.apply();
    }
}
//.......

// your original code, I assume your functions are instance methods
if(age>60){
    doOnWeight(weight, this::function1, this::function3, this::function2)
}else if(age<20){
    doOnWeight(weight, this::function4, this::function6, this::function5)
}else{
    doOnWeight(weight, this::function7, this::function9, this::function8)
}
</code>```

Body:
Suppose I have the code like following:

int age=(from user input);
int weight=(from user input);

if(age>60){
    if(weight>100){
        function1();
    }else if(weight<40){
        function2();
    }else{
        function3();
    }
}else if(age<20){
    if(weight>100){
        function4();
    }else if(weight<40){
        function5();
    }else{
        function6();
    }
}else{
    if(weight>100){
        function7();
    }else if(weight<40){
        function8();
    }else{
        function9();
    }
}

the problem is that the code pattern:

if(weight>100){
    //do something different
}else if(weight<40){
    //do something different
}else{
    //do something different
}

repeats as there are different ranges of age. And I can't enclose the inner if-else into a single function, because the things to do is different even through the condition is the same. Is there any way to modify this code so that the code pattern:

if(age>60){
    //do something different
}else if(age<20){
    //do something different
}else{
    //do something different
}

and

if(weight>100){
    //do something different
}else if(weight<40){
    //do something different
}else{
    //do something different
}

would appear once only?

Body:
Not particularly elegant.  In brief, make up a method that do that inner-condition-check, and allow the "action" for different case to be passed in

// Change to use other proper functional interface.  Using Runnable
// just to align with your sample code.
doOnWeight(int weight,
           Runnable overWeightAction,
           Runnable normalWeightAction,
           Runnable underWeightAction) {
    if(weight>100){
        overWeightAction.apply();
    }else if(weight<40){
        underWeightAction.apply();
    }else{
        normalWeightAction.apply();
    }
}
//.......

// your original code, I assume your functions are instance methods
if(age>60){
    doOnWeight(weight, this::function1, this::function3, this::function2)
}else if(age<20){
    doOnWeight(weight, this::function4, this::function6, this::function5)
}else{
    doOnWeight(weight, this::function7, this::function9, this::function8)
}


问:
How to automate program initialization through GUI
We have a software that needs to get password to be initialized. Software is running on a build server (Windows 10) and used as part of the build process. Password resets after reboot or after RDP session. Therefore RDP access to the server is disabled and it's running VNC.

However, still we have a problem that once in a while server reboots and in this case someone needs to login to the server over VNC and to initialize the software by typing password in.

Is there any way that this process may be automated? Some QA tools that may be utilized for this puprpose?

答: If auto logon is set (find the instruction on SuperUser site), startup script can run on this server without alive VNC connection (in Windows Task Scheduler by logon trigger). As an GUI automation library you can use pywinauto (need any Python on the server + pip install pywinauto). If you keep the server always logged in, maybe another trigger would be useful (from Jenkins slave if it's connected to Jenkins). But it must run not as a service (services can't access GUI).


问:
Visual Studio Code + TypeScript referencing renamed file
I had a file called FooBar.ts and decided to rename it to fooBar.ts but now VS Code keeps referencing the old file. I had to disable forceConsistentCasingInFileNames from tsconfig.json othewise it would keep thinking there were two files with only different casing, but even then, when trying to add the import automatically, VS Code still references the old file.

I tried cleaning it's cache but still getting the same error. Is it something I'm doing wrong or some sort of config I'm missing?

答:
I tried cleaning it's cache but still getting the same error. Is it something I'm doing wrong or some sort of config I'm missing?

Make sure the old file does not exist and then just restart vscode

More

You might need to name file differently intermediately e.g. Foo -> foos -> foo.


问:
How to see static or global variables in Eclipse CDT?
I have been trying to figure out how to display static variables in the eclipse variable window for the CDT and can't figure out how. The menu button for the CDT doesn't seem to have the java->globals menu. How do I display static/global variables in eclipse CDT debugger?</p>

答: Arrow down button > Java > Show Constants / Show Static Variables


问:
What's the purpose of Javascript's Array Method valueOf?
I may get hammered for asking something overly vague, so please interpret this as a meta-programming question, as it is meant to be, and not as some sort of indirect flame war.

In trying to understand Javascript's Array a bit deeper, I ran across this W3 reference for Array.valueOf.

It simply says:

The valueOf() method returns the array.

This method is the default method of the array object. Array.valueOf() will return the same as Array

Note: This method will not change the original array.

So, I ask: what's the point?  Is there a reason to ever use the Array.valueOf() method?  Is it useful in some more complicated constructs, such as when using call or apply?  Does it help in piping together functions?  Is this simply because it creates a standard method, compared to other objects where the associated valueOf is more useful, and therefore help to generalize Array to other objects?

As far as I can tell, it is exactly identical, so I don't see its value.

答:
This method is inherited from Object.prototype; every object that descends from Object.prototype has it. Primitive wrappers override it to return the corresponding primitive, for example, converting new Number(5) to 5. The default implementation returns the object unchanged.

JavaScript calls the valueOf method to convert an object to a primitive value. You rarely need to invoke the valueOf method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected.


问:
Check if string is a valid date, and if it is, whether it is in a specific range
So i'm trying to validate date in format DDMMYYYY.

```<code>string date = "12031996";
</code>```

i want to be able to validate if what user entered is in this specific format. And also want to be able to check if the year is in range of 1980 - 2005.

I'm new to C# so please forgive if it sounds like a stupid question.
Thanks :)

答:
```<code>if (DateTime.TryParseExact(date, "ddMMyyyy", NULL, DateTimeStyle.None, out DateTime dateTime))
{
    int year = dateTime.Year;
    if (year >= 1980 && year <= 2005)
        //do something if in range
    else
        //do something otherwise
}
else
    //do something for invalid format.
</code>```

To learn more about how to parse a date time string in C#, read this page on MSDN and this one.

Body:
So i'm trying to validate date in format DDMMYYYY.

string date = "12031996";

i want to be able to validate if what user entered is in this specific format. And also want to be able to check if the year is in range of 1980 - 2005.

I'm new to C# so please forgive if it sounds like a stupid question.
Thanks :)

Body:
if (DateTime.TryParseExact(date, "ddMMyyyy", NULL, DateTimeStyle.None, out DateTime dateTime))
{
    int year = dateTime.Year;
    if (year >= 1980 && year <= 2005)
        //do something if in range
    else
        //do something otherwise
}
else
    //do something for invalid format.

To learn more about how to parse a date time string in C#, read this page on MSDN and this one.


问:
Foreign characters in website
I found a website that contains the string "donâ€™t". The obvious intent was the word "don't". I looked at the source expecting to see some character references, but didn't (it just shows the literal string "donâ€™t". A Google search yielded nothing (expect lots of other sites that have the same problem!). Can anyone explain what's happening here?

Edit: Here's the meta tag that was used:

```<code><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</code>```

Would this not cause the page to be served up as Latin-1 in the HTTP header?

答: This thread explains all.  A combination of using a weird UTF-8 apostrophe character (probably originating from a Word Document), on a server that probably reports its encoding as non-UTF-8, despite the page having UTF characters (and possible even correctly reporting its own encoding).</p>

Title: Foreign characters in website

Body:
I found a website that contains the string "donâ€™t". The obvious intent was the word "don't". I looked at the source expecting to see some character references, but didn't (it just shows the literal string "donâ€™t". A Google search yielded nothing (expect lots of other sites that have the same problem!). Can anyone explain what's happening here?

Edit: Here's the meta tag that was used:

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">

Would this not cause the page to be served up as Latin-1 in the HTTP header?


问:
Convert variable types into unicode string
I'm looking for a way to convert a variable (which could be an ASCII string, unicode string WITH extra characters like é or £, or a floats or integer) into a unicode string.

variable.encode('utf-8') where variable is an integer results in AttributeError: 'int' object has no attribute 'encode'

str(variable).encode('utf-8') where variable is the string '£' results in UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 0: ordinal not in range(128)

Is there an easy way to do what I'm looking for in Python 2.7? Or do I have to check the type of variable and process it differently?

答:
this is an old post but I had the exact same problem :/ I ended up using the unicode function. this is a builtin function you can read about it here

so the only change is instead of str(theThing) you can use unicode(theThing) , as said in documentation it does behave like str except it converts to a unicode string not an ascii one.

just as a word of caution if you are using some kind of file writing or some other stuff you might run into problems there as well or at least I did :D and this post fixed mine


问:
Pretty-print an entire Pandas Series / DataFrame
I work with Series and DataFrames on the terminal a lot. The default __repr__ for a Series returns a reduced sample, with some head and tail values, but the rest missing.

Is there a builtin way to pretty-print the entire Series / DataFrame?  Ideally, it would support proper alignment, perhaps borders between columns, and maybe even color-coding for the different columns.

答:
Try this</p>

```<code>pd.set_option('display.height',1000)
pd.set_option('display.max_rows',500)
pd.set_option('display.max_columns',500)
pd.set_option('display.width',1000)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Try this

pd.set_option('display.height',1000)
pd.set_option('display.max_rows',500)
pd.set_option('display.max_columns',500)
pd.set_option('display.width',1000)


问:
How do I sum up all remaing amount after get max value from array?
I hesitated to this question either should I ask or not. I think that this is much more logical question. But, I can't really figure it out.

I have a array that may include

```<code>$programFees = [100,200,100,500,800,800]
</code>```

I can get max value from this array using max($programFees). If I have 2 max value like 800,800, I want to take one only. I realized that php max can solve this.

But, I want to sum up all remaining amount from that array.

e.g

```<code>$maxProgramFees = max($programFees);
//I got 800 and remaining amount is [100,200,100,500,800]
</code>```

My total amount should be 1700. Which approach should I use to get this amount?

答:
@helllomatt has already provided a very good answer, however, if you cannot modify the array order for some reason you may want to try something like this.

```<code>$programFees = [100,200,100,500,800,800];
$maxProgramFees = max($programFees);
$sum = array_sum(array_diff($programFees, array($maxProgramFees)));
</code>```

I would assume the rsort() answer would be the faster option.

Body:
I hesitated to this question either should I ask or not. I think that this is much more logical question. But, I can't really figure it out.

I have a array that may include

$programFees = [100,200,100,500,800,800]

I can get max value from this array using max($programFees). If I have 2 max value like 800,800, I want to take one only. I realized that php max can solve this.

But, I want to sum up all remaining amount from that array.

e.g

$maxProgramFees = max($programFees);
//I got 800 and remaining amount is [100,200,100,500,800]

My total amount should be 1700. Which approach should I use to get this amount?

Body:
@helllomatt has already provided a very good answer, however, if you cannot modify the array order for some reason you may want to try something like this.

$programFees = [100,200,100,500,800,800];
$maxProgramFees = max($programFees);
$sum = array_sum(array_diff($programFees, array($maxProgramFees)));

I would assume the rsort() answer would be the faster option.


问:
Impersonation in a multi-forest environment throws ErrorNonExistentMailbox
I am trying to access Exchange in a resource forest with a user that is in the user forest, and impersonate mailboxes that are in the resource forest.

For this, we have created a contact as described here and added it to the ApplicationImpersonation security group as described here.

At first, the impersonation seems to be working, since the error

The account does not have permission to impersonate the requested user.

has gone away as soon as the account has been added to the ApplicationImpersonation group.

However, the impersonating user still cannot access the folders it should access; the error thrown is

The SMTP address has no mailbox associated with it.

Now, that error message seems to be wrong, not only since AutoDiscover returned that very server as the Exchange server associated to that very mailbox. But what is the reason for this error message? Find attached an EWS trace.

```<code>AutodiscoverConfiguration: <Trace Tag="AutodiscoverConfiguration" Tid="19" Time="2017-12-06 11:47:15Z">
Starting SCP lookup for domainName='maildomain.com', root path=''
</Trace>

AutodiscoverConfiguration: <Trace Tag="AutodiscoverConfiguration" Tid="19" Time="2017-12-06 11:47:15Z">
Searching for SCP entries in LDAP://CN=Configuration,DC=resourceforest,DC=local
</Trace>

AutodiscoverConfiguration: <Trace Tag="AutodiscoverConfiguration" Tid="19" Time="2017-12-06 11:47:15Z">
Scanning for SCP pointers Domain=maildomain.com
</Trace>

AutodiscoverConfiguration: <Trace Tag="AutodiscoverConfiguration" Tid="19" Time="2017-12-06 11:47:15Z">
No SCP pointers found for 'Domain=maildomain.com' in configPath='CN=Configuration,DC=resourceforest,DC=local'
</Trace>

AutodiscoverConfiguration: <Trace Tag="AutodiscoverConfiguration" Tid="19" Time="2017-12-06 11:47:15Z">
Scanning for SCP urls for the current computer Site=Default-First-Site-Name
</Trace>

AutodiscoverConfiguration: <Trace Tag="AutodiscoverConfiguration" Tid="19" Time="2017-12-06 11:47:15Z">
Adding (prio 1) 'https://autodiscover.maildomain.com/Autodiscover/Autodiscover.xml' for the 'Site=Default-First-Site-Name' from 'LDAP://CN=EXCHSRV,CN=Autodiscover,CN=Protocols,CN=EXCHSRV,CN=Servers,CN=Exchange Administrative Group (FYDIBOHF23SPDLT),CN=Administrative Groups,CN=EXCH,CN=Microsoft Exchange,CN=Services,CN=Configuration,DC=resourceforest,DC=local' to the top of the list (exact match)
</Trace>

AutodiscoverConfiguration: <Trace Tag="AutodiscoverConfiguration" Tid="19" Time="2017-12-06 11:47:15Z">
Determining which endpoints are enabled for host autodiscover.maildomain.com
</Trace>

AutodiscoverConfiguration: <Trace Tag="AutodiscoverConfiguration" Tid="19" Time="2017-12-06 11:47:15Z">
Request error: The remote server has returned an error: (401) Not authorized.
</Trace>

AutodiscoverConfiguration: <Trace Tag="AutodiscoverConfiguration" Tid="19" Time="2017-12-06 11:47:15Z">
Host returned enabled endpoint flags: Legacy, Soap, WsSecurity, OAuth
</Trace>

AutodiscoverRequestHttpHeaders: <Trace Tag="AutodiscoverRequestHttpHeaders" Tid="19" Time="2017-12-06 11:47:15Z">
POST /autodiscover/autodiscover.svc HTTP/1.1
Content-Type: text/xml; charset=utf-8
Accept: text/xml
User-Agent: ExchangeServicesClient/15.00.0913.015

</Trace>

AutodiscoverRequest: <Trace Tag="AutodiscoverRequest" Tid="19" Time="2017-12-06 11:47:15Z" Version="15.00.0913.015">
  <?xml version="1.0" encoding="utf-8"?>
  <soap:Envelope xmlns:a="http://schemas.microsoft.com/exchange/2010/Autodiscover" xmlns:wsa="http://www.w3.org/2005/08/addressing" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
    <soap:Header>
      <a:RequestedServerVersion>Exchange2010_SP2</a:RequestedServerVersion>
      <wsa:Action>http://schemas.microsoft.com/exchange/2010/Autodiscover/Autodiscover/GetUserSettings</wsa:Action>
      <wsa:To>https://autodiscover.maildomain.com/autodiscover/autodiscover.svc</wsa:To>
    </soap:Header>
    <soap:Body>
      <a:GetUserSettingsRequestMessage xmlns:a="http://schemas.microsoft.com/exchange/2010/Autodiscover">
        <a:Request>
          <a:Users>
            <a:User>
              <a:Mailbox>existingmailbox@maildomain.com</a:Mailbox>
            </a:User>
          </a:Users>
          <a:RequestedSettings>
            <a:Setting>InternalEwsUrl</a:Setting>
            <a:Setting>ExternalEwsUrl</a:Setting>
          </a:RequestedSettings>
        </a:Request>
      </a:GetUserSettingsRequestMessage>
    </soap:Body>
  </soap:Envelope>
</Trace>

AutodiscoverResponseHttpHeaders: <Trace Tag="AutodiscoverResponseHttpHeaders" Tid="19" Time="2017-12-06 11:47:15Z">
HTTP/1.1 200 OK
Transfer-Encoding: chunked
request-id: 2595c423-85bb-4e19-95c0-69fff1b770cf
X-CalculatedBETarget: exchsrv.resourceforest.local
X-DiagInfo: EXCHSRV
X-BEServer: EXCHSRV
Persistent-Auth: true
X-FEServer: EXCHSRV
Cache-Control: private
Content-Type: text/xml; charset=utf-8
Date: Wed, 06 Dec 2017 11:44:00 GMT
Set-Cookie: X-BackEndCookie=S-1-5-21-1233478190-3624727864-577162443-1630=u56Lnp2ejJqBnJ7LyJ3LncnSzJvGnNLLzsma0p6eysbSnpnIns6czp3Mx5vOgYHNz87H0s/O0s/Kq87OxcvLxc/O; expires=Fri, 05-Jan-2018 11:44:01 GMT; path=/autodiscover; secure; HttpOnly
Server: Microsoft-IIS/8.5
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET

</Trace>

AutodiscoverResponse: <Trace Tag="AutodiscoverResponse" Tid="19" Time="2017-12-06 11:47:15Z" Version="15.00.0913.015">
  <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" xmlns:a="http://www.w3.org/2005/08/addressing">
    <s:Header>
      <a:Action s:mustUnderstand="1">http://schemas.microsoft.com/exchange/2010/Autodiscover/Autodiscover/GetUserSettingsResponse</a:Action>
      <h:ServerVersionInfo xmlns:h="http://schemas.microsoft.com/exchange/2010/Autodiscover" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
        <h:MajorVersion>15</h:MajorVersion>
        <h:MinorVersion>0</h:MinorVersion>
        <h:MajorBuildNumber>1347</h:MajorBuildNumber>
        <h:MinorBuildNumber>0</h:MinorBuildNumber>
        <h:Version>Exchange2013_SP1</h:Version>
      </h:ServerVersionInfo>
    </s:Header>
    <s:Body>
      <GetUserSettingsResponseMessage xmlns="http://schemas.microsoft.com/exchange/2010/Autodiscover">
        <Response xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
          <ErrorCode>NoError</ErrorCode>
          <ErrorMessage />
          <UserResponses>
            <UserResponse>
              <ErrorCode>NoError</ErrorCode>
              <ErrorMessage>No error.</ErrorMessage>
              <RedirectTarget i:nil="true" />
              <UserSettingErrors />
              <UserSettings>
                <UserSetting i:type="StringSetting">
                  <Name>InternalEwsUrl</Name>
                  <Value>https://exchsrv.maildomain.com/EWS/Exchange.asmx</Value>
                </UserSetting>
                <UserSetting i:type="StringSetting">
                  <Name>ExternalEwsUrl</Name>
                  <Value>https://exchsrv.maildomain.com/EWS/Exchange.asmx</Value>
                </UserSetting>
              </UserSettings>
            </UserResponse>
          </UserResponses>
        </Response>
      </GetUserSettingsResponseMessage>
    </s:Body>
  </s:Envelope>
</Trace>

EwsRequestHttpHeaders: <Trace Tag="EwsRequestHttpHeaders" Tid="19" Time="2017-12-06 11:47:15Z">
POST /EWS/Exchange.asmx HTTP/1.1
Content-Type: text/xml; charset=utf-8
Accept: text/xml
User-Agent: ExchangeServicesClient/15.00.0913.015
Accept-Encoding: gzip,deflate

</Trace>

EwsRequest: <Trace Tag="EwsRequest" Tid="19" Time="2017-12-06 11:47:15Z" Version="15.00.0913.015">
  <?xml version="1.0" encoding="utf-8"?>
  <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages" xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
    <soap:Header>
      <t:RequestServerVersion Version="Exchange2010_SP2" />
      <t:ExchangeImpersonation>
        <t:ConnectingSID>
          <t:SmtpAddress>existingmailbox@maildomain.com</t:SmtpAddress>
        </t:ConnectingSID>
      </t:ExchangeImpersonation>
    </soap:Header>
    <soap:Body>
      <m:GetFolder>
        <m:FolderShape>
          <t:BaseShape>AllProperties</t:BaseShape>
        </m:FolderShape>
        <m:FolderIds>
          <t:DistinguishedFolderId Id="calendar">
            <t:Mailbox>
              <t:EmailAddress>existingmailbox@maildomain.com</t:EmailAddress>
            </t:Mailbox>
          </t:DistinguishedFolderId>
        </m:FolderIds>
      </m:GetFolder>
    </soap:Body>
  </soap:Envelope>
</Trace>

EwsResponseHttpHeaders: <Trace Tag="EwsResponseHttpHeaders" Tid="19" Time="2017-12-06 11:47:15Z">
HTTP/1.1 500 Internal Server Error
Transfer-Encoding: chunked
request-id: 1027a792-caae-4b8b-99b9-33f35233e2e6
X-CalculatedBETarget: exchsrv.resourceforest.local
X-DiagInfo: EXCHSRV
X-BEServer: EXCHSRV
Cache-Control: private
Content-Type: text/xml; charset=utf-8
Set-Cookie: exchangecookie=d43cb59780624405a5f6874f3c5186f9; expires=Thu, 06-Dec-2018 11:44:01 GMT; path=/; HttpOnly,X-BackEndCookie=S-1-5-21-1233478190-3624727864-577162443-1630=u56Lnp2ejJqBnJ7LyJ3LncnSzJvGnNLLzsma0p6eysbSnpnIns6czp3Mx5vOgYHNz87H0s/O0s/Kq87OxcvLxc/O; expires=Fri, 05-Jan-2018 11:44:01 GMT; path=/EWS; secure; HttpOnly
Server: Microsoft-IIS/8.5
X-AspNet-Version: 4.0.30319
Persistent-Auth: true
X-Powered-By: ASP.NET
X-FEServer: EXCHSRV
Date: Wed, 06 Dec 2017 11:44:00 GMT

</Trace>

EwsResponse: <Trace Tag="EwsResponse" Tid="19" Time="2017-12-06 11:47:15Z" Version="15.00.0913.015">
  <?xml version="1.0" encoding="utf-8"?>
  <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
    <s:Body>
      <s:Fault>
        <faultcode xmlns:a="http://schemas.microsoft.com/exchange/services/2006/types">a:ErrorNonExistentMailbox</faultcode>
        <faultstring xml:lang="de-DE">The SMTP address has no mailbox associated with it.</faultstring>
        <detail>
          <e:ResponseCode xmlns:e="http://schemas.microsoft.com/exchange/services/2006/errors">ErrorNonExistentMailbox</e:ResponseCode>
          <e:Message xmlns:e="http://schemas.microsoft.com/exchange/services/2006/errors">The SMTP address has no mailbox associated with it.</e:Message>
          <t:MessageXml xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types">
            <t:Value Name="SmtpAddress">existingmailbox@maildomain.com</t:Value>
          </t:MessageXml>
        </detail>
      </s:Fault>
    </s:Body>
  </s:Envelope>
</Trace>
</code>```

答: I believe that the impersonation user must have a mailbox as well.</p>

Body:
I am trying to access Exchange in a resource forest with a user that is in the user forest, and impersonate mailboxes that are in the resource forest.

For this, we have created a contact as described here and added it to the ApplicationImpersonation security group as described here.

At first, the impersonation seems to be working, since the error

The account does not have permission to impersonate the requested user.

has gone away as soon as the account has been added to the ApplicationImpersonation group.

However, the impersonating user still cannot access the folders it should access; the error thrown is

The SMTP address has no mailbox associated with it.

Now, that error message seems to be wrong, not only since AutoDiscover returned that very server as the Exchange server associated to that very mailbox. But what is the reason for this error message? Find attached an EWS trace.

AutodiscoverConfiguration: <Trace Tag="AutodiscoverConfiguration" Tid="19" Time="2017-12-06 11:47:15Z">
Starting SCP lookup for domainName='maildomain.com', root path=''
</Trace>

AutodiscoverConfiguration: <Trace Tag="AutodiscoverConfiguration" Tid="19" Time="2017-12-06 11:47:15Z">
Searching for SCP entries in LDAP://CN=Configuration,DC=resourceforest,DC=local
</Trace>

AutodiscoverConfiguration: <Trace Tag="AutodiscoverConfiguration" Tid="19" Time="2017-12-06 11:47:15Z">
Scanning for SCP pointers Domain=maildomain.com
</Trace>

AutodiscoverConfiguration: <Trace Tag="AutodiscoverConfiguration" Tid="19" Time="2017-12-06 11:47:15Z">
No SCP pointers found for 'Domain=maildomain.com' in configPath='CN=Configuration,DC=resourceforest,DC=local'
</Trace>

AutodiscoverConfiguration: <Trace Tag="AutodiscoverConfiguration" Tid="19" Time="2017-12-06 11:47:15Z">
Scanning for SCP urls for the current computer Site=Default-First-Site-Name
</Trace>

AutodiscoverConfiguration: <Trace Tag="AutodiscoverConfiguration" Tid="19" Time="2017-12-06 11:47:15Z">
Adding (prio 1) 'https://autodiscover.maildomain.com/Autodiscover/Autodiscover.xml' for the 'Site=Default-First-Site-Name' from 'LDAP://CN=EXCHSRV,CN=Autodiscover,CN=Protocols,CN=EXCHSRV,CN=Servers,CN=Exchange Administrative Group (FYDIBOHF23SPDLT),CN=Administrative Groups,CN=EXCH,CN=Microsoft Exchange,CN=Services,CN=Configuration,DC=resourceforest,DC=local' to the top of the list (exact match)
</Trace>

AutodiscoverConfiguration: <Trace Tag="AutodiscoverConfiguration" Tid="19" Time="2017-12-06 11:47:15Z">
Determining which endpoints are enabled for host autodiscover.maildomain.com
</Trace>

AutodiscoverConfiguration: <Trace Tag="AutodiscoverConfiguration" Tid="19" Time="2017-12-06 11:47:15Z">
Request error: The remote server has returned an error: (401) Not authorized.
</Trace>

AutodiscoverConfiguration: <Trace Tag="AutodiscoverConfiguration" Tid="19" Time="2017-12-06 11:47:15Z">
Host returned enabled endpoint flags: Legacy, Soap, WsSecurity, OAuth
</Trace>

AutodiscoverRequestHttpHeaders: <Trace Tag="AutodiscoverRequestHttpHeaders" Tid="19" Time="2017-12-06 11:47:15Z">
POST /autodiscover/autodiscover.svc HTTP/1.1
Content-Type: text/xml; charset=utf-8
Accept: text/xml
User-Agent: ExchangeServicesClient/15.00.0913.015

</Trace>

AutodiscoverRequest: <Trace Tag="AutodiscoverRequest" Tid="19" Time="2017-12-06 11:47:15Z" Version="15.00.0913.015">
  <?xml version="1.0" encoding="utf-8"?>
  <soap:Envelope xmlns:a="http://schemas.microsoft.com/exchange/2010/Autodiscover" xmlns:wsa="http://www.w3.org/2005/08/addressing" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
    <soap:Header>
      Exchange2010_SP2
      <wsa:Action>http://schemas.microsoft.com/exchange/2010/Autodiscover/Autodiscover/GetUserSettings</wsa:Action>
      <wsa:To>https://autodiscover.maildomain.com/autodiscover/autodiscover.svc</wsa:To>
    </soap:Header>
    <soap:Body>

              existingmailbox@maildomain.com

            InternalEwsUrl
            ExternalEwsUrl

    </soap:Body>
  </soap:Envelope>
</Trace>

AutodiscoverResponseHttpHeaders: <Trace Tag="AutodiscoverResponseHttpHeaders" Tid="19" Time="2017-12-06 11:47:15Z">
HTTP/1.1 200 OK
Transfer-Encoding: chunked
request-id: 2595c423-85bb-4e19-95c0-69fff1b770cf
X-CalculatedBETarget: exchsrv.resourceforest.local
X-DiagInfo: EXCHSRV
X-BEServer: EXCHSRV
Persistent-Auth: true
X-FEServer: EXCHSRV
Cache-Control: private
Content-Type: text/xml; charset=utf-8
Date: Wed, 06 Dec 2017 11:44:00 GMT
Set-Cookie: X-BackEndCookie=S-1-5-21-1233478190-3624727864-577162443-1630=u56Lnp2ejJqBnJ7LyJ3LncnSzJvGnNLLzsma0p6eysbSnpnIns6czp3Mx5vOgYHNz87H0s/O0s/Kq87OxcvLxc/O; expires=Fri, 05-Jan-2018 11:44:01 GMT; path=/autodiscover; secure; HttpOnly
Server: Microsoft-IIS/8.5
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET

</Trace>

AutodiscoverResponse: <Trace Tag="AutodiscoverResponse" Tid="19" Time="2017-12-06 11:47:15Z" Version="15.00.0913.015">
  <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" xmlns:a="http://www.w3.org/2005/08/addressing">
    <s:Header>
      http://schemas.microsoft.com/exchange/2010/Autodiscover/Autodiscover/GetUserSettingsResponse
      <h:ServerVersionInfo xmlns:h="http://schemas.microsoft.com/exchange/2010/Autodiscover" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
        <h:MajorVersion>15</h:MajorVersion>
        <h:MinorVersion>0</h:MinorVersion>
        <h:MajorBuildNumber>1347</h:MajorBuildNumber>
        <h:MinorBuildNumber>0</h:MinorBuildNumber>
        <h:Version>Exchange2013_SP1</h:Version>
      </h:ServerVersionInfo>
    </s:Header>
    <s:Body>
      <GetUserSettingsResponseMessage xmlns="http://schemas.microsoft.com/exchange/2010/Autodiscover">
        <Response xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
          <ErrorCode>NoError</ErrorCode>
          <ErrorMessage />
          <UserResponses>
            <UserResponse>
              <ErrorCode>NoError</ErrorCode>
              <ErrorMessage>No error.</ErrorMessage>
              <RedirectTarget i:nil="true" />
              <UserSettingErrors />
              <UserSettings>
                <UserSetting i:type="StringSetting">
                  <Name>InternalEwsUrl</Name>
                  <Value>https://exchsrv.maildomain.com/EWS/Exchange.asmx</Value>
                </UserSetting>
                <UserSetting i:type="StringSetting">
                  <Name>ExternalEwsUrl</Name>
                  <Value>https://exchsrv.maildomain.com/EWS/Exchange.asmx</Value>
                </UserSetting>
              </UserSettings>
            </UserResponse>
          </UserResponses>
        </Response>
      </GetUserSettingsResponseMessage>
    </s:Body>
  </s:Envelope>
</Trace>

EwsRequestHttpHeaders: <Trace Tag="EwsRequestHttpHeaders" Tid="19" Time="2017-12-06 11:47:15Z">
POST /EWS/Exchange.asmx HTTP/1.1
Content-Type: text/xml; charset=utf-8
Accept: text/xml
User-Agent: ExchangeServicesClient/15.00.0913.015
Accept-Encoding: gzip,deflate

</Trace>

EwsRequest: <Trace Tag="EwsRequest" Tid="19" Time="2017-12-06 11:47:15Z" Version="15.00.0913.015">
  <?xml version="1.0" encoding="utf-8"?>
  <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages" xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
    <soap:Header>
      <t:RequestServerVersion Version="Exchange2010_SP2" />
      <t:ExchangeImpersonation>
        <t:ConnectingSID>
          <t:SmtpAddress>existingmailbox@maildomain.com</t:SmtpAddress>
        </t:ConnectingSID>
      </t:ExchangeImpersonation>
    </soap:Header>
    <soap:Body>
      <m:GetFolder>
        <m:FolderShape>
          <t:BaseShape>AllProperties</t:BaseShape>
        </m:FolderShape>
        <m:FolderIds>
          <t:DistinguishedFolderId Id="calendar">
            <t:Mailbox>
              <t:EmailAddress>existingmailbox@maildomain.com</t:EmailAddress>
            </t:Mailbox>
          </t:DistinguishedFolderId>
        </m:FolderIds>
      </m:GetFolder>
    </soap:Body>
  </soap:Envelope>
</Trace>

EwsResponseHttpHeaders: <Trace Tag="EwsResponseHttpHeaders" Tid="19" Time="2017-12-06 11:47:15Z">
HTTP/1.1 500 Internal Server Error
Transfer-Encoding: chunked
request-id: 1027a792-caae-4b8b-99b9-33f35233e2e6
X-CalculatedBETarget: exchsrv.resourceforest.local
X-DiagInfo: EXCHSRV
X-BEServer: EXCHSRV
Cache-Control: private
Content-Type: text/xml; charset=utf-8
Set-Cookie: exchangecookie=d43cb59780624405a5f6874f3c5186f9; expires=Thu, 06-Dec-2018 11:44:01 GMT; path=/; HttpOnly,X-BackEndCookie=S-1-5-21-1233478190-3624727864-577162443-1630=u56Lnp2ejJqBnJ7LyJ3LncnSzJvGnNLLzsma0p6eysbSnpnIns6czp3Mx5vOgYHNz87H0s/O0s/Kq87OxcvLxc/O; expires=Fri, 05-Jan-2018 11:44:01 GMT; path=/EWS; secure; HttpOnly
Server: Microsoft-IIS/8.5
X-AspNet-Version: 4.0.30319
Persistent-Auth: true
X-Powered-By: ASP.NET
X-FEServer: EXCHSRV
Date: Wed, 06 Dec 2017 11:44:00 GMT

</Trace>

EwsResponse: <Trace Tag="EwsResponse" Tid="19" Time="2017-12-06 11:47:15Z" Version="15.00.0913.015">
  <?xml version="1.0" encoding="utf-8"?>
  <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
    <s:Body>
      <s:Fault>
        <faultcode xmlns:a="http://schemas.microsoft.com/exchange/services/2006/types">a:ErrorNonExistentMailbox</faultcode>
        <faultstring xml:lang="de-DE">The SMTP address has no mailbox associated with it.</faultstring>
        <detail>
          <e:ResponseCode xmlns:e="http://schemas.microsoft.com/exchange/services/2006/errors">ErrorNonExistentMailbox</e:ResponseCode>
          <e:Message xmlns:e="http://schemas.microsoft.com/exchange/services/2006/errors">The SMTP address has no mailbox associated with it.</e:Message>
          <t:MessageXml xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types">
            <t:Value Name="SmtpAddress">existingmailbox@maildomain.com</t:Value>
          </t:MessageXml>
        </detail>
      </s:Fault>
    </s:Body>
  </s:Envelope>
</Trace>


问:
HostListener and Angular Universal
I'm trying to listen to a MessageEvent sent with postMessage in my Angular 2 component.

My first attempt was simply doing:

```<code>window.addEventListener("message", this.handlePostMessage.bind(this));
</code>```

And then in ngOnDestroy:

```<code>window.removeEventListener("message", this.handlePostMessage.bind(this));
</code>```

However this didn't work as expected. If I navigated to another route and back, there would be two event listeners registered.

So instead I've been trying to decorate the method with HostListener, but I can't get this working when using prerendering (Angular Universal with .NET Core using the asp-prerender-module).

```<code>@HostListener('window:message', ['$event'])
private handlePostMessage(msg: MessageEvent) {
    ...
}
</code>```

That gives me the following error on page load:

```<code>Exception: Call to Node module failed with error: Prerendering failed because of error: ReferenceError: MessageEvent is not defined
</code>```

Is there a workaround for this?

答:
You're getting this error because MessageEvent is not defined. You must import whatever file defines this.

My @HostListeners look like this:

```<code>@HostListener("window:savePDF", ["$event"]) savePDF(event) {
    this.savePDFButtonPushed();
}
</code>```

and you can read more about them here:

https://angular.io/guide/attribute-directives

However, I'm currently experiencing the same issue you are -- that if I navigate to another route and back, I now receive two events. And that is using @HostListener. :-(  However I haven't upgraded Angular in a while (currently using 4.4.6), so maybe they've fixed it since that release.

**Edit: Just upgraded to Angular 5.1.0. The 'duplicate events' @HostListener issue remains. :-(

Edit #2: I tried also using window.addEventListener like you tried, and also had the same issue, despite using window.removeEventListener in ngOnDestroy().

This lead me to dig a little deeper, where I found some code I had added to listen to messages from a child iFrame. Any chance you have something similar in your code?

```<code>        var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
        var eventer = window[eventMethod];
        var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";

                // Listen to messages from child window ("unsign" and "savePDF") and pass those along as events to Angular can pick them up in its context
        eventer(messageEvent,function(e) {
            window.dispatchEvent( new Event( e.data ) );
        },false);
</code>```

This had been in my page's constructor. I protected it so it only executed the first time the page was constructor, and now all is well.

Title: HostListener and Angular Universal

Body:
I'm trying to listen to a MessageEvent sent with postMessage in my Angular 2 component.

My first attempt was simply doing:

window.addEventListener("message", this.handlePostMessage.bind(this));

And then in ngOnDestroy:

window.removeEventListener("message", this.handlePostMessage.bind(this));

However this didn't work as expected. If I navigated to another route and back, there would be two event listeners registered.

So instead I've been trying to decorate the method with HostListener, but I can't get this working when using prerendering (Angular Universal with .NET Core using the asp-prerender-module).

@HostListener('window:message', ['$event'])
private handlePostMessage(msg: MessageEvent) {
    ...
}

That gives me the following error on page load:

Exception: Call to Node module failed with error: Prerendering failed because of error: ReferenceError: MessageEvent is not defined

Is there a workaround for this?

Body:
You're getting this error because MessageEvent is not defined. You must import whatever file defines this.

My @HostListeners look like this:

@HostListener("window:savePDF", ["$event"]) savePDF(event) {
    this.savePDFButtonPushed();
}

and you can read more about them here:

https://angular.io/guide/attribute-directives

However, I'm currently experiencing the same issue you are -- that if I navigate to another route and back, I now receive two events. And that is using @HostListener. :-(  However I haven't upgraded Angular in a while (currently using 4.4.6), so maybe they've fixed it since that release.

**Edit: Just upgraded to Angular 5.1.0. The 'duplicate events' @HostListener issue remains. :-(

Edit #2: I tried also using window.addEventListener like you tried, and also had the same issue, despite using window.removeEventListener in ngOnDestroy().

This lead me to dig a little deeper, where I found some code I had added to listen to messages from a child iFrame. Any chance you have something similar in your code?

        var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
        var eventer = window[eventMethod];
        var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";

                // Listen to messages from child window ("unsign" and "savePDF") and pass those along as events to Angular can pick them up in its context
        eventer(messageEvent,function(e) {
            window.dispatchEvent( new Event( e.data ) );
        },false);

This had been in my page's constructor. I protected it so it only executed the first time the page was constructor, and now all is well.


问:
Large TChart takes a long time to draw
Top post: I have accepted an answer,but it doesn't work for me. I will post a new question, stressing Delphi 7. Thanks to all who gave some good input

I have measurements taken at one second intervals over an hour.

I had a previous question where it was taking 45 seconds to updates a TStringGrid and managed to get that down to "faster than the eye can see". Partly by moving some computation and database related functionality of of the loop, but - surprisingly to me - the change that really made the difference was setting the strindgrid's rowCount to 3600 before the loop rather than incrementing it inside the loop.

Now I have a similar problem with a TChart. Maybe if I try preallocating the chart? So, I could Chart1.Series[0].Count := 3600, but than I can't use AddXy() or Add(), so how would I explicitly set the values in series?

I have a very simple chart, with Floats on the y-axis and hour:seconds on the x-axis

Can anyone help, or suggest another way to speed up chart drawing?

Update: several have suggested using TFastLineSeries, but I don't see how.

Aha - double click on the Chart, to show all series, select one & click change

答:
I manage to draw millons of datapoints in a blink of an eye. Here's how I do it:
What you can do is to create two arrays for the X and Y Values, fill them with your values and then these arrays to your chart. For example:

```<code>var
  XValues, YValues: array of double;
begin

  SetLength(XValues, numberofValues);
  SetLength(YValues, numberofValues);

  for ix := 0 to numberofValues - 1 do
  begin
    XValues[ix] := ...your values
    YValues[ix] := ...your values
  end;

  Chart.Series[0].XValues.Value := TChartValues(XValues);
  Chart.Series[0].XValues.Count := high(XValues);
  Chart.Series[0].XValues.Modified := true;
  Chart.Series[0].YValues.Value := TChartValues(YValues);
  Chart.Series[0].YValues.Count := high(YValues);
  Chart.Series[0].YValues.Modified := True;
</code>```

What also speeds up the drawing is using the TFastLineSeries instead of the regular TLineSeries. When using the FastlineSeries you also have the property DrawAllPoints. When set to false the drawing is even faster. TChart will then skip datapoints that share the same X Position with other datapoints on the screen. It will only draw the first point of these.

This is where you find it the DrawAllPoints option:

Title: Large TChart takes a long time to draw

Body:
I manage to draw millons of datapoints in a blink of an eye. Here's how I do it:
What you can do is to create two arrays for the X and Y Values, fill them with your values and then these arrays to your chart. For example:

var
  XValues, YValues: array of double;
begin

  SetLength(XValues, numberofValues);
  SetLength(YValues, numberofValues);

  for ix := 0 to numberofValues - 1 do
  begin
    XValues[ix] := ...your values
    YValues[ix] := ...your values
  end;

  Chart.Series[0].XValues.Value := TChartValues(XValues);
  Chart.Series[0].XValues.Count := high(XValues);
  Chart.Series[0].XValues.Modified := true;
  Chart.Series[0].YValues.Value := TChartValues(YValues);
  Chart.Series[0].YValues.Count := high(YValues);
  Chart.Series[0].YValues.Modified := True;

What also speeds up the drawing is using the TFastLineSeries instead of the regular TLineSeries. When using the FastlineSeries you also have the property DrawAllPoints. When set to false the drawing is even faster. TChart will then skip datapoints that share the same X Position with other datapoints on the screen. It will only draw the first point of these.

This is where you find it the DrawAllPoints option:


问:
Failed to open /dev/bus/usb/001/007: Permission denied for usb device
I am trying to connect usb device from webpage using webusb api ,but i cannot open the paired device using the below code.

```<code><!DOCTYPE html>
<html>
<head allow="usb"></head>
    <body>
   <input type="submit" onclick="connect()" value="connect"/>

    <script>
    var device;
    function setup(device) {
        alert(device.productName+" open");
        return device.open()

        .then(() => device.selectConfiguration(1))
        .then(() => device.claimInterface(0))
    }

    function connect() {
        if (device == null) {
            navigator.usb.requestDevice({ filters: [{ vendorId : 2352 }] })
            .then(selectedDevice => {
                device = selectedDevice;
                console.log(device);
                return setup(device);
            })

            .catch(error => { console.log(error); })
        }

    }
    navigator.usb.getDevices()
    .then(devices => {
        if (devices.length > 0) {
            device = devices[0];
            return setup(device);
        }
    })
    .catch(error => { console.log(error); });
    </script>
    </body>
</html>
</code>```

Its shows

DOMException Access denied   cannot open usb after paired

答:
Based on the title of this question it appears that you are running on Linux and that the permissions for the device node /dev/bus/usb/001/007 are not set up so that the user running Chrome can open it.

What you need to do is add a udev rule that will set the permissions for this device node so that it can be opened. First you need to figure out the vendor and product IDs for your device. If you run lsusb it will list the devices on your system in a format like this,

Bus BBB Device NNN: ID VVVV:PPPP Manufacturer Product

Where,

BBB: The bus number (usually one per controller, two for USB 3.0 controllers).

NNN: The device number on that bus.

VVVV: The vendor ID (in hexadecimal).

PPPP: The product ID (in hexadecimal).

Once you know this information you can create a file in /etc/udev/rules.d/ containing the line below after plugging in the IDs you discovered in the step above.

SUBSYSTEM=="usb", ATTRS{idVendor}=="VVVV", ATTR{idProduct}=="PPPP", MODE="0660", GROUP="plugdev"

This will make any device with the given vendor and product IDs accessible to users in the plugdev group. This is a vaguely appropriate group for removable device permissions according to the Debian documentation.

From your code already appear to know the vendor ID, 2352, which would be entered into the rule in hexadecimal as "0930".

Body:
I am trying to connect usb device from webpage using webusb api ,but i cannot open the paired device using the below code.

<!DOCTYPE html>

   <input type="submit" onclick="connect()" value="connect"/>

Its shows

DOMException Access denied   cannot open usb after paired


问:
Firebase Auth, acquiring textfield value from different class
I am using Firebase email authentication in my app, I have 2 different view controllers for the sign up process, first view controller asks for the email for firebase and the second view controller asks for the password. How can I set it up for the firebase code?

```<code>if let phoneEmail = phoneEmailTextField.text, let createdpassword = createdPasswordTextField {

            Auth.auth().createUser(withEmail: phoneEmail, password: createdpassword, completion: { (user, error) in
</code>```

I have the textfield "phoneEmailTextField" in the first view controller (class 1) and the textfield "createdPasswordTextField" in the second view controller(class 2). How can I link the textfield "createdPasswordTextField" from the second view controller (class 2) back to the first view controller (class 1) in order to execute the Firebase function?

答:
Something like that;</p>

```<code>    let storyboard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
 if let secondViewController = storyboard.instantiateViewController(withIdentifier: "SecondViewController") as? SecondViewController {
secondViewController.emailTextFieldString = emailTextField.text!
           self.navigationController?.pushViewController(secondViewController, animated: true)
                }
</code>```

Body:
I am using Firebase email authentication in my app, I have 2 different view controllers for the sign up process, first view controller asks for the email for firebase and the second view controller asks for the password. How can I set it up for the firebase code?

if let phoneEmail = phoneEmailTextField.text, let createdpassword = createdPasswordTextField {

            Auth.auth().createUser(withEmail: phoneEmail, password: createdpassword, completion: { (user, error) in

I have the textfield "phoneEmailTextField" in the first view controller (class 1) and the textfield "createdPasswordTextField" in the second view controller(class 2). How can I link the textfield "createdPasswordTextField" from the second view controller (class 2) back to the first view controller (class 1) in order to execute the Firebase function?

Body:
Something like that;

    let storyboard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
 if let secondViewController = storyboard.instantiateViewController(withIdentifier: "SecondViewController") as? SecondViewController {
secondViewController.emailTextFieldString = emailTextField.text!
           self.navigationController?.pushViewController(secondViewController, animated: true)
                }


问:
VS 2017 Debug Mode Cannot See Object Property Values
I recently updated my Visual Studio 2017 from 15.4.2 to 15.4.5.

At some point during the day I realized that in debug mode I could no longer view objects while stepping through code.  I brought up VS 2015 and that environment still works.

Some things I found online suggested setting certain values in the debug options menu on the visual studtio environment, but that did not help either.

The Image shows there is no expand arrow to view the SomeObject item.

(visual studio 2017 bug)

This image shows my same machine with Visual Studio 2015 and the expected behavior.  Until recently 2017 had this behavior.

(visual studio 2015 expected behavior)

答:
I just test it in VS 2017 15.4.4 and 15.5.0. They all could show all items' value.

Since the latest VS 2017 has been updated to 15.5.0, if possible, please try to use the latest version. Debug it again.


问:
Sublime Text 3 - CSS Autocomplete WITHOUT typing property value
So I know autocomplete works great when you start typing a value. For example, the second you type the "c" in text-align:center, the available autocomplete values pop up (such as center, left, right).

However, when I used Dreamweaver, for properties with specific value options like text-align (center, right, left), display (block, inline-block), cursor (pointer, default), etc., the autocomplete popup would show immediately after the property was typed, it did NOT wait until I started typing a value. Right after text-align: was typed out, it would show me the autocomplete popup giving me the options center, right, left.

The value autocomplete should fire right after my property autocomplete fires:

So after I type te...

the autocomplete popup for "te" properties displays text-align, text-decoration, text-shadow etc....

then I press Enter to select text-align...

then immediately after pressing Enter an autocomplete popup should show for the text-align values: center, left, right.

Any idea how this can be accomplished in Sublime Text 3?

答:
You can try out this package. This package indexes your .less and .scss (or .sass) and caches your mixins, variables, class or id names and autocompletes both on html and css. It autocompletes your less and sass mixins with mixin arguments. It also supports emmet completions and gets your css classes on popup window.  -

https://github.com/subhaze/CSS-Extended/


问:
MySQL: the inconsistency of auto increment in id numbers
I wonder if you have come across this that the id numbers of auto increment don't arrange in correct order when you click on Browse button on phpMyAdmin - is it just me? Something I have set incorrectly in the db table?

For instance, when you insert a series of data into a table and you have deleted some of them as well, so when you check this table on phpMyAdmin, these data should appear in an order like this,

```<code>id

2
24
28
296
300
</code>```

but in most of my tables they don't appear in orders, instead they appear in something like this,

```<code>id

24
300
2
296
28
</code>```

as in this picture below,

Can we do something about it so that the IDs appear in the correct order?

EDIT 1:

I think most of you have misunderstood the issue I raided here. I mean when you click on Browser button on the phpMyAdmin to list all the data in your tables - not when you use SQL query to list the output by using order by.

Does it make sense?

EDIT 2:

This is one of my table structure - does it help you to see what is wrong in it?

```<code>CREATE TABLE IF NOT EXISTS `root_pages` (
  `pg_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `pg_url` varchar(255) DEFAULT NULL,
  `pg_title` varchar(255) DEFAULT NULL,
  `pg_subtitle` varchar(255) DEFAULT NULL,
  `pg_description` text,
  `pg_introduction` text,
  `pg_content_1` text,
  `pg_content_2` text,
  `pg_content_3` text,
  `pg_content_4` text,
  `pg_order` varchar(255) DEFAULT NULL,
  `pg_hide` varchar(255) DEFAULT '0',
  `pg_highlight` varchar(255) DEFAULT '0',
  `pg_important` varchar(255) DEFAULT '0',
  `pg_parent` varchar(255) DEFAULT '0',
  `parent_id` varchar(255) DEFAULT NULL,
  `pg_cat_id` varchar(255) DEFAULT NULL COMMENT 'page category id',
  `ps_cat_id` varchar(255) DEFAULT NULL COMMENT 'post category id',
  `tmp_id` varchar(255) DEFAULT NULL COMMENT 'template id',
  `pg_backdate` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  `pg_created` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  `pg_updated` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`pg_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
</code>```

答:
You can order your output however you like: ORDER BY id ASC.

Records in a table have no inherent order.

Body:
I wonder if you have come across this that the id numbers of auto increment don't arrange in correct order when you click on Browse button on phpMyAdmin - is it just me? Something I have set incorrectly in the db table?

For instance, when you insert a series of data into a table and you have deleted some of them as well, so when you check this table on phpMyAdmin, these data should appear in an order like this,

id

2
24
28
296
300

but in most of my tables they don't appear in orders, instead they appear in something like this,

id

24
300
2
296
28

as in this picture below,

Can we do something about it so that the IDs appear in the correct order?

EDIT 1:

I think most of you have misunderstood the issue I raided here. I mean when you click on Browser button on the phpMyAdmin to list all the data in your tables - not when you use SQL query to list the output by using order by.

Does it make sense?

EDIT 2:

This is one of my table structure - does it help you to see what is wrong in it?

CREATE TABLE IF NOT EXISTS `root_pages` (
  `pg_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `pg_url` varchar(255) DEFAULT NULL,
  `pg_title` varchar(255) DEFAULT NULL,
  `pg_subtitle` varchar(255) DEFAULT NULL,
  `pg_description` text,
  `pg_introduction` text,
  `pg_content_1` text,
  `pg_content_2` text,
  `pg_content_3` text,
  `pg_content_4` text,
  `pg_order` varchar(255) DEFAULT NULL,
  `pg_hide` varchar(255) DEFAULT '0',
  `pg_highlight` varchar(255) DEFAULT '0',
  `pg_important` varchar(255) DEFAULT '0',
  `pg_parent` varchar(255) DEFAULT '0',
  `parent_id` varchar(255) DEFAULT NULL,
  `pg_cat_id` varchar(255) DEFAULT NULL COMMENT 'page category id',
  `ps_cat_id` varchar(255) DEFAULT NULL COMMENT 'post category id',
  `tmp_id` varchar(255) DEFAULT NULL COMMENT 'template id',
  `pg_backdate` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  `pg_created` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  `pg_updated` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`pg_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;


问:
How to update a column with incrementally sequenced values that change depending on other column value
I am trying to update a column in a table so that the Index column (which is currently arbitrary numbers) is renumbered sequentially starting at 1000 with increments of 10, and this sequence restarts every time the Group changes.

I have tried ROWNUMBER() with PARTITION and trying to define a SEQUENCE, but I can't seem to get the result I'm looking for.

Table 1

```<code>ID    Group    Index
1         A       1
2         A       2
3         B       3
4         B       4
5         B       5
6         C       6
7         D       7
</code>```

What I want:
Table 1

```<code>ID    Group       Index
1         A       1000
2         A       1010
3         B       1000
4         B       1010
5         B       1020
6         C       1000
7         D       1000
</code>```

答:
You can use row_number() with some arithmetic:

```<code>select t.*,
       990 + 10 * row_number() over (partition by group order by id) as index
from t;
</code>```

Note that group and index are SQL reserved words, so they are really bad column names.

Body:
I am trying to update a column in a table so that the Index column (which is currently arbitrary numbers) is renumbered sequentially starting at 1000 with increments of 10, and this sequence restarts every time the Group changes.

I have tried ROWNUMBER() with PARTITION and trying to define a SEQUENCE, but I can't seem to get the result I'm looking for.

Table 1

ID    Group    Index
1         A       1
2         A       2
3         B       3
4         B       4
5         B       5
6         C       6
7         D       7

What I want:
Table 1

ID    Group       Index
1         A       1000
2         A       1010
3         B       1000
4         B       1010
5         B       1020
6         C       1000
7         D       1000

Body:
You can use row_number() with some arithmetic:

select t.*,
       990 + 10 * row_number() over (partition by group order by id) as index
from t;

Note that group and index are SQL reserved words, so they are really bad column names.


问:
getCurrentPosition delay in Chrome but not Safari?
I'm having a very odd (but minor) issue with a delay in location return using navigator.geolocation.getCurrentPosition(showPosition); in Chrome but not in Safari.

Here's a fiddle explaining the barebones of what I mean:
https://jsfiddle.net/L59kj418/

I get ~4000ms on Chrome but ~30ms on Safari (make sure to run again after allowing location as the time to select will skew results). I've tested this on all my devices too. I'm curious if there's a reason/workaround or if this is a legitimate bug to report.

答: Try specifying the options parameter and set maxAge to 24 hours or a year and see if that makes a difference. Also try setting accuracy to true.</p>


问:
Bash pass one function variable to other function
I have two function first one call usage -file to get the file from the user. It has long filename, so this function strips just what I need.
For example:
./test.sh -file some_example_list_data2017.csv It give me data2017 (which is what I want).

```<code>function get_file_name() {
    filename=$1
    if [ -f $filename ]
    then
        echo "${filename}" | awk (make long filename short)
    else
        echo "${filename} not found"
    fi
}
</code>```

Second function: I want to pass the above $filename here, since it already has full filename. And I want to display only some content on the screen. But this time using
./test.sh -display someexample_list_data2017.csv

```<code>function parse_above_file() {
    // here I want get_file_name and display the content
    filename=$1
    echo ${filename} | awk/sed/egrep (do something and display)
}
</code>```

But second function isn't getting the filename passed. When it ran the script it just prints nothing.

答:
With this code,

```<code>function get_file_name() {
    filename=$1
    echo "$filename"
    }
function parse_above_file() {
    filename=$1
    echo "$filename"
    filename="bli"
    get_file_name "$filename"
    exit
    }
filename="bla"
get_file_name $filename
filename="ble"
parse_above_file $filename
</code>```

I get this output:

```<code>bla
ble
bli
</code>```

Body:
I have two function first one call usage -file to get the file from the user. It has long filename, so this function strips just what I need.
For example:
./test.sh -file some_example_list_data2017.csv It give me data2017 (which is what I want).

function get_file_name() {
    filename=$1
    if [ -f $filename ]
    then
        echo "${filename}" | awk (make long filename short)
    else
        echo "${filename} not found"
    fi
}

Second function: I want to pass the above $filename here, since it already has full filename. And I want to display only some content on the screen. But this time using
./test.sh -display someexample_list_data2017.csv

function parse_above_file() {
    // here I want get_file_name and display the content
    filename=$1
    echo ${filename} | awk/sed/egrep (do something and display)
}

But second function isn't getting the filename passed. When it ran the script it just prints nothing.

Body:
With this code,

function get_file_name() {
    filename=$1
    echo "$filename"
    }
function parse_above_file() {
    filename=$1
    echo "$filename"
    filename="bli"
    get_file_name "$filename"
    exit
    }
filename="bla"
get_file_name $filename
filename="ble"
parse_above_file $filename

I get this output:

bla
ble
bli


问:
Save Variable into LocalStorage
I try to save variable into localStorage, the table already saved into localStorage, but the table just display text, i need to save datatable into localStorage for make datatable view when page reloaded, but no luck.

the result newTable in localStorage just showing [object Object].

why not $("#table1").dataTable(); ?

```<code> /* Create datatable for new table */
    var newTable = $("#table" + localStorage.Index).dataTable();
    localStorage.setItem("newTable", newTable);
    var save_newTable = localStorage.getItem("newTable");
</code>```

My JSFiddle

答:
Don't store an object directly in localstorage. In localstorage, you can just store strings in key-value form. One thing you can do is convert your object to a JSON string (as nnnnn suggested) and store that.

Then you can read its value from the localstorage and parse it back to JSON to use it.

I can't attach a demo as SO prevents us from writing to localstorage, but you can see this for reference: writing table to localstorage

Title: Save Variable into LocalStorage

Body:
I try to save variable into localStorage, the table already saved into localStorage, but the table just display text, i need to save datatable into localStorage for make datatable view when page reloaded, but no luck.

the result newTable in localStorage just showing [object Object].

why not $("#table1").dataTable(); ?

 /* Create datatable for new table */
    var newTable = $("#table" + localStorage.Index).dataTable();
    localStorage.setItem("newTable", newTable);
    var save_newTable = localStorage.getItem("newTable");

My JSFiddle


问:
R e1071 SVM model twitter classification
I have been using the e1071 library to classify text. I have been able to use the NB alogorithm but struggling to apply SVM.
I have been following the guide from the Cran website

The site has piece of code that doesn't explain the object Type and how I would get it for my own code.

```<code>> svm
> svm.model <- svm(Type ~ ., data = trainset, cost = 100, gamma = 1)
> svm.pred <- predict(svm.model, testset[,-10])
</code>```

My code:

```<code>library(e1071)
library(dplyr)
library(caret)
library(rpart)

df<- read.csv("C:/Users/Suki/Projects/RProject/tweets.csv", stringsAsFactors = FALSE)

trainSVM <- apply(dtm.train.svm, 2, convert_count)
testSVM <- apply(dtm.test.svm, 2, convert_count)

svm.model <- svm(Type~., data = trainSVM, cost = 100, gamma = 1)
svm.pred <- predict(svm.model, testSVM)
</code>```

I haven't been able to find an explanation but seen another similar example. Am I right in believing 'Type' is what I want the SVM model to predict? As what I have done so far I'm not sure how I would be able to give the SVM model that information.

Thanks for the time and help.

答:
Type ~ . is a formula that defines a model as "Values in column Type are dependent on values in all other columns". We don't have access to your data file, so let's consider the built-in dataset iris:

```<code>head( iris )   ## Look at the first few rows of the data
#   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
# 1          5.1         3.5          1.4         0.2  setosa
# 2          4.9         3.0          1.4         0.2  setosa
# 3          4.7         3.2          1.3         0.2  setosa
# ...
</code>```

Suppose I want to predict the values in column Species based on values in all other columns. I can define the corresponding model as Species ~ .. Alternatively, if I only wanted to use some of the columns, I would put them on the right-hand side of ~. For example, Species ~ Sepal.Length + Petal.Length would use *Length columns only.

Now that I have my dataset and my formula, I can train my SVM using the code you provided in the answer

```<code>myModel <- e1071::svm( Species ~ ., data = iris )
</code>```

For demonstration purposes, we can apply the model back to the training data to retrieve predictions

```<code>predict( myModel, iris )
#           1          2          3          4          5          6          7
#      setosa     setosa     setosa     setosa     setosa     setosa     setosa
#           8          9         10         11         12         13         14
#      setosa     setosa     setosa     setosa     setosa     setosa     setosa
# ...
</code>```

Finally, note that svm function has an alternative way to supply data / labels (take a look at ?e1071::svm). The following is an equivalent way to train the model:

```<code>e1071::svm( iris[,1:4], iris[,5] )  # Predict Column 5 values from Column 1:4 values
</code>```

Body:
I have been using the e1071 library to classify text. I have been able to use the NB alogorithm but struggling to apply SVM.
I have been following the guide from the Cran website

The site has piece of code that doesn't explain the object Type and how I would get it for my own code.

> svm
> svm.model <- svm(Type ~ ., data = trainset, cost = 100, gamma = 1)
> svm.pred <- predict(svm.model, testset[,-10])

My code:

library(e1071)
library(dplyr)
library(caret)
library(rpart)

df<- read.csv("C:/Users/Suki/Projects/RProject/tweets.csv", stringsAsFactors = FALSE)

trainSVM <- apply(dtm.train.svm, 2, convert_count)
testSVM <- apply(dtm.test.svm, 2, convert_count)

svm.model <- svm(Type~., data = trainSVM, cost = 100, gamma = 1)
svm.pred <- predict(svm.model, testSVM)

I haven't been able to find an explanation but seen another similar example. Am I right in believing 'Type' is what I want the SVM model to predict? As what I have done so far I'm not sure how I would be able to give the SVM model that information.

Thanks for the time and help.

Body:
Type ~ . is a formula that defines a model as "Values in column Type are dependent on values in all other columns". We don't have access to your data file, so let's consider the built-in dataset iris:

head( iris )   ## Look at the first few rows of the data
#   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
# 1          5.1         3.5          1.4         0.2  setosa
# 2          4.9         3.0          1.4         0.2  setosa
# 3          4.7         3.2          1.3         0.2  setosa
# ...

Suppose I want to predict the values in column Species based on values in all other columns. I can define the corresponding model as Species ~ .. Alternatively, if I only wanted to use some of the columns, I would put them on the right-hand side of ~. For example, Species ~ Sepal.Length + Petal.Length would use *Length columns only.

Now that I have my dataset and my formula, I can train my SVM using the code you provided in the answer

myModel <- e1071::svm( Species ~ ., data = iris )

For demonstration purposes, we can apply the model back to the training data to retrieve predictions

predict( myModel, iris )
#           1          2          3          4          5          6          7
#      setosa     setosa     setosa     setosa     setosa     setosa     setosa
#           8          9         10         11         12         13         14
#      setosa     setosa     setosa     setosa     setosa     setosa     setosa
# ...

Finally, note that svm function has an alternative way to supply data / labels (take a look at ?e1071::svm). The following is an equivalent way to train the model:

e1071::svm( iris[,1:4], iris[,5] )  # Predict Column 5 values from Column 1:4 values


问:
How to get Geo-location manually and show in the map using UWP
I want to develop a simple app to allow users to type in longitude and latitude to find the position in the map. I use Bing Map to develop it.
I know how to get the current location, but I don't know how to get the geo-location manually.

Here is my code to get current geo-location and show it in the map. How can I modify it, to let user enter a geo-location?

```<code>Geopoint position = (await new Geolocator().GetGeopositionAsync()).Coordinate.Point;
DependencyObject marker = Library.Marker();
MyMap.Children.Add(marker);
MapControl.SetLocation(marker, position);
MapControl.SetNormalizedAnchorPoint(marker, new Point(0.5, 0.5));
MyMap.ZoomLevel = 15;
MyMap.Center = position;
</code>```

答:
I want to develop a simple app to allow users to type in longitude and latitude to find the position in the map.

Since you already get the longitude and latitude values, you could just build a BasicGeoposition struct with longitude and latitude values, and create a geographic point object for the given position. For example:

```<code>Geopoint position = new Geopoint(new BasicGeoposition()
{
    //Geopoint for Seattle
    Latitude = 47.604,
    Longitude = -122.329
});
...
MapControl.SetLocation(marker, position);
</code>```

Body:
I want to develop a simple app to allow users to type in longitude and latitude to find the position in the map. I use Bing Map to develop it.
I know how to get the current location, but I don't know how to get the geo-location manually.

Here is my code to get current geo-location and show it in the map. How can I modify it, to let user enter a geo-location?

Geopoint position = (await new Geolocator().GetGeopositionAsync()).Coordinate.Point;
DependencyObject marker = Library.Marker();
MyMap.Children.Add(marker);
MapControl.SetLocation(marker, position);
MapControl.SetNormalizedAnchorPoint(marker, new Point(0.5, 0.5));
MyMap.ZoomLevel = 15;
MyMap.Center = position;

Body:
I want to develop a simple app to allow users to type in longitude and latitude to find the position in the map.

Since you already get the longitude and latitude values, you could just build a BasicGeoposition struct with longitude and latitude values, and create a geographic point object for the given position. For example:

Geopoint position = new Geopoint(new BasicGeoposition()
{
    //Geopoint for Seattle
    Latitude = 47.604,
    Longitude = -122.329
});
...
MapControl.SetLocation(marker, position);


问:
c# - abort the execution of a method if its taking too long to run
How can I abort the execution of a method if its taking too long to run?

e.g.

```<code>string foo = DoSomethingComplex();
</code>```

but if DoSomethingComplex() is taking too long (20 seconds lets say).
then just set foo to "";

答: You can't abort the execution of a method. What you could do is to run this method on a separate thread and abort the thread if it takes too long.

Body:
How can I abort the execution of a method if its taking too long to run?

e.g.

string foo = DoSomethingComplex();

but if DoSomethingComplex() is taking too long (20 seconds lets say).
then just set foo to "";


问:
Check if a string contains another string of numbers
So I apologize if this has been asked but I looked around and Ive seen input.split() for words and for single numbers in a string but I dont think they work for me. So I want to have a python script running in like a screen session waiting for an input and after someone enters somethingsomething and presses enter, the program looks for a string of numbers in the string that contains both numbers and special characters. And if it matches, something would run but if not, nothing would happen. What is the best way to accomplish this?

答:
Try this . I hope this is what you are looking for

```<code>s="12342helloworls@#$"
n=raw_input('enter string')
if n in s:
    print "Found"
</code>```

You can in statment to check for substring

Body:
Try this . I hope this is what you are looking for

s="12342helloworls@#$"
n=raw_input('enter string')
if n in s:
    print "Found"

You can in statment to check for substring


问:
Installing APK file to Android Studio-emulator
I am trying to install an APK file to Android Studio-emulator. I tried adding my SDK/platform-tools directory to CMD. I got 'The system cannot find the path specified', but the file is a zip in my downloads file.

Can you please suggest how I can fix this?

答:
From Android Studio User Guide

You can also drag one or more APKs onto the emulator to install them, and then run them.


问:
query editor not visible in azure SQL DB in azure portal
I have created an SQL database in azure portal. But there is no tools section in the overview of my DB, so as there is no query editor for me to use.

Instead i have connect with option where only visual studio is shown and not the query editor. Kindly give me a solution why no tools section and how can i get Query Editor.

I had enable(ON) the allow access to all services in the Firewall settings also.

答:
Now, Azure SQL database supports Data explorer (preview), you could use it  to query.

Note: It only show limited object. For full capability please open SSDT.