问:
Indexing a MYSQL table with many columns
I have a table posts with the following columns:

start_at, sun, mon, tue, wen, thu, fri, sat

start_at is of date type, the others - tinyint.

I make a query the following way:

```<code>SELECT * FROM posts WHERE start_at >= '2017-02-01' AND mon = 1
</code>```

That is after second AND I set proper day of week dynamically.

What is the best way to index this table? Do I need to make a composite index for each day of a week, for example:

```<code>CREATE INDEX mon_index ON posts(start_at,mon);
CREATE INDEX sun_index ON posts(start_at,sun);
</code>```

If I create 7 indexes for each day of the week, I think INSERT and UPDATE will be really slow.

UPDATED: I do need column for each day of week, because a user sets on which days post will be published. There can be a few days at the same time.

答:
AS another said, may be it should be sufficient to index for start_at only.

If you want to investigate on index which include the post publishing day (in particular if your table has lot of field and you want to list only fields start_at and the day of publishing), you could create a table like this:

```<code>CREATE TABLE XX (start_at ..., which_day tinyint UNSIGNED);
</code>```

and an index like this

```<code>CREATE INDEX XX_IX01 (start_at, which_day);
</code>```

where which_day can be, using a sort of coding:

0=no day
2^0=sun
2^1=mon
2^2=..
...
2^6=sat

So, for example if the mon and sat are 1, the value should be 2^1 +2^6=2+64=66.

If possibile avoid SELECT *   and write the field you need.

Use EXPLAIN   to check how db engine use your index/tables.

This link could be useful: How can I index these queries?

Sample data:

```<code>CREATE table et1 (start_at DATE, which_day tinyint UNSIGNED);
CREATE INDEX ET1_IX1 ON et1(start_at, which_day);

INSERT INTO et1 VALUES ('20170701', 132);
INSERT INTO et1 VALUES ('20170702', 3);
INSERT INTO et1 VALUES ('20170704', 5);
INSERT INTO et1 VALUES ('20170630', 2);

SELECT start_at, which_day, which_day & 128 AS X FROM et1;
SELECT start_at, which_day, which_day & 128 AS X FROM et1 WHERE start_at>'20170630' AND which_day & 128 =128;
EXPLAIN SELECT * FROM et1 WHERE start_at>'20170630' AND which_day & 128 =128;

DROP table et1;
</code>```

Body:
I have a table posts with the following columns:

start_at, sun, mon, tue, wen, thu, fri, sat

start_at is of date type, the others - tinyint.

I make a query the following way:

SELECT * FROM posts WHERE start_at >= '2017-02-01' AND mon = 1

That is after second AND I set proper day of week dynamically.

What is the best way to index this table? Do I need to make a composite index for each day of a week, for example:

CREATE INDEX mon_index ON posts(start_at,mon);
CREATE INDEX sun_index ON posts(start_at,sun);

If I create 7 indexes for each day of the week, I think INSERT and UPDATE will be really slow.

UPDATED: I do need column for each day of week, because a user sets on which days post will be published. There can be a few days at the same time.

Body:
AS another said, may be it should be sufficient to index for start_at only.

If you want to investigate on index which include the post publishing day (in particular if your table has lot of field and you want to list only fields start_at and the day of publishing), you could create a table like this:

CREATE TABLE XX (start_at ..., which_day tinyint UNSIGNED);

and an index like this

CREATE INDEX XX_IX01 (start_at, which_day);

where which_day can be, using a sort of coding:

0=no day
2^0=sun
2^1=mon
2^2=..
...
2^6=sat

So, for example if the mon and sat are 1, the value should be 2^1 +2^6=2+64=66.

If possibile avoid SELECT *   and write the field you need.

Use EXPLAIN   to check how db engine use your index/tables.

This link could be useful: How can I index these queries?

Sample data:

CREATE table et1 (start_at DATE, which_day tinyint UNSIGNED);
CREATE INDEX ET1_IX1 ON et1(start_at, which_day);

INSERT INTO et1 VALUES ('20170701', 132);
INSERT INTO et1 VALUES ('20170702', 3);
INSERT INTO et1 VALUES ('20170704', 5);
INSERT INTO et1 VALUES ('20170630', 2);

SELECT start_at, which_day, which_day & 128 AS X FROM et1;
SELECT start_at, which_day, which_day & 128 AS X FROM et1 WHERE start_at>'20170630' AND which_day & 128 =128;
EXPLAIN SELECT * FROM et1 WHERE start_at>'20170630' AND which_day & 128 =128;

DROP table et1;


来源: stackexchange

问:
sum of array fields using jquery closest
I need some help solving this problem,

i have dynamically created div,

```<code><div class='items'>
     Item 1 <input type='text' class='subprice'  name='item[]'> [X]
     Item 2 <input type='text' class='subprice'  name='item[]'> [X]
    <input type='text' class='subprice'  name='subtotal'>
</div>

<div class='items'>
    Item 1 <input type='text' class='subprice'  name='item[]'> [X]
    Item 2 <input type='text' class='subprice'  name='item[]'> [X]
    Item 3 <input type='text' class='subprice'  name='item[]'> [X]
    <input type='text' class='subprice'  name='subtotal'>
</div>
</code>```

how am i able to get the total array value of item[] by using .closest and display it to the subtotal text field.. note that class items is dynamically created, therefore it can be created multiple times.

i tried

```<code>var i = $(.items).closest();
var arr =  i.find('[name="item[]"]');
</code>```

so arr should contain the sum of item[] within the nearest class items

Thank you in advance.

答:
Alternatively, you can start at the subtotals and get its siblings (in the example setup, no further filtering is needed):

```<code>$('[name=subtotal]').val(function(){
    return $(this).siblings().toArray().reduce(function(sum,inp){return sum + +inp.value;} ,0);
});
</code>```

