问:
Cumulatively expand a category to include all previous observations in R
I have this dataframe:

```<code>df = as.data.frame(structure(list(ID = c(1,2,1,2),
                              value = c(10,12,14,16),
                              category = c(1,1,2,2))))
</code>```

And I want to make it into this cumulative dataframe for each category, where each row is inserted in the sequential category:

```<code>desired_df = as.data.frame(structure(list(ID = c(1,2,1,2,1,2),
                              value = c(10,12,10,12,14,16),
                              category = c(1,1,2,2,2,2))))
</code>```

With the desired_df, I want to be able to plot the distribution of observations in each category cumulatively (each category is a time step).

答:
We can loop through the unique elements of 'category', get the sequence, use that to subset the original dataset, transform the category column, and rbind the list elements

```<code>do.call(rbind, lapply(unique(df$category), function(i)
         transform(df[df$category %in% seq_len(i),], category = i)))
#   ID value category
#1  1    10        1
#2  2    12        1
#3  1    10        2
#4  2    12        2
#5  1    14        2
#6  2    16        2
</code>```

Body:
I have this dataframe:

df = as.data.frame(structure(list(ID = c(1,2,1,2),
                              value = c(10,12,14,16),
                              category = c(1,1,2,2))))

And I want to make it into this cumulative dataframe for each category, where each row is inserted in the sequential category:

desired_df = as.data.frame(structure(list(ID = c(1,2,1,2,1,2),
                              value = c(10,12,10,12,14,16),
                              category = c(1,1,2,2,2,2))))

With the desired_df, I want to be able to plot the distribution of observations in each category cumulatively (each category is a time step).

Body:
We can loop through the unique elements of 'category', get the sequence, use that to subset the original dataset, transform the category column, and rbind the list elements

do.call(rbind, lapply(unique(df$category), function(i)
         transform(df[df$category %in% seq_len(i),], category = i)))
#   ID value category
#1  1    10        1
#2  2    12        1
#3  1    10        2
#4  2    12        2
#5  1    14        2
#6  2    16        2


来源: stackexchange

问:
Hoodie postinstall failed: process.env.PWD is undefined
I'm trying to experiment with hoodie, but the npm install isn't working for me.

Windows 10
Node 7.0.0
NPM 3.10.8

```<code>npm ERR! hoodie@28.1.2 postinstall: `node ./bin/setup.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the hoodie@28.1.2 postinstall script 'node ./bin/setup.js'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the hoodie package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     node ./bin/setup.js
npm ERR! You can get information on how to open an issue for this project with:
npm ERR!     npm bugs hoodie
npm ERR! Or if that isn't available, you can get their info via:
npm ERR!     npm owner ls hoodie
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     F:\dev\mrkennedy-ca\countby\npm-debug.log
F:\dev\mrkennedy-ca\countby [gh-pages +0 ~3 -0]> node -v
v7.0.0
F:\dev\mrkennedy-ca\countby [gh-pages +0 ~3 -0]> npm -v
3.10.8
</code>```

The problem is with the post-install script, specifically, process.env.PWD is undefined, but the script is trying to access it:

```<code>> hoodie@28.1.2 postinstall F:\dev\mrkennedy-ca\countby\node_modules\hoodie
> node ./bin/setup.js

F:\dev\mrkennedy-ca\countby\node_modules\hoodie\bin\setup.js:7
var installIntoApp = process.env.PWD.indexOf('node_modules') !== -1
                                ^

TypeError: Cannot read property 'indexOf' of undefined
at Object.<anonymous> (F:\dev\mrkennedy-ca\countby\node_modules\hoodie\bin\setup.js:7:37)
at Module._compile (module.js:573:32)
at Object.Module._extensions..js (module.js:582:10)
at Module.load (module.js:490:32)
at tryModuleLoad (module.js:449:12)
at Function.Module._load (module.js:441:3)
at Module.runMain (module.js:607:10)
at run (bootstrap_node.js:382:7)
at startup (bootstrap_node.js:137:9)
at bootstrap_node.js:497:3
</code>```

Advice? THIS install is inside of an existing package, but I get the same result when attempting the install on a fresh package as in the quickstart directions.

答:
This is caused by a change that was only released a day ago via https://github.com/hoodiehq/hoodie/pull/760. I’ve created an issue that you can follow to be notified when the problem is resolved: https://github.com/hoodiehq/hoodie/issues/763

for the time being, please try npm install --save hoodie@28.1.1 which installs the previous version.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to experiment with hoodie, but the npm install isn't working for me.

Windows 10
Node 7.0.0
NPM 3.10.8

npm ERR! hoodie@28.1.2 postinstall: `node ./bin/setup.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the hoodie@28.1.2 postinstall script 'node ./bin/setup.js'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the hoodie package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     node ./bin/setup.js
npm ERR! You can get information on how to open an issue for this project with:
npm ERR!     npm bugs hoodie
npm ERR! Or if that isn't available, you can get their info via:
npm ERR!     npm owner ls hoodie
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     F:\dev\mrkennedy-ca\countby\npm-debug.log
F:\dev\mrkennedy-ca\countby [gh-pages +0 ~3 -0]> node -v
v7.0.0
F:\dev\mrkennedy-ca\countby [gh-pages +0 ~3 -0]> npm -v
3.10.8

The problem is with the post-install script, specifically, process.env.PWD is undefined, but the script is trying to access it:

> hoodie@28.1.2 postinstall F:\dev\mrkennedy-ca\countby\node_modules\hoodie
> node ./bin/setup.js

F:\dev\mrkennedy-ca\countby\node_modules\hoodie\bin\setup.js:7
var installIntoApp = process.env.PWD.indexOf('node_modules') !== -1
                                ^

TypeError: Cannot read property 'indexOf' of undefined
at Object.<anonymous> (F:\dev\mrkennedy-ca\countby\node_modules\hoodie\bin\setup.js:7:37)
at Module._compile (module.js:573:32)
at Object.Module._extensions..js (module.js:582:10)
at Module.load (module.js:490:32)
at tryModuleLoad (module.js:449:12)
at Function.Module._load (module.js:441:3)
at Module.runMain (module.js:607:10)
at run (bootstrap_node.js:382:7)
at startup (bootstrap_node.js:137:9)
at bootstrap_node.js:497:3

Advice? THIS install is inside of an existing package, but I get the same result when attempting the install on a fresh package as in the quickstart directions.


问:
Difference Windows Azure and GoDaddy
What are all the differences between Microsofts Window's azure and web hosting companies like   GoDaddy, hostgator ? </p>

答:
Azure is like AWS or Google App Engine. They have tons of servers, you buy (cheap) time on them, and serve from them. It's not so much a replacement for webhosting as it is a replacement for a small datacenter.

Your personal website probably doesn't need the kind of on-demand scalability that cloud computing can provide, but a Web startup that can't invest in a datacenter might - and depending on a lot of factors, the economics might work out in favor of it. But perhaps not.

Webhosts are great for static or dynamic content, or databases and so forth. AWS/Azure/GAE are great for when your demand is twice what you'd expected, so you adjust the little slider.

ContentLicense: CC BY-SA 2.5

Title: Difference Windows Azure and GoDaddy


问:
How to pass array as url parameter to Azure Function
Having a bit of problem with Azure Functions parameters
I understood that url parameters are sent as usual to Azure Function "www.asdf.com?myParam=arnold" and being read like this

```<code>req.GetQueryNameValuePairs().FirstOrDefault(q => string.Compare(q.Key, "myParam", true) == 0).Value
</code>```

What i don't understant is how to send array as a parameter.

答:
for complex data I would suggest you to pass it in the body of a POST request as a json, then you can deserialize it in a dynamic object or a Jobject or a custom class you can define. Here is an example from the Azure docs

```<code>#r "Newtonsoft.Json"

using System;
using System.Net;
using System.Threading.Tasks;
using Newtonsoft.Json;

public static async Task<object> Run(HttpRequestMessage req, TraceWriter log)
{
    string jsonContent = await req.Content.ReadAsStringAsync();
    dynamic data = JsonConvert.DeserializeObject(jsonContent);

    log.Info($"WebHook was triggered! Comment: {data.comment.body}");

    return req.CreateResponse(HttpStatusCode.OK, new {
        body = $"New GitHub comment: {data.comment.body}"
    });
}
</code>```

In this example the request body is deserialized in data object. The request body contains a comment property and comment contains a body property as follows

```<code>{
    "comment": {
        "body": "blablabla"
    }
}
</code>```

Of course in the json you can add as many arrays as you need

Hope it helps

Body:
Having a bit of problem with Azure Functions parameters
I understood that url parameters are sent as usual to Azure Function "www.asdf.com?myParam=arnold" and being read like this

req.GetQueryNameValuePairs().FirstOrDefault(q => string.Compare(q.Key, "myParam", true) == 0).Value

What i don't understant is how to send array as a parameter.

Body:
for complex data I would suggest you to pass it in the body of a POST request as a json, then you can deserialize it in a dynamic object or a Jobject or a custom class you can define. Here is an example from the Azure docs

#r "Newtonsoft.Json"

using System;
using System.Net;
using System.Threading.Tasks;
using Newtonsoft.Json;

public static async Task<object> Run(HttpRequestMessage req, TraceWriter log)
{
    string jsonContent = await req.Content.ReadAsStringAsync();
    dynamic data = JsonConvert.DeserializeObject(jsonContent);

    log.Info($"WebHook was triggered! Comment: {data.comment.body}");

    return req.CreateResponse(HttpStatusCode.OK, new {
        body = $"New GitHub comment: {data.comment.body}"
    });
}

In this example the request body is deserialized in data object. The request body contains a comment property and comment contains a body property as follows

{
    "comment": {
        "body": "blablabla"
    }
}

Of course in the json you can add as many arrays as you need

Hope it helps


问:
How can I change the color of one letter in JavaScript?
I have a string and I want to change just one color letter in JavaScript.

HTML:

```<code><div id="lettersList">Hello</div>
</code>```

In my JavaScript file, I retrieve like this (normal)

```<code>var lettres = document.getElementById("lettersList");
</code>```

But I don't know how to change the color of just one word (the 'o' of "hello" for example).
If I change thanks to

