问:
How to parse a BIG JSON file in python
I am working with a very big dataset and I got a problem that could not find any answer for that.
I am trying to parse the data from JSON and here is what I did for a piece of data from the whole dataset and works:

```<code>import json

s = set()

with open("data.raw", "r") as f:

    for line in f:
        d = json.loads(line)
</code>```

The confusing part is that when I apply this code on my main data (the size is about 200G) it shows the following error (without going out of memory):

```<code>    d = json.loads(line)
  File "C:\Users\Sathyanarayanan\AppData\Local\Programs\Python\Python35-32\lib\json\__init__.py", line 319, in loads
    return _default_decoder.decode(s)
  File "C:\Users\Sathyanarayanan\AppData\Local\Programs\Python\Python35-32\lib\json\decoder.py", line 339, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Users\Sathyanarayanan\AppData\Local\Programs\Python\Python35-32\lib\json\decoder.py", line 357, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 2 column 1 (char 1)
</code>```

The type(f) = TextIOWrapper if it helps... but this data type is also for the small dataset...

Here are few lines of my data to see the format:

```<code>{"MessageType": "SALES.CONTRACTS.SALESTATUSCHANGED", "Event": {"Id": {"Source": 1, "SourceId": "ZGA=-3-1-002-0801743-2330650"}, "RefInfo": {"TenantId": {"Id": "ZGA="}, "UserId": {"Id": "ZMKj"}, "SentUtc": "2013-01-14T20:17:57.9681547", "Source": 1}, "OldStatus": {"Status": 3, "AutoRemoveInfo": null}, "NewStatus": {"Status": 4, "AutoRemoveInfo": null}, "Items": {"Items": [{"Id": {"Id": 1193}, "Sku": {"Sku": "Con BM20"}, "Quantity": 1, "UnitPrice": {"amount": 11.92, "currency": 840}}], "FulfilledItems": []}, "ShippingInfo": {"Carrier": "", "Class": "", "Region": null, "Country": 0, "PostalCode": null, "Costs": null, "Charges": null}, "SaleDate": "2013-01-13T13:39:57", "PendingItems": null, "Kits": null, "Products": null, "OldSaleDate": "0001-01-01T00:00:00", "AdditionalSaleInfo": null}}
{"MessageType": "SALES.CONTRACTS.SALESHIPPINGINFOCHANGED", "Event": {"Id": {"Source": 1, "SourceId": "ZGA=-3-1-002-0801743-2330650"}, "RefInfo": {"TenantId": {"Id": "ZGA="}, "UserId": {"Id": "ZMKj"}, "SentUtc": "2013-01-14T20:17:57.9681547", "Source": 1}, "Status": {"Status": 4, "AutoRemoveInfo": null}, "Items": {"Items": [{"Id": {"Id": 1193}, "Sku": {"Sku": "Con BM20"}, "Quantity": 1, "UnitPrice": {"amount": 11.92, "currency": 840}}], "FulfilledItems": []}, "OldShippingInfo": {"Carrier": "", "Class": "", "Region": null, "Country": 0, "PostalCode": null, "Costs": null, "Charges": null}, "NewShippingInfo": {"Carrier": "USPS", "Class": "FIRST/RECTPARCEL", "Region": null, "Country": 0, "PostalCode": null, "Costs": null, "Charges": null}, "SaleDate": "0001-01-01T00:00:00", "PendingItems": null, "Kits": null, "Products": null, "OldSaleDate": "0001-01-01T00:00:00", "AdditionalSaleInfo": null}}
{"MessageType": "SALES.CONTRACTS.SALECREATED", "Event": {"Id": {"Source": 1, "SourceId": "ZGA=-3-1-002-4851828-6514632"}, "RefInfo": {"TenantId": {"Id": "ZGA="}, "UserId": {"Id": "ZMKj"}, "SentUtc": "2013-01-14T20:17:58.1402505", "Source": 1}, "Status": {"Status": 4, "AutoRemoveInfo": null}, "Items": {"Items": [{"Id": {"Id": 9223372036854775807}, "Sku": {"Sku": "NFL Blanket Seahawks"}, "Quantity": 1, "UnitPrice": {"amount": 22.99, "currency": 840}}], "FulfilledItems": []}, "ShippingInfo": {"Carrier": "USPS", "Class": "FIRST/RECTPARCEL", "Region": null, "Country": 0, "PostalCode": null, "Costs": null, "Charges": null}, "SaleDate": "2013-01-13T15:51:12", "Kits": null, "Products": null, "AdditionalSaleInfo": null}}
{"MessageType": "SALES.CONTRACTS.SALECREATED", "Event": {"Id": {"Source": 1, "SourceId": "ZGA=-3-1-102-3824485-2270645"}, "RefInfo": {"TenantId": {"Id": "ZGA="}, "UserId": {"Id": "ZMKj"}, "SentUtc": "2013-01-14T20:17:58.3436109", "Source": 1}, "Status": {"Status": 4, "AutoRemoveInfo": null}, "Items": {"Items": [{"Id": {"Id": 9223372036854775807}, "Sku": {"Sku": "NFL CD Wallet Chargers"}, "Quantity": 1, "UnitPrice": {"amount": 12.99, "currency": 840}}], "FulfilledItems": []}, "ShippingInfo": {"Carrier": "USPS", "Class": "FIRST/RECTPARCEL", "Region": null, "Country": 0, "PostalCode": null, "Costs": null, "Charges": null}, "SaleDate": "2013-01-12T02:49:58", "Kits": null, "Products": null, "AdditionalSaleInfo": null}}
</code>```

It is Json because I'm already parsing first 2000 lines and it works perfectly. But when I try to use the same procedure for the big file it shows the error from very first lines of the data.

答:
Here's some simple code to see what data isn't valid JSON and where it is:</p>

```<code>for i, line in enumerate(f):
    try:
        d = json.loads(line)
    except json.decoder.JSONDecodeError:
        print('Error on line', i + 1, ':\n', repr(line))
</code>```

Title: How to parse a BIG JSON file in python

Body:
I am working with a very big dataset and I got a problem that could not find any answer for that.
I am trying to parse the data from JSON and here is what I did for a piece of data from the whole dataset and works:

import json

s = set()

with open("data.raw", "r") as f:

    for line in f:
        d = json.loads(line)

The confusing part is that when I apply this code on my main data (the size is about 200G) it shows the following error (without going out of memory):

    d = json.loads(line)
  File "C:\Users\Sathyanarayanan\AppData\Local\Programs\Python\Python35-32\lib\json\__init__.py", line 319, in loads
    return _default_decoder.decode(s)
  File "C:\Users\Sathyanarayanan\AppData\Local\Programs\Python\Python35-32\lib\json\decoder.py", line 339, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Users\Sathyanarayanan\AppData\Local\Programs\Python\Python35-32\lib\json\decoder.py", line 357, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 2 column 1 (char 1)

The type(f) = TextIOWrapper if it helps... but this data type is also for the small dataset...

Here are few lines of my data to see the format:

{"MessageType": "SALES.CONTRACTS.SALESTATUSCHANGED", "Event": {"Id": {"Source": 1, "SourceId": "ZGA=-3-1-002-0801743-2330650"}, "RefInfo": {"TenantId": {"Id": "ZGA="}, "UserId": {"Id": "ZMKj"}, "SentUtc": "2013-01-14T20:17:57.9681547", "Source": 1}, "OldStatus": {"Status": 3, "AutoRemoveInfo": null}, "NewStatus": {"Status": 4, "AutoRemoveInfo": null}, "Items": {"Items": [{"Id": {"Id": 1193}, "Sku": {"Sku": "Con BM20"}, "Quantity": 1, "UnitPrice": {"amount": 11.92, "currency": 840}}], "FulfilledItems": []}, "ShippingInfo": {"Carrier": "", "Class": "", "Region": null, "Country": 0, "PostalCode": null, "Costs": null, "Charges": null}, "SaleDate": "2013-01-13T13:39:57", "PendingItems": null, "Kits": null, "Products": null, "OldSaleDate": "0001-01-01T00:00:00", "AdditionalSaleInfo": null}}
{"MessageType": "SALES.CONTRACTS.SALESHIPPINGINFOCHANGED", "Event": {"Id": {"Source": 1, "SourceId": "ZGA=-3-1-002-0801743-2330650"}, "RefInfo": {"TenantId": {"Id": "ZGA="}, "UserId": {"Id": "ZMKj"}, "SentUtc": "2013-01-14T20:17:57.9681547", "Source": 1}, "Status": {"Status": 4, "AutoRemoveInfo": null}, "Items": {"Items": [{"Id": {"Id": 1193}, "Sku": {"Sku": "Con BM20"}, "Quantity": 1, "UnitPrice": {"amount": 11.92, "currency": 840}}], "FulfilledItems": []}, "OldShippingInfo": {"Carrier": "", "Class": "", "Region": null, "Country": 0, "PostalCode": null, "Costs": null, "Charges": null}, "NewShippingInfo": {"Carrier": "USPS", "Class": "FIRST/RECTPARCEL", "Region": null, "Country": 0, "PostalCode": null, "Costs": null, "Charges": null}, "SaleDate": "0001-01-01T00:00:00", "PendingItems": null, "Kits": null, "Products": null, "OldSaleDate": "0001-01-01T00:00:00", "AdditionalSaleInfo": null}}
{"MessageType": "SALES.CONTRACTS.SALECREATED", "Event": {"Id": {"Source": 1, "SourceId": "ZGA=-3-1-002-4851828-6514632"}, "RefInfo": {"TenantId": {"Id": "ZGA="}, "UserId": {"Id": "ZMKj"}, "SentUtc": "2013-01-14T20:17:58.1402505", "Source": 1}, "Status": {"Status": 4, "AutoRemoveInfo": null}, "Items": {"Items": [{"Id": {"Id": 9223372036854775807}, "Sku": {"Sku": "NFL Blanket Seahawks"}, "Quantity": 1, "UnitPrice": {"amount": 22.99, "currency": 840}}], "FulfilledItems": []}, "ShippingInfo": {"Carrier": "USPS", "Class": "FIRST/RECTPARCEL", "Region": null, "Country": 0, "PostalCode": null, "Costs": null, "Charges": null}, "SaleDate": "2013-01-13T15:51:12", "Kits": null, "Products": null, "AdditionalSaleInfo": null}}
{"MessageType": "SALES.CONTRACTS.SALECREATED", "Event": {"Id": {"Source": 1, "SourceId": "ZGA=-3-1-102-3824485-2270645"}, "RefInfo": {"TenantId": {"Id": "ZGA="}, "UserId": {"Id": "ZMKj"}, "SentUtc": "2013-01-14T20:17:58.3436109", "Source": 1}, "Status": {"Status": 4, "AutoRemoveInfo": null}, "Items": {"Items": [{"Id": {"Id": 9223372036854775807}, "Sku": {"Sku": "NFL CD Wallet Chargers"}, "Quantity": 1, "UnitPrice": {"amount": 12.99, "currency": 840}}], "FulfilledItems": []}, "ShippingInfo": {"Carrier": "USPS", "Class": "FIRST/RECTPARCEL", "Region": null, "Country": 0, "PostalCode": null, "Costs": null, "Charges": null}, "SaleDate": "2013-01-12T02:49:58", "Kits": null, "Products": null, "AdditionalSaleInfo": null}}