$('[name=subtotal]').val(function(){
 return $(this).siblings().toArray().reduce(function(sum,inp){return sum + +inp.value;} ,0);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='items'>
     Item 1 <input value=10 type='text' class='subprice'  name='item[]'>
     Item 2 <input value=11 type='text' class='subprice'  name='item[]'>
    <input type='text' class='subprice'  name='subtotal'>
</div>

<div class='items'>
    Item 1 <input value = 5 type='text' class='subprice'  name='item[]'>
    Item 2 <input value = 6 type='text' class='subprice'  name='item[]'>
    Item 3 <input value = 7 type='text' class='subprice'  name='item[]'>
    <input type='text' class='subprice'  name='subtotal'>
</div></code>```

ContentLicense: CC BY-SA 3.0

Body:
I need some help solving this problem,

i have dynamically created div,

     Item 1 <input type='text' class='subprice'  name='item[]'> [X]
     Item 2 <input type='text' class='subprice'  name='item[]'> [X]
    <input type='text' class='subprice'  name='subtotal'>

    Item 1 <input type='text' class='subprice'  name='item[]'> [X]
    Item 2 <input type='text' class='subprice'  name='item[]'> [X]
    Item 3 <input type='text' class='subprice'  name='item[]'> [X]
    <input type='text' class='subprice'  name='subtotal'>

how am i able to get the total array value of item[] by using .closest and display it to the subtotal text field.. note that class items is dynamically created, therefore it can be created multiple times.

i tried

var i = $(.items).closest();
var arr =  i.find('[name="item[]"]');

so arr should contain the sum of item[] within the nearest class items

Thank you in advance.

Body:
Alternatively, you can start at the subtotals and get its siblings (in the example setup, no further filtering is needed):

$('[name=subtotal]').val(function(){
    return $(this).siblings().toArray().reduce(function(sum,inp){return sum + +inp.value;} ,0);
});

$('[name=subtotal]').val(function(){
 return $(this).siblings().toArray().reduce(function(sum,inp){return sum + +inp.value;} ,0);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='items'>
     Item 1 <input value=10 type='text' class='subprice'  name='item[]'>
     Item 2 <input value=11 type='text' class='subprice'  name='item[]'>
    <input type='text' class='subprice'  name='subtotal'>
</div>

<div class='items'>
    Item 1 <input value = 5 type='text' class='subprice'  name='item[]'>
    Item 2 <input value = 6 type='text' class='subprice'  name='item[]'>
    Item 3 <input value = 7 type='text' class='subprice'  name='item[]'>
    <input type='text' class='subprice'  name='subtotal'>
</div>


问:
Extracting integers from a list
I have a list like this:

```<code>fmt_string="I am a smoker male of 25 years who wants a policy for 30
yrs with a sum assured amount of 1000000 rupees"
</code>```

from the above list I removed stopwords and got this
Now I have a list as following:

```<code>['smoker', 'male', '25', 'years', 'wants', 'policy', '30', 'yrs',
'sum', 'assured', 'amount', '1000000', 'rupees']
</code>```

from this list I want to extract just 25, 30 and 1000000, but the code should be something like 25 would be before or after years. 30 could either be after policy and 1000000 can be at any position

finally output should be like:

```<code>'1000000 30 25 male smoker'
</code>```

I just want a robust code that wherever I find these values i return me a list like this.

答:
This should be helpful

```<code>import re
# Variation in places of the numbers in strings:
str1 = "I am a smoker male of 25 years who wants a policy for 30  yrs with a sum assured amount of 1000000 rupees"
str2 = "I am a smoker male of 25 years who wants a for 30 policy  yrs with a sum assured amount of 1000000 rupees"
str3 = "I am a smoker male of years 25 who wants a for 30 policy yrs with a sum assured amount of 1000000 rupees"
str4 = "I am a smoker male of 25 years who wants a for 30 policy yrs with a sum assured amount of 1000000 rupees"

regex = r".*?(((\d{2})\s?years)|(years\s?(\d{2}))).*(policy.*?(\d{2})|(\d{2}).*?policy).*(\d{7}).*$"
replacements = r"\9 \7 \8 \3 \5"

res_str1 = re.sub(regex, replacements, str1)
res_str2 = re.sub(regex, replacements, str2)
res_str3 = re.sub(regex, replacements, str3)
res_str4 = re.sub(regex, replacements, str4)

def clean_spaces(string):
    return re.sub(r"\s{1,2}", ' ', string)

print(clean_spaces(res_str1))
print(clean_spaces(res_str2))
print(clean_spaces(res_str3))
print(clean_spaces(res_str4))
</code>```

Output:

```<code>1000000 30 25
1000000 30 25
1000000 30 25
1000000 30 25
</code>```

Update

The regular expression above has some bugs. While I trying to improve it, I noticed that it is inefficient and ugly as it parses each single character each time. We could do better if we stick to your original approach of parsing the words instead. So my new solution is:

```<code># Algorithm
# for each_word in the_list:
#     maintain a pre_list of terms that come before a number
#     if each_word is number:
#         if there is any element of desired_terms_list exists in pre_list:
#             pair the number & the desired_term and insert into the_dictionary
#             remove this desired_term from desired_terms_list
#             reset the pre_list
#         else:
#             put the number in number_at_hand
#     else:
#         if no number_at_hand:
#             add the current word into pre_list
#         else:
#             if the current_word an element of desired_terms_list:
#                 pair the number & the desired_term and insert into the_dictionary
#                 remove this desired_term from desired_terms_list
#                 reset number_at_hand
</code>```

Code:

```<code>from pprint import pprint

class Extractor:
    def __init__(self, search_terms, string):
        self.pre_list = list()
        self.list = string.split()
        self.terms_to_look_for = search_terms
        self.dictionary = {}

    @staticmethod
    def is_number(string):
        try:
            int(string)
            return True
        except ValueError:
            return False

    def check_pre_list(self):
        for term in self.terms_to_look_for:
            if term in self.pre_list:
                return term
            else:
                return None

    def extract(self):
        number_at_hand = str()
        for word in self.list:
            if Extractor.is_number(word):
                check_result = self.check_pre_list()
                if check_result is not None:
                    self.dictionary[check_result] = word
                    self.terms_to_look_for.remove(check_result)
                    self.pre_list = list()
                else:
                    number_at_hand = word
            else:
                if number_at_hand == '':
                    self.pre_list.append(word)
                else:
                    if word in self.terms_to_look_for:
                        self.dictionary[word] = number_at_hand
                        self.terms_to_look_for.remove(word)
                        number_at_hand = str()
        return self.dictionary
</code>```

Usage:

```<code>ex1 = Extractor(['years', 'policy', 'amount'],
                'I am a smoker male of 25 years who wants a policy for 30 yrs with a sum assured amount of 1000000 rupees')
ex2 = Extractor(['years', 'policy', 'amount'],
                'I am a smoker male of 25 years who wants a for 30 yrs policy with a sum assured amount of 1000000 rupees')
ex3 = Extractor(['years', 'policy', 'amount'],
                'I am a smoker male of years 25 who wants a policy for 30 yrs with a sum assured amount of 1000000 rupees')
ex4 = Extractor(['years', 'policy', 'amount'],
                'I am a smoker male of years 25 who wants a for 30 yrs policy with a sum assured amount of 1000000 rupees')
pprint(ex1.extract())
pprint(ex2.extract())
pprint(ex3.extract())
pprint(ex4.extract())
</code>```

Output:

```<code>{'amount': '1000000', 'policy': '30', 'years': '25'}
{'amount': '1000000', 'policy': '30', 'years': '25'}
{'amount': '1000000', 'policy': '30', 'years': '25'}
{'amount': '1000000', 'policy': '30', 'years': '25'}
</code>```

I expect better performance now.

Title: Extracting integers from a list

Body:
I have a list like this:

fmt_string="I am a smoker male of 25 years who wants a policy for 30
yrs with a sum assured amount of 1000000 rupees"

from the above list I removed stopwords and got this
Now I have a list as following:

['smoker', 'male', '25', 'years', 'wants', 'policy', '30', 'yrs',
'sum', 'assured', 'amount', '1000000', 'rupees']

from this list I want to extract just 25, 30 and 1000000, but the code should be something like 25 would be before or after years. 30 could either be after policy and 1000000 can be at any position

finally output should be like:

'1000000 30 25 male smoker'

I just want a robust code that wherever I find these values i return me a list like this.

Body:
This should be helpful

import re
# Variation in places of the numbers in strings:
str1 = "I am a smoker male of 25 years who wants a policy for 30  yrs with a sum assured amount of 1000000 rupees"
str2 = "I am a smoker male of 25 years who wants a for 30 policy  yrs with a sum assured amount of 1000000 rupees"
str3 = "I am a smoker male of years 25 who wants a for 30 policy yrs with a sum assured amount of 1000000 rupees"
str4 = "I am a smoker male of 25 years who wants a for 30 policy yrs with a sum assured amount of 1000000 rupees"

regex = r".*?(((\d{2})\s?years)|(years\s?(\d{2}))).*(policy.*?(\d{2})|(\d{2}).*?policy).*(\d{7}).*$"
replacements = r"\9 \7 \8 \3 \5"

res_str1 = re.sub(regex, replacements, str1)
res_str2 = re.sub(regex, replacements, str2)
res_str3 = re.sub(regex, replacements, str3)
res_str4 = re.sub(regex, replacements, str4)

def clean_spaces(string):
    return re.sub(r"\s{1,2}", ' ', string)

print(clean_spaces(res_str1))
print(clean_spaces(res_str2))
print(clean_spaces(res_str3))
print(clean_spaces(res_str4))

Output:

1000000 30 25
1000000 30 25
1000000 30 25
1000000 30 25

Update

The regular expression above has some bugs. While I trying to improve it, I noticed that it is inefficient and ugly as it parses each single character each time. We could do better if we stick to your original approach of parsing the words instead. So my new solution is:

# Algorithm
# for each_word in the_list:
#     maintain a pre_list of terms that come before a number
#     if each_word is number:
#         if there is any element of desired_terms_list exists in pre_list:
#             pair the number & the desired_term and insert into the_dictionary
#             remove this desired_term from desired_terms_list
#             reset the pre_list
#         else:
#             put the number in number_at_hand
#     else:
#         if no number_at_hand:
#             add the current word into pre_list
#         else:
#             if the current_word an element of desired_terms_list:
#                 pair the number & the desired_term and insert into the_dictionary
#                 remove this desired_term from desired_terms_list
#                 reset number_at_hand

Code:

from pprint import pprint

class Extractor:
    def __init__(self, search_terms, string):
        self.pre_list = list()
        self.list = string.split()
        self.terms_to_look_for = search_terms
        self.dictionary = {}

    @staticmethod
    def is_number(string):
        try:
            int(string)
            return True
        except ValueError:
            return False

    def check_pre_list(self):
        for term in self.terms_to_look_for:
            if term in self.pre_list:
                return term
            else:
                return None

    def extract(self):
        number_at_hand = str()
        for word in self.list:
            if Extractor.is_number(word):
                check_result = self.check_pre_list()
                if check_result is not None:
                    self.dictionary[check_result] = word
                    self.terms_to_look_for.remove(check_result)
                    self.pre_list = list()
                else:
                    number_at_hand = word
            else:
                if number_at_hand == '':
                    self.pre_list.append(word)
                else:
                    if word in self.terms_to_look_for:
                        self.dictionary[word] = number_at_hand
                        self.terms_to_look_for.remove(word)
                        number_at_hand = str()
        return self.dictionary

Usage:

ex1 = Extractor(['years', 'policy', 'amount'],
                'I am a smoker male of 25 years who wants a policy for 30 yrs with a sum assured amount of 1000000 rupees')
ex2 = Extractor(['years', 'policy', 'amount'],
                'I am a smoker male of 25 years who wants a for 30 yrs policy with a sum assured amount of 1000000 rupees')
ex3 = Extractor(['years', 'policy', 'amount'],
                'I am a smoker male of years 25 who wants a policy for 30 yrs with a sum assured amount of 1000000 rupees')
ex4 = Extractor(['years', 'policy', 'amount'],
                'I am a smoker male of years 25 who wants a for 30 yrs policy with a sum assured amount of 1000000 rupees')
pprint(ex1.extract())
pprint(ex2.extract())
pprint(ex3.extract())
pprint(ex4.extract())

Output:

{'amount': '1000000', 'policy': '30', 'years': '25'}
{'amount': '1000000', 'policy': '30', 'years': '25'}
{'amount': '1000000', 'policy': '30', 'years': '25'}
{'amount': '1000000', 'policy': '30', 'years': '25'}

I expect better performance now.


问:
Rotate an image around its center in canvas
I'm trying to do my first image animation on canvas. I want the image to rotate but something is not correct in my code. Any ideas?  This is all in a jquery document ready:</p>

```<code>var canvas = document.getElementById('logobg1');
    var ctx = canvas.getContext('2d');

    var img = new Image();   // Create new Image object
    img.src = 'images/containerbg.png'; // Set source path // set img src

    img.onload = function(){ // when image loads
        ctx.drawImage(img,0,0);
        setInterval(function() {
            ctx.save();
            ctx.clearRect(-ctx.canvas.width/2, -ctx.canvas.height/2, ctx.canvas.width, ctx.canvas.height);
            ctx.drawImage(img,0,0);
            ctx.translate(ctx.canvas.width/2, ctx.canvas.height/2); // set canvas context to center
            ctx.rotate(Math.PI / 180 * 0.5); // 1/2 a degree
            ctx.restore();
        }, 16);
    }
</code>```

答:
Based in the accepted answer, this example, allows you to use a fixed canvas size (and not in relation to the image size):

 $(function() {

        var canvas = document.getElementById('logobg1');
        var ctx = canvas.getContext('2d');
        var img = new Image();

        var ang = 0; //angle
        var fps = 1000 / 25; //number of frames per sec
        img.onload = function () { //on image load do the following stuff
            canvas.width = 500; //Any width
            canvas.height = 500; //Any height
            var cache = this; //cache the local copy of image element for future reference
            var iw = cache.width;
            var ih = cache.height;
            setInterval(function () {
                ctx.save(); //saves the state of canvas
                ctx.clearRect(0, 0, canvas.width, canvas.height); //clear the canvas
                ctx.translate(canvas.width/2, canvas.height/2); //let's translate
                ctx.rotate(Math.PI / 180 * (ang += 5)); //increment the angle and rotate the image
                ctx.translate(-(canvas.width/2), -(canvas.height/2)); //let's translate
                ctx.drawImage(img, canvas.width/2 - iw/2, canvas.height/2 - ih/2, iw, ih); //draw the image ;)
                ctx.restore(); //restore the state of canvas
            }, fps);
        };

        img.src = 'https://lh4.ggpht.com/wKrDLLmmxjfRG2-E-k5L5BUuHWpCOe4lWRF7oVs1Gzdn5e5yvr8fj-ORTlBF43U47yI=w300'; //img

 })
 ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<canvas id="logobg1" > test canvas <canvas></code>```

Working example: jsbin.com/suwovibove/

Note: try removing ctx.save and ctx.restore for a cool spin.

Body:
I'm trying to do my first image animation on canvas. I want the image to rotate but something is not correct in my code. Any ideas?  This is all in a jquery document ready:

var canvas = document.getElementById('logobg1');
    var ctx = canvas.getContext('2d');

    var img = new Image();   // Create new Image object
    img.src = 'images/containerbg.png'; // Set source path // set img src

    img.onload = function(){ // when image loads
        ctx.drawImage(img,0,0);
        setInterval(function() {
            ctx.save();
            ctx.clearRect(-ctx.canvas.width/2, -ctx.canvas.height/2, ctx.canvas.width, ctx.canvas.height);
            ctx.drawImage(img,0,0);
            ctx.translate(ctx.canvas.width/2, ctx.canvas.height/2); // set canvas context to center
            ctx.rotate(Math.PI / 180 * 0.5); // 1/2 a degree
            ctx.restore();
        }, 16);
    }

Body:
Based in the accepted answer, this example, allows you to use a fixed canvas size (and not in relation to the image size):

 $(function() {

        var canvas = document.getElementById('logobg1');
        var ctx = canvas.getContext('2d');
        var img = new Image();

        var ang = 0; //angle
        var fps = 1000 / 25; //number of frames per sec
        img.onload = function () { //on image load do the following stuff
            canvas.width = 500; //Any width
            canvas.height = 500; //Any height
            var cache = this; //cache the local copy of image element for future reference
            var iw = cache.width;
            var ih = cache.height;
            setInterval(function () {
                ctx.save(); //saves the state of canvas
                ctx.clearRect(0, 0, canvas.width, canvas.height); //clear the canvas
                ctx.translate(canvas.width/2, canvas.height/2); //let's translate
                ctx.rotate(Math.PI / 180 * (ang += 5)); //increment the angle and rotate the image
                ctx.translate(-(canvas.width/2), -(canvas.height/2)); //let's translate
                ctx.drawImage(img, canvas.width/2 - iw/2, canvas.height/2 - ih/2, iw, ih); //draw the image ;)
                ctx.restore(); //restore the state of canvas
            }, fps);
        };

        img.src = 'https://lh4.ggpht.com/wKrDLLmmxjfRG2-E-k5L5BUuHWpCOe4lWRF7oVs1Gzdn5e5yvr8fj-ORTlBF43U47yI=w300'; //img

 })

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<canvas id="logobg1" > test canvas <canvas>

Working example: jsbin.com/suwovibove/

Note: try removing ctx.save and ctx.restore for a cool spin.

ContentLicense: CC BY-SA 4.0


问:
tornado: how to add www if user doesn't type
I'm using the Tornado with python to build a web server. I want to allow users not to type www.

For example, if user types example.com to visit my web page, I want to add www for user. In other words, if user types example.com in his browser and type "Enter", a www will be inserted automatically in front of example.com.

This is my code for now:

```<code>application.add_handlers(r"^(www).*", [(r"/$", IndexHandler)])
</code>```

With the code above, if user visits www.example.com, the class IndexHandler will get the request and render the index page (self.render('/index.html')).

Then I've tried like this:

```<code>application.add_handlers(r"^(example).*", [(r"/$", RedirectionHandler)])

class RedirectionHandler(tornado.web.RequestHandler):
    def get(self):
        self.redirect('www.example.com')
</code>```

Well, it doesn't work because self.redirect gives me example.com/www.example.com

答:
Do

seft.redirect('http://www.example.com')

In general in any language when you redirect plain text, the system thinks it's a relative url and tries to append/complete the url with the existing hostname in the already typed url (here example.com).

Putting http(s):// at the beginning tells that the address is absolute, so you rewrite all the address from scratch.

Body:
I'm using the Tornado with python to build a web server. I want to allow users not to type www.

For example, if user types example.com to visit my web page, I want to add www for user. In other words, if user types example.com in his browser and type "Enter", a www will be inserted automatically in front of example.com.

This is my code for now:

application.add_handlers(r"^(www).*", [(r"/$", IndexHandler)])

With the code above, if user visits www.example.com, the class IndexHandler will get the request and render the index page (self.render('/index.html')).

Then I've tried like this:

application.add_handlers(r"^(example).*", [(r"/$", RedirectionHandler)])

class RedirectionHandler(tornado.web.RequestHandler):
    def get(self):
        self.redirect('www.example.com')

Well, it doesn't work because self.redirect gives me example.com/www.example.com


问:
I want to execute this event every 10 minutes in my MYSQL , but it is not working can anyone suggest
```<code>DELIMITER $$

DROP EVENT IF EXISTS delete_name $$

CREATE DEFINER=`root`@`LOCALHOST`
EVENT `delete_name`
ON SCHEDULE EVERY 10 MINUTE starts now()
ON COMPLETION NOT PRESERVE ENABLE
DO
BEGIN
DELETE FROM CLTX_SOFS WHERE STR_TO_DATE(CONCAT('2017-07-07',' ','11:30:00'),'%Y-%m-%d %H:%i:%s') < (NOW() - INTERVAL 10 MINUTE);
END $$
</code>```

Body:
Incidentally, note that

STR_TO_DATE(CONCAT('2017-07-07',' ','11:30:00'),'%Y-%m-%d %H:%i:%s')

is equivalent to

'2017-07-07 11:30:00'


问:
Facebook Android SDK Invalid_key

Possible Duplicate:

  Login failed invalid key error with Facebook SDK

I am using a sample app for here ibm.com/developerworks/library/x-androidfacebookapi/
to test facebook android SDK,
I have given my APP ID in this sample app.
I have done all setups and prerequisites.
I have signed app with my keystore and generated hash key
I submitted hash key to facebook app settings page,
I installed facebook app on my device.
But after all doing the app gives Facebook error invalid_key.
Pls help me in this regards,
Thank you.

答:
Invalid Key could be for a number of reasons -

Make sure you have Keytool and OpenSSL installed.

Make sure you are giving the correct Keystore file in the command.

Make sure you are giving the correct Alias.

Make sure you copied the generated Hash Key correctly to the Facebook application correctly.

When I got Invalid Key initially, it was because I was giving the wrong Alias. The strange thing is, that Keytool and OpenSSl won't mention that the alias is wrong. If you give the command to generate the Hash Key, and it doen't ask you for your password, you're probably doing it wrong.

ContentLicense: CC BY-SA 2.5

Title: Facebook Android SDK Invalid_key


问:
How to install Atom packages offline or when the atom package manager doesn't work?
I have a computer behind a very restrictive proxy server it only allows me to surf the web and download programs it does not allow programs like the Atom text editor to download it's packages.

My question is how do I install them using only browser based downloads?

答:
The answer of Richard Slater is informative and the answer of Andriy Buday could look less professional. But, in my case, the answer of Andriy Buday was also very important.

I tried to install two packages atom-beautify and prettier-atom by following the answer of Richard Slater and had some problems of not being able to find some modules. It was not only me who had these problems. Consider checking the following links.

The issue of "cannot find module event-kit"

https://github.com/Glavin001/atom-beautify/issues/1734

https://github.com/Glavin001/atom-beautify/issues/1366#issuecomment-269716306

When I decompressed a file (atom-beautify-0.30.3.tar.gz) I received from GitHub respository, I could find out directories like appveyor, docs, and examples. But I could not find out a directory named node_modules which was present when I installed this package atom-beautify using Atom Editor online.

To check if the absence of directory node_modules is the only problem, I went through the following steps.

Start Atom Editor.

Install atom-beautify using Atom Editor online like the answer of Andriy Buday suggests.

Close Atom Editor.

Move atom-beautify directory from ~/.atom/packages (that was %HOMEDIRECTORY%%HOMEPATH%.atom\packages in my case because I used cmd on Windows 10) to somewhere else.

Decompress atom-beautify-0.30.3.tar.gz and move or copy atom-beautify-0.30.3 directory from this decompressed result into %HOMEDIRECTORY%%HOMEPATH%.atom\packages as the answer of Andriy Buday suggests.

Rename directory %HOMEDIRECTORY%%HOMEPATH%.atom\packages\atom-beautify-0.30.3 to %HOMEDIRECTORY%%HOMEPATH%.atom\packages\atom-beautify as the answer of Richard Slater suggests.

Move or copy node_modules directory from the directory moved at step 4 into %HOMEDIRECTORY%%HOMEPATH%.atom\packages\atom-beautify.

Start Atom Editor.

I found that no error message appeared and that package atom-beautify worked properly, thus I am thinking that absence of node_modules directory was the only problem of the file atom-beautify-0.30.3.tar.gz I received from GitHub repository.

I am afraid if it is normal that directory node_modules is not contained in the file atom-beautify-0.30.3.tar.gz downloaded from GitHub repository because of any rules I do not know yet, like placing directories like node_modules somewhere else. If there really are such rules and somebody tells me about such rules by adding an answer or a comment here, I will appreciate it a lot.

I am not sure if it is same with all other packages, but I found that it was same at least with package prettier-atom.

I wish it helps somebody.

+++++++++++++++++++++++++++

I found why the directory node_modules was not contained in atom-beautify-0.30.3.tar.gz.

I checked answers of the following link.

How can I manually download packages for atom editor and install them (manually)?

Answer by D3181 included a link to a page of http://discuss.atom.io/ (I could get a helpful answer by Alchiadus from the link) and suggested running apm install in the package's directory. If it is necessary to use a file downloaded from GitHub repository like atom-beautify-0.30.3.tar.gz, it is necessary to run apm install in the package's directory before copying or moving into %HOMEDIRECTORY%%HOMEPATH%\.atom\package (~/.atom/package in case of *nix) of the offline computer.

Decompress the file downloaded from GitHub repository like atom-beautify-0.30.3.tar.gz.

Go into the directory like atom-beautify-0.30.3 of the decompressed result.

Run apm install on an online computer. (If the directory of apm.cmd is not in PATH, run {directory of apm.cmd}\apm.cmd install.)

Rename directory like atom-beautify-0.30.3 to the correct name of the package like atom-beautify.

Move directory with the correct name of the package like atom-beautify into %HOMEDIRECTORY%%HOMEPATH%\.atom\packages of the offline computer.

Run Atom Editor on the offline computer and check if the package works properly.

It seems normal that the directory node_modules is not included the the compressed file downloaded from GitHub repository.


答:
You can get a counting table for year and month as following:

```<code>SET @mn = 1; SET @r = 2015;
SELECT @mn, FLOOR(@yr / 12), CASE
    WHEN @mn = 12 THEN @mn := 1
    WHEN @mn < 12 THEN @mn := @mn + 1
END,
@yr := @yr + 1 FROM anything WHERE @yr < (2018 * 12)
</code>```

This you can LEFT JOIN to your data table and get a list of all years and months. Maybe there are more elegant SELECT-statements to achieve the same, but at least it works. anything is just any table that you have as placeholder for the SELECT statement. For speed it should be a small one.

Title: mysql select months for 3 years including those with no values

Body:
I have 2 tables: months and starter

mysql > select * from months
---------------------
| id   | month      |
| ---- | ---------- |
| 1    | 2012-01-31 |
| 2    | 2012-02-29 |
| 3    | 2012-03-31 |
| 4    | 2012-04-30 |
| 5    | 2012-05-31 |
| 6    | 2012-06-30 |
| 7    | 2012-07-31 |
| 8    | 2012-08-31 |
| 9    | 2012-09-30 |
| 10   | 2012-10-31 |
| 11   | 2012-11-30 |
| 12   | 2012-12-31 |
---------------------

Query from the table starter returns

+----------+------------+
|       id | startdate  |
+----------+------------+
|        1 | 2017-07-20 |
|        2 | 2017-07-19 |
|        4 | 2017-07-01 |
|        5 | 2017-06-28 |
|        6 | 2017-05-04 |
|        7 | 2017-04-03 |
|        8 | 2017-01-09 |
|        9 | 2017-02-01 |
|       10 | 2016-01-01 |
|       11 | 2015-01-07 |
|       12 | 2015-01-19 |
|       13 | 2016-02-09 |
+----------+------------+

I modified https://stackoverflow.com/a/17916395/8104587 to this:

SELECT concat(date_format(m.month,'%b'),' ',year(CURRENT_DATE())) as Months,
COUNT(s.id) AS Total FROM months AS m LEFT JOIN starter s ON
MONTH(m.month) = MONTH(s.startdate) AND YEAR(s.startdate) =
YEAR(CURRENT_DATE()) GROUP BY m.month

Output:

+----------+-------+
| Months   | Total |
+----------+-------+
| Jan 2017 |     1 |
| Feb 2017 |     1 |
| Mar 2017 |     0 |
| Apr 2017 |     1 |
| May 2017 |     1 |
| Jun 2017 |     1 |
| Jul 2017 |     3 |
| Aug 2017 |     0 |
| Sep 2017 |     0 |
| Oct 2017 |     0 |
| Nov 2017 |     0 |
| Dec 2017 |     0 |
+----------+-------+

I want to be able to generate for 3 years from 2015 to 2017 in this order

+----------+-------+
| Months   | Total |
+----------+-------+
| Jan 2017 |     1 |
| Jan 2016 |     1 |
| Jan 2015 |     0 |
| Feb 2017 |     1 |
| Feb 2016 |     1 |
| Feb 2015 |     0 |
...
| Dec 2017 |     0 |
| Dec 2016 |     0 |
| Dec 2015 |     0 |
+----------+-------+

Any assistance will be appreciated.

Body:
You can get a counting table for year and month as following:

SET @mn = 1; SET @r = 2015;
SELECT @mn, FLOOR(@yr / 12), CASE
    WHEN @mn = 12 THEN @mn := 1
    WHEN @mn < 12 THEN @mn := @mn + 1
END,
@yr := @yr + 1 FROM anything WHERE @yr < (2018 * 12)

This you can LEFT JOIN to your data table and get a list of all years and months. Maybe there are more elegant SELECT-statements to achieve the same, but at least it works. anything is just any table that you have as placeholder for the SELECT statement. For speed it should be a small one.


问:
Facebook comments analyzing
Hi I am trying to analyse Facebook comments using r so when I am browsing through the codes I came across one code can anyone explain me clearly what is it

I got the comments after that to clean the comments the code was written as below

```<code>sapply(comments, function(x) iconv(enc2utf8(x),sub="byte"))
</code>```

Can anyone explain me what is function doing ?

答:
sapply is designed to recursively apply the function in 2nd position to the element in first position.

This is a shortcut of the apply function. To know more about the apply family, check https://stat.ethz.ch/R-manual/R-devel/library/base/html/apply.html

comment is the element on which the function is applied.

function(x) iconv(enc2utf8(x),sub="byte") is a function that converts characters between encoding.

iconv(enc2utf8(x),sub="byte") does the encoding converting.

enc2utf8(x) sets the encoding.

In this case, this is an anonymous function, meaning that you call it "on the fly", without having to name it.

You could also have written this code :

```<code>a_function <- function(x) {
    iconv(enc2utf8(x),sub="byte")
}

sapply(comments, a_function)
</code>```

Best,

Colin

Title: Facebook comments analyzing

Body:
Hi I am trying to analyse Facebook comments using r so when I am browsing through the codes I came across one code can anyone explain me clearly what is it

I got the comments after that to clean the comments the code was written as below

sapply(comments, function(x) iconv(enc2utf8(x),sub="byte"))

Can anyone explain me what is function doing ?

Body:
sapply is designed to recursively apply the function in 2nd position to the element in first position.

This is a shortcut of the apply function. To know more about the apply family, check https://stat.ethz.ch/R-manual/R-devel/library/base/html/apply.html

comment is the element on which the function is applied.

function(x) iconv(enc2utf8(x),sub="byte") is a function that converts characters between encoding.

iconv(enc2utf8(x),sub="byte") does the encoding converting.

enc2utf8(x) sets the encoding.

In this case, this is an anonymous function, meaning that you call it "on the fly", without having to name it.

You could also have written this code :

a_function <- function(x) {
    iconv(enc2utf8(x),sub="byte")
}

sapply(comments, a_function)

Best,

Colin


问:
Jerky animation with jquery accordion, don't understand why
I'm using a number of jQueryUI accordions on a single page inside of AnythingSlider. It used to be that it was pretty smooth, but has gotten jerky.

Now, instead inserting a bunch of code, how about I just give the link and you can look. If it works fine for you, then, well, I just don't know. Of course, if there's more you'd like to have, let me know.

Click here

答: I've got an aged laptop that sometimes lags behind my year-old Android phone.  Your accordions looked slick in Chrome, a little less so in FireFox, and the site was utterly trashed and unintelligible in IE7.</p>


问:
How to install two different app on android device using Ionic
I am installing an app on an android device using the following command.

"ionic cordova run android"

but when I am installing another app, it is replacing the old app.

so please tell me the solution so that old and another new app both should be there in android device

答:
Please check the config.xml file, and change the id of the app:

```<code><widget id="new.app.id" version="0.0.1" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
</code>```

That way, it will be considered as a different app and will not replace the previous one.

Body:
Please check the config.xml file, and change the id of the app:

<widget id="new.app.id" version="0.0.1" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">

That way, it will be considered as a different app and will not replace the previous one.


问:
"Add to Homescreen" Banner in Rails PWA
I've made a small PWA in RoR; following and I followed Google's guide on having "Add to Homescreen" banners. Everything in devtools is fine: the service worker is registered, the manifest.json is found, the "Add to Homescreen" link is displayed and runs in the tool drawer.

I even installed Lighthouse like they said and ran the report; it says everything should work. However, I have yet to see the banner (yes, it isn't already on my homescreen; yes, I visited at least five minutes apart).

Does anyone have an idea on what the threshold is WRT users activity to make the banner appear?

(ps. does anyone want to try it out here?)

答:
I saw you referenced two manifests on your page:

Line 20:

```<code><link rel="manifest" href="/manifest.json" />
</code>```

Line 27:

```<code><link rel="manifest" href="/assets/favicon/manifest-71676a3789f8b2a25498b2271ddc3288b14553d94e25c37030e6d69d46d72b81.json" />
</code>```

When I frist load the page I see the mainfest definition in chrome dev tools, but when I reload the page the manifest is gone.

Title: "Add to Homescreen" Banner in Rails PWA

Body:
I saw you referenced two manifests on your page:

Line 20:

<link rel="manifest" href="/manifest.json" />

Line 27:

<link rel="manifest" href="/assets/favicon/manifest-71676a3789f8b2a25498b2271ddc3288b14553d94e25c37030e6d69d46d72b81.json" />

When I frist load the page I see the mainfest definition in chrome dev tools, but when I reload the page the manifest is gone.


问:
Change which paper-tabs displayed on-click data binding - Polymer
I am wanting to dynamically change the paper-tabs that are displayed in my page when the buttons on the sidebar are selected.

ie. (selection | tabs to display)

Expert | 3 tabs

Admin | 4 tabs

etc.

I have managed to get data binding working when I select the tabs themselves with regards to the data shown within the scrollable dialog, I'm just stuck on this.

page-tabs.html

```<code><!-- THIS IS STILL A PRETTY BASIC EXAMPLE -->
<paper-tabs selected="{{selected}}" noink>
   <paper-tab link>
      <a href="#tab1" tabindex="-1">TAB 1</a>
    </paper-tab>
    <paper-tab link>
      <a href="#tab2" tabindex="-1">TAB 2</a>
    </paper-tab>
    <paper-tab link>
      <a href="#tab3" tabindex="-1">TAB 3</a>
    </paper-tab>
</paper-tabs>

<iron-pages selected="{{selected}}">
    <div>CONTENT OF PAGE 1</div>
    <div>CONTENT OF PAGE 2</div>
    <div>CONTENT OF PAGE 3</div>
</iron-pages>
</code>```

side-bar.html

```<code><div class="drawer-content vertical layout" id="drawer">

      <div class="userItemInfo horizontal layout">
        <img id="avatar" class="userAvatar" src="../images/hipster.png" slot="item-icon"></img>
        <div class="userDetails vertical layout" id="userDetails">
          <div class=username>USERNAME</div>
          <div class="subheader">further function</div>
        </div>
      </div>

      <paper-icon-item on-click="{{homePage}}">
        <iron-icon icon="home" slot="item-icon"></iron-icon> <span>Home</span>
      </paper-icon-item>
      <paper-icon-item on-click="{{expertPage}}">
        <iron-icon icon="done" slot="item-icon"></iron-icon> <span>Expert</span>
      </paper-icon-item>
      <paper-icon-item on-click="{{searchBar}}">
        <iron-icon icon="search" slot="item-icon"></iron-icon> <span>Search</span>
      </paper-icon-item>
      <paper-icon-item on-click="{{adminPage}}">
        <iron-icon icon="supervisor-account" slot="item-icon"></iron-icon> <span>Admin</span>
      </paper-icon-item>
      <div class="flex"></div> <!-- THIS IS THE ONLY WAY THAT I COULD GET THE LAST ENTRY TO BE FLEXED TO THE BOTTOM -->
      <paper-icon-item on-click="{{settingsPage}}">
        <iron-icon icon="settings" slot="item-icon"></iron-icon> <span id="">Settings</span>
      </paper-icon-item>

    </div>
</code>```

Any help is appreciated.

答:
You can manage your tabs page with <iron-pages>, e.g.

```<code><iron-pages selected="[[page]]">
    <!-- Expert | 3 tabs -->
    <page-tabs-expert></page-tabs-expert>
    <!--- Admin | 4 tabs -->
    <page-tabs-admin></page-tabs-admin>
    <!-- etc. -->
    <page-tabs-etc></page-tabs-etc>
</iron-pages>
</code>```

And, make your sidebar select-able with perhaps <iron-selector>, https://www.webcomponents.org/element/PolymerElements/iron-selector

```<code><iron-selector selected={{page}}>
</code>```

Body:
I am wanting to dynamically change the paper-tabs that are displayed in my page when the buttons on the sidebar are selected.

ie. (selection | tabs to display)

Expert | 3 tabs

Admin | 4 tabs

etc.

I have managed to get data binding working when I select the tabs themselves with regards to the data shown within the scrollable dialog, I'm just stuck on this.

page-tabs.html

<paper-tabs selected="{{selected}}" noink>
   <paper-tab link>
      TAB 1
    </paper-tab>
    <paper-tab link>
      TAB 2
    </paper-tab>
    <paper-tab link>
      TAB 3
    </paper-tab>
</paper-tabs>

<iron-pages selected="{{selected}}">

CONTENT OF PAGE 1

CONTENT OF PAGE 2

CONTENT OF PAGE 3

</iron-pages>

side-bar.html

USERNAME

further function

      <paper-icon-item on-click="{{homePage}}">
        <iron-icon icon="home" slot="item-icon"></iron-icon> Home
      </paper-icon-item>
      <paper-icon-item on-click="{{expertPage}}">
        <iron-icon icon="done" slot="item-icon"></iron-icon> Expert
      </paper-icon-item>
      <paper-icon-item on-click="{{searchBar}}">
        <iron-icon icon="search" slot="item-icon"></iron-icon> Search
      </paper-icon-item>
      <paper-icon-item on-click="{{adminPage}}">
        <iron-icon icon="supervisor-account" slot="item-icon"></iron-icon> Admin
      </paper-icon-item>

      <paper-icon-item on-click="{{settingsPage}}">
        <iron-icon icon="settings" slot="item-icon"></iron-icon> Settings
      </paper-icon-item>

Any help is appreciated.

Body:
You can manage your tabs page with <iron-pages>, e.g.

<iron-pages selected="[[page]]">
    <!-- Expert | 3 tabs -->
    <page-tabs-expert></page-tabs-expert>
    <!--- Admin | 4 tabs -->
    <page-tabs-admin></page-tabs-admin>
    <!-- etc. -->
    <page-tabs-etc></page-tabs-etc>
</iron-pages>

And, make your sidebar select-able with perhaps <iron-selector>, https://www.webcomponents.org/element/PolymerElements/iron-selector

<iron-selector selected={{page}}>


问:
May I have remote git repository on my hosting?
I had been using free github account as a remote repository. Now I am wondering if I can create a github repository on my hosting. There is a git command present on it, but is it enough? I am not permitted to install anything on my hosting. How to check if I can place github repository there.

If it was the posibility to have github a repository there, how to create it? What internet address would it have?

答:
Gitlab community could be the solution too.
If you have more than 5 users.</p>


问:
Getting a Nan Error SSRS
Getting a NaN error. My original statement is:

```<code>=SUM(Fields!Outstanding_Commitments.Value/Fields!Conversion.Value, "Cost")
</code>```

After getting the NaN error, i changed my code to the following:

```<code>=IIF(Double.IsNAN(SUM(Fields!Outstanding_Commitments.Value/Fields!Conversion.Value, "Cost"))
,0,
SUM(Fields!Outstanding_Commitments.Value/Fields!Conversion.Value, "Cost"))
</code>```

Using the second part doesnt provide me with any values at all. Something isn't right.

Thanks in advance

答:
Try the expression below</p>

```<code>=SUM(
Iif(Fields!Conversion.Value=0,0,Fields!Outstanding_Commitments.Value)
/
Iif(Fields!Conversion.Value=0,1,Fields!Conversion.Value)
, "Cost")
</code>```

Title: Getting a Nan Error SSRS

Body:
Getting a NaN error. My original statement is:

=SUM(Fields!Outstanding_Commitments.Value/Fields!Conversion.Value, "Cost")

After getting the NaN error, i changed my code to the following:

=IIF(Double.IsNAN(SUM(Fields!Outstanding_Commitments.Value/Fields!Conversion.Value, "Cost"))
,0,
SUM(Fields!Outstanding_Commitments.Value/Fields!Conversion.Value, "Cost"))

Using the second part doesnt provide me with any values at all. Something isn't right.

Thanks in advance

Body:
Try the expression below

=SUM(
Iif(Fields!Conversion.Value=0,0,Fields!Outstanding_Commitments.Value)
/
Iif(Fields!Conversion.Value=0,1,Fields!Conversion.Value)
, "Cost")


问:
Switching Between VS Code and VS 2015
I am a single developer starting out on an ASP.Net Core MVC project with Angular 2. I used the Steve Sanderson template VS Angular 2 Template which works well in Visual Studio 2015. Up until now I have been developing the structure, and my understanding, of ASP.Net Core, Entity Framework Core, Identity, WebPack, NPM etc. and working in VS 2015 has been great.

Now I am moving on to learning and developing the client side of the project which in places will involve Angular 2. Already I am finding VS 2015 a bit clumsy and would like to try Visual Studio Code.

Is it possible to switch between the two on the same project? It would be great to be able to develop Angular components in VS Code and switch back to VS 2015 for any C# work. Writing code in VS Code I imagine would be fine, but what about the debugging/webpack building side of things?

Any experience or suggestions very welcome. Thanks.

答:
I've successfully setup my Visual Studio 2015+ ASP.NET project on VSCode.

I've created an gulpfile that handle the build for me:

It starts an IISExpress instance.

Refresh my browser on razor code change.

And automatically rebuild my application when I change C# code.

You can find the gulpfile on my project's Github

Important note if you are going to switch between VSCode and Visual Studio:
When you want to create a new file, I strongly suggest you to do it in Visual Studio.

Title: Switching Between VS Code and VS 2015


问:
google map is not displaying with bootstrap

var map;
      function initMap() {
        map = new google.maps.Map(document.getElementById('map'), {
          zoom: 16,
          center: new google.maps.LatLng(18.511325, 73.820176),
          mapTypeId: 'roadmap'
        });

        var iconBase = 'img/contactus/';
        var icons = {
          info: {
            icon: iconBase + 'map.png'
          }
        };

        var features = [
          {
            position: new google.maps.LatLng(18.511325, 73.820176),
            type: 'info'
          }
        ];

        // Create markers.
        features.forEach(function(feature) {
          var marker = new google.maps.Marker({
            position: feature.position,
            icon: icons[feature.type].icon,
            map: map
          });
        });
      }```
<pre class="snippet-code-css lang-css prettyprint-override"><code> #map{
    margin-left: 20%;
    height:100;
  }</code>```

```

hello above code is for Google map, i am integrating Google map inside my project & display custom logo in it. but its not displaying map to me i am using bootstrap.but when click on inspect element & uncheck position:relative then my map is displaying but not in proper way it should look like.

答:
I have created a fiddle, modified your css and it seems working. The only issue was css. The map is getting hidden after loading. here is the CSS:</p>

```<code> #map{
  position:fixed !important;
  display:block !important;
  width: 100%;
  height: 100%;
}
</code>```

Body:
var map;
      function initMap() {
        map = new google.maps.Map(document.getElementById('map'), {
          zoom: 16,
          center: new google.maps.LatLng(18.511325, 73.820176),
          mapTypeId: 'roadmap'
        });

        var iconBase = 'img/contactus/';
        var icons = {
          info: {
            icon: iconBase + 'map.png'
          }
        };

        var features = [
          {
            position: new google.maps.LatLng(18.511325, 73.820176),
            type: 'info'
          }
        ];

        // Create markers.
        features.forEach(function(feature) {
          var marker = new google.maps.Marker({
            position: feature.position,
            icon: icons[feature.type].icon,
            map: map
          });
        });
      }

 #map{
    margin-left: 20%;
    height:100;
  }

hello above code is for Google map, i am integrating Google map inside my project & display custom logo in it. but its not displaying map to me i am using bootstrap.but when click on inspect element & uncheck position:relative then my map is displaying but not in proper way it should look like.

Body:
I have created a fiddle, modified your css and it seems working. The only issue was css. The map is getting hidden after loading. here is the CSS:

 #map{
  position:fixed !important;
  display:block !important;
  width: 100%;
  height: 100%;
}


问:
Generate all possible choices of elements each from a distinct set
Suppose that we have k sets each of which contains q elements. I want to generate all possible sets in which we select exactly 1 element from each set. Assume that the sets are represented as a table where each row is a set and its columns are its elements. Also assume that all elements are indexed row-wise like this

Set 1: 1 2 3

Set 2: 4 5 6

Set 3: 7 8 9

The thing is that k,q may vary so I cannot use nested for loops. I work in C++ and this structure is actually a std::vector of std::vector of int, but I am not asking for code here, just an idea on how to do this.

答:
If you are unaware of the number of sets and of the number of elements in each set, then you can generate the set of all elements you want the following way.  Basically, you can loop over all the elements of a set and include that in the previous remaining product of whatever had been computed so far.  Let me know if something is still unclear</p>

```<code>#include <iostream>
#include <set>
#include <tuple>
#include <vector>

using std::cout;
using std::endl;

void append_results(const std::set<int>& set,
                    std::vector<std::vector<int>>& results);

int main() {

    auto sets = std::vector<std::set<int>>{
        std::set<int>{1, 2, 3},
        std::set<int>{4, 5, 6},
        std::set<int>{7, 8, 9}
    };

    auto results = std::vector<std::vector<int>>{};

    for (const auto& set : sets) {
        append_results(set, results);
    }

    for (const auto& result : results) {
        for (auto integer : result) {
            cout << integer << " ";
        }
        cout << endl;
    }

    return 0;
}

void append_results(const std::set<int>& set,
                    std::vector<std::vector<int>>& results) {

    if (results.empty()) {
        for (auto integer : set) {
            results.push_back(std::vector<int>{integer});
        }
    } else {
        auto old_results = results;
        results.clear();
        for (auto integer : set) {
            for (auto old_result : old_results) {
                old_result.push_back(integer);
                results.push_back(std::move(old_result));
            }
        }
    }
}
</code>```

Body:
If you are unaware of the number of sets and of the number of elements in each set, then you can generate the set of all elements you want the following way.  Basically, you can loop over all the elements of a set and include that in the previous remaining product of whatever had been computed so far.  Let me know if something is still unclear

#include <iostream>
#include <set>
#include <tuple>
#include <vector>

using std::cout;
using std::endl;

void append_results(const std::set<int>& set,
                    std::vector<std::vector<int>>& results);

int main() {

    auto sets = std::vector<std::set<int>>{
        std::set<int>{1, 2, 3},
        std::set<int>{4, 5, 6},
        std::set<int>{7, 8, 9}
    };

    auto results = std::vector<std::vector<int>>{};

    for (const auto& set : sets) {
        append_results(set, results);
    }

    for (const auto& result : results) {
        for (auto integer : result) {
            cout << integer << " ";
        }
        cout << endl;
    }

    return 0;
}

void append_results(const std::set<int>& set,
                    std::vector<std::vector<int>>& results) {

    if (results.empty()) {
        for (auto integer : set) {
            results.push_back(std::vector<int>{integer});
        }
    } else {
        auto old_results = results;
        results.clear();
        for (auto integer : set) {
            for (auto old_result : old_results) {
                old_result.push_back(integer);
                results.push_back(std::move(old_result));
            }
        }
    }
}


问:
TSQL puzzle, why is my update not random?
I was looking at postgres question and it called for updating a table with random values.

I only noticed it was targeted at postgres after answering it, but in answering it I hit a mystery.

Here is my sample code in question:

```<code>create table #Buildings([Use] varchar(50), n int)

insert #Buildings
select null,null from sysobjects

update #Buildings
set [Use] =
        case (ABS(CAST(CAST(NEWID() AS VARBINARY) AS int)) % 6)
            when 0 then null
            when 1 then 'warehouse'
            when 2 then 'office'
            when 3 then 'market'
            when 4 then 'retail'
            when 5 then 'workshop'
            else 'HOW IS THIS POSSIBLE'
        end,
    n = ABS(CAST(CAST(NEWID() AS VARBINARY) AS int)) % 6

select [Use], count(*) from
#Buildings
group by [Use]

select n, count(*) from
#Buildings
group by n
</code>```

It returns a very odd result set:

```<code>Use
-------------------------------------------------- -----------
workshop                                           128
HOW IS THIS POSSIBLE                               633
NULL                                               287
retail                                             140
warehouse                                          258
market                                             177
office                                             209
</code>```

And a second result set that makes complete sense:

```<code>n
----------- -----------
0           292
3           300
1           313
4           277
5           311
2           339
</code>```

The data for both result sets was generated in the same update statement.

So my question is why is a number out of the range of 0 - 5 hitting my case statement? What is that number? Why when I update the int directly is stuff distributed properly?

答:
```<code>create table #Buildings([Use] varchar(50), n int)
insert #Buildings
select null,null from sysobjects

declare @i int

update #Buildings
set
    @i = (ABS(CAST(CAST(NEWID() AS VARBINARY) AS int)) % 6),
    [Use] =
        case @i -- if the expression is evaluated on-the-fly for each WHEN, MSSQL variable-in-SQL capability will alleviate this problem
                when 0 then null
                when 1 then 'warehouse'
                when 2 then 'office'
                when 3 then 'market'
                when 4 then 'retail'
                when 5 then 'workshop'
                else 'HOW IS THIS POSSIBLE'
        end,
    n = @i

select [Use], count(*) from
#Buildings
group by [Use]

select n, count(*) from
#Buildings
group by n
</code>```

Body:
I was looking at postgres question and it called for updating a table with random values.

I only noticed it was targeted at postgres after answering it, but in answering it I hit a mystery.

Here is my sample code in question:

create table #Buildings([Use] varchar(50), n int)

insert #Buildings
select null,null from sysobjects

update #Buildings
set [Use] =
        case (ABS(CAST(CAST(NEWID() AS VARBINARY) AS int)) % 6)
            when 0 then null
            when 1 then 'warehouse'
            when 2 then 'office'
            when 3 then 'market'
            when 4 then 'retail'
            when 5 then 'workshop'
            else 'HOW IS THIS POSSIBLE'
        end,
    n = ABS(CAST(CAST(NEWID() AS VARBINARY) AS int)) % 6

select [Use], count(*) from
#Buildings
group by [Use]

select n, count(*) from
#Buildings
group by n

It returns a very odd result set:

Use
-------------------------------------------------- -----------
workshop                                           128
HOW IS THIS POSSIBLE                               633
NULL                                               287
retail                                             140
warehouse                                          258
market                                             177
office                                             209

And a second result set that makes complete sense:

n
----------- -----------
0           292
3           300
1           313
4           277
5           311
2           339

The data for both result sets was generated in the same update statement.

So my question is why is a number out of the range of 0 - 5 hitting my case statement? What is that number? Why when I update the int directly is stuff distributed properly?

OwnerDisplayName: Michael Buen


问:
node.js install on Amazon EC2
So I'm installing node.js on amazon ec2 with ubuntu 8.04, and and have run node sayhello.js which is this code:

```<code> var sys = require('sys'),
    http = require('http');
 http.createServer(function (req, res) {
   setTimeout(function () {
     res.writeHead(200, {'Content-Type': 'text/html'});
     res.write('<br/><strong>    Hello World!</strong>');
     res.end();
     sys.puts(sys.inspect(req, false));
   }, 2000);
 }).listen(8000);
   sys.puts('Server running at http://ec2-174-12-132-193.compute-1.amazonaws.com:8000/');
</code>```

I see

Server running at
  http://ec2-174-12-132-193.compute-1.amazonaws.com:8000/

being displayed in the console correctly.

The tutorial says: go to :8000 in the browser and you should see Hello World!

I go to http://ec2-174-12-132-193.compute-1.amazonaws.com:8000/ (not the real address) but it doesn't load (just connecting...). The example uses localhost, is doing the public domain incorrect or some such?

Thanks.

答: Within the security group associated with the EC2 instance, make sure you have port 8000 open to your IP or to the public.</p>

Title: node.js install on Amazon EC2

Body:
So I'm installing node.js on amazon ec2 with ubuntu 8.04, and and have run node sayhello.js which is this code:

 var sys = require('sys'),
    http = require('http');
 http.createServer(function (req, res) {
   setTimeout(function () {
     res.writeHead(200, {'Content-Type': 'text/html'});
     res.write('
    Hello World!');
     res.end();
     sys.puts(sys.inspect(req, false));
   }, 2000);
 }).listen(8000);
   sys.puts('Server running at http://ec2-174-12-132-193.compute-1.amazonaws.com:8000/');

I see

Server running at
  http://ec2-174-12-132-193.compute-1.amazonaws.com:8000/

being displayed in the console correctly.

The tutorial says: go to :8000 in the browser and you should see Hello World!

I go to http://ec2-174-12-132-193.compute-1.amazonaws.com:8000/ (not the real address) but it doesn't load (just connecting...). The example uses localhost, is doing the public domain incorrect or some such?

Thanks.


问:
How to pass multiple parameters to $on service
I have two fields which I want to pass to my controller using $on service.
This is first js

```<code>$scope.submitFilterForm = function(query){
    var query='test';
    var deviceType= filterStateService.getActiveFilterState();
    messageBus.send(Message.SubmitFilterForm,query,deviceType);
}
</code>```

Now I have to pass both variables to other controllers. A query is coming correct in other controller but Device type is coming as undefined.
My question is can we pass multiple parameters.

```<code>$scope.$onMessage(Message.SubmitFilterForm,function(event,data,deviceType) {
    console.log("Value of data n device type is",data);
    console.log("Value of data n device type is",deviceType);
}
</code>```

答:
you can pass an object: </p>

```<code>messageBus.send(Message.SubmitFilterForm,{ query: query, deviceType: deviceType});

$scope.$onMessage(Message.SubmitFilterForm,function(event,data) {
            console.log("Value of data n device type is",data.query);
            console.log("Value of data n device type is",data.deviceType);
            }
</code>```

Body:
I have two fields which I want to pass to my controller using $on service.
This is first js

$scope.submitFilterForm = function(query){
    var query='test';
    var deviceType= filterStateService.getActiveFilterState();
    messageBus.send(Message.SubmitFilterForm,query,deviceType);
}

Now I have to pass both variables to other controllers. A query is coming correct in other controller but Device type is coming as undefined.
My question is can we pass multiple parameters.

$scope.$onMessage(Message.SubmitFilterForm,function(event,data,deviceType) {
    console.log("Value of data n device type is",data);
    console.log("Value of data n device type is",deviceType);
}

Body:
you can pass an object:

messageBus.send(Message.SubmitFilterForm,{ query: query, deviceType: deviceType});

$scope.$onMessage(Message.SubmitFilterForm,function(event,data) {
            console.log("Value of data n device type is",data.query);
            console.log("Value of data n device type is",data.deviceType);
            }


问:
When should I call the componentWillUnmount() method?
I would like to Unmount my component and then mount again at certain time.to do that i am assigning a new key to component.

```<code> <div>
 <Game key = {this.state.gameId}
 createNewGame = {this.createNewGame.bind(this)}
 rows = {5}
 columns = {5}
 activeCellsCount = {6} />;
 </div>
</code>```

I have some timers to clear which i placed them in componentWillUnmount() as follows,

```<code>componentWillUnmount() {
    console.log("I am in Component will Unmount");
    clearTimeOut( this.memorizeTimerId );
    clearTimeOut( this.recallTimerId );
    this.finishGame();
}
</code>```

When i am trying to do Unmount and mount, Getting error inside componentWillUnmount() as "Uncaught ReferenceError: clearTimeOut is not defined" by indicating both clearTimeOut() methods. componentWillUnmount() is placed inside 'Game' component. is anything wrong with this method?

答:
There is a typo in your code.

```<code>clearTimeOut( this.memorizeTimerId );
</code>```

Change this to

```<code>clearTimeout( this.memorizeTimerId );
</code>```

It works fine, I have tried it.

Body:
I would like to Unmount my component and then mount again at certain time.to do that i am assigning a new key to component.

 <Game key = {this.state.gameId}
 createNewGame = {this.createNewGame.bind(this)}
 rows = {5}
 columns = {5}
 activeCellsCount = {6} />;

I have some timers to clear which i placed them in componentWillUnmount() as follows,

componentWillUnmount() {
    console.log("I am in Component will Unmount");
    clearTimeOut( this.memorizeTimerId );
    clearTimeOut( this.recallTimerId );
    this.finishGame();
}

When i am trying to do Unmount and mount, Getting error inside componentWillUnmount() as "Uncaught ReferenceError: clearTimeOut is not defined" by indicating both clearTimeOut() methods. componentWillUnmount() is placed inside 'Game' component. is anything wrong with this method?

Body:
There is a typo in your code.

clearTimeOut( this.memorizeTimerId );

Change this to

clearTimeout( this.memorizeTimerId );

It works fine, I have tried it.


问:
How do I fix this code to display the correct message after an upload?
I have this code below where it checks to see if a file was uploaded successfully, unsuccessfully or canceled:

```<code>  if (success === 1){
    result = '<span class="imagemsg'+imagecounter+'">The file was uploaded successfully</span><br/><br/>';
    $('.listImage').eq(window.lastUploadImageIndex).append('<div>' + htmlEncode(imagefilename) + '<button type="button" class="deletefileimage" image_file_name="' + imagefilename + '">Remove</button><br/><hr/></div>');
    displayInfo = replaceForm;
  }
  else if (success === 2){
    result = '<span class="imagemsg'+imagecounter+'"> The file upload was canceled</span><br/><br/>';
    displayInfo = updateForm;
  }
  else {
    result = '<span class="imagemsg'+imagecounter+'">There was an error during file upload</span><br/><br/>';
    displayInfo = updateForm;
  }
</code>```

But I have a JavaScript function where it outputs this below in the PHP script:

```<code><script language="javascript" type="text/javascript">
    window.top.stopImageUpload(<?php echo $result ? 1 : 2; ?>, '<?php echo $_FILES['fileImage']['name'] ?>');
</script>
</code>```

Now if the file uploaded successfully, the correct message is displayed, if canceled, the correct mssage appear but the problem is that if the file fails to upload, then it displays the cancel message and not the error while uploading message. I tried to change part of the above code so it will be like this:

...<?php echo $result ? 1 : 2 : 3 ?>..

But this gives me an error. My question is how do I change the above code so that it will be able to output the correct message for when a file does not upload successfully?

答:
```<code>$.ajax(
{
url: _spPageContextInfo.siteAbsoluteUrl + "/_api/Web/Lists/getByTitle('" + libTitle + "')/Items",
type: "GET",
contentType: "application/json;odata=verbose",

  headers: {
    'Accept': 'application/json;odata=verbose',
    'X-RequestDigest': $("#__REQUESTDIGEST").val()
  },
    success: fetchSuccess,
    error: onFailure
  });

function fetchSuccess(r) {
  // How to display the count of "r"
  console.log(r.length);

}

function onFailure(r) {
  alert("Error + r + working");
}
</code>```

Body:
I have this code below where it checks to see if a file was uploaded successfully, unsuccessfully or canceled:

  if (success === 1){
    result = 'The file was uploaded successfully

';
    $('.listImage').eq(window.lastUploadImageIndex).append('
' + htmlEncode(imagefilename) + '<button type="button" class="deletefileimage" image_file_name="' + imagefilename + '">Remove</button>

');
    displayInfo = replaceForm;
  }
  else if (success === 2){
    result = ' The file upload was canceled

';
    displayInfo = updateForm;
  }
  else {
    result = 'There was an error during file upload

';
    displayInfo = updateForm;
  }

But I have a JavaScript function where it outputs this below in the PHP script:

Now if the file uploaded successfully, the correct message is displayed, if canceled, the correct mssage appear but the problem is that if the file fails to upload, then it displays the cancel message and not the error while uploading message. I tried to change part of the above code so it will be like this:

...<?php echo $result ? 1 : 2 : 3 ?>..

But this gives me an error. My question is how do I change the above code so that it will be able to output the correct message for when a file does not upload successfully?


问:
JMeter - Performance Testing
I'm using JMeter for performance testing. I tried to use Blazemeter. I need to know main features of Blazemeter.

Why Blazemeter is better than JMeter? Can anyone explain the reason and the major differences between JMeter and Blazemeter?

答:
I have been using JMeter and Blazemeter for my script creation.
There is not much difference between them for scripting phase. Blazemeter uses the jMeter services to record the script just it provides a better visual interface.

For a web application on my PC i will prefer to record it using JMeter but blazemeter is helpful when you are recording  a mobile application say iOS or Android. You can avoid the hassle of creating a temporary root certificate and also your device and system need not be wired connected.
If you proceed using blazemeter you just need create a blazemeter proxy and configure your device to the same proxy settings. This link can help you get on with it:- Recording mobile app using blazemeter.
The main advantage that blazemeter has on Jmeter is for for script execution and bottleneck identification.

You need not worry about the latency resulting in due to poor netwrok connectivity as you will be executing your tests on the cloud servers.

You need not maintain an infrastructure to generate load when performing a
distributed testing. But there will be cost involved in-case you are planning
to run a test with more than 50 users.

You will be provided an option to simulate your load with different network speeds,  say wifi, 4g, 3g etc and with different geographical locations.

Blazemeter will provide you with rich perfromance test reports with better visual representations

All the major APM's- New Relic, Dynatrace and APPdynamaics has an extension for Blazemeter which you can very conveniently use for bottleneck identification.

Title: JMeter - Performance Testing


问:
Openlayers 3 Reproject EPSG:4326 vector to EPSG:3857
I am needing to transform GeoJSON vector data from EPSG:4326 to EPSG:3857...

I have a map...

```<code>var olMapDiv = document.getElementById('olmap');
            control.map = new ol.Map({
                target: olMapDiv,
                renderer: 'canvas',
                layers: layers,
                interactions: ol.interaction.defaults({
                    altShiftDragRotate: false,
                    dragPan: false,
                    rotate: false
                }).extend([new ol.interaction.DragPan({ kinetic: null })]),
                pixelRatio: 1,
                loadTilesWhileAnimating: true,
                loadTilesWhileInteracting: true,
                view: view
            });
</code>```

and a view...

```<code>var view = new ol.View({
                // make sure the view doesn't go beyond the 22 zoom levels of Google Maps
                maxZoom: 21,
                projection: 'EPSG:3857',
                center: [0, 0],
                zoom: 0
            });
</code>```

I define my geoJson Object...

```<code>var geoJsonObj = {
                        'type': 'Feature',
                        'geometry': JSON.parse(shape),
                        'name': 'V',
                        'id': V.vID

                    }
</code>```

I try to read the features into a open layers Vector object and provide projection parameters...

```<code>var vectorSource = new ol.source.Vector({
                        features: (new ol.format.GeoJSON()).readFeatures(geoJsonObj, {defaultDataProjection:"EPSG:4326",featureProjection:"EPSG:3857"})
                    });
</code>```

Then I use the "vectorSource" above in a new Vector layer...

```<code>vectors = new ol.layer.Vector({
                        title: V.vID,
                        source: vectorSource,
                        id: V.vID,
                        name: 'V',
                        label: response.VList[key].Acres,
                        fill: response.VList[key].Shade,
                        stroke: defaultStrokeHex,
                        style: function (feature, resolution) {
                            var text = resolution * 100000 < 10 ? response.VList[key].Acres : '';

                            if (text != "") {
                                styleCache[text] = [new ol.style.Style({
                                    stroke: new ol.style.Stroke({
                                        color: '#319FD3',
                                        width: 1
                                    }),
                                    text: new ol.style.Text({
                                        font: '12px Calibri,sans-serif',
                                        text: text,
                                        fill: new ol.style.Fill({
                                            color: '#000'
                                        }),
                                        stroke: new ol.style.Stroke({
                                            color: '#fff',
                                            width: 3
                                        })
                                    }),
                                    fill: new ol.style.Fill({
                                        color: rcisWebMapUtilities.convertHex(response.VList[key].Shade, '0.5')
                                    })
                                })];
                            }
                            else if (text == "") {
                                styleCache[text] = [new ol.style.Style({
                                    fill: new ol.style.Fill({
                                        color: rcisWebMapUtilities.convertHex(response.VList[key].Shade, '0.5')
                                    })
                                })
                                ]
                            } return styleCache[text];
                        }

                    });
</code>```

No matter what I do I either see the vector drawn...but in EPSG:4326 or nothing loads...

I've spent way too much time trying to figure out how to get OpenLayers3 to do this...Any help is greatly appreciated!!

答:
If you use EPSG:4326 in your view then your geojson vector declaration should be

```<code>var vectorSource = new ol.source.Vector({
features: (new ol.format.GeoJSON()).readFeatures(geojsonObject, {
dataProjection: 'EPSG:4326',
featureProjection:'EPSG:4326' })
});
</code>```

If you use EPSG:3857 in your view use this:

```<code>var vectorSource = new ol.source.Vector({
features: (new ol.format.GeoJSON()).readFeatures(geojsonObject, {
dataProjection: 'EPSG:4326',
featureProjection:'EPSG:3857' })
});
</code>```

Just to explain dataProjection is the source coords. Means the epsg of your coordinates within the geojson file. While featureProjection is the EPSG of your view and thus the EPSG of your map. Means is the EPSG original coords should be trasformed.

So try to remember this rule: featureProjection and ol.View projection declaration should be equal.

Note that I am assuming your geojson coords are projected in EPSG:4326.

Body:
I am needing to transform GeoJSON vector data from EPSG:4326 to EPSG:3857...

I have a map...

var olMapDiv = document.getElementById('olmap');
            control.map = new ol.Map({
                target: olMapDiv,
                renderer: 'canvas',
                layers: layers,
                interactions: ol.interaction.defaults({
                    altShiftDragRotate: false,
                    dragPan: false,
                    rotate: false
                }).extend([new ol.interaction.DragPan({ kinetic: null })]),
                pixelRatio: 1,
                loadTilesWhileAnimating: true,
                loadTilesWhileInteracting: true,
                view: view
            });

and a view...

var view = new ol.View({
                // make sure the view doesn't go beyond the 22 zoom levels of Google Maps
                maxZoom: 21,
                projection: 'EPSG:3857',
                center: [0, 0],
                zoom: 0
            });

I define my geoJson Object...

var geoJsonObj = {
                        'type': 'Feature',
                        'geometry': JSON.parse(shape),
                        'name': 'V',
                        'id': V.vID

                    }

I try to read the features into a open layers Vector object and provide projection parameters...

var vectorSource = new ol.source.Vector({
                        features: (new ol.format.GeoJSON()).readFeatures(geoJsonObj, {defaultDataProjection:"EPSG:4326",featureProjection:"EPSG:3857"})
                    });

Then I use the "vectorSource" above in a new Vector layer...

vectors = new ol.layer.Vector({
                        title: V.vID,
                        source: vectorSource,
                        id: V.vID,
                        name: 'V',
                        label: response.VList[key].Acres,
                        fill: response.VList[key].Shade,
                        stroke: defaultStrokeHex,
                        style: function (feature, resolution) {
                            var text = resolution * 100000 < 10 ? response.VList[key].Acres : '';

                            if (text != "") {
                                styleCache[text] = [new ol.style.Style({
                                    stroke: new ol.style.Stroke({
                                        color: '#319FD3',
                                        width: 1
                                    }),
                                    text: new ol.style.Text({
                                        font: '12px Calibri,sans-serif',
                                        text: text,
                                        fill: new ol.style.Fill({
                                            color: '#000'
                                        }),
                                        stroke: new ol.style.Stroke({
                                            color: '#fff',
                                            width: 3
                                        })
                                    }),
                                    fill: new ol.style.Fill({
                                        color: rcisWebMapUtilities.convertHex(response.VList[key].Shade, '0.5')
                                    })
                                })];
                            }
                            else if (text == "") {
                                styleCache[text] = [new ol.style.Style({
                                    fill: new ol.style.Fill({
                                        color: rcisWebMapUtilities.convertHex(response.VList[key].Shade, '0.5')
                                    })
                                })
                                ]
                            } return styleCache[text];
                        }

                    });

No matter what I do I either see the vector drawn...but in EPSG:4326 or nothing loads...

I've spent way too much time trying to figure out how to get OpenLayers3 to do this...Any help is greatly appreciated!!

Body:
If you use EPSG:4326 in your view then your geojson vector declaration should be

var vectorSource = new ol.source.Vector({
features: (new ol.format.GeoJSON()).readFeatures(geojsonObject, {
dataProjection: 'EPSG:4326',
featureProjection:'EPSG:4326' })
});

If you use EPSG:3857 in your view use this:

var vectorSource = new ol.source.Vector({
features: (new ol.format.GeoJSON()).readFeatures(geojsonObject, {
dataProjection: 'EPSG:4326',
featureProjection:'EPSG:3857' })
});

Just to explain dataProjection is the source coords. Means the epsg of your coordinates within the geojson file. While featureProjection is the EPSG of your view and thus the EPSG of your map. Means is the EPSG original coords should be trasformed.

So try to remember this rule: featureProjection and ol.View projection declaration should be equal.

Note that I am assuming your geojson coords are projected in EPSG:4326.


问:
Unable to locate webelement on text box?
I used below link to automate testing:

https://roundtheworld.skyteam.com/B2C/en/Home/WelcomePage

but I am not able to locate the text box web element.

please let me know, if any body know the solution how to locate web element for this website.

答: May this can help you :- <code>//div[@class="inner_circle"]/form//*/input[contains(@name,"CityOfOrigin")]</code> .If you want to locate some other field u just need to find attribute and put it in side xpath </p>

Body: May this can help you :- //div[@class="inner_circle"]/form//*/input[contains(@name,"CityOfOrigin")] .If you want to locate some other field u just need to find attribute and put it in side xpath


问:
Running an async task and invoking winform control
If have this code:

```<code>Task[] tasks = new Task[3];

int index = 0;
foreach (KeyValuePair<string, int> packageId in PackageIds)
{
    await Task.Run(() => _logger.Log(packageId.Key));

    tasks[index] = Task.Factory.StartNew(() =>
    {
        Log(packageId.Key);
    });
    index++;
}

Task.WaitAll(tasks);
_logger.Log("all done");
</code>```

This is the Log function:

```<code>private void Log(string message)
{
    ListViewItem lv = new ListViewItem
    {
        Text = $"{DateTime.Now:dd-MM-yyyy hh:mm:ss}"
    };
    lv.SubItems.Add(message);

    if (listView1.InvokeRequired)
        Invoke(new Action(() => Log(message)));
    else
        listView1.Items.Add(lv);
}
</code>```

When I run it I can see the code tries to invoke the listView1. But after that, the application hangs and doesn't continue at all. When I remove the Log() and run it again, it works perfectly.

How can I run this code with the logging?

答:
You are using the InvokeRequiered/Invoke pattern in a dangerous way.

The problem is that you use InvokeRequired to check if your thread can call functions from ListView1. If not, you don't use Invoke to call the ListView1 functions, but call your own function (this.Log).

The proper way to implement this pattern is to check if invoke is required is for your own form. Ask: this.InvokeRequired instead of listview1.InvokeRequired:

```<code>class MyForm : Form
{
    ...

    private void MyEventHandler(object sender, ...)
    {
        if (this.InvokeRequired)
        {
            Invoke(new MethodInvoker( () => this.MyEventHandler(sender, ...));
        }
    }
    else
    {
        ProcessMyEvent(...);
    }
</code>```

If you use a debugger to step through this function, you'll see that invoke is required, and thus you invoke the same function again after which invoke is no longer required.

By the way, the reason to use MethodInvoker instead of Action is given in StackOverFlow: MethodInvoker vs Action for Control.BeginInvoke

Body:
If have this code:

Task[] tasks = new Task[3];

int index = 0;
foreach (KeyValuePair<string, int> packageId in PackageIds)
{
    await Task.Run(() => _logger.Log(packageId.Key));

    tasks[index] = Task.Factory.StartNew(() =>
    {
        Log(packageId.Key);
    });
    index++;
}

Task.WaitAll(tasks);
_logger.Log("all done");

This is the Log function:

private void Log(string message)
{
    ListViewItem lv = new ListViewItem
    {
        Text = $"{DateTime.Now:dd-MM-yyyy hh:mm:ss}"
    };
    lv.SubItems.Add(message);

    if (listView1.InvokeRequired)
        Invoke(new Action(() => Log(message)));
    else
        listView1.Items.Add(lv);
}

When I run it I can see the code tries to invoke the listView1. But after that, the application hangs and doesn't continue at all. When I remove the Log() and run it again, it works perfectly.

How can I run this code with the logging?

Body:
You are using the InvokeRequiered/Invoke pattern in a dangerous way.

The problem is that you use InvokeRequired to check if your thread can call functions from ListView1. If not, you don't use Invoke to call the ListView1 functions, but call your own function (this.Log).

The proper way to implement this pattern is to check if invoke is required is for your own form. Ask: this.InvokeRequired instead of listview1.InvokeRequired:

class MyForm : Form
{
    ...

    private void MyEventHandler(object sender, ...)
    {
        if (this.InvokeRequired)
        {
            Invoke(new MethodInvoker( () => this.MyEventHandler(sender, ...));
        }
    }
    else
    {
        ProcessMyEvent(...);
    }

If you use a debugger to step through this function, you'll see that invoke is required, and thus you invoke the same function again after which invoke is no longer required.

By the way, the reason to use MethodInvoker instead of Action is given in StackOverFlow: MethodInvoker vs Action for Control.BeginInvoke


问:
WordPress Registration with only email
I looking for a plugin or custom coding solution that a user only needs to type in his mail adress for register. no username, no password.

I found this plugin, but the last update is two years ago.. https://wordpress.org/plugins/smart-wp-login/

答:
YES, you can achieve this.

Rule 1: WordPress requires a username. We must provide a username.

Rule 2: Don't edit WordPress core code.

We can achieve this by hiding username field, get email and store it as username.

Step-1: Remove Username textfield

```<code>add_action('login_head', function(){
?>
<style>
    #registerform > p:first-child{
        display:none;
    }
</style>

<script type="text/javascript" src="<?php echo site_url('/wp-includes/js/jquery/jquery.js'); ?>"></script>
<script type="text/javascript">
    jQuery(document).ready(function($){
        $('#registerform > p:first-child').css('display', 'none');
    });
</script>
<?php
});
</code>```

Step-2: Remove Username error

```<code>//Remove error for username, only show error for email only.
add_filter('registration_errors', function($wp_error, $sanitized_user_login, $user_email){
if(isset($wp_error->errors['empty_username'])){
    unset($wp_error->errors['empty_username']);
}

if(isset($wp_error->errors['username_exists'])){
    unset($wp_error->errors['username_exists']);
}
return $wp_error;
}, 10, 3);
</code>```

Step-3: Manipulate Background Registration Functionality.

```<code>add_action('login_form_register', function(){
if(isset($_POST['user_login']) && isset($_POST['user_email']) && !empty($_POST['user_email'])){
    $_POST['user_login'] = $_POST['user_email'];
}
});
</code>```

Put above code in your theme's functions.php file.

Title: WordPress Registration with only email

Body:
YES, you can achieve this.

Rule 1: WordPress requires a username. We must provide a username.

Rule 2: Don't edit WordPress core code.

We can achieve this by hiding username field, get email and store it as username.

Step-1: Remove Username textfield

add_action('login_head', function(){
?>
<style>
    #registerform > p:first-child{
        display:none;
    }
</style>

<script type="text/javascript" src="<?php echo site_url('/wp-includes/js/jquery/jquery.js'); ?>"></script>
<script type="text/javascript">
    jQuery(document).ready(function($){
        $('#registerform > p:first-child').css('display', 'none');
    });
</script>
<?php
});

Step-2: Remove Username error

//Remove error for username, only show error for email only.
add_filter('registration_errors', function($wp_error, $sanitized_user_login, $user_email){
if(isset($wp_error->errors['empty_username'])){
    unset($wp_error->errors['empty_username']);
}

if(isset($wp_error->errors['username_exists'])){
    unset($wp_error->errors['username_exists']);
}
return $wp_error;
}, 10, 3);

Step-3: Manipulate Background Registration Functionality.

add_action('login_form_register', function(){
if(isset($_POST['user_login']) && isset($_POST['user_email']) && !empty($_POST['user_email'])){
    $_POST['user_login'] = $_POST['user_email'];
}
});

Put above code in your theme's functions.php file.


问:
How to Create a Multiple Question?
I need to retrieve 6 questions from a plist and check the answer if is correct from the plist itself??

i will use a QR code scanner api to scan for answer, the api will covert to a string and read from the plist to check if the answer is correct... is there any tutorial or references for me to look @ ??

In my plist there is:
question ~ Dictionary with the following strings:

NumberOfOption ~ which define if the question is a multiple choice or a QR code question
Question ~ question itself
Answer ~ Answer itself
Option 1 ~ 4 ~ if it is a multiple choice question

Thanks in advance for answering my questions, i appreciated it

cheers

Desmond

答:
I hope your 1.plist has questions and 2.plist has corresponding answers. In this case you should make your plists containing arrays only.

But in your case you have other information like option in your questions plist so you should go with the dictionary structure for this plist and make other plist an array. Following the array structure is really easy to access and store your questions, but in case of dictionary you should be little careful.

I would suggest that you should store the questions and answers with same corresponding keys in both the plists. Like for the question number 1 you use the key @"0" and for 2 use @"1" and so on. hence accessing answers from 2 will be the easier.

Hope this helps.

Title: How to Create a Multiple Question?


问:
How to get credit memo by order id
I am trying to get credit memo collection by order id in external php file in magento 1.9.x

Here is my code to get credit memo by order id.

```<code>$collection = Mage::getResourceModel('sales/order_creditmemo_collection')
              ->addFieldToFilter('order_id', $order->getId());
foreach($collection as $item) {
    echo $item->getId();
}
</code>```

But it is showing NULL

i tried with various example available on SO but they didn't help me.

Any help will be greatly appreciated.

答:
If you get the object of Mage_Sales_Model_Order class then you can get the credit memo collection by using getCreditmemosCollection() function
eg. $order->getCreditmemosCollection()

it will return you all the creditmemo created for the current loaded order...

Title: How to get credit memo by order id

Body:
I am trying to get credit memo collection by order id in external php file in magento 1.9.x

Here is my code to get credit memo by order id.

$collection = Mage::getResourceModel('sales/order_creditmemo_collection')
              ->addFieldToFilter('order_id', $order->getId());
foreach($collection as $item) {
    echo $item->getId();
}

But it is showing NULL

i tried with various example available on SO but they didn't help me.

Any help will be greatly appreciated.


问:
Error.String reference not set to an instance of a String. Parameter name: s (While Sending Email For Account Verification in MVC4 C#)
I am doing an MVC application and trying to send an email to registered user for his account activation and email account verification.
Its working Fine on LocalHost but when i Deployed it on live server it gave me this error:

Error.String reference not set to an instance of a String. Parameter name: s
Following is the Code which i have written for sending email:

```<code> var verifyUrl = string.Empty;
                verifyUrl = Request.Url.GetLeftPart(UriPartial.Authority) + "/Account/AccountVerify?I=" + NewUserID;

            string body = "<html><head><meta content=\"text/html; charset=utf-8\" /></head><body><p>Dear " + objuserdet.Email + "" +
                        ", </p><p>To verify your account, please click the following link:</p>"
                        + "<p><a href=\"" + verifyUrl + "\" target=\"_blank\">" + verifyUrl + ""
                        + "</a></p><div>Best regards,</div><div>" + NewUserID + " Team.</div><p>Note: Do not forward "
                        + "this email. The verify link is private.</p></body></html>";
            string To = objuserdet.Email;
            string Subject = "Account Activation";

            SendEmail(To,Subject,body);
</code>```

and here is the Email Method:

```<code>public void SendEmail(string To, string Subject, string Body)
        {
            try
            {
                MailMessage mail = new MailMessage();
               // mail.From = new MailAddress(System.Configuration.ConfigurationManager.AppSettings["EmailID"].ToString());
                mail.From = new MailAddress("blue.naina9@gmail.com");
                mail.To.Add(To.Trim());
                mail.Subject = Subject.Trim();
                mail.Body = Body;
                mail.IsBodyHtml = true;

            SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
            System.Net.NetworkCredential BasicAuthenticationInfo = new System.Net.NetworkCredential("blue.naina9@gmail.com","*******");
            smtp.Timeout = 600000;
            smtp.UseDefaultCredentials = false;
            smtp.Credentials = BasicAuthenticationInfo;
            smtp.EnableSsl = true;
            smtp.Send(mail);
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
</code>```

..

Any Help will be appreciated.
Thanks

答:
This Error Occurs because Gmail blocks Sign-in Request of Sender Email Account From my Application due to change in my current location and Deployment server location(that is in US).
So i added a US based Account for Sending Email and it stats working Fine For me..
Hope this Help Others As well..</p>

Body:
I am doing an MVC application and trying to send an email to registered user for his account activation and email account verification.
Its working Fine on LocalHost but when i Deployed it on live server it gave me this error:

Error.String reference not set to an instance of a String. Parameter name: s
Following is the Code which i have written for sending email:

 var verifyUrl = string.Empty;
                verifyUrl = Request.Url.GetLeftPart(UriPartial.Authority) + "/Account/AccountVerify?I=" + NewUserID;

            string body = "<meta content=\"text/html; charset=utf-8\" />
Dear " + objuserdet.Email + "" +
                        ",

To verify your account, please click the following link:
"
                        + "
" + verifyUrl + ""
                        + "

Best regards,

" + NewUserID + " Team.

Note: Do not forward "
                        + "this email. The verify link is private.
";
            string To = objuserdet.Email;
            string Subject = "Account Activation";

            SendEmail(To,Subject,body);

and here is the Email Method:

public void SendEmail(string To, string Subject, string Body)
        {
            try
            {
                MailMessage mail = new MailMessage();
               // mail.From = new MailAddress(System.Configuration.ConfigurationManager.AppSettings["EmailID"].ToString());
                mail.From = new MailAddress("blue.naina9@gmail.com");
                mail.To.Add(To.Trim());
                mail.Subject = Subject.Trim();
                mail.Body = Body;
                mail.IsBodyHtml = true;

            SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
            System.Net.NetworkCredential BasicAuthenticationInfo = new System.Net.NetworkCredential("blue.naina9@gmail.com","*******");
            smtp.Timeout = 600000;
            smtp.UseDefaultCredentials = false;
            smtp.Credentials = BasicAuthenticationInfo;
            smtp.EnableSsl = true;
            smtp.Send(mail);
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

..

Any Help will be appreciated.
Thanks