for (var i=0; i<lettres.length; i++ { lettres[i].style.color = "yellow"; }

it changes all the text (of course). But I don't want that.

答:
In your code :

```<code> var letters = document.getElementById()
</code>```

you actually retrieve the whole element, not the text in it. That might be the reason that it changed its color totally.

So I suggest you to use

```<code>document.getElementById().innerHtml()
</code>```

.
This function will retrieve the content in your HTML tags (div). Then you do the color changing like

```<code>for(var i = 0; i<letters.length; i++){
    //only change the one you want to
    if(i == 4 // or whatever you like){
        element.innerHTML = element.innerHTML.replace(letters[i], '<span style="color: yellow;">'+letters[i]+'</span>');
    }
}
</code>```

Body:
I have a string and I want to change just one color letter in JavaScript.

HTML:

Hello

In my JavaScript file, I retrieve like this (normal)

var lettres = document.getElementById("lettersList");

But I don't know how to change the color of just one word (the 'o' of "hello" for example).
If I change thanks to

for (var i=0; i<lettres.length; i++ { lettres[i].style.color = "yellow"; }

it changes all the text (of course). But I don't want that.

Body:
In your code :

 var letters = document.getElementById()

you actually retrieve the whole element, not the text in it. That might be the reason that it changed its color totally.

So I suggest you to use

document.getElementById().innerHtml()

.
This function will retrieve the content in your HTML tags (div). Then you do the color changing like

for(var i = 0; i<letters.length; i++){
    //only change the one you want to
    if(i == 4 // or whatever you like){
        element.innerHTML = element.innerHTML.replace(letters[i], '<span style="color: yellow;">'+letters[i]+'</span>');
    }
}


问:
Generating a string hash to compare two substrings

I have a string "abcdbca" and I'm instructed to slice two subarrays, say [0:3] and [4:7], I get strings "abc" and "bca". I've to find out if the two substrings are similar(same elements, max_allowed_mismatch_error = 1).

I tried count sort, but it's not that much of optimization. So, I though the next more optimized method could be hashing. But I can't figure out hash function to accurately solve the problem. I need to perform the operation several times.

答:
Hashing is no good.

There are two solutions, the simple one, which is to insist that the sub strings be of equal length and count equal characters, and the complex one, which is to use an alignment algorithm like Needleman-Wunch. That will give a much more robust idea of string similarity.


问:
Pragmatic Way to Store String Formats
Suppose I have a protocol that accepts a string in the form:

```<code>static final String PROTOCOL_FORMAT = "%s%sT%s%sT%s%s%s%s%s%s%s%s%s%s";
</code>```

Where every %s refers to some piece of data that must substituted into the format in order to complete the message.

Personally, I find storing the format in this sort of string substitution to be quite hard to read. Is there any standard way to handle stuff like this? How could I make this more expressive? The only thing I can think of is abstracting the PROTOCOL_FORMAT out to its own class.

Edit (Example of usage):

```<code>String.format("%s%sT%s%sT%s%s%s%s%s%s%s%s%s%s",
              data1,data2,data3...);
</code>```

Where every every piece data{n} could contain different information from every other piece.

```<code>Output:12T12T1234567890
</code>```

However, that last 0 could easily be 99999999 - or any string of any length.

答:
I found a pragmatic way to go about building the message format. In this case, it's best to use a builder class to construct the message on the fly. The MESSAGE_FORMAT is stored in the builder.

What I did was create a MessageBuilder class that has methods which slowly fill in the required data. For those unfamiliar, this is the builder design pattern.

For example:

```<code>String message = MessageBuilder()
    .displayValue(123)
    .lightColorOne(RED)
    .lightColorTwo(GREEN)
    .lightColorThree(BLUE)
    .build();
</code>```

message >> "12T12T1234567890"

Title: Pragmatic Way to Store String Formats

Body:
Suppose I have a protocol that accepts a string in the form:

static final String PROTOCOL_FORMAT = "%s%sT%s%sT%s%s%s%s%s%s%s%s%s%s";

Where every %s refers to some piece of data that must substituted into the format in order to complete the message.

Personally, I find storing the format in this sort of string substitution to be quite hard to read. Is there any standard way to handle stuff like this? How could I make this more expressive? The only thing I can think of is abstracting the PROTOCOL_FORMAT out to its own class.

Edit (Example of usage):

String.format("%s%sT%s%sT%s%s%s%s%s%s%s%s%s%s",
              data1,data2,data3...);

Where every every piece data{n} could contain different information from every other piece.

Output:12T12T1234567890

However, that last 0 could easily be 99999999 - or any string of any length.

Body:
I found a pragmatic way to go about building the message format. In this case, it's best to use a builder class to construct the message on the fly. The MESSAGE_FORMAT is stored in the builder.

What I did was create a MessageBuilder class that has methods which slowly fill in the required data. For those unfamiliar, this is the builder design pattern.

For example:

String message = MessageBuilder()
    .displayValue(123)
    .lightColorOne(RED)
    .lightColorTwo(GREEN)
    .lightColorThree(BLUE)
    .build();

message >> "12T12T1234567890"


问:
BeautifulSoup Parse Text after  and before

I have this code trying to parse search results from a grant website (please find the URL in the code, I can't post the link yet until my rep is higher), the "Year"and "Amount Award" after  tags and before  tags.

Two questions:

1) Why is this only returning the 1st table?

2) Any way I can get the text that is after the  (i.e. Year and Amount Award strings) and  (i.e. the actual number such as 2015 and $100000)

Specifically:

                Year: 2014

                Award Amount: $84,907                                                                                ```
</div>
</div>
</p>

<p>Here is my script:</p>

```import requests
from bs4 import BeautifulSoup
import pandas as pd

url = 'http://www.ned.org/wp-content/themes/ned/search/grant-search.php?' \
    'organizationName=&region=ASIA&projectCountry=China&amount=&fromDate=&toDate=&' \
    'projectFocus%5B%5D=&search=&maxCount=25&orderBy=Year&start=1&sbmt=1'

r = requests.get(url)

html_content = r.text

soup = BeautifulSoup(html_content, "html.parser")

tables = soup.find_all('table')

data = {
        'col_names': [],
        'info' : [],
        'year_amount':[]
        }

index = 0

for table in tables:
    rows = table.find_all('tr')[1:]
    for row in rows:
        cols = row.find_all('td')
        data['col_names'].append(cols[0].get_text())
        data['info'].append(cols[1].get_text())
        try:
            data['year_amount'].append(cols[2].get_text())
        except IndexError:
            data['year_amount'].append(None)
    grant_df = pd.DataFrame(data)
    index += 1
    filename = 'grant ' + str(index) + '.csv'
    grant_df.to_csv(filename)
```

答:
I would suggest approaching the table parsing in a different manner.  All of the information is available in the first row of each table.  So you can parse the text of the row like:

Code:

```<code>text = '\n'.join([x.strip() for x in rows[0].get_text().split('\n')
                  if x.strip()]).replace(':\n', ': ')
data_dict = {k.strip(): v.strip() for k, v in
             [x.split(':', 1) for x in text.split('\n')]}
</code>```

How?:

This takes the text and

splits it on newlines

removes any blank lines

removes any leading/trailing space

joins the lines back together into a single text

joins any line ending in : with the next line

Then:

split the text again by newline

split each line by :

strip any whitespace of ends of text on either side of :

use the split text as key and value to a dict

Test Code:

```<code>import requests
from bs4 import BeautifulSoup
import pandas as pd

url = 'http://www.ned.org/wp-content/themes/ned/search/grant-search.php?' \
      'organizationName=&region=ASIA&projectCountry=China&amount=&' \
      'fromDate=&toDate=&projectFocus%5B%5D=&search=&maxCount=25&' \
      'orderBy=Year&start=1&sbmt=1'

r = requests.get(url)
soup = BeautifulSoup(r.text, "html.parser")

data = []
for table in soup.find_all('table'):
    rows = table.find_all('tr')
    text = '\n'.join([x.strip() for x in rows[0].get_text().split('\n')
                      if x.strip()]).replace(':\n', ': ')
    data_dict = {k.strip(): v.strip() for k, v in
                 [x.split(':', 1) for x in text.split('\n')]}

    if data_dict.get('Award Amount'):
        data.append(data_dict)
grant_df = pd.DataFrame(data)
print(grant_df.head())
</code>```

Results:

```<code>  Award Amount                                        Description  \
0      $84,907  To strengthen the capacity of China's rights d...
1     $204,973  To provide an effective forum for free express...
2      $48,000  To promote religious freedom in China. The org...
3      $89,000  To educate and train civil society activists o...
4      $65,000  To encourage greater public discussion, transp...

            Organization Name Project Country                Project Focus  \
0                         NaN  Mainland China                  Rule of Law
1  Princeton China Initiative  Mainland China       Freedom of Information
2                         NaN  Mainland China                  Rule of Law
3                         NaN  Mainland China  Democratic Ideas and Values
4                         NaN  Mainland China                  Rule of Law

  Project Region                                      Project Title  Year
0           Asia             Empowering the Chinese Legal Community  2014
1           Asia  Supporting Free Expression and Open Debate for...  2014
2           Asia  Religious Freedom, Rights Defense and Rule of ...  2014
3           Asia     Education on Civil Society and Democratization  2014
4           Asia        Promoting Democratic Policy Change in China  2014
</code>```

Title: BeautifulSoup Parse Text after <b> and before </br>

Body:
I have this code trying to parse search results from a grant website (please find the URL in the code, I can't post the link yet until my rep is higher), the "Year"and "Amount Award" after  tags and before  tags.

Two questions:

1) Why is this only returning the 1st table?

2) Any way I can get the text that is after the  (i.e. Year and Amount Award strings) and  (i.e. the actual number such as 2015 and $100000)

Specifically:

                Year: 2014

                Award Amount: $84,907

Here is my script:

import requests
from bs4 import BeautifulSoup
import pandas as pd

url = 'http://www.ned.org/wp-content/themes/ned/search/grant-search.php?' \
    'organizationName=&region=ASIA&projectCountry=China&amount=&fromDate=&toDate=&' \
    'projectFocus%5B%5D=&search=&maxCount=25&orderBy=Year&start=1&sbmt=1'

r = requests.get(url)

html_content = r.text

soup = BeautifulSoup(html_content, "html.parser")

tables = soup.find_all('table')

data = {
        'col_names': [],
        'info' : [],
        'year_amount':[]
        }

index = 0

for table in tables:
    rows = table.find_all('tr')[1:]
    for row in rows:
        cols = row.find_all('td')
        data['col_names'].append(cols[0].get_text())
        data['info'].append(cols[1].get_text())
        try:
            data['year_amount'].append(cols[2].get_text())
        except IndexError:
            data['year_amount'].append(None)
    grant_df = pd.DataFrame(data)
    index += 1
    filename = 'grant ' + str(index) + '.csv'
    grant_df.to_csv(filename)

Body:
I would suggest approaching the table parsing in a different manner.  All of the information is available in the first row of each table.  So you can parse the text of the row like:

Code:

text = '\n'.join([x.strip() for x in rows[0].get_text().split('\n')
                  if x.strip()]).replace(':\n', ': ')
data_dict = {k.strip(): v.strip() for k, v in
             [x.split(':', 1) for x in text.split('\n')]}

How?:

This takes the text and

splits it on newlines

removes any blank lines

removes any leading/trailing space

joins the lines back together into a single text

joins any line ending in : with the next line

Then:

split the text again by newline

split each line by :

strip any whitespace of ends of text on either side of :

use the split text as key and value to a dict

Test Code:

import requests
from bs4 import BeautifulSoup
import pandas as pd

url = 'http://www.ned.org/wp-content/themes/ned/search/grant-search.php?' \
      'organizationName=&region=ASIA&projectCountry=China&amount=&' \
      'fromDate=&toDate=&projectFocus%5B%5D=&search=&maxCount=25&' \
      'orderBy=Year&start=1&sbmt=1'

r = requests.get(url)
soup = BeautifulSoup(r.text, "html.parser")

data = []
for table in soup.find_all('table'):
    rows = table.find_all('tr')
    text = '\n'.join([x.strip() for x in rows[0].get_text().split('\n')
                      if x.strip()]).replace(':\n', ': ')
    data_dict = {k.strip(): v.strip() for k, v in
                 [x.split(':', 1) for x in text.split('\n')]}

    if data_dict.get('Award Amount'):
        data.append(data_dict)
grant_df = pd.DataFrame(data)
print(grant_df.head())

Results:

  Award Amount                                        Description  \
0      $84,907  To strengthen the capacity of China's rights d...
1     $204,973  To provide an effective forum for free express...
2      $48,000  To promote religious freedom in China. The org...
3      $89,000  To educate and train civil society activists o...
4      $65,000  To encourage greater public discussion, transp...

            Organization Name Project Country                Project Focus  \
0                         NaN  Mainland China                  Rule of Law
1  Princeton China Initiative  Mainland China       Freedom of Information
2                         NaN  Mainland China                  Rule of Law
3                         NaN  Mainland China  Democratic Ideas and Values
4                         NaN  Mainland China                  Rule of Law

  Project Region                                      Project Title  Year
0           Asia             Empowering the Chinese Legal Community  2014
1           Asia  Supporting Free Expression and Open Debate for...  2014
2           Asia  Religious Freedom, Rights Defense and Rule of ...  2014
3           Asia     Education on Civil Society and Democratization  2014
4           Asia        Promoting Democratic Policy Change in China  2014


问:
Problems with php display folders in template
everyone!
I want to display folder's name in the table in HTML template.

PHP:

```<code>$path = "albums/";
$albums = scandir($path);
$skip = array('.', '..')

;
</code>```

HTML template:

```<code><table>
    <tr>
        <th>Альбом</th>
        <th colspan="2">Операции</th>
    </tr>

    <? foreach ($albums as $album): ?>
    <tr>
        <td>
            <?php print $album ?>
        </td>
        <td>
            <a href="#">
                Редактировать
            </a>
        </td>
        <td>
            <a href="#">
                Удалить
            </a>
        </td>
    </tr>
    <? endforeach ?>
</table>
</code>```

Unfortunately, I get the error like this:

Notice: Undefined variable: album in D:\xampp\htdocs\homework\5\view\albums.html on line 20

How can I display folders' name correctly? What was a mistake?

答:
It's because you have short tags disabled. Try this.</p>

```<code><?php
$path = "albums/";
$albums = scandir($path);
$skip = array('.', '..');
?>
<table>
    <tr>
        <th>Альбом</th>
        <th colspan="2">Операции</th>
    </tr>

    <?php foreach ($albums as $album): ?>
    <tr>
        <td>
            <?php print $album ?>
        </td>
        <td>
            <a href="#">
                Редактировать
            </a>
        </td>
        <td>
            <a href="#">
                Удалить
            </a>
        </td>
    </tr>
    <?php endforeach ?>
</table>
</code>```

Body:
everyone!
I want to display folder's name in the table in HTML template.

PHP:

$path = "albums/";
$albums = scandir($path);
$skip = array('.', '..')

;

HTML template:

        Альбом
        Операции

    <? foreach ($albums as $album): ?>

            <?php print $album ?>

                Редактировать

                Удалить

    <? endforeach ?>

Unfortunately, I get the error like this:

Notice: Undefined variable: album in D:\xampp\htdocs\homework\5\view\albums.html on line 20

How can I display folders' name correctly? What was a mistake?

Body:
It's because you have short tags disabled. Try this.

<?php
$path = "albums/";
$albums = scandir($path);
$skip = array('.', '..');
?>
<table>
    <tr>
        <th>Альбом</th>
        <th colspan="2">Операции</th>
    </tr>

    <?php foreach ($albums as $album): ?>
    <tr>
        <td>
            <?php print $album ?>
        </td>
        <td>
            <a href="#">
                Редактировать
            </a>
        </td>
        <td>
            <a href="#">
                Удалить
            </a>
        </td>
    </tr>
    <?php endforeach ?>
</table>


问:
Android set up Volley to use from cache
I'm trying to create and use a cache for a server JSON response.

For example:

cache JSON objects to internal memory and use that when we don't have an internet connection.

In the following sample code, I can not find any document about how to cache it with Volley and reuse that when server header for update again don't expire.

Like this: set expiration to header and use cache and try to load again after expiration.

I'm trying to set cache mechanism for this method:

```<code>private void makeJsonArryReq() {
    JsonArrayRequest req = new JsonArrayRequest(Const.URL_JSON_ARRAY,
            new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {
                    msgResponse.setText(response.toString());
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
        }
    });
    AppController.getInstance().addToRequestQueue(req,tag_json_arry);
}
</code>```

Cache method:

```<code>public static Cache.Entry parseIgnoreCacheHeaders(NetworkResponse response) {
    long now = System.currentTimeMillis();

    Map<String, String> headers = response.headers;
    long serverDate = 0;
    String serverEtag = null;
    String headerValue;

    headerValue = headers.get("Date");
    if (headerValue != null) {
        serverDate = HttpHeaderParser.parseDateAsEpoch(headerValue);
    }

    serverEtag = headers.get("ETag");

    final long cacheHitButRefreshed = 3 * 60 * 1000; // in 3 minutes cache will be hit, but also refreshed on background
    final long cacheExpired = 24 * 60 * 60 * 1000; // in 24 hours this cache entry expires completely
    final long softExpire = now + cacheHitButRefreshed;
    final long ttl = now + cacheExpired;

    Cache.Entry entry = new Cache.Entry();
    entry.data = response.data;
    entry.etag = serverEtag;
    entry.softTtl = softExpire;
    entry.ttl = ttl;
    entry.serverDate = serverDate;
    entry.responseHeaders = headers;

    return entry;
}
</code>```

答:
If the response is taking from server using String Request then just Replace the Line

```<code>return Response.success(new JSONObject(jsonString), cacheEntry);
</code>```

with this

```<code>return Response.success(new String(jsonString), cacheEntry);
</code>```

It works in my case. Try in your own code.

Title: Android set up Volley to use from cache

Body:
I'm trying to create and use a cache for a server JSON response.

For example:

cache JSON objects to internal memory and use that when we don't have an internet connection.

In the following sample code, I can not find any document about how to cache it with Volley and reuse that when server header for update again don't expire.

Like this: set expiration to header and use cache and try to load again after expiration.

I'm trying to set cache mechanism for this method:

private void makeJsonArryReq() {
    JsonArrayRequest req = new JsonArrayRequest(Const.URL_JSON_ARRAY,
            new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {
                    msgResponse.setText(response.toString());
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
        }
    });
    AppController.getInstance().addToRequestQueue(req,tag_json_arry);
}

Cache method:

public static Cache.Entry parseIgnoreCacheHeaders(NetworkResponse response) {
    long now = System.currentTimeMillis();

    Map<String, String> headers = response.headers;
    long serverDate = 0;
    String serverEtag = null;
    String headerValue;

    headerValue = headers.get("Date");
    if (headerValue != null) {
        serverDate = HttpHeaderParser.parseDateAsEpoch(headerValue);
    }

    serverEtag = headers.get("ETag");

    final long cacheHitButRefreshed = 3 * 60 * 1000; // in 3 minutes cache will be hit, but also refreshed on background
    final long cacheExpired = 24 * 60 * 60 * 1000; // in 24 hours this cache entry expires completely
    final long softExpire = now + cacheHitButRefreshed;
    final long ttl = now + cacheExpired;

    Cache.Entry entry = new Cache.Entry();
    entry.data = response.data;
    entry.etag = serverEtag;
    entry.softTtl = softExpire;
    entry.ttl = ttl;
    entry.serverDate = serverDate;
    entry.responseHeaders = headers;

    return entry;
}

Body:
If the response is taking from server using String Request then just Replace the Line

return Response.success(new JSONObject(jsonString), cacheEntry);

with this

return Response.success(new String(jsonString), cacheEntry);

It works in my case. Try in your own code.


问:
Display names using matching ID from two tables and returning a name value from the one pool of names
I have two tables. Using SQL I want to find the names from the one pool of names. e.g.:

```<code>if foodid1 = foodID return foodName,
if foodid2 = foodID return foodName,
if foodid3 = foodid return foodname
</code>```

My tables look like:

```<code>food table               order table
FoodID   FoodName        OrderID   FoodID1   FoodID2    FoodID3
1         chicken           1        1         2           3
2          fish             2        3         4           5
3          lamb             3        1         3           2
4          pie
5         steak
</code>```

I want a query that returns a value something like:

```<code>OrderID    FoodID1   FooDID2   FoodID3
1          chicken   fish      lamb
2          lamb      pie       steak
3          chicken   lamb      fish
</code>```

I can get it to display the related IDs and the first set of names but I get errors when I alter the code for more. Not sure on the correct syntax for this query.

```<code>SELECT [ORDER TABLE].OID, [ORDER TABLE].FID1, [FOOD TABLE].[Food Name], [ORDER TABLE].FID2
FROM [FOOD TABLE] INNER JOIN [ORDER TABLE] ON [FOOD TABLE].[FID] = [ORDER TABLE].[FID2];
</code>```

答:
You need to join the [order table] on the [food table] thrice, once for each FoodId:

```<code>SELECT     o.[OrderId], f1.[Food Name], f2.[Food Name], f3.[Food Name]
FROM       [ORDER TABLE] o
INNER JOIN [FOOD TABLE] f1 ON o.[FoodId1] = f1.[FoodId]
INNER JOIN [FOOD TABLE] f2 ON o.[FoodId2] = f2.[FoodId]
INNER JOIN [FOOD TABLE] f3 ON o.[FoodId3] = f3.[FoodId]
</code>```

Body:
I have two tables. Using SQL I want to find the names from the one pool of names. e.g.:

if foodid1 = foodID return foodName,
if foodid2 = foodID return foodName,
if foodid3 = foodid return foodname

My tables look like:

food table               order table
FoodID   FoodName        OrderID   FoodID1   FoodID2    FoodID3
1         chicken           1        1         2           3
2          fish             2        3         4           5
3          lamb             3        1         3           2
4          pie
5         steak

I want a query that returns a value something like:

OrderID    FoodID1   FooDID2   FoodID3
1          chicken   fish      lamb
2          lamb      pie       steak
3          chicken   lamb      fish

I can get it to display the related IDs and the first set of names but I get errors when I alter the code for more. Not sure on the correct syntax for this query.

SELECT [ORDER TABLE].OID, [ORDER TABLE].FID1, [FOOD TABLE].[Food Name], [ORDER TABLE].FID2
FROM [FOOD TABLE] INNER JOIN [ORDER TABLE] ON [FOOD TABLE].[FID] = [ORDER TABLE].[FID2];

Body:
You need to join the [order table] on the [food table] thrice, once for each FoodId:

SELECT     o.[OrderId], f1.[Food Name], f2.[Food Name], f3.[Food Name]
FROM       [ORDER TABLE] o
INNER JOIN [FOOD TABLE] f1 ON o.[FoodId1] = f1.[FoodId]
INNER JOIN [FOOD TABLE] f2 ON o.[FoodId2] = f2.[FoodId]
INNER JOIN [FOOD TABLE] f3 ON o.[FoodId3] = f3.[FoodId]


问:
How do I index every Nth element of an array in Fortran?
I am struggling to index every nth element of an array in Fortran.

I have an array of 24 hours x 365 days x 91 steps of latitude, which I have declared as

```<code> integer, dimension(1:24, 1:365, 1:91) :: my_array
</code>```

I now would like to pick only every nth (lets say 10th) degree of latitude do reduce the resolution and write them no a second array

```<code>integer, dimension(1:24, 1:365, 1:10) :: my_new_array
</code>```

I have no problem writing any 10 consecutive degrees of latitude to the new array e.g.

```<code>my_new_array = my_array(:,:,50:60)
</code>```

but cant figure out how to do it with every nth element. In R or Matlab I would simply write a sequence from 1 to 91 by steps of 10, however that doesn't work for Fortran.

答:
You can add a third element to the array slice:

```<code>my_new_array = my_array(:,:,1:91:10)
</code>```

See section 6.5.3 Array elements and array sections in the Fortran Standard.

Since this is latitude, you might want to consider going from 0 to 90:

```<code>integer, dimension(1:24, 1:365, 0:90) :: my_array
</code>```

And if you are doing the southern hemisphere, too:

```<code>integer, dimension(1:24, 1:365, -90:90) :: my_array
</code>```

Body:
I am struggling to index every nth element of an array in Fortran.

I have an array of 24 hours x 365 days x 91 steps of latitude, which I have declared as

 integer, dimension(1:24, 1:365, 1:91) :: my_array

I now would like to pick only every nth (lets say 10th) degree of latitude do reduce the resolution and write them no a second array

integer, dimension(1:24, 1:365, 1:10) :: my_new_array

I have no problem writing any 10 consecutive degrees of latitude to the new array e.g.

my_new_array = my_array(:,:,50:60)

but cant figure out how to do it with every nth element. In R or Matlab I would simply write a sequence from 1 to 91 by steps of 10, however that doesn't work for Fortran.

Body:
You can add a third element to the array slice:

my_new_array = my_array(:,:,1:91:10)

See section 6.5.3 Array elements and array sections in the Fortran Standard.

Since this is latitude, you might want to consider going from 0 to 90:

integer, dimension(1:24, 1:365, 0:90) :: my_array

And if you are doing the southern hemisphere, too:

integer, dimension(1:24, 1:365, -90:90) :: my_array


问:
Nagios / MySQL error
Ireceived a downtime alert from Nagios that mysql was down on a host. I logged in to the host and found the following error in the mysql error.log file. What are the proper steps to troubleshoot this?</p>

```<code>root@ubuntu:/var/log# tail -f mysql/error.log
101202 11:09:21 [ERROR] Can't open the mysql.plugin table. Please run
                        mysql_upgrade to create it.