It is Json because I'm already parsing first 2000 lines and it works perfectly. But when I try to use the same procedure for the big file it shows the error from very first lines of the data.

Body:
Here's some simple code to see what data isn't valid JSON and where it is:

for i, line in enumerate(f):
    try:
        d = json.loads(line)
    except json.decoder.JSONDecodeError:
        print('Error on line', i + 1, ':\n', repr(line))


来源: stackexchange

问:
How to use map/filter to modify contents of an array of objects?
I have the following array:

```<code>myarray = [
    { "key": "A" },
    { "key": "B" }
]
</code>```

How can I use a map/filter function in JavaScript to do the equivalent of:

```<code>for (var i = 0; i < myarray.length; i++) {
    if ( myarray[i].key == 'B') {
        myarray[i].mark = "marked!"
    }
}
</code>```

In my attempt, I don't get the mark property in the output:

```<code>myarray.filter((someobject) => someobject.key == 'B').mark = "marked!"
console.log(myarray) // this does not show the "mark" key.
</code>```

NB: I want to modify the original array.

答:
If there is exactly one match, then you can use find:

```<code>myarray.find(someobject => someobject.key == 'B').mark = "marked!"
</code>```

If you don't know the number of matches, then your for loop seems the best way to do it. Otherwise you could for instance go for filter and forEach:

```<code>myarray.filter(someobject => someobject.key == 'B')
       .forEach(someobject => someobject.mark = "marked!")
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have the following array:

myarray = [
    { "key": "A" },
    { "key": "B" }
]

How can I use a map/filter function in JavaScript to do the equivalent of:

for (var i = 0; i < myarray.length; i++) {
    if ( myarray[i].key == 'B') {
        myarray[i].mark = "marked!"
    }
}

In my attempt, I don't get the mark property in the output:

myarray.filter((someobject) => someobject.key == 'B').mark = "marked!"
console.log(myarray) // this does not show the "mark" key.

NB: I want to modify the original array.

Body:
If there is exactly one match, then you can use find:

myarray.find(someobject => someobject.key == 'B').mark = "marked!"

If you don't know the number of matches, then your for loop seems the best way to do it. Otherwise you could for instance go for filter and forEach:

myarray.filter(someobject => someobject.key == 'B')
       .forEach(someobject => someobject.mark = "marked!")

ContentLicense: CC BY-SA 3.0


问:
Drupal 6 - change Author of a node
Is there an easy way to change the author of a node to another user? I can't seem to find it. I found a workaround, which was to setup an "action" to change the author of a node to a specific user, and then temporarily setup a "trigger" so that whenever i update a node, it should run that action. It works, but is ugly. I suppose I could also attack the db directly, but these both seem like rather inelegant solutions.

I appreciate this shouldn't be that common an requirement. This is what happened: I setup the site, including place-holder content, which the publisher users then populated with real content. This was clearly not the right way to go about it, but it's the situation I find myself in...

答:
Can't you simply edit the node, expand the Authoring Information section near the bottom of the page, and change the Author name.

You can also change the Authored on date too.

If you need to change the Authoring information of lots of pages, I'd recommend Views Bulk Operations. Changing the Author is one of the options.

ContentLicense: CC BY-SA 2.5

Title: Drupal 6 - change Author of a node


问:
Unable to pass the ylim argument to ggplot in a function
Say we have this toy data:

```<code>temp <- data.frame(A=1:6, gr=c("A","A","A","B","B","B"))
</code>```

I can easily create a plot as

```<code>lev <- c("A", "B")
ggplot()+geom_point(data=temp,aes(x=A, y=gr))+ylim(lev)
</code>```

I get this

But I would like to convert it to a function in order to easily change the input parameters

```<code>myplot <- function(lev=lev) {ggplot()+geom_point(data=temp,aes(x=A, y=gr))+ylim(lev)}
</code>```

But when I run

```<code>lev <- c("B","A")
myplot()
</code>```

I get this error:

Error in limits(c(...), "y") :    promise already under evaluation:
  recursive default argument reference or earlier problems?

I've tried converting ylim to a factor, and using eval, but it doesn't work either.

I've tried parametrizing other things such as the input dataset and they work well, but I don't understand why ylim doesn't.

There is a question that speaks about a related problem with aes parameters

Pass function argument to ggplot label

but its solution uses aes_string and doesn't apply here.

答:
I've found that strangely just calling the function's parameter with a different name than the input data works.

```<code>temp <- data.frame(A=1:6, gr=c("A","A","A","B","B","B"))
mylev <- c("A", "B")

myplot <- function(lev=mylev) {ggplot()+geom_point(data=temp,aes(x=A, y=gr))+ylim(lev)}
</code>```

myplot()  works

That way I can have the default parameter pointing to a given definition.

PD:
Still doesn't work well. It's strange.
THe first time you run it works.
But If I run the it again I get this error:

Error: length(lims) == 2 is not TRUE

Body:
Say we have this toy data:

temp <- data.frame(A=1:6, gr=c("A","A","A","B","B","B"))

I can easily create a plot as

lev <- c("A", "B")
ggplot()+geom_point(data=temp,aes(x=A, y=gr))+ylim(lev)

I get this

But I would like to convert it to a function in order to easily change the input parameters

myplot <- function(lev=lev) {ggplot()+geom_point(data=temp,aes(x=A, y=gr))+ylim(lev)}

But when I run

lev <- c("B","A")
myplot()

I get this error:

Error in limits(c(...), "y") :    promise already under evaluation:
  recursive default argument reference or earlier problems?

I've tried converting ylim to a factor, and using eval, but it doesn't work either.

I've tried parametrizing other things such as the input dataset and they work well, but I don't understand why ylim doesn't.

There is a question that speaks about a related problem with aes parameters

Pass function argument to ggplot label

but its solution uses aes_string and doesn't apply here.

Body:
I've found that strangely just calling the function's parameter with a different name than the input data works.

temp <- data.frame(A=1:6, gr=c("A","A","A","B","B","B"))
mylev <- c("A", "B")

myplot <- function(lev=mylev) {ggplot()+geom_point(data=temp,aes(x=A, y=gr))+ylim(lev)}

myplot()  works

That way I can have the default parameter pointing to a given definition.

PD:
Still doesn't work well. It's strange.
THe first time you run it works.
But If I run the it again I get this error:

Error: length(lims) == 2 is not TRUE


问:
How to Generate all the characters in the UTF-8 charset in .net
I have been given the task of generating all the characters in the UTF-8 character set to test how a system handles each of them.   I do not have much experience with character encoding.  The approaching I was going to try was to increment a counter, and then try to translate that base ten number into it's equivalent UTF-8 character, but so far I have no been able to find an effective way to to this in C# 3.5

Any suggestions would be greatly appreciated.

答:
You can brute-force an Encoding to figure out which code points it supports. To do so, simply go through all possible code points, convert them to strings, and see if Encoding.GetBytes() throws an exception or not (after setting Encoding.EncoderFallback to EncoderExceptionFallback).

```<code>IEnumerable<int> GetAllWritableCodepoints(Encoding encoding)
{
    encoding = Encoding.GetEncoding(encoding.WebName, new EncoderExceptionFallback(), new DecoderExceptionFallback());

    var i = -1;
    // Docs for char.ConvertFromUtf32() say that 0x10ffff is the maximum code point value.
    while (i != 0x10ffff)
    {
        i++;

        var success = false;
        try
        {
            encoding.GetByteCount(char.ConvertFromUtf32(i));
            success = true;
        }
        catch (ArgumentException)
        {
        }
        if (success)
        {
            yield return i;
        }
    }
}
</code>```

This method should support discovering characters represented by surrogate pairs of Char in .net. However, it is very slow (takes minutes to run on my machine) and probably impractical.

Body:
You can brute-force an Encoding to figure out which code points it supports. To do so, simply go through all possible code points, convert them to strings, and see if Encoding.GetBytes() throws an exception or not (after setting Encoding.EncoderFallback to EncoderExceptionFallback).

IEnumerable<int> GetAllWritableCodepoints(Encoding encoding)
{
    encoding = Encoding.GetEncoding(encoding.WebName, new EncoderExceptionFallback(), new DecoderExceptionFallback());

    var i = -1;
    // Docs for char.ConvertFromUtf32() say that 0x10ffff is the maximum code point value.
    while (i != 0x10ffff)
    {
        i++;

        var success = false;
        try
        {
            encoding.GetByteCount(char.ConvertFromUtf32(i));
            success = true;
        }
        catch (ArgumentException)
        {
        }
        if (success)
        {
            yield return i;
        }
    }
}

This method should support discovering characters represented by surrogate pairs of Char in .net. However, it is very slow (takes minutes to run on my machine) and probably impractical.


问:
Increasing the font size in html/css of scraped links (python code creating an html file)
I've scraped some links from a website, I'm then attempting to write the links
to a html file as html list items. I can't figure out how to increase the font size of the  links (and text associated with the links).

```<code>links =(soup.find_all('a', class_ ='link')) #get the links
with open ('testing.html', 'w') as file:
    file.write('<ul>')  #creating an list
    for link in links:
        make_list =  '<li> style="font-size:100px";>{}</li>'.format(link)
        file.write(make_list)

    file.write('</ul>')