101202 11:09:21  InnoDB: Started; log sequence number 0 44233
101202 11:09:21 [ERROR] /usr/sbin/mysqld: Can't find file: './mysql/host.frm'
                        (errno: 13)
101202 11:09:21 [ERROR] Fatal error: Can't open and lock privilege tables:
                        Can't find file: './mysql/host.frm' (errno: 13)
101202 11:09:51 [Note] Plugin 'FEDERATED' is disabled.
                       /usr/sbin/mysqld: Can't find file: './mysql/plugin.frm'
                       (errno: 13)
101202 11:09:51 [ERROR] Can't open the mysql.plugin table. Please run
                        mysql_upgrade to create it.
101202 11:09:52  InnoDB: Started; log sequence number 0 44233
101202 11:09:52 [ERROR] /usr/sbin/mysqld: Can't find file: './mysql/host.frm'
                        (errno: 13)
101202 11:09:52 [ERROR] Fatal error: Can't open and lock privilege tables:
                        Can't find file: './mysql/host.frm' (errno: 13)
101202 11:10:22 [Note] Plugin 'FEDERATED' is disabled.
                       /usr/sbin/mysqld: Can't find file: './mysql/plugin.frm'
                       (errno: 13)
101202 11:10:22 [ERROR] Can't open the mysql.plugin table. Please run
                        mysql_upgrade to create it.
101202 11:10:22  InnoDB: Started; log sequence number 0 44233
101202 11:10:22 [ERROR] /usr/sbin/mysqld: Can't find file: './mysql/host.frm'
                        (errno: 13)
101202 11:10:22 [ERROR] Fatal error: Can't open and lock privilege tables:
                        Can't find file: './mysql/host.frm' (errno: 13)
</code>```

答: Figure out why MySQL can't find its tables. Go to the MySQL data directory and look for the mysql subdirectory (corresponding to the mysql database which contains things like users, procs, privileges, etc.). Perhaps someone deleted the mysql database. Perhaps someone overwrote your my.cnf configuration file with one pointing to the wrong data directory.

Title: Nagios / MySQL error

Body:
Ireceived a downtime alert from Nagios that mysql was down on a host. I logged in to the host and found the following error in the mysql error.log file. What are the proper steps to troubleshoot this?

root@ubuntu:/var/log# tail -f mysql/error.log
101202 11:09:21 [ERROR] Can't open the mysql.plugin table. Please run
                        mysql_upgrade to create it.
101202 11:09:21  InnoDB: Started; log sequence number 0 44233
101202 11:09:21 [ERROR] /usr/sbin/mysqld: Can't find file: './mysql/host.frm'
                        (errno: 13)
101202 11:09:21 [ERROR] Fatal error: Can't open and lock privilege tables:
                        Can't find file: './mysql/host.frm' (errno: 13)
101202 11:09:51 [Note] Plugin 'FEDERATED' is disabled.
                       /usr/sbin/mysqld: Can't find file: './mysql/plugin.frm'
                       (errno: 13)
101202 11:09:51 [ERROR] Can't open the mysql.plugin table. Please run
                        mysql_upgrade to create it.
101202 11:09:52  InnoDB: Started; log sequence number 0 44233
101202 11:09:52 [ERROR] /usr/sbin/mysqld: Can't find file: './mysql/host.frm'
                        (errno: 13)
101202 11:09:52 [ERROR] Fatal error: Can't open and lock privilege tables:
                        Can't find file: './mysql/host.frm' (errno: 13)
101202 11:10:22 [Note] Plugin 'FEDERATED' is disabled.
                       /usr/sbin/mysqld: Can't find file: './mysql/plugin.frm'
                       (errno: 13)
101202 11:10:22 [ERROR] Can't open the mysql.plugin table. Please run
                        mysql_upgrade to create it.
101202 11:10:22  InnoDB: Started; log sequence number 0 44233
101202 11:10:22 [ERROR] /usr/sbin/mysqld: Can't find file: './mysql/host.frm'
                        (errno: 13)
101202 11:10:22 [ERROR] Fatal error: Can't open and lock privilege tables:
                        Can't find file: './mysql/host.frm' (errno: 13)


问:
How to update each and every keys of redux state by iteration with immutable principle
I have a redux state as follows:-

```<code>data = {"facebook":true,"twitter":false,"google":false,"instagram":false,"watsapp":false}
</code>```

I will be passing the key values in action ex:-("facebook","twitter")

lets say i passed "facebook".
Then I want the state to be updated to

```<code>{"facebook":true,"twitter":false,"google":false,"instagram":false,"watsapp":false}
</code>```

here is my reducer function

```<code>function data = (state=initialstate,action) => {
   return {...state, [action.account]=true}
}
</code>```

For first time, it will give desired result.

```<code>{"facebook":true,"twitter":false,"google":false,"instagram":false,"watsapp":false}
</code>```

Now lets say, I am passing the key "twitter"

What I want:

```<code>{"facebook":false,"twitter":true,"google":false,"instagram":false,"watsapp":false}
</code>```

What I was getting with above reducer function (as expected)

```<code>{"facebook":true,"twitter":true,"google":false,"instagram":false,"watsapp":false}
</code>```

So I updated my reducer function to as following:-

```<code>function data = (state, action) => {
  Object.keys(state).forEach(function(key) {
    if(key!=action.account){
      state[key]=false;
    } else {
      state[key]=true;
    }
   });
  return state
}
</code>```

But this is against redux principle of immutable data.
As I am using selector as well, it is showing some unexpected behaviour.

How to update my reducer function which will set all the previously set values to false and will only set the current key to true keeping in mind immutable data principle of redux

答:
If you're using Underscore,* you could use _.map(state, (v, k) => /* logic that returns true/false */) to produce a new state instance, whilst leaving the previous one untouched.

Note that it feels like a better data model may simply be to store a single string in your state, corresponding to the "current" account.

* Equivalent behaviour is achievable using Object.entries()...., but it's gross and I don't want to figure it out :)

Body:
I have a redux state as follows:-

data = {"facebook":true,"twitter":false,"google":false,"instagram":false,"watsapp":false}

I will be passing the key values in action ex:-("facebook","twitter")

lets say i passed "facebook".
Then I want the state to be updated to

{"facebook":true,"twitter":false,"google":false,"instagram":false,"watsapp":false}

here is my reducer function

function data = (state=initialstate,action) => {
   return {...state, [action.account]=true}
}

For first time, it will give desired result.

{"facebook":true,"twitter":false,"google":false,"instagram":false,"watsapp":false}

Now lets say, I am passing the key "twitter"

What I want:

{"facebook":false,"twitter":true,"google":false,"instagram":false,"watsapp":false}

What I was getting with above reducer function (as expected)

{"facebook":true,"twitter":true,"google":false,"instagram":false,"watsapp":false}

So I updated my reducer function to as following:-

function data = (state, action) => {
  Object.keys(state).forEach(function(key) {
    if(key!=action.account){
      state[key]=false;
    } else {
      state[key]=true;
    }
   });
  return state
}

But this is against redux principle of immutable data.
As I am using selector as well, it is showing some unexpected behaviour.

How to update my reducer function which will set all the previously set values to false and will only set the current key to true keeping in mind immutable data principle of redux


问:
Multiple barplot using ggplot2
According to this example I try to plot the following

Dataset is the following:

```<code>df <- structure(list(year = 2002:2005, work = c(1L, 2L, 3L, 2L), confid = c(8L,
5L, 0L, 6L), jrs = c(0L, 3L, 4L, 5L)), .Names = c("year", "work",
"confid", "jrs"), class = "data.frame", row.names = c(NA, -4L
))
</code>```

The code in order to plot:

```<code>library(ggplot2)
library(reshape)
md <- melt(df, id=(c("year")))
temp.plot<-ggplot(data=md, aes(x=year, y=value, fill=variable) ) +
    geom_bar()+ opts(axis.text.x=theme_text(angle=90)) +
    opts(title = "Score Distribtion")
</code>```

And the error I receive:

```<code>Error: could not find function "opts"
</code>```

I tried to remove the opts() from graph but again I receive the same error.

What could it be the problem?

答:
An updated version of your code using theme in substitution of opts:

```<code>df <- structure(list(year = 2002:2005, work = c(1L, 2L, 3L, 2L), confid = c(8L,
5L, 0L, 6L), jrs = c(0L, 3L, 4L, 5L)), .Names = c("year", "work",
"confid", "jrs"), class = "data.frame", row.names = c(NA, -4L
))

library(ggplot2)
library(reshape)
md <- melt(df, id=(c("year")))
temp.plot <- ggplot(data=md, aes(x=year, y=value, fill=variable) ) +
    geom_bar(stat="identity")+
    theme(axis.text.x=element_text(angle=90))+
    ggtitle("Score Distribtion")