webbrowser.open('testing.html')
</code>```

This is resulting in something like (each link being prefaced by the style code)

```<code>style="font-size:100px";>
style="font-size:100px";>The most valuable brands in the world are overwhelmingly tech names...and American
style="font-size:100px";>German bonds may offer the clearest warning that the stock market痴 bull run is sputtering
</code>```

答:
@A.L. spotted your error.  style="..." is supposed to be a property of the
 tag, like so:

```<code><li style="font-size:100px;">some text here</li>
</code>```

But instead, you put it after the tag opening:

```<code><li> style="font-size:100px";>some text here</li>
</code>```

So it was being interpreted as part of "some text here".

Body:
I've scraped some links from a website, I'm then attempting to write the links
to a html file as html list items. I can't figure out how to increase the font size of the  links (and text associated with the links).

links =(soup.find_all('a', class_ ='link')) #get the links
with open ('testing.html', 'w') as file:
    file.write('
')  #creating an list
    for link in links:
        make_list =  '
 style="font-size:100px";>{}
'.format(link)
        file.write(make_list)

    file.write('
')
webbrowser.open('testing.html')

This is resulting in something like (each link being prefaced by the style code)

style="font-size:100px";>
style="font-size:100px";>The most valuable brands in the world are overwhelmingly tech names...and American
style="font-size:100px";>German bonds may offer the clearest warning that the stock market痴 bull run is sputtering

Body:
@A.L. spotted your error.  style="..." is supposed to be a property of the <li> tag, like so:

<li style="font-size:100px;">some text here</li>

But instead, you put it after the tag opening:

<li> style="font-size:100px";>some text here</li>

So it was being interpreted as part of "some text here".


问:
mysql_query WHERE `id` = '$user' && '$post'
so I have a mysql query that looks like this.

```<code>$copy = mysql_query("SELECT `id` FROM `brain` WHERE `id` = '$user_screen_name' && '$posts['title']'");
</code>```

I want the query to search for the id that is in the table where screen name and post title strings are matched and put the found id in a variable. How would I do this?

答:
First, some warnings:

Please stop using mysql_* functions. These extensions have been removed in PHP 7. Learn about prepared statements for PDO and MySQLi and consider using PDO, it's really pretty easy.

Little Bobby says your script is at risk for SQL Injection Attacks.. Even escaping the string is not safe!

To fix your query you need a separate AND condition for each item you want to filter against:

```<code>WHERE `id` = '$user_screen_name'
AND `title` = '$posts["title"]'
</code>```

Without seeing your table layout it would be hard to go much further but if you want the id in a variable you would do this after the query:

```<code>$row = mysql_fetch_array($copy);
</code>```

Once done, $row['id'] will be the variable containing the id.

Body:
so I have a mysql query that looks like this.

$copy = mysql_query("SELECT `id` FROM `brain` WHERE `id` = '$user_screen_name' && '$posts['title']'");

I want the query to search for the id that is in the table where screen name and post title strings are matched and put the found id in a variable. How would I do this?

Body:
First, some warnings:

Please stop using mysql_* functions. These extensions have been removed in PHP 7. Learn about prepared statements for PDO and MySQLi and consider using PDO, it's really pretty easy.

Little Bobby says your script is at risk for SQL Injection Attacks.. Even escaping the string is not safe!

To fix your query you need a separate AND condition for each item you want to filter against:

WHERE `id` = '$user_screen_name'
AND `title` = '$posts["title"]'

Without seeing your table layout it would be hard to go much further but if you want the id in a variable you would do this after the query:

$row = mysql_fetch_array($copy);

Once done, $row['id'] will be the variable containing the id.


答:
What is the best way so that I can make it such that I can use a map/filter function in javascript to do the equivalent of this code?

Not all, since neither map nor filter modify an array. They create new ones. You could use something like

```<code>let newArray = myArray.map(({key} => ({key, marked: key=='B'}));
</code>```

but the best ES6 equivalent to your code is

```<code>for (let v of myArray) if (v.key == 'B') v.mark = 'marked';
</code>```

You could also use forEach, but I heavily recommend against disguising side effects in a functional approach:

```<code>myArray.filter(({key}) => key == 'B').forEach(v => { v.mark = 'marked'; });
</code>```

Title: How to use map/filter to modify contents of an array of objects?

Body:
What is the best way so that I can make it such that I can use a map/filter function in javascript to do the equivalent of this code?

Not all, since neither map nor filter modify an array. They create new ones. You could use something like

let newArray = myArray.map(({key} => ({key, marked: key=='B'}));

but the best ES6 equivalent to your code is

for (let v of myArray) if (v.key == 'B') v.mark = 'marked';

You could also use forEach, but I heavily recommend against disguising side effects in a functional approach:

myArray.filter(({key}) => key == 'B').forEach(v => { v.mark = 'marked'; });


问:
Rewriting one part of a URL into a link
I am trying to get one part of a URL to insert into another.

URL in address bar will read domain.com/test.php?/12345 then link in page must become domain.com/do/Login/12345 (this end number will change for every user)

(Note that I can't change the URL domain.com/test.php?/12345 as this has already been set by the site owner.)

For the URLs above I had to remove the http://www. part above as new user can't submit more than one link for spam prevention. The final script should include http://www.

You will be able to see that all I need to get is the number at the end ie 12345 but I'm not too sure how to achieve this (javascript beginner). This is what I have so far:

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Path test</title>
</head>

<body>

<script>
// get URL eg http://www.domain.com/test.php?/12345
newURL = window.location.protocol + "//" + window.location.host + "/" + window.location.pathname;
</script>

<script>
//write new domain then add user number ie 12345
document.write('http://www.domain.com/do/Login/' + window.location.pathname);
</script>
</body>
</html>
</code>```

This obviously does not work but shows where I got to.

I've had some luck using a script I found at http://www.sitepoint.com/forums/showthread.php?t=244955 but it only worked with filenames with an extension name on like .html, .php etc.

Any ideas?

Thanks in advance.

答:
Could this do the work? It uses the whole URL, splits it from the '?' (meaning from the start of the parameters) and then concatenates the parameters to the base URL.</p>

```<code>var oldUrl = window.location.href;
var parameters = oldUrl.substring(oldUrl.indexOf('?',0),oldUrl.length);

var newUrlBase = 'http://www.domain.com/do/Login/';
var newUrl = newUrlBase + parameters;
</code>```

Title: Rewriting one part of a URL into a link

Body:
I am trying to get one part of a URL to insert into another.

URL in address bar will read domain.com/test.php?/12345 then link in page must become domain.com/do/Login/12345 (this end number will change for every user)

(Note that I can't change the URL domain.com/test.php?/12345 as this has already been set by the site owner.)

For the URLs above I had to remove the http://www. part above as new user can't submit more than one link for spam prevention. The final script should include http://www.

You will be able to see that all I need to get is the number at the end ie 12345 but I'm not too sure how to achieve this (javascript beginner). This is what I have so far:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Path test</title>

This obviously does not work but shows where I got to.

I've had some luck using a script I found at http://www.sitepoint.com/forums/showthread.php?t=244955 but it only worked with filenames with an extension name on like .html, .php etc.

Any ideas?

Thanks in advance.

Body:
Could this do the work? It uses the whole URL, splits it from the '?' (meaning from the start of the parameters) and then concatenates the parameters to the base URL.

var oldUrl = window.location.href;
var parameters = oldUrl.substring(oldUrl.indexOf('?',0),oldUrl.length);

var newUrlBase = 'http://www.domain.com/do/Login/';
var newUrl = newUrlBase + parameters;


问:
Xcode 8 hangs / unresponsive when opening storyboard
I've recently upgraded to Xcode 8 and updated my project to Swift 3. All worked fine for a little while. Storyboard loading has always been slow (even when still running Xcode 7) and was about the same 'slow' with Xcode 8. I always imagined this is because I'm on a older (late 2011) Macbook Pro.

But recently sometimes Xcode would just hang when I tried to open the storyboard. And since yesterday it's ALWAYS 'hanging'. Xcode becomes unresponsive and I have to Force Quit it.

In Activity Monitor I see Xcode using 102% CPU and Memory usage just keeps on growing (over 10GB if I let it).

Now I'm really stuck because when I open Xcode it immediately opens my project and wants to open the storyboard. I can't even change to a swift file. I'm not getting the window where I choose my project anymore. So, can't open my project anymore without Xcode turning unresponsive. Even when I double click another project to open Xcode it still tries to open my project (on the storyboard).

I've tried a number of things (based on SO threads I could find on similar problems with older versions of Xcode):

Removed Xcode and removed contents of ˜/Library/Developer. Then reinstalled Xcode.

Removed contents of var/folders

Removed contents of derived data folder

Restart Macbook

My next try is going to be to download the Xcode 8.1 beta. But really rather not do that.

Any other suggestions on things I could try?

SMALL UPDATE:
Managed to clear the 'state' of Xcode where it opens my project by default and also opens it on the storyboard. Did this by:

Removing the ~/Library/Saved Application State/com.apple.dt.Xcode.savedState folder (this will show the recent project window again on startup)

To also prevent the project from loading a specific file upon opening I went to the contents of .xcworkspace (in my project folder) and then removed /xcuserdata/myusername.xcuserdatad/UserInterfaceState.xcuserstate. Now the project opened without any file selected.

Still... the main problem remains. When I click on my storyboard Xcode becomes unresponsive.

答:
Delete your derived data from
/Users/{username}/Library/Developer/Xcode/DerivedData

(You can get exact path from)
File -> Project Setting:
or
File -> Workspace Settings


问:
Unity Tutorial, IEnumerator ShotEffect(), error
[Unity Version 5.6.1f1; Visual Studio 2017]

Hi,
I am going through a basic Unity FPS tutorial using Raycast. I get an error when calling

private IEnumerator ShotEffect()

as follows,

Feature "local Functions" is not available in C#4. Please use Language version 7 or greater.

How do I fix this? This is copy/pasted from a Unity Tutorial. Is there an alternative to this type call? https://unity3d.com/learn/tutorials/lets-try/shooting-with-raycasts?playlist=41639&_ga=2.32575166.1847645017.1499027918-1229599585.1498623818

```<code> void Update() {
        if (Input.GetButtonDown("Fire1") && Time.time > nextFire)
        {
            // Update the time when our player can fire next
            nextFire = Time.time + fireRate;

            // Start our ShotEffect coroutine to turn our laser line on and off
            StartCoroutine(ShotEffect()); //**Call here**

            // Create a vector at the center of our camera's viewport
            Vector3 rayOrigin = fpsCam.ViewportToWorldPoint(new Vector3(0.5f, 0.5f, 0.0f));

            // Declare a raycast hit to store information about what our raycast has hit
            RaycastHit hit;

        }

         private IEnumerator ShotEffect() //**Error here**
        {
            // Play the shooting sound effect
            gunAudio.Play();

            // Turn on our line renderer
            laserLine.enabled = true;

            //Wait for .07 seconds
            yield return shotDuration;

            // Deactivate our line renderer after waiting
            laserLine.enabled = false;
        }
</code>```

答:
You have defined ShotEffect inside the Update function. Check your braces.

```<code>    void Update() {
        if (Input.GetButtonDown("Fire1") && Time.time > nextFire)
        {
            // Update the time when our player can fire next
            nextFire = Time.time + fireRate;

            // Start our ShotEffect coroutine to turn our laser line on and off
            StartCoroutine(ShotEffect()); //**Call here**

            // Create a vector at the center of our camera's viewport
            Vector3 rayOrigin = fpsCam.ViewportToWorldPoint(new Vector3(0.5f, 0.5f, 0.0f));

            // Declare a raycast hit to store information about what our raycast has hit
            RaycastHit hit;

        }

    } // Add brace here

    private IEnumerator ShotEffect()
    {
        // Play the shooting sound effect
        gunAudio.Play();

        // Turn on our line renderer
        laserLine.enabled = true;

        //Wait for .07 seconds
        yield return shotDuration;

        // Deactivate our line renderer after waiting
        laserLine.enabled = false;
    }
</code>```

Body:
[Unity Version 5.6.1f1; Visual Studio 2017]

Hi,
I am going through a basic Unity FPS tutorial using Raycast. I get an error when calling

private IEnumerator ShotEffect()

as follows,

Feature "local Functions" is not available in C#4. Please use Language version 7 or greater.

How do I fix this? This is copy/pasted from a Unity Tutorial. Is there an alternative to this type call? https://unity3d.com/learn/tutorials/lets-try/shooting-with-raycasts?playlist=41639&_ga=2.32575166.1847645017.1499027918-1229599585.1498623818

 void Update() {
        if (Input.GetButtonDown("Fire1") && Time.time > nextFire)
        {
            // Update the time when our player can fire next
            nextFire = Time.time + fireRate;

            // Start our ShotEffect coroutine to turn our laser line on and off
            StartCoroutine(ShotEffect()); //**Call here**

            // Create a vector at the center of our camera's viewport
            Vector3 rayOrigin = fpsCam.ViewportToWorldPoint(new Vector3(0.5f, 0.5f, 0.0f));

            // Declare a raycast hit to store information about what our raycast has hit
            RaycastHit hit;

        }

         private IEnumerator ShotEffect() //**Error here**
        {
            // Play the shooting sound effect
            gunAudio.Play();

            // Turn on our line renderer
            laserLine.enabled = true;

            //Wait for .07 seconds
            yield return shotDuration;

            // Deactivate our line renderer after waiting
            laserLine.enabled = false;
        }

Body:
You have defined ShotEffect inside the Update function. Check your braces.

    void Update() {
        if (Input.GetButtonDown("Fire1") && Time.time > nextFire)
        {
            // Update the time when our player can fire next
            nextFire = Time.time + fireRate;

            // Start our ShotEffect coroutine to turn our laser line on and off
            StartCoroutine(ShotEffect()); //**Call here**

            // Create a vector at the center of our camera's viewport
            Vector3 rayOrigin = fpsCam.ViewportToWorldPoint(new Vector3(0.5f, 0.5f, 0.0f));

            // Declare a raycast hit to store information about what our raycast has hit
            RaycastHit hit;

        }

    } // Add brace here

    private IEnumerator ShotEffect()
    {
        // Play the shooting sound effect
        gunAudio.Play();

        // Turn on our line renderer
        laserLine.enabled = true;

        //Wait for .07 seconds
        yield return shotDuration;

        // Deactivate our line renderer after waiting
        laserLine.enabled = false;
    }


问:
How to extract Facebook page likes and profile picture from Facebook API output
I'm using Nokogiri 1.7.1 and Rails 4.2.4 in my application. When I view Facebook's source code, there is no HTML or CSS allowing me to select and scrape the text.

Facebook is using React code:

```<code>// ....
showSponsorTaggerButtonNUX:false,showSponsorTaggerDirectBoost:false,showSponsorTaggerSponsorRelationship:false}},attachmentsConfig:{STATUS:{canScrapeShare:true,canAttachLocation:false,enabled:true,largeTextThreshold:85,profileID:null,profileName:null,profileURI:null,profilePicSrc:"https://scontent.fsvg1-1.fna.fbcdn.net/v/t1.0-1/c12.0.40.40/p40x40/10354686_10150004552801856_220367501106153455_n.jpg?oh=3ad0945d50cb5c25455167972e2cb9c6&oe=5A0CA7F8"
// ....
</code>```

For instance I found profilePicSrc. I tried using at_css and xpath. I might doing it wrong or it can't scrape them because there is no CSS or HTML that Nokogiri can select/find.

I managed to get these details from the Facebook API:

```<code>{
   "id": "7270241753",
   "name": "YouTube",
   "cover": {
      "cover_id": "10156001238986754",
      "offset_x": 0,
      "offset_y": 0,
      "source": "https://scontent.xx.fbcdn.net/v/t1.0-9/s720x720/14591676_10156001238986754_7091829954587846661_n.jpg?oh=b5bc4ca11e6a5d47f18b798eb38cc176&oe=59DBEC50",
      "id": "10156001238986754"
   },
   "fan_count": 82634405,
   "picture": {
      "data": {
         "is_silhouette": false,
         "url": "https://scontent.xx.fbcdn.net/v/t1.0-1/p50x50/19424472_10156001229851754_375700039380897185_n.jpg?oh=965b50ea998545bcbcb99fb90b3ba606&oe=59CEF703"
      }
   }
}
</code>```

How can I select the profile picture, name, the number of likes the page has and its big header image from this output?

答: As nokogiri doesn't process javascript, I end up using Facebook open graph to get page data in json format and did a JSON.load(open(link)) and parsed them from the output.

Body:
I'm using Nokogiri 1.7.1 and Rails 4.2.4 in my application. When I view Facebook's source code, there is no HTML or CSS allowing me to select and scrape the text.

Facebook is using React code:

// ....
showSponsorTaggerButtonNUX:false,showSponsorTaggerDirectBoost:false,showSponsorTaggerSponsorRelationship:false}},attachmentsConfig:{STATUS:{canScrapeShare:true,canAttachLocation:false,enabled:true,largeTextThreshold:85,profileID:null,profileName:null,profileURI:null,profilePicSrc:"https://scontent.fsvg1-1.fna.fbcdn.net/v/t1.0-1/c12.0.40.40/p40x40/10354686_10150004552801856_220367501106153455_n.jpg?oh=3ad0945d50cb5c25455167972e2cb9c6&oe=5A0CA7F8"
// ....

For instance I found profilePicSrc. I tried using at_css and xpath. I might doing it wrong or it can't scrape them because there is no CSS or HTML that Nokogiri can select/find.

I managed to get these details from the Facebook API:

{
   "id": "7270241753",
   "name": "YouTube",
   "cover": {
      "cover_id": "10156001238986754",
      "offset_x": 0,
      "offset_y": 0,
      "source": "https://scontent.xx.fbcdn.net/v/t1.0-9/s720x720/14591676_10156001238986754_7091829954587846661_n.jpg?oh=b5bc4ca11e6a5d47f18b798eb38cc176&oe=59DBEC50",
      "id": "10156001238986754"
   },
   "fan_count": 82634405,
   "picture": {
      "data": {
         "is_silhouette": false,
         "url": "https://scontent.xx.fbcdn.net/v/t1.0-1/p50x50/19424472_10156001229851754_375700039380897185_n.jpg?oh=965b50ea998545bcbcb99fb90b3ba606&oe=59CEF703"
      }
   }
}

How can I select the profile picture, name, the number of likes the page has and its big header image from this output?


问:
Does the new Microsoft Lync 2010 Client API work in non-IE browsers?
I'm writing a Silverlight app that uses the Lync 2010 Client API to communicate with the Lync 2010 Client. Works fine in Internet Explorer, but in Chrome/Firefox i get this:

Microsoft.Lync.Model.UnsupportedBrowserException:
  Browser doesn't support ActiveX
         at Microsoft.Lync.Model.LyncClient.HandleJavascriptException(String
  error)
         at Microsoft.Lync.Model.LyncClient.EnsureOfficeIntegration()
         at Microsoft.Lync.Model.LyncClient.GetClient()
         at LyncSilverlightApplication2.Page.button1_Click(Object
  sender, RoutedEventArgs a)

The documentation hints that the API might only work in IE: "Internet Explorer 7 and Internet Explorer 8 currently support Lync Controls." This statement doesn't really exclude other browsers and the API could be independent from the controls. But still.

So; Does the new Microsoft Lync 2010 Client API work in non-IE browsers?

答:
You get an error about ActiveX so apparently the Lync API uses ActiveX. That technology is only available in Internet Explorer I'm afraid.

Some browsers offers plugins to enable ActiveX but I'm not sure it will solve your problem.


问:
How to center text when you have another div with float
I'm getting a little bit confused about how to center vertically text inside div which have two divs inside (first: text, second: button with float)

Is that possible to do it without any multiple lines?
https://jsfiddle.net/jr9yx3kx/

HTML

```<code><div class="alert alert-success">
  <span>Information box lorem ipsum</span>
  <a href="" class="btn btn-solid">Why is it not correct?</a>
  <div class="clearfix"></div>
</div>
</code>```

CSS

```<code>.alert {
    padding: 17px;
    margin-bottom: 2rem;
    border: 1px solid transparent;
    font-size: 12px;
    border-radius: 0.215rem;
    background: #ccc;
    color: #fff;
}
.alert a.btn {
  float: right;
}
.btn {
  padding: 0.429rem 0.929rem;
    font-size: 0.858rem;
    border-radius: 0.143rem;
    font-weight: 400;
    line-height: 1.57142857;
    text-align: center;
    white-space: nowrap;
    vertical-align: middle;
    background: blue;
    color: #fff;
}
.clearfix {
  clear: both;
}
</code>```

答:
I think you want the span to be centered in the gray box and button to be under the text, but floated to the right?

If so, add some CSS for the span:

```<code>span {
    text-align:center;
    width:100%;
    display:block;
}
</code>```

https://jsfiddle.net/jr9yx3kx/1/

Body:
I'm getting a little bit confused about how to center vertically text inside div which have two divs inside (first: text, second: button with float)

Is that possible to do it without any multiple lines?
https://jsfiddle.net/jr9yx3kx/

HTML

  Information box lorem ipsum
  Why is it not correct?

CSS

.alert {
    padding: 17px;
    margin-bottom: 2rem;
    border: 1px solid transparent;
    font-size: 12px;
    border-radius: 0.215rem;
    background: #ccc;
    color: #fff;
}
.alert a.btn {
  float: right;
}
.btn {
  padding: 0.429rem 0.929rem;
    font-size: 0.858rem;
    border-radius: 0.143rem;
    font-weight: 400;
    line-height: 1.57142857;
    text-align: center;
    white-space: nowrap;
    vertical-align: middle;
    background: blue;
    color: #fff;
}
.clearfix {
  clear: both;
}

Body:
I think you want the span to be centered in the gray box and button to be under the text, but floated to the right?

If so, add some CSS for the span:

span {
    text-align:center;
    width:100%;
    display:block;
}

https://jsfiddle.net/jr9yx3kx/1/


问:
How do I get rid of chart in all workbooks in vba?
I tried running this code to delete any charts before allowing the code to run but error of "Object doesn't support this method" keeps coming up. </p>

```<code>Dim wksht As Worksheets

Set Source_Workbook = ThisWorkbook

For Each wksht In Source_Workbook

   If ChartObjects.Count > 0 Then

      ChartObjects.Delete

   End If

Next wksht
</code>```

答: You need to enumerate each chart and delete it individually.  You're trying to delete the collection.</p>

Body:
I tried running this code to delete any charts before allowing the code to run but error of "Object doesn't support this method" keeps coming up.

Dim wksht As Worksheets

Set Source_Workbook = ThisWorkbook

For Each wksht In Source_Workbook

   If ChartObjects.Count > 0 Then

      ChartObjects.Delete

   End If

Next wksht


问:
Web application that uses scikit-learn
I have locally trained a sklearn classifier and I have to create a simple web application that demonstrate its use. I'm a complete noob on web app development and I don't want to waste hours on creating a web app using a framework that doesn't support the modules I'm using.

What do you suggest would be a good approach for this task?

What web app development framework should I use (if any)?

Do I have to dive into things like Heroku , django etc. or is there more simple and quicker solutions for a simple scientific demo?

My thought was to take the classifier I trained, pickle it and un-pickle it on the server, then to run classify from the server, but I'm not sure where to begin.

答:
I'm working on a Docker image that wraps predict and predictproba methods and expose them as a web api: https://github.com/hexacta/docker-sklearn-predict-http-api

You need to save your model:

```<code>from sklearn.externals import joblib
joblib.dump(clf, 'iris-svc.pkl')
</code>```

create a Dockerfile:

```<code>FROM hexacta/sklearn-predict-http-api:latest
COPY iris-svc.pkl /usr/src/app/model.pkl
</code>```

and run the container:

```<code>$ docker build -t iris-svc .
$ docker run -d -p 4000:8080 iris-svc
</code>```

then you can make requests:

```<code>$ curl -H "Content-Type: application/json" -X POST -d '{"sepal length (cm)":4.4}' http://localhost:4000/predictproba
  [{"0":0.8284069169,"1":0.1077571623,"2":0.0638359208}]
$ curl -H "Content-Type: application/json" -X POST -d '[{"sepal length (cm)":4.4}, {"sepal length (cm)":15}]' http://localhost:4000/predict
  [0, 2]
</code>```

Title: Web application that uses scikit-learn

Body:
I'm working on a Docker image that wraps predict and predictproba methods and expose them as a web api: https://github.com/hexacta/docker-sklearn-predict-http-api

You need to save your model:

from sklearn.externals import joblib
joblib.dump(clf, 'iris-svc.pkl')

create a Dockerfile:

FROM hexacta/sklearn-predict-http-api:latest
COPY iris-svc.pkl /usr/src/app/model.pkl

and run the container:

$ docker build -t iris-svc .
$ docker run -d -p 4000:8080 iris-svc

then you can make requests:

$ curl -H "Content-Type: application/json" -X POST -d '{"sepal length (cm)":4.4}' http://localhost:4000/predictproba
  [{"0":0.8284069169,"1":0.1077571623,"2":0.0638359208}]
$ curl -H "Content-Type: application/json" -X POST -d '[{"sepal length (cm)":4.4}, {"sepal length (cm)":15}]' http://localhost:4000/predict
  [0, 2]


问:
SQL Server and Microsoft.ACE.OLEDB.12.0
I am getting the following:

Msg 7399, Level 16, State 1, Line 1 The OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)" reported an error. The provider did not give any information about the error. Msg 7303, Level 16, State 1, Line 1 Cannot initialize the data source object of OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)".

When I execute the following from a Stored Procedure in SQLServer -

```<code>SELECT * FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0', 'Excel 12.0;Database=c:\Users\v-bimoss\Source\Workspaces\External\Onesite\URLoadDB\Templates\T1-Current.xlsx', 'SELECT * FROM [Sheet1$]')
</code>```

I have been through all the threads I could find on this topic - but still am having the problem

I have verified that:

The 64 bit Microsoft.ACE.OLEDB.12.0 drivers are loaded

Ad Hoc Distributed Queries is set to 1

Dynamic Parameter and Allow Inprocess are both set to 1

Changed MSSQL to run under my account

The account that is running MSSQL and the account I am using both have full access to C:\Windows\ServiceProfiles\LocalService\AppData\Local\Temp

Any help would be appreciated. -wmm

答:
I would check into the steps in these two but in particular checking and changing, if you can, the user who runs SQL Server:

Cannot create an instance of OLE DB provider Microsoft.Jet.OLEDB.4.0 for linked server null

The OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)"

Title: SQL Server and Microsoft.ACE.OLEDB.12.0

Body:
I am getting the following:

Msg 7399, Level 16, State 1, Line 1 The OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)" reported an error. The provider did not give any information about the error. Msg 7303, Level 16, State 1, Line 1 Cannot initialize the data source object of OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)".

When I execute the following from a Stored Procedure in SQLServer -

SELECT * FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0', 'Excel 12.0;Database=c:\Users\v-bimoss\Source\Workspaces\External\Onesite\URLoadDB\Templates\T1-Current.xlsx', 'SELECT * FROM [Sheet1$]')

I have been through all the threads I could find on this topic - but still am having the problem

I have verified that:

The 64 bit Microsoft.ACE.OLEDB.12.0 drivers are loaded

Ad Hoc Distributed Queries is set to 1

Dynamic Parameter and Allow Inprocess are both set to 1

Changed MSSQL to run under my account

The account that is running MSSQL and the account I am using both have full access to C:\Windows\ServiceProfiles\LocalService\AppData\Local\Temp

Any help would be appreciated. -wmm


问:
Sending final welcome mail with Mailchimp API v3.0 without double opt-in
I would like to use the Mailchimp v3.0 API to send a final welcome mail, without going through the double opt-in procedure.

If I set the status to "pending" I get the double opt-in, at least sometimes, and of course the final welcome mail, as described in this post
Realize Mailchimp Double-Opt-In with API 3.0

But I would like to do it without the double opt-in, as indicated should work automatically in this post Sending Welcome Email when using Mailchimp API 3 List/Member Method

I assume that the last post also requires the double opt-in, even if that is not mentioned in the post.