temp.plot
</code>```

Title: Multiple barplot using ggplot2

Body:
According to this example I try to plot the following

Dataset is the following:

df <- structure(list(year = 2002:2005, work = c(1L, 2L, 3L, 2L), confid = c(8L,
5L, 0L, 6L), jrs = c(0L, 3L, 4L, 5L)), .Names = c("year", "work",
"confid", "jrs"), class = "data.frame", row.names = c(NA, -4L
))

The code in order to plot:

library(ggplot2)
library(reshape)
md <- melt(df, id=(c("year")))
temp.plot<-ggplot(data=md, aes(x=year, y=value, fill=variable) ) +
    geom_bar()+ opts(axis.text.x=theme_text(angle=90)) +
    opts(title = "Score Distribtion")

And the error I receive:

Error: could not find function "opts"

I tried to remove the opts() from graph but again I receive the same error.

What could it be the problem?

Body:
An updated version of your code using theme in substitution of opts:

df <- structure(list(year = 2002:2005, work = c(1L, 2L, 3L, 2L), confid = c(8L,
5L, 0L, 6L), jrs = c(0L, 3L, 4L, 5L)), .Names = c("year", "work",
"confid", "jrs"), class = "data.frame", row.names = c(NA, -4L
))

library(ggplot2)
library(reshape)
md <- melt(df, id=(c("year")))
temp.plot <- ggplot(data=md, aes(x=year, y=value, fill=variable) ) +
    geom_bar(stat="identity")+
    theme(axis.text.x=element_text(angle=90))+
    ggtitle("Score Distribtion")

temp.plot


问:
Clojure - Adding pairs of numbers in a vector
I have a vector [1 2 3 4]. Is there a way of adding each pair to get [(+ 1 2) (+ 2 3) (+ 3 4)]

I tried

```<code>(loop [x 0]
  (when (< x (count y))
    (+ (nth y x) (nth y (+ 1 x)))
    (recur (+ x 1))))
</code>```

But I get an out of bounds error IndexOutOfBoundsException   clojure.lang.PersistentVector.arrayFor (PersistentVector.java:158)

答:
Here is a destructuring example:</p>

```<code>(->> [1 2 3 4]
     (partition 2 1)
     (mapv (fn [[f s]] (+ f s))))
</code>```

Body:
I have a vector [1 2 3 4]. Is there a way of adding each pair to get [(+ 1 2) (+ 2 3) (+ 3 4)]

I tried

(loop [x 0]
  (when (< x (count y))
    (+ (nth y x) (nth y (+ 1 x)))
    (recur (+ x 1))))

But I get an out of bounds error IndexOutOfBoundsException   clojure.lang.PersistentVector.arrayFor (PersistentVector.java:158)

Body:
Here is a destructuring example:

(->> [1 2 3 4]
     (partition 2 1)
     (mapv (fn [[f s]] (+ f s))))


问:
Python - filter column from a .dat file and return a given value from other columns
I'm new to Python and been practicing with sample data I created (150 rows) of student ID numbers, grades, age, class_code, area_code, etc. What I'm trying to do with the data is not only filtered by a certain column (by grade, age, etc), but then to also create a list of a different column from that row (student ID). I've manged to find how to isolate the column I need to find the certain value by, but then can't figure out how to create that list of the values I need to return.

So here's a sample of 5 rows of the data:

```<code>1/A/15/13/43214
2/I/15/21/58322
3/C/17/89/68470
4/I/18/6/57362
5/I/14/4/00000
6/A/16/23/34567
</code>```

I need a list of the 1st column (student ID), based on filtering the second column (grade)...(and eventually the 3rd column, 4th column, etc. But if I see how it looks with just the 2nd, I think I can figure out the others) Also note: I didn't use headers in the .dat file.

I figured out how to isolate/view the 2nd column.

```<code>import numpy

data = numpy.genfromtxt('/testdata.dat', delimiter='/', dtype='unicode')

grades = data[:,1]
print (grades)
</code>```

to print:

```<code>['A' 'I' 'C' 'I' 'I' 'A']
</code>```

But now, how can I pull just the first column's that correspond to the A's, C's, I's into separate  lists?

So I'd want to see a list, also with the commas between the integers of column 1 for the A's, C's, and I's

```<code>list from A = [1, 6]
list from C = [3]
list from I = [2, 4, 5]
</code>```

Again, if I can just see how it's done with just the 2nd column, with just one of the values (say A's), I think I could figure out how to do it for B's, C's, D's, etc and probably the other columns. I just need to see one example to how the syntax would be applied and then like to play around with the rest.

Also, I've been using numpy, but also read about panda, csv and I think those libraries could be possibilities too. But like I said, been using numpy for the .dat files. I don't know if the other libraries would be easier to use?

答:
Pandas solution:

```<code>import pandas as pd

df = pd.read_csv('data.txt', header=None, sep='/')
dfs = {k:v for k,v in df.groupby(1)}
</code>```

As a result we have a dictionary of DataFrames:

```<code>In [59]: dfs.keys()
Out[59]: dict_keys(['I', 'C', 'A'])

In [60]: dfs['I']
Out[60]:
   0  1   2   3      4
1  2  I  15  21  58322
3  4  I  18   6  57362
4  5  I  14   4      0

In [61]: dfs['C']
Out[61]:
   0  1   2   3      4
2  3  C  17  89  68470

In [62]: dfs['A']
Out[62]:
   0  1   2   3      4
0  1  A  15  13  43214
5  6  A  16  23  34567
</code>```

If you want to have groupped lists of first columns:

```<code>In [67]: dfs['I'].iloc[:, 0].tolist()
Out[67]: [2, 4, 5]

In [68]: dfs['C'].iloc[:, 0].tolist()
Out[68]: [3]

In [69]: dfs['A'].iloc[:, 0].tolist()
Out[69]: [1, 6]
</code>```

Body:
I'm new to Python and been practicing with sample data I created (150 rows) of student ID numbers, grades, age, class_code, area_code, etc. What I'm trying to do with the data is not only filtered by a certain column (by grade, age, etc), but then to also create a list of a different column from that row (student ID). I've manged to find how to isolate the column I need to find the certain value by, but then can't figure out how to create that list of the values I need to return.

So here's a sample of 5 rows of the data:

1/A/15/13/43214
2/I/15/21/58322
3/C/17/89/68470
4/I/18/6/57362
5/I/14/4/00000
6/A/16/23/34567

I need a list of the 1st column (student ID), based on filtering the second column (grade)...(and eventually the 3rd column, 4th column, etc. But if I see how it looks with just the 2nd, I think I can figure out the others) Also note: I didn't use headers in the .dat file.

I figured out how to isolate/view the 2nd column.

import numpy

data = numpy.genfromtxt('/testdata.dat', delimiter='/', dtype='unicode')

grades = data[:,1]
print (grades)

to print:

['A' 'I' 'C' 'I' 'I' 'A']

But now, how can I pull just the first column's that correspond to the A's, C's, I's into separate  lists?

So I'd want to see a list, also with the commas between the integers of column 1 for the A's, C's, and I's

list from A = [1, 6]
list from C = [3]
list from I = [2, 4, 5]

Again, if I can just see how it's done with just the 2nd column, with just one of the values (say A's), I think I could figure out how to do it for B's, C's, D's, etc and probably the other columns. I just need to see one example to how the syntax would be applied and then like to play around with the rest.

Also, I've been using numpy, but also read about panda, csv and I think those libraries could be possibilities too. But like I said, been using numpy for the .dat files. I don't know if the other libraries would be easier to use?

Body:
Pandas solution:

import pandas as pd

df = pd.read_csv('data.txt', header=None, sep='/')
dfs = {k:v for k,v in df.groupby(1)}

As a result we have a dictionary of DataFrames:

In [59]: dfs.keys()
Out[59]: dict_keys(['I', 'C', 'A'])

In [60]: dfs['I']
Out[60]:
   0  1   2   3      4
1  2  I  15  21  58322
3  4  I  18   6  57362
4  5  I  14   4      0

In [61]: dfs['C']
Out[61]:
   0  1   2   3      4
2  3  C  17  89  68470

In [62]: dfs['A']
Out[62]:
   0  1   2   3      4
0  1  A  15  13  43214
5  6  A  16  23  34567

If you want to have groupped lists of first columns:

In [67]: dfs['I'].iloc[:, 0].tolist()
Out[67]: [2, 4, 5]

In [68]: dfs['C'].iloc[:, 0].tolist()
Out[68]: [3]

In [69]: dfs['A'].iloc[:, 0].tolist()
Out[69]: [1, 6]


问:
More efficient algorithm to find OR of two sets
Given a matrix of n rows and m columns of 1's and 0's, it is required to find out the number of pairs of rows that can be selected so that their OR is 11111....m times.

Example:

```<code>1 0 1 0 1
0 1 0 0 1
1 1 1 1 0
</code>```

Answer:

```<code>2 ---> OR of row number [1,3] and [2,3]
</code>```

Given n and m can be an order upto <= 3000, how efficiently can this problem be solved?

PS: I already tried with a naive O(n*n*m) method. I was thinking of a better solution.

答:
Here is an algorithm that takes advantage of the knowledge that two rows with a zero in the same column are automatically disqualified as partners. The less zeros we have in the present row, the less we visit other rows; but also the more zeros we have overall, the less we visit other rows.

```<code>create two sets, one with a list of indexes of all rows, and the other empty
assign a variable, total = 0
</code>```

Iterate over each row from right to left, from the bottom row to the top (could be in another order, too; I just pictured it that way).

```<code>while row i is not the first row:
  call the non-empty set A and the empty set dont_match
  remove i, the index of the current row, from A

  traverse row i:
    if A is empty:
      stop the traversal
    if a zero is encountered:
      traverse up that column, visiting only rows listed in A:
        if a zero is encountered:
          move that row index from A to dont_match

  the remaining indexes in A point to row partners to row i
  add their count to total and move the elements from the
  shorter of A and dont_match to the other set