Anyone that have been able to do it in v3.0? I can do it in v2.0, but would like to use 3.0 going forward.

答:
I needed the same kind of functionality, but unfortunately the final welcome email is only sent after a person has completed the double-opt in. Thus, as of right now Mailchimp does not support this out of the box in the list settings and you have to resort to other ways to send this kind of mail to your users.

Fortunately, you can actually achieve the same behavior using Mailchimp's automation feature: https://help.mailmunch.com/hc/en-us/articles/206143089-How-to-Enable-MailChimp-s-Welcome-Email-

For reference, the send final welcome mail option in the Mailchimp list dashboard has a tooltip that explicitly reads:

When people opt-in to your list, send them an email welcoming them to your newsletter.


问:
Why should you use an ORM?
If you are motivate to the "pros" of an ORM and why would you use an ORM to management/client, what are those reasons would be?

Try and keep one reason per answer so that we can see which one gets voted up as the best reason.

答:
The most important reason to use an ORM is so that you can have a rich, object oriented business model and still be able to store it and write effective queries quickly against a relational database.  From my viewpoint, I don't see any real advantages that a good ORM gives you when compared with other generated DAL's other than the advanced types of queries you can write.

One type of query I am thinking of is a polymorphic query.  A simple ORM query might select all shapes in your database.  You get a collection of shapes back.  But each instance is a square, circle or rectangle according to its discriminator.

Another type of query would be one that eagerly fetches an object and one or more related objects or collections in a single database call.  e.g. Each shape object is returned with its vertex and side collections populated.

I'm sorry to disagree with so many others here, but I don't think that code generation is a good enough reason by itself to go with an ORM.  You can write or find many good DAL templates for code generators that do not have the conceptual or performance overhead that ORM's do.

Or, if you think that you don't need to know how to write good SQL to use an ORM, again, I disagree.  It might be true that from the perspective of writing single queries, relying on an ORM is easier.  But, with ORM's it is far too easy to create poor performing routines when developers don't understand how their queries work with the ORM and the SQL they translate into.

Having a data layer that works against multiple databases can be a benefit.  It's not one that I have had to rely on that often though.

In the end, I have to reiterate that in my experience, if you are not using the more advanced query features of your ORM, there are other options that solve the remaining problems with less learning and fewer CPU cycles.

Oh yeah, some developers do find working with ORM's to be fun so ORM's are also good from the keep-your-developers-happy perspective. =)

OwnerDisplayName: Simon Munro

Title: Why should you use an ORM?

OwnerDisplayName: Chuck


问:
Android animation sequence
I am facing problem in getting a sequence of animation on a particular view.
I used animationset in my code and i have set the offset for each animation and the duration for the animation correctly.

somebody pls help with this.

Thanks...

答:
For page transition use the below snippet

```<code>pageTransition(Context context, View view){
Animation mAnim = AnimationUtils.loadAnimation(context, R.anim.slide_top_to_bottom);
        mAnim.setRepeatMode(Animation.ABSOLUTE);
        view.startAnimation(mAnim);
        }
</code>```

refer the below link for more details deVogella

Title: Android animation sequence

Body:
For page transition use the below snippet

pageTransition(Context context, View view){
Animation mAnim = AnimationUtils.loadAnimation(context, R.anim.slide_top_to_bottom);
        mAnim.setRepeatMode(Animation.ABSOLUTE);
        view.startAnimation(mAnim);
        }

refer the below link for more details deVogella


问:
How to pass param from controller to service in AngularJs
I'm currently working on a project to help me better understand angularjs! I am currently stuck on how to pass a parameter from the controller to service.

In my program, I have created a function called "GetForecastByLocation" when a user types in an input clicks on a button. From there I want to take their input and then pass it to the http call in service.js.

Originally, $http.get was in a long giant string of the API url, but I googled around and it seems that I'm supposed to use parameters when trying to change a portion of the string. As of right now, I know parameter is hardcoded to a specific city, but I want to take new input and pass the value of vm.city to the $http.get call.

If any one can help I would greatly appreciate it. Thank you!

controller.js

```<code>    var app = angular.module('weatherApp.controllers', [])
    app.controller('weatherCtrl', ['$scope','Data',
        function($scope, Data) {

        $scope.getForecastByLocation = function(myName) {
            $scope.city = myName;
            Data.getApps($scope.city);},

        Data.getApps(city)
        .then(function(data)){
        //doing a bunch of things like converting units, etc
        },
        function(res){
            if(res.status === 500) {
            // server error, alert user somehow
        } else {
            // probably deal with these errors differently
        }
        }); // end of function
}]) // end of controller
</code>```

service.js

```<code>.factory('Data', function($http, $q) {
       var data = [],
           lastRequestFailed = true,
           promise;
       return {
          getApps: function() {
             if(!promise || lastRequestFailed) {
            promise = $http.get('http://api.openweathermap.org/data/2.5/weather?',{
              params: {
                q: Tokyo,
              }
            })
            .then(function(res) {
                lastRequestFailed = false;
                data = res.data;
                return data;
            }, function(res) {
                return $q.reject(res);
            });
         }
         return promise;
      }
   }
});
</code>```

答:
Passing arguments to a factory method is no different than passing arguments to a plain old function.

First, set up getApps to accept a parameter:

```<code>.factory('Data', function($http, $q){
    // ...
    return {
        getApps: function(city){
            promise = $http.get(URL, {
                params: {q: city}
            }).then( /* ... */ );
            // ...
            return promise;
        }
    };
});
</code>```

Then pass it your argument:

```<code>$scope.getForecastByLocation = function(myName) {
    $scope.city = myName;
    Data.getApps($scope.city);
}
</code>```

Body:
I'm currently working on a project to help me better understand angularjs! I am currently stuck on how to pass a parameter from the controller to service.

In my program, I have created a function called "GetForecastByLocation" when a user types in an input clicks on a button. From there I want to take their input and then pass it to the http call in service.js.

Originally, $http.get was in a long giant string of the API url, but I googled around and it seems that I'm supposed to use parameters when trying to change a portion of the string. As of right now, I know parameter is hardcoded to a specific city, but I want to take new input and pass the value of vm.city to the $http.get call.

If any one can help I would greatly appreciate it. Thank you!

controller.js

    var app = angular.module('weatherApp.controllers', [])
    app.controller('weatherCtrl', ['$scope','Data',
        function($scope, Data) {

        $scope.getForecastByLocation = function(myName) {
            $scope.city = myName;
            Data.getApps($scope.city);},

        Data.getApps(city)
        .then(function(data)){
        //doing a bunch of things like converting units, etc
        },
        function(res){
            if(res.status === 500) {
            // server error, alert user somehow
        } else {
            // probably deal with these errors differently
        }
        }); // end of function
}]) // end of controller

service.js

.factory('Data', function($http, $q) {
       var data = [],
           lastRequestFailed = true,
           promise;
       return {
          getApps: function() {
             if(!promise || lastRequestFailed) {
            promise = $http.get('http://api.openweathermap.org/data/2.5/weather?',{
              params: {
                q: Tokyo,
              }
            })
            .then(function(res) {
                lastRequestFailed = false;
                data = res.data;
                return data;
            }, function(res) {
                return $q.reject(res);
            });
         }
         return promise;
      }
   }
});

Body:
Passing arguments to a factory method is no different than passing arguments to a plain old function.

First, set up getApps to accept a parameter:

.factory('Data', function($http, $q){
    // ...
    return {
        getApps: function(city){
            promise = $http.get(URL, {
                params: {q: city}
            }).then( /* ... */ );
            // ...
            return promise;
        }
    };
});

Then pass it your argument:

$scope.getForecastByLocation = function(myName) {
    $scope.city = myName;
    Data.getApps($scope.city);
}


问:
Selenium - How to open new Chrome Window, using Javascript Executors
I have an edit button on a page. I want to open this in a new window.

At the moment, this code will click the edit button and have it open in the default window:

```<code>    Actions actions = new Actions(driver);
    JavascriptExecutor jse = (JavascriptExecutor) driver;
    actions.moveToElement(elem1).click();
    jse.executeScript("arguments[0].click()", elem1);
</code>```

To open it in another window, I tried doing something like

```<code>Actions newwin = new Actions(driver);
newwin.keyDown(Keys.SHIFT).click(elem1).keyUp(Keys.SHIFT).build().perform();
</code>```

However, this returns an error, because it's not actually moving to the element and finding it. If I scroll down to where the edit button is manually while my script is running, the edit page will get opened in a new window, as wanted.
However, I don't want to manually have to scroll down to the edit button every time I run my Selenium script.

I tried doing something like this:

Actions newwin = new Actions(driver);       newwin.moveToElement(elem1).keyDown(Keys.SHIFT).click(elem1).keyUp(Keys.SHIFT).build().perform();

But it still was not able to select the edit element and open it in a new window.

Does anyone have any ideas how I can make this work?

答:
Okay got it guys..

I needed to scroll it into view first, then I could right click and open it in a new window

I was having issues because I really wanted to do it in 1 step, but I broke it down into 2:

```<code>        ((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);",
elem1);
    Thread.sleep(500);

    Actions newwin = new Actions(driver);
    newwin.keyDown(Keys.SHIFT).click(elem1).keyUp(Keys.SHIFT).build().perform();
</code>```

Body:
I have an edit button on a page. I want to open this in a new window.

At the moment, this code will click the edit button and have it open in the default window:

    Actions actions = new Actions(driver);
    JavascriptExecutor jse = (JavascriptExecutor) driver;
    actions.moveToElement(elem1).click();
    jse.executeScript("arguments[0].click()", elem1);

To open it in another window, I tried doing something like

Actions newwin = new Actions(driver);
newwin.keyDown(Keys.SHIFT).click(elem1).keyUp(Keys.SHIFT).build().perform();

However, this returns an error, because it's not actually moving to the element and finding it. If I scroll down to where the edit button is manually while my script is running, the edit page will get opened in a new window, as wanted.
However, I don't want to manually have to scroll down to the edit button every time I run my Selenium script.

I tried doing something like this:

Actions newwin = new Actions(driver);       newwin.moveToElement(elem1).keyDown(Keys.SHIFT).click(elem1).keyUp(Keys.SHIFT).build().perform();

But it still was not able to select the edit element and open it in a new window.

Does anyone have any ideas how I can make this work?

Body:
Okay got it guys..

I needed to scroll it into view first, then I could right click and open it in a new window

I was having issues because I really wanted to do it in 1 step, but I broke it down into 2:

        ((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);",
elem1);
    Thread.sleep(500);

    Actions newwin = new Actions(driver);
    newwin.keyDown(Keys.SHIFT).click(elem1).keyUp(Keys.SHIFT).build().perform();


问:
Adressing PHP array decoded from JSON
I'm loading a JSON array and decode it to an PHP array

```<code>$jsonfile = file_get_contents('https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=MSFT&interval=15min&outputsize=full&apikey=demo');
$jsonarray = json_decode($jsonfile);
var_dump($jsonarray);
</code>```

So far so good I get an array that looks like that:

```<code>object(stdClass)#1 (2) {
    ["Meta Data"]=> object(stdClass)#2 (5) {
        ["1. Information"]=> string(49) "Daily Prices (open, high, low, close) and Volumes"
        ["2. Symbol"]=> string(5) "AAWVX"
        ["3. Last Refreshed"]=> string(10) "2017-06-30"
        ["4. Output Size"]=> string(9) "Full size"
        ["5. Time Zone"]=> string(10) "US/Eastern"
    }
    ["Time Series (Daily)"]=> object(stdClass)#3 (105) {
        ["2017-06-30"]=> object(stdClass)#4 (5) {
            ["1. open"]=> string(7) "10.5100"
            ["2. high"]=> string(7) "10.5100"
            ["3. low"]=> string(7) "10.5100"
            ["4. close"]=> string(7) "10.5100"
            ["5. volume"]=> string(1) "0"
        }
        ["2017-06-29"]=> object(stdClass)#5 (5) { ["1. open"]=> string(7) "10.4800" ["2. high"]=> string(7) "10.4800" ["3. low"]=> string(7) "10.4800" ["4. close"]=> string(7) "10.4800" ["5. volume"]=> string(1) "0" }
        ["2017-06-28"]=> object(stdClass)#6 (5) { ["1. open"]=> string(7) "10.5600" ["2. high"]=> string(7) "10.5600" ["3. low"]=> string(7) "10.5600" ["4. close"]=> string(7) "10.5600" ["5. volume"]=> string(1) "0" } ...
</code>```

But when I try to adress the array like

```<code>var_dump($jsonarray['Meta Data']);
</code>```

It doesn't work.

答:
This is because json_decode() with no parameters attempts to convert your json string to an stdClass object. If you want to convert it to an array, you need to set the 2nd parameters (the $assoc boolean) to true:

```<code>$json = file_get_contents('LINK TO JSON OUTPUT');
$array = json_decode($json, true);
</code>```

Title: Adressing PHP array decoded from JSON

Body:
I'm loading a JSON array and decode it to an PHP array

$jsonfile = file_get_contents('https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=MSFT&interval=15min&outputsize=full&apikey=demo');
$jsonarray = json_decode($jsonfile);
var_dump($jsonarray);

So far so good I get an array that looks like that:

object(stdClass)#1 (2) {
    ["Meta Data"]=> object(stdClass)#2 (5) {
        ["1. Information"]=> string(49) "Daily Prices (open, high, low, close) and Volumes"
        ["2. Symbol"]=> string(5) "AAWVX"
        ["3. Last Refreshed"]=> string(10) "2017-06-30"
        ["4. Output Size"]=> string(9) "Full size"
        ["5. Time Zone"]=> string(10) "US/Eastern"
    }
    ["Time Series (Daily)"]=> object(stdClass)#3 (105) {
        ["2017-06-30"]=> object(stdClass)#4 (5) {
            ["1. open"]=> string(7) "10.5100"
            ["2. high"]=> string(7) "10.5100"
            ["3. low"]=> string(7) "10.5100"
            ["4. close"]=> string(7) "10.5100"
            ["5. volume"]=> string(1) "0"
        }
        ["2017-06-29"]=> object(stdClass)#5 (5) { ["1. open"]=> string(7) "10.4800" ["2. high"]=> string(7) "10.4800" ["3. low"]=> string(7) "10.4800" ["4. close"]=> string(7) "10.4800" ["5. volume"]=> string(1) "0" }
        ["2017-06-28"]=> object(stdClass)#6 (5) { ["1. open"]=> string(7) "10.5600" ["2. high"]=> string(7) "10.5600" ["3. low"]=> string(7) "10.5600" ["4. close"]=> string(7) "10.5600" ["5. volume"]=> string(1) "0" } ...

But when I try to adress the array like

var_dump($jsonarray['Meta Data']);

It doesn't work.

Body:
This is because json_decode() with no parameters attempts to convert your json string to an stdClass object. If you want to convert it to an array, you need to set the 2nd parameters (the $assoc boolean) to true:

$json = file_get_contents('LINK TO JSON OUTPUT');
$array = json_decode($json, true);


问:
res.download(NodeJS) not triggering a download on the browser
I've been struggling with this for a while and can't seem to find an answer, I'm developing a website with a budgeting option, I'm sending an object from the client to the server, and that server is using PDFKit to create a PDF version of the budget, once it's created I want to actually send back that PDF to the client and trigger a download, this is what I've done

Client-side code:

```<code>let data = {
  nombre: this.state.name,
  email: this.state.email,
  telefono: this.state.phone,
  carrito: this.props.budget.cart,
  subTotal: this.props.budget.subTotal,
  IVA: this.props.budget.tax,
  total: this.props.budget.subTotal + this.props.budget.tax
}
  axios({
    method: 'post',
    url: 'http://localhost:1337/api/budget',
    data: data
  })
    .then((response) => {
      console.log('This is the response', response);
      window.open('/download')
    })
    .catch((error) => {
      alert(error);
    })
</code>```

So that data goes to my server-side code perfectly and it looks like this

```<code>const pdf = require('pdfkit');
const fs = require('fs');
const path = require('path');

exports.makePDFBudget = (req, res) => {
  let myDoc = new pdf;
  myDoc.pipe(fs.createWriteStream(`PDFkit/budget.pdf`));
  myDoc.font('Times-Roman')
       .fontSize(12)
       .text(`${req.body.name} ${req.body.phone} ${req.body.email} ${req.body.cart} ${req.body.subTotal} ${req.body.total} ${req.body.tax}`);
  myDoc.end()
}
</code>```

That's creating my PDF, what I want now is that once it's created and the response is sent back to the client, the client opens a new window with the URL "/download" which is set to download that PDF, but that's not happening for some reason, it opens up the new window but the download never starts and it throws absolutely no error I'm my Node console or browser console
this is how I send my file to the client

```<code>const fs = require('fs');
const path = require('path');

exports.downloadPDFBudget = (req, res) => {
  res.download(__dirname + 'budget.pdf', 'budget.pdf');
}
</code>```

And this is how my server index looks like

```<code>const bodyParser = require('body-parser');
const express = require('express');
const app = express();
const api = express.Router();
const { makePDFBudget } = require('./PDFkit/makePDFBudget.js');
const { downloadPDFBudget } = require('./PDFkit/downloadPDFBudget.js')

app.use(express.static(__dirname + '/../public'));
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json({extended: true}));

api.route('/budget')
  .post(makePDFBudget)

api.route('/download')
  .get(downloadPDFBudget)

app.use('/api', api);

const port = 1337;

app.listen(port);

console.log('Listening on port ', port);

module.exports = app;
</code>```