return total
</code>```

Body:
Given a matrix of n rows and m columns of 1's and 0's, it is required to find out the number of pairs of rows that can be selected so that their OR is 11111....m times.

Example:

1 0 1 0 1
0 1 0 0 1
1 1 1 1 0

Answer:

2 ---> OR of row number [1,3] and [2,3]

Given n and m can be an order upto <= 3000, how efficiently can this problem be solved?

PS: I already tried with a naive O(n*n*m) method. I was thinking of a better solution.

Body:
Here is an algorithm that takes advantage of the knowledge that two rows with a zero in the same column are automatically disqualified as partners. The less zeros we have in the present row, the less we visit other rows; but also the more zeros we have overall, the less we visit other rows.

create two sets, one with a list of indexes of all rows, and the other empty
assign a variable, total = 0

Iterate over each row from right to left, from the bottom row to the top (could be in another order, too; I just pictured it that way).

while row i is not the first row:
  call the non-empty set A and the empty set dont_match
  remove i, the index of the current row, from A

  traverse row i:
    if A is empty:
      stop the traversal
    if a zero is encountered:
      traverse up that column, visiting only rows listed in A:
        if a zero is encountered:
          move that row index from A to dont_match

  the remaining indexes in A point to row partners to row i
  add their count to total and move the elements from the
  shorter of A and dont_match to the other set

return total


问:
Python subprocess module equivalent for double-click in Windows
I want to open a file using the subprocess module as though the file was double-clicked in Explorer. How do I do that?

I tried the following line:

```<code>subprocess.call("C:/myfile.csv", shell=True)
</code>```

which throws an error saying:

The syntax of the command is
  incorrect.

  'C:\' is not recognized as
  an internal or external command,
  operable program or batch file.

How do I emulate a double-click using subprocess? Basically I want to open a CSV file in Excel 2007.

答:
I think part of your problem is you're using a unix style slash / as a path separator, instead of the windows backslash . It looks like windows is interpreting /myfile.csv as an argument for the program C:, which is why you're getting that message.

However if you corrected that, I think you'd just get it saying that C:\myfile.csv isn't a program.

Body:
I want to open a file using the subprocess module as though the file was double-clicked in Explorer. How do I do that?

I tried the following line:

subprocess.call("C:/myfile.csv", shell=True)

which throws an error saying:

The syntax of the command is
  incorrect.

  'C:\' is not recognized as
  an internal or external command,
  operable program or batch file.

How do I emulate a double-click using subprocess? Basically I want to open a CSV file in Excel 2007.


问:
jquery focus to sibling without focusing out from parent
I am try to iterate through all li elements in ul on keydown event by firing focus() event for next sibling li. In this process, I dont want to focus out from parent ul.
But its not happening. Even changing focus on siblings is causing focusout event on parent. I want that only when someone clicks somewhere else on the screen should focus out of parent be fired.

var KEY_DOWN=40;

$(document).on('keydown', 'li', function(e){
 let keyCode = e.keyCode || e.which;
 if(keyCode == KEY_DOWN)
 {
  if($(this).next().length != 0)
  {
   $(this).next().focus();
  }
  else
  {
   $(this).parent().children().first().focus();
  }
  return false;
 }
});

$(document).on('focusout','ul', function(e)
{
 console.log('focused')
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>li
{
  border: 1px solid black;
}

li:focus
{
  background: #999;
}</code>```

First

Second

Third

```

In the snippet, focused in getting printed on every down key press. How to solve this situation.

答:
Only way I found was to disable focusout event on parent ul when I am trying to focus any li

var KEY_DOWN=40;

$(document).on('keydown', 'li', function(e){
 let keyCode = e.keyCode || e.which;
 if(keyCode == KEY_DOWN)
 {
                $(document).off('blur','ul', doWork);
  if($(this).next().length != 0)
  {
   $(this).next().focus();
  }
  else
  {
   $(this).parent().children().first().focus();
  }
                $(document).on('blur','ul', doWork);
  return false;
 }
});

doWork = function(e)
{
 console.log('focused')
};

$(document).on('blur','ul', doWork);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>li
{
  border: 1px solid black;
}

li:focus
{
  background: #999;
}</code>```

First

Second

Third

```

Body:
I am try to iterate through all li elements in ul on keydown event by firing focus() event for next sibling li. In this process, I dont want to focus out from parent ul.
But its not happening. Even changing focus on siblings is causing focusout event on parent. I want that only when someone clicks somewhere else on the screen should focus out of parent be fired.

var KEY_DOWN=40;

$(document).on('keydown', 'li', function(e){
 let keyCode = e.keyCode || e.which;
 if(keyCode == KEY_DOWN)
 {
  if($(this).next().length != 0)
  {
   $(this).next().focus();
  }
  else
  {
   $(this).parent().children().first().focus();
  }
  return false;
 }
});

$(document).on('focusout','ul', function(e)
{
 console.log('focused')
});

li
{
  border: 1px solid black;
}

li:focus
{
  background: #999;
}

First

Second

Third

In the snippet, focused in getting printed on every down key press. How to solve this situation.

Body:
Only way I found was to disable focusout event on parent ul when I am trying to focus any li

var KEY_DOWN=40;

$(document).on('keydown', 'li', function(e){
 let keyCode = e.keyCode || e.which;
 if(keyCode == KEY_DOWN)
 {
                $(document).off('blur','ul', doWork);
  if($(this).next().length != 0)
  {
   $(this).next().focus();
  }
  else
  {
   $(this).parent().children().first().focus();
  }
                $(document).on('blur','ul', doWork);
  return false;
 }
});

doWork = function(e)
{
 console.log('focused')
};

$(document).on('blur','ul', doWork);

li
{
  border: 1px solid black;
}

li:focus
{
  background: #999;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul tabindex="-1">
<li tabindex="-1">First</li>
<li tabindex="-1">Second</li>
<li tabindex="-1">Third</li>
</ul>


问:
Strange behavior in ajax rails form calculator (pre-filling)
I have ajax rails no database form calculator. It works well, but it behaves very strange. I will try to explain it.

I go to /interest_calculator page

fill_in @first_0 with 10

fill_in @second_0 with 100

I get result equal to:

Number 50 from number 100 = 50%

Then I go to root page

Go back to /interest_calculator

Reload page and my form is pre-filled with previous value. I believe it is buggy behavior.  My JavaScript knowledge is very basic, so detailed response would be very helpful.

InterestCalculator controller:

```<code>class InterestCalculatorController < ApplicationController

  def index
    @result_0 = 0
  end

  def new

    respond_to do |format|
      format.html { render 'index.html.erb' }
      format.js
    end

    # If accepted parameter is integer, then it shows in view as 5, when it
    # is float, it shows as 5.1
    @first_0   = params[:a_0].to_f % 1 != 0 ? params[:a_0].to_f : params[:a_0].to_i
    @second_0  = params[:b_0].to_f % 1 != 0 ? params[:b_0].to_f : params[:b_0].to_i

    # How many percent is number from the number
    number_to_number(@first_0, @second_0)

  end

 private

   def number_to_number(a = 0, b = 0)
    # If the first number is zero, it sends 0% answer. If the second number is zero
    # and the first number is nonzero, it sends infinity. Otherwise simple formula calculation.
    if a.zero?
      @result_0 = 0
    elsif b.zero?
      @result_0 = "infinity"
    else
      @result_0 = a.to_f / b.to_f * 100
    end
  end
end
</code>```

My view index.html.erb

```<code>  <div id="interest_calculator">
    <%= form_for :interest_calculator, url: { action: :new }, method: :get, remote: true do |f|   %>
      <p>Сколько % составляет число</p>
      <%= number_field_tag :a_0, params[:a_0], step: :any, id: "first_number_0" %>
      <p>от числа</p>
      <%= number_field_tag :b_0, params[:b_0], step: :any, id: "second_number_0" %>
      <%= f.submit 'Calculate!', id: "number_to_number" %>
    <% end %>

    <% unless @result_0.nil? %>
      <p>Number <span id="first_0"><%= @first_0 %></span> from number <span id="second_0"><%= @second_0 %></span> = <label id="answer_0"></label>%</p>
    <% end %>
  </div>
</code>```

My new.js.erb

```<code>document.getElementById("answer_0").innerHTML = "<%= @result_0 %>"
document.getElementById("first_0").innerHTML = "<%= @first_0 %>"
document.getElementById("second_0").innerHTML = "<%= @second_0 %>"
</code>```

答:
It may be that the autocomplete pre-fills the values for you, try disabling it in your form:

```<code><%= form_for :interest_calculator, url: { action: :new }, method: :get, autocomplete: false, remote: true do |f| %>
</code>```

Another option will be to use POST method instead of GET.

First, remove method: get from form_for (default method is POST):

```<code><%= form_for :interest_calculator, url: { action: :new }, remote: true do |f| %>
</code>```

Second, update your routes:

```<code>post '/interest_calculator/new'
</code>```

Body:
I have ajax rails no database form calculator. It works well, but it behaves very strange. I will try to explain it.

I go to /interest_calculator page

fill_in @first_0 with 10

fill_in @second_0 with 100

I get result equal to:

Number 50 from number 100 = 50%

Then I go to root page

Go back to /interest_calculator

Reload page and my form is pre-filled with previous value. I believe it is buggy behavior.  My JavaScript knowledge is very basic, so detailed response would be very helpful.

InterestCalculator controller:

class InterestCalculatorController < ApplicationController

  def index
    @result_0 = 0
  end

  def new

    respond_to do |format|
      format.html { render 'index.html.erb' }
      format.js
    end

    # If accepted parameter is integer, then it shows in view as 5, when it
    # is float, it shows as 5.1
    @first_0   = params[:a_0].to_f % 1 != 0 ? params[:a_0].to_f : params[:a_0].to_i
    @second_0  = params[:b_0].to_f % 1 != 0 ? params[:b_0].to_f : params[:b_0].to_i

    # How many percent is number from the number
    number_to_number(@first_0, @second_0)

  end

 private

   def number_to_number(a = 0, b = 0)
    # If the first number is zero, it sends 0% answer. If the second number is zero
    # and the first number is nonzero, it sends infinity. Otherwise simple formula calculation.
    if a.zero?
      @result_0 = 0
    elsif b.zero?
      @result_0 = "infinity"
    else
      @result_0 = a.to_f / b.to_f * 100
    end
  end
end

My view index.html.erb

    <%= form_for :interest_calculator, url: { action: :new }, method: :get, remote: true do |f|   %>

Сколько % составляет число

      <%= number_field_tag :a_0, params[:a_0], step: :any, id: "first_number_0" %>

от числа

      <%= number_field_tag :b_0, params[:b_0], step: :any, id: "second_number_0" %>
      <%= f.submit 'Calculate!', id: "number_to_number" %>
    <% end %>

    <% unless @result_0.nil? %>

Number <%= @first_0 %> from number <%= @second_0 %> = %

    <% end %>

My new.js.erb

document.getElementById("answer_0").innerHTML = "<%= @result_0 %>"
document.getElementById("first_0").innerHTML = "<%= @first_0 %>"
document.getElementById("second_0").innerHTML = "<%= @second_0 %>"

Body:
It may be that the autocomplete pre-fills the values for you, try disabling it in your form:

<%= form_for :interest_calculator, url: { action: :new }, method: :get, autocomplete: false, remote: true do |f| %>

Another option will be to use POST method instead of GET.

First, remove method: get from form_for (default method is POST):

<%= form_for :interest_calculator, url: { action: :new }, remote: true do |f| %>

Second, update your routes:

post '/interest_calculator/new'


问:
android java insertsort using ArrayList
First of all, I'm writing program to visualize sorting algorithms on Android
I wrote method for insertion sort algorithm. I'm using MPAndroidChart for it.

```<code>    void insertionSort(int[] arr) {
    int i, j, newValue;
    for (i = 1; i < arr.length; i++) {
        newValue = arr[i];
        j = i;
        while (j > 0 && arr[j - 1] > newValue) {
            arr[j] = arr[j - 1];
            j--;
        }
        arr[j] = newValue;
    }
}
</code>```

...and it works fine. I want to redesign it to get the same result using ArrayList, but unfortunately, it crashes, and I have no idea why! This is my collection approach insertionSort:

```<code>void insertionSort(ArrayList<BarEntry> list) {
    int i, j;
    float newValue;
    for (i = 1; i < list.size(); i++) {
        newValue = list.get(i).getY();
        j = i;
        while (j > 0 && list.get(j-1).getY() > newValue) {
            list.set(j, list.get(j-1));
            j--;
        }
        BarEntry be = list.get(list.indexOf(newValue));
        list.set(j, be);
    }
}
</code>```

BarEntry is class used to create charts. I want to sort my data by its Y coordinate, what I do by getY() function. Program shuts down there:

BarEntry be = list.get(list.indexOf(newValue));
          list.set(j, be);

In a nutshell:
How can I substitute

arr[j] = newValue;

to collection approach like this (not working):

list.set(j, list.get(list.indexOf(newValue)));

答:
You took newValue out from list.get(i), and i hasn’t changed since, so I believe you can just do that again:

```<code>    BarEntry be = list.get(i);
</code>```

I have not tested.

I suppose what happened was: newValue was the y value from the BarEntry you are moving, it’s not the whole BarEntry. So list.indexOf(newValue) doesn’t find the element and returns -1. list.get(-1) doesn’t work. Your app crashes.

Title: android java insertsort using ArrayList

Body:
First of all, I'm writing program to visualize sorting algorithms on Android
I wrote method for insertion sort algorithm. I'm using MPAndroidChart for it.

    void insertionSort(int[] arr) {
    int i, j, newValue;
    for (i = 1; i < arr.length; i++) {
        newValue = arr[i];
        j = i;
        while (j > 0 && arr[j - 1] > newValue) {
            arr[j] = arr[j - 1];
            j--;
        }
        arr[j] = newValue;
    }
}

...and it works fine. I want to redesign it to get the same result using ArrayList, but unfortunately, it crashes, and I have no idea why! This is my collection approach insertionSort:

void insertionSort(ArrayList<BarEntry> list) {
    int i, j;
    float newValue;
    for (i = 1; i < list.size(); i++) {
        newValue = list.get(i).getY();
        j = i;
        while (j > 0 && list.get(j-1).getY() > newValue) {
            list.set(j, list.get(j-1));
            j--;
        }
        BarEntry be = list.get(list.indexOf(newValue));
        list.set(j, be);
    }
}

BarEntry is class used to create charts. I want to sort my data by its Y coordinate, what I do by getY() function. Program shuts down there:

BarEntry be = list.get(list.indexOf(newValue));
          list.set(j, be);

In a nutshell:
How can I substitute

arr[j] = newValue;

to collection approach like this (not working):

list.set(j, list.get(list.indexOf(newValue)));

Body:
You took newValue out from list.get(i), and i hasn’t changed since, so I believe you can just do that again:

    BarEntry be = list.get(i);

I have not tested.

I suppose what happened was: newValue was the y value from the BarEntry you are moving, it’s not the whole BarEntry. So list.indexOf(newValue) doesn’t find the element and returns -1. list.get(-1) doesn’t work. Your app crashes.


问:
Most deployable way to build a web framework on IIS?
So... I've never used IIS (always Apache), but I'm writing a framework now in C# (because I love C#), so I suspect it will be deployed on IIS (possibly mono/apache), and I'm trying to figure out how I should design it such that it's easy to install.

Most PHP frameworks come with an .htaccess file which sets up the routing, so you basically just extract the files and you're good to go. If I'm not mistaken, I can do something similar enough with web.config. Is that the route to go?

Or is it customary for IIS users to be expected to configure their settings when using a new framework? I'm thinking in terms of Windows-based shared hosting. What would be most compatible?

答: All of your application's configurations will need to be setup in your web.config. You can setup the version of .NET, custom binaries, email settings, custom error pages, etc. with your web.config. It basically tells IIS how to run your application. You can also define custom settings and read them from your application.</p>


问:
How to post user id in two different site using curl
I want to post user id via curl init on two url one is site1/hcomments.php and other that I want to add is site2/hcomments.php

```<code>$ch = curl_init('https://site1/hcomments.php');
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_POST, 1);
curl_setopt ($ch, CURLOPT_POSTFIELDS, "id=$postid");
$hasil = curl_exec ($ch);
curl_close ($ch);
if (strpos($hasil,'GAGAL') !== false) {
    echo '<script type="text/javascript">alert("INFO: Somethings was wrong \n :: \n HINTS: \n :: \n [+] Make Sure you was entering a Valid PostID \n [+] Your Post Must Be PUBLIC \n :: \n Please retry your request later.");</script>';
}else{
}
</code>```

Is this possible r not if not than any other way to do this without opening that file?

答:
Not sure but this should work</p>

```<code>$ch = curl_init('https://flexy.tk/hcomments.php');
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_POST, 1);
curl_setopt ($ch, CURLOPT_POSTFIELDS, "id=$postid");
$hasil = curl_exec ($ch);
curl_close ($ch);