答:
I guess the main problem here:

res.download(__dirname + 'budget.jpg', 'budget.pdf');

Make a correct file name. Your file is pdf, not jpg.

At this code res.end(Buffer.from('budget.pdf')) you sending string, not file content. But headers like you want to send a file.

The last. Your application designed like you will have only one user. Could you add userId to file names? Or use DB for storing data and generate pdf on request without storing a file to the file system.

Body:
I've been struggling with this for a while and can't seem to find an answer, I'm developing a website with a budgeting option, I'm sending an object from the client to the server, and that server is using PDFKit to create a PDF version of the budget, once it's created I want to actually send back that PDF to the client and trigger a download, this is what I've done

Client-side code:

let data = {
  nombre: this.state.name,
  email: this.state.email,
  telefono: this.state.phone,
  carrito: this.props.budget.cart,
  subTotal: this.props.budget.subTotal,
  IVA: this.props.budget.tax,
  total: this.props.budget.subTotal + this.props.budget.tax
}
  axios({
    method: 'post',
    url: 'http://localhost:1337/api/budget',
    data: data
  })
    .then((response) => {
      console.log('This is the response', response);
      window.open('/download')
    })
    .catch((error) => {
      alert(error);
    })

So that data goes to my server-side code perfectly and it looks like this

const pdf = require('pdfkit');
const fs = require('fs');
const path = require('path');

exports.makePDFBudget = (req, res) => {
  let myDoc = new pdf;
  myDoc.pipe(fs.createWriteStream(`PDFkit/budget.pdf`));
  myDoc.font('Times-Roman')
       .fontSize(12)
       .text(`${req.body.name} ${req.body.phone} ${req.body.email} ${req.body.cart} ${req.body.subTotal} ${req.body.total} ${req.body.tax}`);
  myDoc.end()
}

That's creating my PDF, what I want now is that once it's created and the response is sent back to the client, the client opens a new window with the URL "/download" which is set to download that PDF, but that's not happening for some reason, it opens up the new window but the download never starts and it throws absolutely no error I'm my Node console or browser console
this is how I send my file to the client

const fs = require('fs');
const path = require('path');

exports.downloadPDFBudget = (req, res) => {
  res.download(__dirname + 'budget.pdf', 'budget.pdf');
}

And this is how my server index looks like

const bodyParser = require('body-parser');
const express = require('express');
const app = express();
const api = express.Router();
const { makePDFBudget } = require('./PDFkit/makePDFBudget.js');
const { downloadPDFBudget } = require('./PDFkit/downloadPDFBudget.js')

app.use(express.static(__dirname + '/../public'));
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json({extended: true}));

api.route('/budget')
  .post(makePDFBudget)

api.route('/download')
  .get(downloadPDFBudget)

app.use('/api', api);

const port = 1337;

app.listen(port);

console.log('Listening on port ', port);

module.exports = app;


问:
How to replace unity Injection on runtime
I have one abstract Class and tow implementation for it.

```<code>public abstract class Person{
    public abstract string GetName();
}

public class Doctor : Person{
    public override string GetName()
    {
        return "Doctor";
    }
}

public class Teacher : Person{
    public override string GetName()
    {
        return "teacher";
    }
}
</code>```

I am using unity to dependency injection.In unity I register Doctor and in run time I need to use teacher ,actually replace that injection in my test2 method :
here is my unity injection :

```<code>container.RegisterType<Person, Doctor>();
</code>```

here is my class constructor :

```<code>private readonly Iperson _person;
pubice myclass(Iperson person)
{
    _person=person
}

public voide test1()
{
    var Name=_person.GetName();
    // Name is : Doctor
}

public void test2()
{
    //????
    var Name=_person.GetName();
    // Name must be teacher
}
</code>```

答:
I suggest you to register both of your derived classes: Doctor and Teacher

```<code>container.RegisterType<Person, Doctor>(nameof(Doctor));
container.RegisterType<Person, Teacher>(nameof(Teacher));
</code>```

Pass IUnityContainer to MyClass and resolve in runtime what you want by name:

```<code>private readonly IUnityContainer _container;

public MyClass(IUnityContainer container)
{
    _container = container
}

public void test1()
{
    var name = container.Resolve<Person>(nameof(Doctor)).GetName();
    // Name is : Doctor
}

public void test2()
{
    var name = container.Resolve<Person>(nameof(Teacher)).GetName();
    // Name is : Teacher
}
</code>```

Body:
I have one abstract Class and tow implementation for it.

public abstract class Person{
    public abstract string GetName();
}

public class Doctor : Person{
    public override string GetName()
    {
        return "Doctor";
    }
}

public class Teacher : Person{
    public override string GetName()
    {
        return "teacher";
    }
}

I am using unity to dependency injection.In unity I register Doctor and in run time I need to use teacher ,actually replace that injection in my test2 method :
here is my unity injection :

container.RegisterType<Person, Doctor>();

here is my class constructor :

private readonly Iperson _person;
pubice myclass(Iperson person)
{
    _person=person
}

public voide test1()
{
    var Name=_person.GetName();
    // Name is : Doctor
}

public void test2()
{
    //????
    var Name=_person.GetName();
    // Name must be teacher
}

Body:
I suggest you to register both of your derived classes: Doctor and Teacher

container.RegisterType<Person, Doctor>(nameof(Doctor));
container.RegisterType<Person, Teacher>(nameof(Teacher));

Pass IUnityContainer to MyClass and resolve in runtime what you want by name:

private readonly IUnityContainer _container;

public MyClass(IUnityContainer container)
{
    _container = container
}

public void test1()
{
    var name = container.Resolve<Person>(nameof(Doctor)).GetName();
    // Name is : Doctor
}

public void test2()
{
    var name = container.Resolve<Person>(nameof(Teacher)).GetName();
    // Name is : Teacher
}


问:
How can I represent probabilistic grammars in BNF?
I've found a grammar online which I want to rewrite to BNF so I can use it in a grammatical evolution experiment. From what I've read online BNF is given by this form:

```<code><symbol> := <expression> | <term>
</code>```

...but I don't see where probabilities factor into it.

答:
In a probabilistic context-free grammar (PCFG), every production also is assigned a probability. How you choose to write this probability is up to you; I don't know of a standard notation.

Generally, the probabilities are learned rather than assigned, so the representation issue doesn't come up; the system is given a normal CFG as well as a large corpus with corresponding parse trees, and it derives probabilities by analysing the parse trees.

Note that PCFGs are usually ambiguous. Probabilities are not used to decide whether a sentence is in the language but rather which parse is correct, so with an unambiguous grammar, the probabilities would be of little use.

Body:
I've found a grammar online which I want to rewrite to BNF so I can use it in a grammatical evolution experiment. From what I've read online BNF is given by this form:

<symbol> := <expression> | <term>

...but I don't see where probabilities factor into it.


答:
It's just like setting a value to a function's context variable.

Services.js

Simple example of a service.

```<code>.factory('RouteService', function() {
    var route = {}; // $Object

    var setRoute_ = function(obj)
    {
        return route = obj;
    };

    var getRoute_ = function()
    {
        if(typeof route == 'string')
        {
            return JSON.parse(route);
        }

        return null;
    };

    return {
        setRoute: setRoute_,
        getRoute: getRoute_
    };
})
</code>```

Controllers.js

Simple example of Service usage:

```<code>.controller('RoutesCtrl', function ($scope, RouteService) {
    // This is only the set part.
    var route = {
        'some_key': 'some_value'
    };

    RouteService.setRoute(route);
})
</code>```

Title: How to pass param from controller to service in AngularJs

Body:
It's just like setting a value to a function's context variable.

Services.js

Simple example of a service.

.factory('RouteService', function() {
    var route = {}; // $Object

    var setRoute_ = function(obj)
    {
        return route = obj;
    };

    var getRoute_ = function()
    {
        if(typeof route == 'string')
        {
            return JSON.parse(route);
        }

        return null;
    };

    return {
        setRoute: setRoute_,
        getRoute: getRoute_
    };
})

Controllers.js

Simple example of Service usage:

.controller('RoutesCtrl', function ($scope, RouteService) {
    // This is only the set part.
    var route = {
        'some_key': 'some_value'
    };

    RouteService.setRoute(route);
})


答:
You can use the usual method for vertical centering, giving the container position: relativeand the span these settings:

```<code>.alert span {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}
</code>```

Here it is in a snippet:

.alert {
  padding: 17px;
  margin-bottom: 2rem;
  border: 1px solid transparent;
  font-size: 12px;
  border-radius: 0.215rem;
  background: #ccc;
  color: #fff;
  position: relative;
}

.alert span {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}

.alert a.btn {
  float: right;
}

.btn {
  padding: 0.429rem 0.929rem;
  font-size: 0.858rem;
  border-radius: 0.143rem;
  font-weight: 400;
  line-height: 1.57142857;
  text-align: center;
  white-space: nowrap;
  vertical-align: middle;
  background: blue;
  color: #fff;
}