$ch1 = curl_init('https://othersite/hcomments.php');
curl_setopt ($ch1, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch1, CURLOPT_POST, 1);
curl_setopt ($ch1, CURLOPT_POSTFIELDS, "id=$postid");
$hasil1 = curl_exec ($ch1);
curl_close ($ch1);
</code>```

Body:
I want to post user id via curl init on two url one is site1/hcomments.php and other that I want to add is site2/hcomments.php

$ch = curl_init('https://site1/hcomments.php');
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_POST, 1);
curl_setopt ($ch, CURLOPT_POSTFIELDS, "id=$postid");
$hasil = curl_exec ($ch);
curl_close ($ch);
if (strpos($hasil,'GAGAL') !== false) {
    echo '';
}else{
}

Is this possible r not if not than any other way to do this without opening that file?

Body:
Not sure but this should work

$ch = curl_init('https://flexy.tk/hcomments.php');
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_POST, 1);
curl_setopt ($ch, CURLOPT_POSTFIELDS, "id=$postid");
$hasil = curl_exec ($ch);
curl_close ($ch);

$ch1 = curl_init('https://othersite/hcomments.php');
curl_setopt ($ch1, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch1, CURLOPT_POST, 1);
curl_setopt ($ch1, CURLOPT_POSTFIELDS, "id=$postid");
$hasil1 = curl_exec ($ch1);
curl_close ($ch1);


问:
Get parent page on creating new Wagtail Page
I need to change some field default value given a value from the parent page when creating a new page. When editing an existing page, this is not a problem, but when creating a new page, I need to set a default value for a field. I have tried overriding the admin form, on init for WagtailAdminPageForm, the parent_page parameter is empty. And if I try to do it on the init method form Page subclass, there is no arg or kwargs with the parent information.

is there a way to get the page for which the new page will be the parent?

This is what I tried on Page constructor

```<code>class CMSPage(Page):
    .
    .
    .
    def __init__(self, *args, **kwargs):
        super(BaseContentMixin, self).__init__(*args, **kwargs)

        if hasattr(self.get_parent().specific, 'published_site') and self.get_parent().specific.published_site == 'extranet':
            self.published_site = 'extranet'
</code>```

This works editing a page, for new page, I get that NoneType objects has no attribute specific.

Django version is 1.10, Python version is 3.6, Wagtail version is 1.9

答:
I would recommend using the Wagtail Hooks:

http://docs.wagtail.io/en/v1.10.1/reference/hooks.html

Here is a basic example that works (in the Wagtaildemo app), in this example, I am just getting the parent page's title. It should work the same if you are getting something else from the parent's page specific model. Note that this updates the record after it has been created, not as part of the creation itself.

```<code># my_app/wagtail_hooks.py
from wagtail.wagtailcore.models import Page
from wagtail.wagtailcore import hooks

@hooks.register('after_create_page')
def do_after_page_create(request, page):
    # get the parent page from the current page
    parent = page.get_parent().specific
    # get the value from the parent page
    parent_title = parent.title
    # get a new instance of the page that was just created
    new_page = Page.objects.get(id=page.id).specific
    # update the value in the page that was just created & save
    new_page.parent_title = parent_title
    new_page.save()
</code>```

I have used the Wagtail hooks a lot and they work well, you could further refine this by checking the new_page.content_type == "CMSPage" to ensure this only updates pages of that specific model.

Finally, it might be good to look into how Wagtail sites works, this might be a more specific solution to your issue in the example code. You can add extra settings to your Site Model and have multiple Sites in Wagtail. I am not sure if your example was just a rough example or the exact issue you are facing.

Body:
I need to change some field default value given a value from the parent page when creating a new page. When editing an existing page, this is not a problem, but when creating a new page, I need to set a default value for a field. I have tried overriding the admin form, on init for WagtailAdminPageForm, the parent_page parameter is empty. And if I try to do it on the init method form Page subclass, there is no arg or kwargs with the parent information.

is there a way to get the page for which the new page will be the parent?

This is what I tried on Page constructor

class CMSPage(Page):
    .
    .
    .
    def __init__(self, *args, **kwargs):
        super(BaseContentMixin, self).__init__(*args, **kwargs)

        if hasattr(self.get_parent().specific, 'published_site') and self.get_parent().specific.published_site == 'extranet':
            self.published_site = 'extranet'

This works editing a page, for new page, I get that NoneType objects has no attribute specific.

Django version is 1.10, Python version is 3.6, Wagtail version is 1.9

Body:
I would recommend using the Wagtail Hooks:

http://docs.wagtail.io/en/v1.10.1/reference/hooks.html

Here is a basic example that works (in the Wagtaildemo app), in this example, I am just getting the parent page's title. It should work the same if you are getting something else from the parent's page specific model. Note that this updates the record after it has been created, not as part of the creation itself.

# my_app/wagtail_hooks.py
from wagtail.wagtailcore.models import Page
from wagtail.wagtailcore import hooks

@hooks.register('after_create_page')
def do_after_page_create(request, page):
    # get the parent page from the current page
    parent = page.get_parent().specific
    # get the value from the parent page
    parent_title = parent.title
    # get a new instance of the page that was just created
    new_page = Page.objects.get(id=page.id).specific
    # update the value in the page that was just created & save
    new_page.parent_title = parent_title
    new_page.save()

I have used the Wagtail hooks a lot and they work well, you could further refine this by checking the new_page.content_type == "CMSPage" to ensure this only updates pages of that specific model.

Finally, it might be good to look into how Wagtail sites works, this might be a more specific solution to your issue in the example code. You can add extra settings to your Site Model and have multiple Sites in Wagtail. I am not sure if your example was just a rough example or the exact issue you are facing.


问:
Is there a way to see if MySQL database has been accessed through SQL Injection attack?
I recently discovered that my website had a page with a SQL Injection vulnerability. Upon testing, it was easily exploitable with a pentesting tool like sqlmap. How do I figure out if the site database has been accessed with a SQL Injection attack, possibly exploiting this loophole? The server is running Apache/2.4.18 and MySQL Ver 14.14 Distrib 5.7.16.

答:
Without proper logging there is no way to check that.
To mitigate risks, I advise to change passwords and tell your users to change their passwords.</p>


问:
Swift 3. Stop UIView.animate
I'am trying to learn Swift. I use this 2 functions:

```<code>func getRandomColor(){
    let red   = Float((arc4random() % 256)) / 255.0
    let green = Float((arc4random() % 256)) / 255.0
    let blue  = Float((arc4random() % 256)) / 255.0
    let alpha = Float(1.0)
    colours = UIColor(colorLiteralRed: red, green: green, blue: blue, alpha: alpha)

    UIView.animate(withDuration: 2, delay: 1.0, options:[UIViewAnimationOptions.repeat, UIViewAnimationOptions.autoreverse], animations: {
        self.view.backgroundColor = self.colours}, completion:nil)
}

func updateTimer(){
        if seconds! == 0 {
            timer.invalidate()
            isTimerRunning = false
        }
        else {
            seconds! -= 1
            timerLabel.text = timeString(time: TimeInterval(seconds!))
        }
        if seconds! < 55 {
            getRandomColor()
        }
    }