.clearfix {
  clear: both;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="alert alert-success">
  <span>Information box lorem ipsum</span>
  Why is it not correct?
  <div class="clearfix"></div>
</div></code>```

Title: How to center text when you have another div with float

Body:
I'm getting a little bit confused about how to center vertically text inside div which have two divs inside (first: text, second: button with float)

Is that possible to do it without any multiple lines?
https://jsfiddle.net/jr9yx3kx/

HTML

  Information box lorem ipsum
  Why is it not correct?

CSS

.alert {
    padding: 17px;
    margin-bottom: 2rem;
    border: 1px solid transparent;
    font-size: 12px;
    border-radius: 0.215rem;
    background: #ccc;
    color: #fff;
}
.alert a.btn {
  float: right;
}
.btn {
  padding: 0.429rem 0.929rem;
    font-size: 0.858rem;
    border-radius: 0.143rem;
    font-weight: 400;
    line-height: 1.57142857;
    text-align: center;
    white-space: nowrap;
    vertical-align: middle;
    background: blue;
    color: #fff;
}
.clearfix {
  clear: both;
}

Body:
You can use the usual method for vertical centering, giving the container position: relativeand the span these settings:

.alert span {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}

Here it is in a snippet:

.alert {
  padding: 17px;
  margin-bottom: 2rem;
  border: 1px solid transparent;
  font-size: 12px;
  border-radius: 0.215rem;
  background: #ccc;
  color: #fff;
  position: relative;
}

.alert span {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}

.alert a.btn {
  float: right;
}

.btn {
  padding: 0.429rem 0.929rem;
  font-size: 0.858rem;
  border-radius: 0.143rem;
  font-weight: 400;
  line-height: 1.57142857;
  text-align: center;
  white-space: nowrap;
  vertical-align: middle;
  background: blue;
  color: #fff;
}

.clearfix {
  clear: both;
}

<div class="alert alert-success">
  <span>Information box lorem ipsum</span>
  <a href="" class="btn btn-solid">Why is it not correct?</a>
  <div class="clearfix"></div>
</div>


问:
Custom skin and flicker
I created a custom skin with overlaying transparent images and TransparencyKey.

http://jesconsultancy.nl/vb.rar
(Only right bottom corner works to resize)

I have written custom code to resize and drag the application. But when i resize the application it flickers. There wil become some space between the borders of the image/panels. How do I solve this?

I can't make a screenshot of the problem because on the screenshot there is no flicker effect :/

答: Are you redrawing on every resize event? If so, you might be redrawing too often, and might need to decouple your render from the resize event (e.g. while resizing and mouse down, don't render). I've had similar problems before, but on dragging objects in a window ...</p>

Title: Custom skin and flicker


问:
Show image name on text click
hello all i want to show image  name on text click without creating multiple ids for p tag element . thanks in advance.

$('img').click(function()
{
 var test = $(this).attr('src').split("/").pop();
 document.getElementById("result").value= test;
});```
<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="row">
    <div>
     <img src="1.png">
     <div>
     <p>click<p>
     </div>
    </div>
    <div>
     <img src="2.png">
     <div>
     <p>click</p>
     </div>
    </div>
    <div>
     <img src="3.png">
     <div>
     <p>click</p>
     </div>
    </div>
</div>
<form>
 <input type="text" id="result">
</form></code>```

答:
You can do:

$('.row p').click(function() {
  //simple version
  var text = $(this).parent().prev().attr('src').split("/").pop();

  //a more generic version would be
  //var text = $(this).parent().parent().find('img').attr('src').split("/").pop();

  $("#result").val(text);
});```
<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="row">
  <div>
    <img src="1.png">
    <div>
      <p>click</p>
    </div>
  </div>
  <div>
    <img src="2.png">
    <div>
      <p>click</p>
    </div>
  </div>
  <div>
    <img src="3.png">
    <div>
      <p>click</p>
    </div>
  </div>
</div>
<form>
  <input type="text" id="result">
</form></code>```

Also note that your first
click
 tag is not properly closed, and it should be
click

Title: Show image name on text click

Body:
hello all i want to show image  name on text click without creating multiple ids for p tag element . thanks in advance.

$('img').click(function()
{
 var test = $(this).attr('src').split("/").pop();
 document.getElementById("result").value= test;
});

click

click

click

<form>
 <input type="text" id="result">
</form>

Body:
You can do:

$('.row p').click(function() {
  //simple version
  var text = $(this).parent().prev().attr('src').split("/").pop();

  //a more generic version would be
  //var text = $(this).parent().parent().find('img').attr('src').split("/").pop();

  $("#result").val(text);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
  <div>
    <img src="1.png">
    <div>
      <p>click</p>
    </div>
  </div>
  <div>
    <img src="2.png">
    <div>
      <p>click</p>
    </div>
  </div>
  <div>
    <img src="3.png">
    <div>
      <p>click</p>
    </div>
  </div>
</div>
<form>
  <input type="text" id="result">
</form>

Also note that your first <p>click<p> tag is not properly closed, and it should be <p>click</p>


问:
Azure Encoding Job returns no OuputAssetFiles
Using the REST API documentation I am encoding a video using the following request to azure:

```<code>{
    "Name": "NewTestJob",
    "InputMediaAssets": [{
            "__metadata": {
                "uri": "https://media.windows.net/api/Assets('nb%3Acid%3AUUID%3Ab5cb32de-AAAA-BBBB-a6eb-1b3a61c795be')"
            }
        }
    ],
    "Tasks": [{
            "Configuration": "H264 Single Bitrate 720p",
            "MediaProcessorId": "nb:mpid:UUID:ff4df607-d419-42f0-bc17-a481b1331e56",
            "TaskBody": "<?xml version=\"1.0\" encoding=\"utf-8\"?><taskBody><inputAsset>JobInputAsset(0)</inputAsset><outputAsset>JobOutputAsset(0)</outputAsset></taskBody>"
        }
    ]
}
</code>```

From what I can see in the Azure dashboard this creates an encoded version of my video, the problem I have is that the returned job information does not have any OutputMediaAssets. The response is:

```<code>{
    "odata.metadata": "https://wamsamsclus001rest-hs.cloudapp.net/api/$metadata#Jobs/@Element",
    "Id": "nb:jid:UUID:e4bf4cff-0300-80c0-c4c5-f1e75c34a72c",
    "Name": "NewTestJob",
    "Created": "2017-06-28T19:04:55.8442399Z",
    "LastModified": "2017-06-28T19:04:55.8442399Z",
    "EndTime": null,
    "Priority": 0,
    "RunningDuration": 0.0,
    "StartTime": null,
    "State": 0,
    "TemplateId": null,
    "JobNotificationSubscriptions": []
}
</code>```

This means I can't locate the newly created encoded asset. What am I doing wrong? Is there another way to locate the generated asset?

答:
The problem wasn't caused by the Request Body but instead the header.

I was passing the header:

```<code>Accept: application/json
</code>```

Instead of the header:

```<code>Accept: application/json;odata=verbose
</code>```

The lack of the odata=verbose means that only a subset of the available data is returned.

Body:
Using the REST API documentation I am encoding a video using the following request to azure:

{
    "Name": "NewTestJob",
    "InputMediaAssets": [{
            "__metadata": {
                "uri": "https://media.windows.net/api/Assets('nb%3Acid%3AUUID%3Ab5cb32de-AAAA-BBBB-a6eb-1b3a61c795be')"
            }
        }
    ],
    "Tasks": [{
            "Configuration": "H264 Single Bitrate 720p",
            "MediaProcessorId": "nb:mpid:UUID:ff4df607-d419-42f0-bc17-a481b1331e56",
            "TaskBody": "<?xml version=\"1.0\" encoding=\"utf-8\"?><taskBody><inputAsset>JobInputAsset(0)</inputAsset><outputAsset>JobOutputAsset(0)</outputAsset></taskBody>"
        }
    ]
}

From what I can see in the Azure dashboard this creates an encoded version of my video, the problem I have is that the returned job information does not have any OutputMediaAssets. The response is:

{
    "odata.metadata": "https://wamsamsclus001rest-hs.cloudapp.net/api/$metadata#Jobs/@Element",
    "Id": "nb:jid:UUID:e4bf4cff-0300-80c0-c4c5-f1e75c34a72c",
    "Name": "NewTestJob",
    "Created": "2017-06-28T19:04:55.8442399Z",
    "LastModified": "2017-06-28T19:04:55.8442399Z",
    "EndTime": null,
    "Priority": 0,
    "RunningDuration": 0.0,
    "StartTime": null,
    "State": 0,
    "TemplateId": null,
    "JobNotificationSubscriptions": []
}

This means I can't locate the newly created encoded asset. What am I doing wrong? Is there another way to locate the generated asset?

Body:
The problem wasn't caused by the Request Body but instead the header.

I was passing the header:

Accept: application/json

Instead of the header:

Accept: application/json;odata=verbose

The lack of the odata=verbose means that only a subset of the available data is returned.


问:
Longest substring without repeating characters in python
This is a pretty standard interview question. Find the longest substring without repeating characters. Here are the test cases,

```<code>abcabcbb -> 3
bbbbb -> 1
pwwkew -> 3
bpfbhmipx -> 7
tmmzuxt -> 5
</code>```

Here's my code which uses a pretty simple approach with 2 pointers.

```<code>def lengthOfLongestSubstring(s):
    checklist = {}
    starting_index_of_current_substring = 0
    length_of_longest_substring = 0
    for i, v in enumerate(s):
        if v in checklist:
            starting_index_of_current_substring = checklist[v] + 1
        else:
            length_of_current_substring = i - starting_index_of_current_substring + 1
            length_of_longest_substring = max(length_of_current_substring, length_of_longest_substring)

        checklist[v] = i
    return length_of_longest_substring
</code>```

My code passes all the test cases except the last one (actual 4, expected 5). Can someone help me modify the code to take care of the last test case. I don't wish to reinvent the algorithm.

答:
Here is a simple tweak in your code with 2 pointers to find the longest sub-string without repeating characters.

Change in your code is instead of calculating the length of longest substring when v is not present in checklist, I am calculating length of longest substring for all cases.

```<code>def lengthOfLongestSubstring(s):
    checklist = {}
    starting_index_of_current_substring = 0
    length_of_longest_substring = 0
    for i, v in enumerate(s):
        if v in checklist:
            starting_index_of_current_substring = max(starting_index_of_current_substring, checklist[v] + 1)
        checklist[v] = i
        length_of_longest_substring = max(length_of_longest_substring, i - starting_index_of_current_substring + 1)
    return length_of_longest_substring

## Main
result = {}
for string in ['abcabcbb', 'bbbbb', 'ppwwkew', 'wcabcdeghi', 'bpfbhmipx', 'tmmzuxt', 'AABGAKGIMN', 'stackoverflow']:
    result[string] = lengthOfLongestSubstring(string)
print(result)
</code>```

Sample run:

```<code>{'abcabcbb': 3, 'bbbbb': 1, 'ppwwkew': 3, 'wcabcdeghi': 8, 'bpfbhmipx': 7, 'tmmzuxt': 5, 'AABGAKGIMN': 6, 'stackoverflow': 11}
</code>```

Body:
This is a pretty standard interview question. Find the longest substring without repeating characters. Here are the test cases,

abcabcbb -> 3
bbbbb -> 1
pwwkew -> 3
bpfbhmipx -> 7
tmmzuxt -> 5

Here's my code which uses a pretty simple approach with 2 pointers.

def lengthOfLongestSubstring(s):
    checklist = {}
    starting_index_of_current_substring = 0
    length_of_longest_substring = 0
    for i, v in enumerate(s):
        if v in checklist:
            starting_index_of_current_substring = checklist[v] + 1
        else:
            length_of_current_substring = i - starting_index_of_current_substring + 1
            length_of_longest_substring = max(length_of_current_substring, length_of_longest_substring)

        checklist[v] = i
    return length_of_longest_substring

My code passes all the test cases except the last one (actual 4, expected 5). Can someone help me modify the code to take care of the last test case. I don't wish to reinvent the algorithm.

Body:
Here is a simple tweak in your code with 2 pointers to find the longest sub-string without repeating characters.

Change in your code is instead of calculating the length of longest substring when v is not present in checklist, I am calculating length of longest substring for all cases.

def lengthOfLongestSubstring(s):
    checklist = {}
    starting_index_of_current_substring = 0
    length_of_longest_substring = 0
    for i, v in enumerate(s):
        if v in checklist:
            starting_index_of_current_substring = max(starting_index_of_current_substring, checklist[v] + 1)
        checklist[v] = i
        length_of_longest_substring = max(length_of_longest_substring, i - starting_index_of_current_substring + 1)
    return length_of_longest_substring

## Main
result = {}
for string in ['abcabcbb', 'bbbbb', 'ppwwkew', 'wcabcdeghi', 'bpfbhmipx', 'tmmzuxt', 'AABGAKGIMN', 'stackoverflow']:
    result[string] = lengthOfLongestSubstring(string)
print(result)

Sample run:

{'abcabcbb': 3, 'bbbbb': 1, 'ppwwkew': 3, 'wcabcdeghi': 8, 'bpfbhmipx': 7, 'tmmzuxt': 5, 'AABGAKGIMN': 6, 'stackoverflow': 11}