</code>```

When the seconds = 0, the timer stop, but the animation continue. How can stop the animation when the timer is stoped?

答:
In your:

```<code>if seconds! == 0 {
    timer.invalidate()
    isTimerRunning = false
}
</code>```

Add this row:

```<code>self.view.layer.removeAllAnimations()
</code>```

To remove all animations from it.

Title: Swift 3. Stop UIView.animate

Body:
I'am trying to learn Swift. I use this 2 functions:

func getRandomColor(){
    let red   = Float((arc4random() % 256)) / 255.0
    let green = Float((arc4random() % 256)) / 255.0
    let blue  = Float((arc4random() % 256)) / 255.0
    let alpha = Float(1.0)
    colours = UIColor(colorLiteralRed: red, green: green, blue: blue, alpha: alpha)

    UIView.animate(withDuration: 2, delay: 1.0, options:[UIViewAnimationOptions.repeat, UIViewAnimationOptions.autoreverse], animations: {
        self.view.backgroundColor = self.colours}, completion:nil)
}

func updateTimer(){
        if seconds! == 0 {
            timer.invalidate()
            isTimerRunning = false
        }
        else {
            seconds! -= 1
            timerLabel.text = timeString(time: TimeInterval(seconds!))
        }
        if seconds! < 55 {
            getRandomColor()
        }
    }

When the seconds = 0, the timer stop, but the animation continue. How can stop the animation when the timer is stoped?

Body:
In your:

if seconds! == 0 {
    timer.invalidate()
    isTimerRunning = false
}

Add this row:

self.view.layer.removeAllAnimations()

To remove all animations from it.


问:
How to create a list from another list according to a function?
I would like to create a list which has values which correspond to another list.
For example if I had:

```<code>listA = [1, 2, 3, 4, 5,...]
</code>```

and I would like to create another list which is the same, except all the values were varied according to x^2 (or any other function), giving:

```<code>listB = [1, 4, 9, 16,25, ...]
</code>```

I have already tried to do this by doing a while loop:

```<code>listA = [1, 2, 3, 4]
listB = range(1, 4, 1)
i = 0
while i <= 4:
    listB [i] = (listA [i]) ** 2
    i = i + 1
print listA
print listB
</code>```

But it just spits out an error message:

```<code>Traceback (most recent call last):
  File "/home/tim/Desktop/Python/test.py", line 5, in <module>
    listB [i] = (listA [i]) ** 2
IndexError: list assignment index out of range
</code>```

Any advice?
Thanks

答:
Python provides the enumerate function when you need to iterate over a list and need the index. That way you avoid easy-to-avoid IndexErrors like these:

```<code>listA = [1, 2, 3, 4]
listB = [None]*4
for idx, item in enumerate(listA):
    listB[idx] = item ** 2
</code>```

But in most cases you don't even need to create listB beforehand, you could let Python create it for you with map or a "list comprehension". The other answers already covered that but I wanted to share some way of using map without lambda:

```<code>import itertools
listB = list(map(pow, listA, itertools.repeat(2, len(listA))))
</code>```

You can omit the outer list() if you're using python 2.x.

Body:
I would like to create a list which has values which correspond to another list.
For example if I had:

listA = [1, 2, 3, 4, 5,...]

and I would like to create another list which is the same, except all the values were varied according to x^2 (or any other function), giving:

listB = [1, 4, 9, 16,25, ...]

I have already tried to do this by doing a while loop:

listA = [1, 2, 3, 4]
listB = range(1, 4, 1)
i = 0
while i <= 4:
    listB [i] = (listA [i]) ** 2
    i = i + 1
print listA
print listB

But it just spits out an error message:

Traceback (most recent call last):
  File "/home/tim/Desktop/Python/test.py", line 5, in <module>
    listB [i] = (listA [i]) ** 2
IndexError: list assignment index out of range

Any advice?
Thanks

Body:
Python provides the enumerate function when you need to iterate over a list and need the index. That way you avoid easy-to-avoid IndexErrors like these:

listA = [1, 2, 3, 4]
listB = [None]*4
for idx, item in enumerate(listA):
    listB[idx] = item ** 2

But in most cases you don't even need to create listB beforehand, you could let Python create it for you with map or a "list comprehension". The other answers already covered that but I wanted to share some way of using map without lambda:

import itertools
listB = list(map(pow, listA, itertools.repeat(2, len(listA))))

You can omit the outer list() if you're using python 2.x.


问:
Android Studio: Creating new Activity: "package not recognized"
Package On the Left Dropdown Menu

Any idea why this is happening?

答:
It is very simple..
just right click on your package and create new activity.

OR

Just For Your Information if u want to create new layout file then right click on layout folder.....

Just try it


问:
Netlink sockets
I am trying send a list/array of struct to kernel space from userspace. Similar to Link
As recommended there, I am thinking of using sockets for which i found link. Message is set hello in this line

```<code>strcpy(NLMSG_DATA(nlh), "Hello");
</code>```

I tried

```<code>NLMSG_DATA(nlh) = my_list
</code>```

That gave me error: lvalue required as left operand of assignment.

How can I change this to send an array/list using netlinks? If it can't be send this way, how else easily can I do this?

Update

My structure

```<code>typedef struct {
 int val1;
 int val2;
} mystruct;
</code>```

I need to allocate an array/list of these in kernel memory so other system calls can access that list.

答:
NLMSG_DATA() evaluates to a pointer rvalue, so you need to use a copying function like memcpy(NLMSG_DATA(nlh), my_list, sizeof my_list).

The exact details will depend on your data structure.  Presumably you will want to send the number of list entries, then each entry separately.

Title: Netlink sockets

Body:
I am trying send a list/array of struct to kernel space from userspace. Similar to Link
As recommended there, I am thinking of using sockets for which i found link. Message is set hello in this line

strcpy(NLMSG_DATA(nlh), "Hello");

I tried

NLMSG_DATA(nlh) = my_list

That gave me error: lvalue required as left operand of assignment.

How can I change this to send an array/list using netlinks? If it can't be send this way, how else easily can I do this?

Update

My structure

typedef struct {
 int val1;
 int val2;
} mystruct;

I need to allocate an array/list of these in kernel memory so other system calls can access that list.


问:
Update query that should apply numbers to a text field fail
I have a simple update query that should apply numbers to a text field, but it keeps dropping the leading zero. Should be 054846, but ends up as 54846. Can't figure out what I'm missing.

```<code>Dim strsql As String
strsql = "UPDATE [Action]" _
       & "SET [Action] = (" & "054846" & ")"

DoCmd.RunSQL strsql
</code>```

Please help out

答:
Surround number with single qoute '

Dim strsql As String strsql = "UPDATE [Action]" _ & "SET [Action] = '" & "054846" & "' "
 DoCmd.RunSQL strsql

Body:
I have a simple update query that should apply numbers to a text field, but it keeps dropping the leading zero. Should be 054846, but ends up as 54846. Can't figure out what I'm missing.

Dim strsql As String
strsql = "UPDATE [Action]" _
       & "SET [Action] = (" & "054846" & ")"

DoCmd.RunSQL strsql

Please help out


问:
Javascript/HTML5 - Store and display score in local storage
I created a game with a score. Every time that there's a collision, it ads 10 points and when the user has made 16 collisions, the game ends, and the score gets stored in localstorage so it can be displayed on a scoreboard.

```<code>  //everytime there's a collision, contador++
  // when contador reaches 16, there's a pop up and the score is saved in local storage.

  if (contador == 16)  {

  localStorage.setItem("pontosSalvos", pontos);

  var pop = document.getElementById ( "alerta_ajuda");
  pop.style.display = 'inline';
  contador = 0;

          }
</code>```

Then, there's a page for the scoreboard with the following code:

```<code>    //the score gets displayed on a span called mensagem

    function mostraPontos() {
    var pontos = localStorage.getItem ("pontosSalvos");
    var span = document.getElementById ("mensagem_pontos");

    span.innerHTML = pontos;
}
</code>```

What I wanted to know is this:
With the code like this, whenever there's a new score, it replaces the previous score in the scoreboard and it only shows the new score.
Is there a way to store/display multiple scores without replacing the old ones?
Thank you!

答:
The localStorage can only store strings. You can store arrays in it using numerous formats. I would recommend JSON to do this. Have some array with the scores, and when reading from localStorage, JSON.parse it, and when writing, JSON.stringify. You probably want to change the span to an ordered list.</p>

```<code>if (contador == 16)  {
    var pontosArr = JSON.parse(localStorage.pontosSalvos || '[]');
    pontosArr.push(+pontos);
    // Sorts highest to lowest
    pontosArr.sort(function(a, b) { return b - a; });
    localStorage.pontosSalvos = JSON.stringify(pontosArr);

    var pop = document.getElementById ( "alerta_ajuda");
    pop.style.display = 'inline';
    contador = 0;

}
</code>```

```<code>function mostraPontos() {
    // pontos is an empty array if nothing has been stored yet.
    var pontos = JSON.parse(localStorage.pontosSalvos || '[]');
    var ol = document.getElementById("mensagem_pontos");
    ol.innerHTML = '';
    // Appends all the scores as list elements
    for (var i = 0; i < pontos.length; i++) {
        var li = document.createElement('li');
        li.textContent = pontos[i];
        ol.appendChild(li);
    }
}
</code>```

Body:
I created a game with a score. Every time that there's a collision, it ads 10 points and when the user has made 16 collisions, the game ends, and the score gets stored in localstorage so it can be displayed on a scoreboard.

  //everytime there's a collision, contador++
  // when contador reaches 16, there's a pop up and the score is saved in local storage.

  if (contador == 16)  {

  localStorage.setItem("pontosSalvos", pontos);

  var pop = document.getElementById ( "alerta_ajuda");
  pop.style.display = 'inline';
  contador = 0;

          }

Then, there's a page for the scoreboard with the following code:

    //the score gets displayed on a span called mensagem

    function mostraPontos() {
    var pontos = localStorage.getItem ("pontosSalvos");
    var span = document.getElementById ("mensagem_pontos");

    span.innerHTML = pontos;
}

What I wanted to know is this:
With the code like this, whenever there's a new score, it replaces the previous score in the scoreboard and it only shows the new score.
Is there a way to store/display multiple scores without replacing the old ones?
Thank you!

Body:
The localStorage can only store strings. You can store arrays in it using numerous formats. I would recommend JSON to do this. Have some array with the scores, and when reading from localStorage, JSON.parse it, and when writing, JSON.stringify. You probably want to change the span to an ordered list.

if (contador == 16)  {
    var pontosArr = JSON.parse(localStorage.pontosSalvos || '[]');
    pontosArr.push(+pontos);
    // Sorts highest to lowest
    pontosArr.sort(function(a, b) { return b - a; });
    localStorage.pontosSalvos = JSON.stringify(pontosArr);

    var pop = document.getElementById ( "alerta_ajuda");
    pop.style.display = 'inline';
    contador = 0;

}

function mostraPontos() {
    // pontos is an empty array if nothing has been stored yet.
    var pontos = JSON.parse(localStorage.pontosSalvos || '[]');
    var ol = document.getElementById("mensagem_pontos");
    ol.innerHTML = '';
    // Appends all the scores as list elements
    for (var i = 0; i < pontos.length; i++) {
        var li = document.createElement('li');
        li.textContent = pontos[i];
        ol.appendChild(li);
    }
}