问:
Changing ASP.NET InProc session state mode into State Server or SQL Server State
First, I am new to Web app programming. I come from Desktop apps (WinForms & WPF).
Recently I have been assigned a project that was made in the past by ohter people. This project is done in ASP.NET MVC and it uses an InProc session state mode.

Now, I want to build a web gardening, that is, use multiple worker process for the application pool. I have googled and I have discovered that InProc session does not work with web gardening because each worker process within app pool uses its own session state. So I am planning to switch it into another session state mode such as State Server or SQL Server.

Now I have a doubt. Apart from changing session state mode in Web.config:

```<code><configuration>
  <system.web>
    <sessionState mode="InProc" timeout="25"></sessionState>
  </system.web>
</configuration>
</code>```

... Do I need to do some extra work? for example reprogramming the ASP.NET MVC app, configuration or some other things in order it to work?

Below I share some interesting links:

Configuring Server and SQL Server State

HOW TO: Configure SQL Server to Store ASP.NET Session State

答:
For web farms you should keep your session either in StateServer  or Sql Server.
 To do so you need to add following configuration

```<code>     <connectionStrings>
           <add name="ConnectionString1"
           connectionString="Data Source=YourServer;Initial
           Catalog=SessionDatabase;Integrated Security=True"
           providerName="System.Data.SqlClient" />
    </connectionStrings>

<!--Change your <sessionState mode="InProc" timeout="25"></sessionState>  to this.-->

<sessionState mode="SQLServer" customProvider="DefaultSessionProvider">
  <providers>
    <add name="DefaultSessionProvider" type="System.Web.Providers.DefaultSessionStateProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="ConnectionString1" />
  </providers>
</code>```

Body:
First, I am new to Web app programming. I come from Desktop apps (WinForms & WPF).
Recently I have been assigned a project that was made in the past by ohter people. This project is done in ASP.NET MVC and it uses an InProc session state mode.

Now, I want to build a web gardening, that is, use multiple worker process for the application pool. I have googled and I have discovered that InProc session does not work with web gardening because each worker process within app pool uses its own session state. So I am planning to switch it into another session state mode such as State Server or SQL Server.

Now I have a doubt. Apart from changing session state mode in Web.config:

<configuration>
  <system.web>
    <sessionState mode="InProc" timeout="25"></sessionState>
  </system.web>
</configuration>

... Do I need to do some extra work? for example reprogramming the ASP.NET MVC app, configuration or some other things in order it to work?

Below I share some interesting links:

Configuring Server and SQL Server State

HOW TO: Configure SQL Server to Store ASP.NET Session State

Body:
For web farms you should keep your session either in StateServer  or Sql Server.
 To do so you need to add following configuration

     <connectionStrings>
           <add name="ConnectionString1"
           connectionString="Data Source=YourServer;Initial
           Catalog=SessionDatabase;Integrated Security=True"
           providerName="System.Data.SqlClient" />
    </connectionStrings>

<!--Change your <sessionState mode="InProc" timeout="25"></sessionState>  to this.-->

<sessionState mode="SQLServer" customProvider="DefaultSessionProvider">
  <providers>
    <add name="DefaultSessionProvider" type="System.Web.Providers.DefaultSessionStateProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="ConnectionString1" />
  </providers>


来源: stackexchange

问:
Cannot visualise the Postgresql database
I'm new to SQL and I'm following a tutorial on how to create a database. The new database I'm creating is called sample_db.

```<code>postgres=# create database sample_db

postgres=# \l
                                  List of databases
   Name    |  Owner   | Encoding |   Collate   |    Ctype    |   Access privileges
-----------+----------+----------+-------------+-------------+-----------------------
 postgres  | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 |
 sample_db | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 |
 template0 | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 | =c/postgres          +
           |          |          |             |             | postgres=CTc/postgres
 template1 | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 | =c/postgres          +
           |          |          |             |             | postgres=CTc/postgres
(4 rows)
</code>```

Everything looks great so far. I'm using Datagrip to visualise the database. However when I test the connection I get an error. (See image below):

The error message says "the server requested password-based authentication but no password was provided". However I didn't make a password and the tutorial I followed didn't either.

答:
I  believe you created the database using the Postgres local user access (trust authentication). To connect using a JDBC driver (which is the case of DataGrip), you have to create an user and grant him access to the database. This is an usual procedure using psql client:

```<code>> sudo -u postgres psql;
> CREATE USER <username> WITH PASSWORD '<password>';
> GRANT ALL PRIVILEGES ON DATABASE <database_name> TO <username>;
</code>```

After this sequence of commands, you should be allowed to connect to your database using DataGrip

ContentLicense: CC BY-SA 4.0

Body:
I'm new to SQL and I'm following a tutorial on how to create a database. The new database I'm creating is called sample_db.

postgres=# create database sample_db

postgres=# \l
                                  List of databases
   Name    |  Owner   | Encoding |   Collate   |    Ctype    |   Access privileges
-----------+----------+----------+-------------+-------------+-----------------------
 postgres  | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 |
 sample_db | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 |
 template0 | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 | =c/postgres          +
           |          |          |             |             | postgres=CTc/postgres
 template1 | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 | =c/postgres          +
           |          |          |             |             | postgres=CTc/postgres
(4 rows)

Everything looks great so far. I'm using Datagrip to visualise the database. However when I test the connection I get an error. (See image below):

The error message says "the server requested password-based authentication but no password was provided". However I didn't make a password and the tutorial I followed didn't either.

Body:
I  believe you created the database using the Postgres local user access (trust authentication). To connect using a JDBC driver (which is the case of DataGrip), you have to create an user and grant him access to the database. This is an usual procedure using psql client:

> sudo -u postgres psql;
> CREATE USER <username> WITH PASSWORD '<password>';
> GRANT ALL PRIVILEGES ON DATABASE <database_name> TO <username>;

After this sequence of commands, you should be allowed to connect to your database using DataGrip


问:
Commands with multiple common options going into one argument using custom decorator
I would like to make a module that makes it very simple to build click commands that share a lot of options. Those options would be distilled into a single object that is passed into the command. As an illustrative example:

```<code>from magic import magic_command
import click

@magic_command('Colored')
@click.option('--color')
def cmd(magic, color):
    pass
</code>```

The total command would then have many --magic-... options that go into the magic object passed into cmd. I was able to achieve that using the following:

```<code>def magic_command(name):
    def decorator(func):
        @click.option('--magic-foo')
        @click.option('--magic-bar')
        def wrapper(magic_foo, magic_bar, **kwargs):
            print(f'initializing Magic with {magic_foo} and {magic_bar}')
            magic = Magic(magic_foo, magic_bar)
            func(magic, **kwargs)

        try:
            wrapper.__click_params__.extend(func.__click_params__)
        except AttributeError:
            pass

        return click.command(f'{name}-Magic')(wrapper)
    return decorator
</code>```

However, messing with the __click_params__ doesn't seem particularly clean.

The question is somewhat similar to this one, however this approach does not allow me to condense the many magic options into a magic object.

To elaborate, with this approach I would have to do

```<code>@magic_command('Colored')
@click.option('--color')
def cmd(magic_foo, magic_bar, color):
    magic = Magic(magic_foo, magic_bar)
    pass
</code>```

But that means the custom code needs to be aware what magic options there are and how to construct the magic. I guess that can be simplified using **kwargs but still - ideally I'd like to just have a ready magic object passed to cmd.

答:
You can distill multiple options into a single object quite simply by constructing a decorator like:

Code:

```<code>def magic_options(func):
    @click.option('--magic-bar')
    @click.option('--magic-foo')
    def distill_magic(magic_foo, magic_bar, **kwargs):
        kwargs['magic'] = Magic(magic_foo, magic_bar)
        func(**kwargs)

    return distill_magic
</code>```

Using the decorator

You can then apply the decorator to the command function like:

```<code>@click.command('Colored-Magic')
@click.option('--color')
@magic_options
def cli(magic, color):
    ...
</code>```

It needs to be applied to the bare function.  This is because the function returned by click.option has been modified by the click framework and it won't work the way you expected.

Test Code:

```<code>import click

@click.command('Colored-Magic')
@click.option('--color')
@magic_options
def cli(magic, color):
    click.echo(str(magic))
    click.echo(color)

class Magic(object):
    def __init__(self, magic_foo, magic_bar):
        self.magic_foo = magic_foo
        self.magic_bar = magic_bar

    def __str__(self):
        return "foo: {}  bar: {}".format(self.magic_foo, self.magic_bar)

if __name__ == "__main__":
    commands = (
        '--magic-foo fooby --magic-bar barbecue',
        '--magic-foo fooby',
        '--magic-bar barbecue',
        '',
        '--help',
    )

    import sys, time

    time.sleep(1)
    print('Click Version: {}'.format(click.__version__))
    print('Python Version: {}'.format(sys.version))
    for cmd in commands:
        try:
            time.sleep(0.1)
            print('-----------')
            print('> ' + cmd)
            time.sleep(0.1)
            cli(cmd.split())

        except BaseException as exc:
            if str(exc) != '0' and \
                    not isinstance(exc, (click.ClickException, SystemExit)):
                raise
</code>```

Results:

```<code>Click Version: 6.7
Python Version: 3.6.3 (v3.6.3:2c5fed8, Oct  3 2017, 18:11:49) [MSC v.1900 64 bit (AMD64)]
-----------
> --magic-foo fooby --magic-bar barbecue
foo: fooby  bar: barbecue

-----------
> --magic-foo fooby
foo: fooby  bar: None

-----------
> --magic-bar barbecue
foo: None  bar: barbecue

-----------
>
foo: None  bar: None

-----------
> --help
Usage: test.py [OPTIONS]

Options:
  --color TEXT
  --magic-bar TEXT
  --magic-foo TEXT
  --help            Show this message and exit.
</code>```

Body:
I would like to make a module that makes it very simple to build click commands that share a lot of options. Those options would be distilled into a single object that is passed into the command. As an illustrative example:

from magic import magic_command
import click

@magic_command('Colored')
@click.option('--color')
def cmd(magic, color):
    pass

The total command would then have many --magic-... options that go into the magic object passed into cmd. I was able to achieve that using the following:

def magic_command(name):
    def decorator(func):
        @click.option('--magic-foo')
        @click.option('--magic-bar')
        def wrapper(magic_foo, magic_bar, **kwargs):
            print(f'initializing Magic with {magic_foo} and {magic_bar}')
            magic = Magic(magic_foo, magic_bar)
            func(magic, **kwargs)

        try:
            wrapper.__click_params__.extend(func.__click_params__)
        except AttributeError:
            pass

        return click.command(f'{name}-Magic')(wrapper)
    return decorator

However, messing with the __click_params__ doesn't seem particularly clean.

The question is somewhat similar to this one, however this approach does not allow me to condense the many magic options into a magic object.

To elaborate, with this approach I would have to do

@magic_command('Colored')
@click.option('--color')
def cmd(magic_foo, magic_bar, color):
    magic = Magic(magic_foo, magic_bar)
    pass

But that means the custom code needs to be aware what magic options there are and how to construct the magic. I guess that can be simplified using **kwargs but still - ideally I'd like to just have a ready magic object passed to cmd.

Body:
You can distill multiple options into a single object quite simply by constructing a decorator like:

Code:

def magic_options(func):
    @click.option('--magic-bar')
    @click.option('--magic-foo')
    def distill_magic(magic_foo, magic_bar, **kwargs):
        kwargs['magic'] = Magic(magic_foo, magic_bar)
        func(**kwargs)

    return distill_magic

Using the decorator

You can then apply the decorator to the command function like:

@click.command('Colored-Magic')
@click.option('--color')
@magic_options
def cli(magic, color):
    ...

It needs to be applied to the bare function.  This is because the function returned by click.option has been modified by the click framework and it won't work the way you expected.

Test Code:

import click

@click.command('Colored-Magic')
@click.option('--color')
@magic_options
def cli(magic, color):
    click.echo(str(magic))
    click.echo(color)

class Magic(object):
    def __init__(self, magic_foo, magic_bar):
        self.magic_foo = magic_foo
        self.magic_bar = magic_bar

    def __str__(self):
        return "foo: {}  bar: {}".format(self.magic_foo, self.magic_bar)

if __name__ == "__main__":
    commands = (
        '--magic-foo fooby --magic-bar barbecue',
        '--magic-foo fooby',
        '--magic-bar barbecue',
        '',
        '--help',
    )

    import sys, time

    time.sleep(1)
    print('Click Version: {}'.format(click.__version__))
    print('Python Version: {}'.format(sys.version))
    for cmd in commands:
        try:
            time.sleep(0.1)
            print('-----------')
            print('> ' + cmd)
            time.sleep(0.1)
            cli(cmd.split())

        except BaseException as exc:
            if str(exc) != '0' and \
                    not isinstance(exc, (click.ClickException, SystemExit)):
                raise

Results:

Click Version: 6.7
Python Version: 3.6.3 (v3.6.3:2c5fed8, Oct  3 2017, 18:11:49) [MSC v.1900 64 bit (AMD64)]
-----------
> --magic-foo fooby --magic-bar barbecue
foo: fooby  bar: barbecue

-----------
> --magic-foo fooby
foo: fooby  bar: None

-----------
> --magic-bar barbecue
foo: None  bar: barbecue

-----------
>
foo: None  bar: None

-----------
> --help
Usage: test.py [OPTIONS]

Options:
  --color TEXT
  --magic-bar TEXT
  --magic-foo TEXT
  --help            Show this message and exit.


问:
How to calculate the length of JSON values in php?
I have a JSON as shown below in which I want to calculate through php how many values are present inside posts_id_en. At present, it is 7 as shown below:

```<code>{
    "posts_id_en": "149968, 149939, 149883, 149877, 149876, 149847, 154303",
    "posts_id_fr": "149974,149953,149926, 149920, 149901",
    "episode_status": "3"
}
</code>```

In php code on doing echo $data->{"posts_id_en"};, it displays the values as shown below:

```<code>149968, 149939, 149883, 149877, 149876, 149847, 154303
</code>```

Problem Statement:

I am wondering what php code I need to use so that we can calculate number of values entered inside posts_id_en. At this moment, it is entered 7 as shown above.

答:
One simple way would be that we first json_decode, then validate numbers in our desired attribute, and count the matches:

```<code>$str = '{
    "posts_id_en": "149968, 149939, 149883, 149877, 149876, 149847, 154303",
    "posts_id_fr": "149974,149953,149926, 149920, 149901",
    "episode_status": "3"
}';

$str_array = json_decode($str, true);

preg_match_all('/(\d+)/s', $str_array["posts_id_en"], $matches);

echo sizeof($matches[0]);
</code>```

Output

```<code>7
</code>```

Body:
I have a JSON as shown below in which I want to calculate through php how many values are present inside posts_id_en. At present, it is 7 as shown below:

{
    "posts_id_en": "149968, 149939, 149883, 149877, 149876, 149847, 154303",
    "posts_id_fr": "149974,149953,149926, 149920, 149901",
    "episode_status": "3"
}

In php code on doing echo $data->{"posts_id_en"};, it displays the values as shown below:

149968, 149939, 149883, 149877, 149876, 149847, 154303

Problem Statement:

I am wondering what php code I need to use so that we can calculate number of values entered inside posts_id_en. At this moment, it is entered 7 as shown above.

Body:
One simple way would be that we first json_decode, then validate numbers in our desired attribute, and count the matches:

$str = '{
    "posts_id_en": "149968, 149939, 149883, 149877, 149876, 149847, 154303",
    "posts_id_fr": "149974,149953,149926, 149920, 149901",
    "episode_status": "3"
}';

$str_array = json_decode($str, true);

preg_match_all('/(\d+)/s', $str_array["posts_id_en"], $matches);

echo sizeof($matches[0]);

Output

7


问:
How to get exit code when using Python subprocess communicate method?
How do I retrieve the exit code when using Python's subprocess module and the communicate() method?

Relevant code:

```<code>import subprocess as sp
data = sp.Popen(openRTSP + opts.split(), stdout=sp.PIPE).communicate()[0]
</code>```

Should I be doing this another way?

答: You should first make sure that the process has completed running and the return code has been read out using the .wait method. This will return the code. If you want access to it later, it's stored as .returncode in the Popen object.

ContentLicense: CC BY-SA 3.0

Body:
How do I retrieve the exit code when using Python's subprocess module and the communicate() method?

Relevant code:

import subprocess as sp
data = sp.Popen(openRTSP + opts.split(), stdout=sp.PIPE).communicate()[0]

Should I be doing this another way?


问:
Git: Update PR with specific changes after branch diverges
I have a local branch, my_branch, that I made after cloning repo.  I made two commits (more recent commit first):

YAML updates

Main changes

I pushed my branch and made a PR.  It took a while to get it approved and now I can't merge cleanly into origin/master.

I'd like to get rid of my YAML updates commit, re-run the process that generates those changes locally, and replay my changes on origin/master, fixing any conflicts along the way.

Is this the right approach:

Drop my YAML updates commit with git reset --soft HEAD^

git checkout master; git pull origin master

git checkout my_branch; git checkout origin/master config1.yaml; git checkout origin/master config2.yaml

Re-run process to create YAML updates

git add config1.yaml config2.yaml

git commit -m "Updating YAML files"

git rebase -i master

If I run into merge conflicts, I should fix them and run git rebase --
continue

Assuming 7. is successful, git push -f

EDIT: Is running the same steps above but swapping steps 4. and 7. equivalent to running steps 1. through 8. in sequence?

I'd normally just try the above before asking, but don't want to mess up my local branch or PR.

答:
The steps do look good, but anyway, you have low risk of messing up:

your local branch: you can always mark it with a new branch or tag, it before starting those step. If the end result isn't what you expect, you can reset to that old state, and start again

your PR branch: again, if the new pushed PR branch has any issue, you can force push the old one.

Is swapping steps 4. and 7. equivalent to running steps 1. through 8. in sequence?

Yes: the rebase change the history of commits anyway: so doing your new commit before or after the rebase won't have any adverse effect, and the last step (8) will remain a git push --force.


问:
Unable to load gem after its installation
How to use an external library in Ruby?

I just installed Addressable library as stated in the documentation and write the following code:

```<code>require 'addressable/uri'
</code>```

and it still says:

E:/software/Ruby22/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in
  `require': cannot load such file -- addressable/uri (LoadError)

What am I doing wrong? How can I fix it?

答:
You need install addressable. Run the following in your command line:</p>

```<code>$ gem install addressable
</code>```

Body:
How to use an external library in Ruby?

I just installed Addressable library as stated in the documentation and write the following code:

require 'addressable/uri'

and it still says:

E:/software/Ruby22/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in
  `require': cannot load such file -- addressable/uri (LoadError)

What am I doing wrong? How can I fix it?

Body:
You need install addressable. Run the following in your command line:

$ gem install addressable


问:
Sum of certain items in a list
I'm working on a probability-related problem. I need to sum only specific items on a certain list.

I've tried using "for" functions and it hasn't worked. I'm looking for a way to select items based on their positions on the list, and summing them.

答:
You really should have put more into your question, but:

stuff = [1, 2, 3, 4, 5, 6, 7, 8]
# sum the numbers that have even indices:
funny_total = sum([x for i, x in enumerate(stuff) if i % 2 == 0 ])

funny_total
# 16
```

<p>That should get you started. An approach with a <code>for</code> loop would have worked, as well. You just likely have a bug in your code.</p>

<pre class="lang-py prettyprint-override"><code>stuff = [1, 2, 3, 4, 5, 6, 7, 8]
indices_to_include = [1, 3, 4, 5, 6]
funny_total = 0
for i, x in enumerate(stuff):
    if i in indices_to_include:
        funny_total += x
</code>```

You could also:

def keep_every_third(i):
    return i % 3 == 0
# variable definitions as above...
for i, x in enumerate(stuff):
    if keep_every_third(i):
        # do stuff
```

Title: Sum of certain items in a list

Body:
You really should have put more into your question, but:

stuff = [1, 2, 3, 4, 5, 6, 7, 8]
# sum the numbers that have even indices:
funny_total = sum([x for i, x in enumerate(stuff) if i % 2 == 0 ])

funny_total
# 16

That should get you started. An approach with a for loop would have worked, as well. You just likely have a bug in your code.

stuff = [1, 2, 3, 4, 5, 6, 7, 8]
indices_to_include = [1, 3, 4, 5, 6]
funny_total = 0
for i, x in enumerate(stuff):
    if i in indices_to_include:
        funny_total += x

You could also:

def keep_every_third(i):
    return i % 3 == 0
# variable definitions as above...
for i, x in enumerate(stuff):
    if keep_every_third(i):
        # do stuff


问:
PHP/MySQL error: Could not execute INSERT INTO with PDO
I'm a beginner to PHP/MySQL trying to insert data into a table via a form, but I keep getting this:

Connected successfully ERROR: Could not execute INSERT INTO foo (firstname, lastname, landline, mobile) VALUES ('', '', ', ').

My limited understanding tells me I'm connecting successfully but nothing's getting into the table. Checking the table confirms this.

I'm trying to send the data from a PHP 7.1 WHMCS server to a remote host running MySQL 5.1.73. I'm pulling a user ID from WHMCS and pre-populating the that field with the idea to send that along with the rest of the form data. I had that field set to "hidden" and "text," no luck.

I even copied/pasted the form to a separate html and tried running everything at the root. No luck.

I used this example as my guide.

form.tpl:

```<code><form method="post" action="includes/action.php">
User ID:<input type ="text" name = "userid" value={$d} readonly> //pulls userID from WHMCS
First name:<input type="text" name="firstname">
Last name:<input type="text" name="lastname">
Landline:<input type="text" name="landline">
Mobile:<input type="text" name="mobile">
<input type="submit" value="Submit"></form>
</code>```

dbconnect.php:

```<code>$servername = "fqdn.com";
$username = "few";
$password = "2many";

try {
    $conn = new PDO("mysql:host=$servername;dbname=data_base", $username, $password);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "Connected successfully";
    }
catch(PDOException $e)
    {
    echo "Connection failed: " . $e->getMessage();
    }
</code>```

action.php:

```<code>//Open MySql Connection
include "dbconnect.php";

// prepare sql and bind parameters
$stmt = $conn->prepare("INSERT INTO foo (userid, firstname, lastname, landline, mobile) VALUES (:userid, :firstname, :lastname, :landline, :mobile)");
$stmt->bindParam(':userid', $userid);
$stmt->bindParam(':firstname', $firstname);
$stmt->bindParam(':lastname', $lastname);
$stmt->bindParam(':landline', $landline);
$stmt->bindParam(':mobile', $mobile);

// insert a row
$userid = $_POST["userid"];
$firstname = $_POST["firstname"];
$lastname = $_POST["lastname"];
$landline = $_POST["landline"];
$mobile = $_POST["mobile"];
$stmt->execute();

    echo "New records created successfully";
} catch(PDOException $e)
    {
        echo "Error: " . $e->getMessage();
    }

if (!$stmt) {
    echo "\nPDO::errorInfo():\n";
    print_r($dbh->errorInfo());
}

$conn = null;
</code>```

答:
in action.php you are using variables before you have set them.</p>

```<code>// insert a row
$userid = $_POST["userid"];
$firstname = $_POST["firstname"];
$lastname = $_POST["lastname"];
$landline = $_POST["landline"];
$mobile = $_POST["mobile"];

// prepare sql and bind parameters
$stmt = $conn->prepare("INSERT INTO foo (id, firstname, lastname, landline, mobile) VALUES (:userid, :firstname, :lastname, :landline, :mobile)");
$stmt->bindParam(':userid', $userid);
$stmt->bindParam(':firstname', $firstname);
$stmt->bindParam(':lastname', $lastname);
$stmt->bindParam(':landline', $landline);
$stmt->bindParam(':mobile', $mobile);
$stmt->execute();
</code>```

Body:
I'm a beginner to PHP/MySQL trying to insert data into a table via a form, but I keep getting this:

Connected successfully ERROR: Could not execute INSERT INTO foo (firstname, lastname, landline, mobile) VALUES ('', '', ', ').

My limited understanding tells me I'm connecting successfully but nothing's getting into the table. Checking the table confirms this.

I'm trying to send the data from a PHP 7.1 WHMCS server to a remote host running MySQL 5.1.73. I'm pulling a user ID from WHMCS and pre-populating the that field with the idea to send that along with the rest of the form data. I had that field set to "hidden" and "text," no luck.

I even copied/pasted the form to a separate html and tried running everything at the root. No luck.

I used this example as my guide.

form.tpl:

<form method="post" action="includes/action.php">
User ID:<input type ="text" name = "userid" value={$d} readonly> //pulls userID from WHMCS
First name:<input type="text" name="firstname">
Last name:<input type="text" name="lastname">
Landline:<input type="text" name="landline">
Mobile:<input type="text" name="mobile">
<input type="submit" value="Submit"></form>

dbconnect.php:

$servername = "fqdn.com";
$username = "few";
$password = "2many";

try {
    $conn = new PDO("mysql:host=$servername;dbname=data_base", $username, $password);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "Connected successfully";
    }
catch(PDOException $e)
    {
    echo "Connection failed: " . $e->getMessage();
    }

action.php:

//Open MySql Connection
include "dbconnect.php";

// prepare sql and bind parameters
$stmt = $conn->prepare("INSERT INTO foo (userid, firstname, lastname, landline, mobile) VALUES (:userid, :firstname, :lastname, :landline, :mobile)");
$stmt->bindParam(':userid', $userid);
$stmt->bindParam(':firstname', $firstname);
$stmt->bindParam(':lastname', $lastname);
$stmt->bindParam(':landline', $landline);
$stmt->bindParam(':mobile', $mobile);

// insert a row
$userid = $_POST["userid"];
$firstname = $_POST["firstname"];
$lastname = $_POST["lastname"];
$landline = $_POST["landline"];
$mobile = $_POST["mobile"];
$stmt->execute();

    echo "New records created successfully";
} catch(PDOException $e)
    {
        echo "Error: " . $e->getMessage();
    }

if (!$stmt) {
    echo "\nPDO::errorInfo():\n";
    print_r($dbh->errorInfo());
}

$conn = null;

Body:
in action.php you are using variables before you have set them.

// insert a row
$userid = $_POST["userid"];
$firstname = $_POST["firstname"];
$lastname = $_POST["lastname"];
$landline = $_POST["landline"];
$mobile = $_POST["mobile"];

// prepare sql and bind parameters
$stmt = $conn->prepare("INSERT INTO foo (id, firstname, lastname, landline, mobile) VALUES (:userid, :firstname, :lastname, :landline, :mobile)");
$stmt->bindParam(':userid', $userid);
$stmt->bindParam(':firstname', $firstname);
$stmt->bindParam(':lastname', $lastname);
$stmt->bindParam(':landline', $landline);
$stmt->bindParam(':mobile', $mobile);
$stmt->execute();


问:
How to calculate Jaccard similarity coefficient with sqlite
I have a database made with sqlite3 where each user has 3 possible hobbies, which are saved as a boolean value (1 if the user likes it, 0 if he doesn't).
I want to get a list of the pairs that are similar ordered by their Jaccard similarity coefficient, which means I have to count the number of hobbies that are true for both  of them and divide it by the number of hobbies that either of them chose.

I have created this VIEW
All of the pairs must contain wonka in the view. Carros, tecnologia and comida are hobbies.

答:
Instead of trying to store all hobbies in a single row per user, and joining them (Like your view appears to be doing), and then trying to add them up, it's a lot easier to calculate with a better database design that expresses the relationships between users and hobbies by tracking them in another table (Think about what needs to be done to add a fourth hobby.). You'll want to look up terms like many-to-many relationship and junction table for more, and/or find a good resource on database design.

With a design like that, given these tables:

```<code>CREATE TABLE users(userID INTEGER PRIMARY KEY, userName TEXT UNIQUE);
CREATE TABLE hobbies(hobbyID INTEGER PRIMARY KEY, hobbyName TEXT UNIQUE);
CREATE TABLE interests(userID INTEGER REFERENCES users(userID) ON DELETE CASCADE
                     , hobbyID INTEGER REFERENCES hobbies(hobbyID) ON DELETE CASCADE
                     , liked INTEGER
                     , PRIMARY KEY(userID, hobbyID)) WITHOUT ROWID;
</code>```

you can calculate the similarity coefficient for all pairs with something like:

```<code>SELECT u1.userName AS "Person 1", u2.UserName AS "Person 2"
     , ifnull(total(i1.liked AND i2.liked) / total(i1.liked OR i2.liked), 0.0) AS Similarity
FROM users AS u1
JOIN users AS u2 ON u1.userId <> u2.userId
LEFT JOIN interests AS i1 ON u1.userId = i1.userId
LEFT JOIN interests AS i2 ON u2.userId = i2.userId AND i1.hobbyId = i2.hobbyID
GROUP BY u1.userId, u2.userId;
</code>```

Body:
Instead of trying to store all hobbies in a single row per user, and joining them (Like your view appears to be doing), and then trying to add them up, it's a lot easier to calculate with a better database design that expresses the relationships between users and hobbies by tracking them in another table (Think about what needs to be done to add a fourth hobby.). You'll want to look up terms like many-to-many relationship and junction table for more, and/or find a good resource on database design.

With a design like that, given these tables:

CREATE TABLE users(userID INTEGER PRIMARY KEY, userName TEXT UNIQUE);
CREATE TABLE hobbies(hobbyID INTEGER PRIMARY KEY, hobbyName TEXT UNIQUE);
CREATE TABLE interests(userID INTEGER REFERENCES users(userID) ON DELETE CASCADE
                     , hobbyID INTEGER REFERENCES hobbies(hobbyID) ON DELETE CASCADE
                     , liked INTEGER
                     , PRIMARY KEY(userID, hobbyID)) WITHOUT ROWID;

you can calculate the similarity coefficient for all pairs with something like:

SELECT u1.userName AS "Person 1", u2.UserName AS "Person 2"
     , ifnull(total(i1.liked AND i2.liked) / total(i1.liked OR i2.liked), 0.0) AS Similarity
FROM users AS u1
JOIN users AS u2 ON u1.userId <> u2.userId
LEFT JOIN interests AS i1 ON u1.userId = i1.userId
LEFT JOIN interests AS i2 ON u2.userId = i2.userId AND i1.hobbyId = i2.hobbyID
GROUP BY u1.userId, u2.userId;


问:
How to merge and combine rows with same id (index) in python?
I am new in python and I am working with CSV file with over 10000 rows. In my CSV file, there are many rows with the same id which I would like to merge them in one and also combine their information as well.

For instance, the data.csv look like (id and info is the name of columns):

```<code>id| info

1112| storage is full and needs extra space

1112| there is many problems with space

1113| pickup cars come and take the garbage

1113| payment requires for the garbage
</code>```

and I want to get the output as:

```<code>id| info

1112| storage is full and needs extra space there is many problems with space

1113| pickup cars come and take the garbage payment requires for the garbage
</code>```

I already looked at a few posts such as 1 2 3 but none of them helped me to answer my question.

It would be great if you could use python code to describe your help that I can also run and learn in my side.

Thank you

答:
Just make a dictionary where id's are keys:</p>

```<code>from collections import defaultdict

by_id = defaultdict(list)

for id, info in your_list:
    by_id[id].append(info)

for key, value in by_id.items():
    print(key, value)
</code>```

Body:
I am new in python and I am working with CSV file with over 10000 rows. In my CSV file, there are many rows with the same id which I would like to merge them in one and also combine their information as well.

For instance, the data.csv look like (id and info is the name of columns):

id| info

1112| storage is full and needs extra space

1112| there is many problems with space

1113| pickup cars come and take the garbage

1113| payment requires for the garbage

and I want to get the output as:

id| info

1112| storage is full and needs extra space there is many problems with space

1113| pickup cars come and take the garbage payment requires for the garbage

I already looked at a few posts such as 1 2 3 but none of them helped me to answer my question.

It would be great if you could use python code to describe your help that I can also run and learn in my side.

Thank you

Body:
Just make a dictionary where id's are keys:

from collections import defaultdict

by_id = defaultdict(list)

for id, info in your_list:
    by_id[id].append(info)

for key, value in by_id.items():
    print(key, value)


问:
How to track a spoke of a wheel in two subsequent video frames?
Consider two subsequent frames of a video that look as follows:

What is a possible way to track the movement of one of the spokes?

I am asking this because I don't have any experience with video processing. So any advice would be helpful! What am I tracking? From what I have read, usually I would have to detect the object I want to track first. And I am using a corner detection algorithm for this such as goodfeaturestotrack. But how do I make sure I detect the correct spoke, etc. ?

Some additional information: The framerate of the video is 30fps. The wheel rotates in clockwise-direction only. And when I click through the video frame by frame it is pretty obvious that a spoke does not move by more than half of the angle between two spokes (from frame to frame).
Also: The radius of the wheel is 5cm.

I have now tried out Mark's answer. I have logged Tmax and the timestamp of the frame in a txt-file and then wrote the following code to compute the corresponding velocity:

```<code>ListOfVelocities = []
for idx in range(1,len(ListOfAngles)):
    if ListOfAngles[idx] < ListOfAngles[idx-1]:
        rotation = (360-ListOfAngles[idx]) + ListOfAngles[idx-1]
    else:
        rotation = ListOfAngles[idx] - ListOfAngles[idx-1]
    timePassed = VideoTimestamp[idx]-VideoTimestamp[idx-1]
    velocity = 2*np.pi/360 * rotation * RADIUS * timePassed
    ListOfVelocities.append(velocity)
</code>```

答:
For provided frames, it's impossible to track a single spoke, because all spokes have identical shape and color. The practical way to track one is by physically marking the spoke. Then, as long as your camera has movement, you need image registration to align frames. It's not difficult to track the spoke afterward.

Edit: The physical mark can be a colored spot on the spoke (for simplicity, use a color that is unique in the image). Then use thresholding technique to single out the color. You may need some enhancement to remove noises then.

Body:
Consider two subsequent frames of a video that look as follows:

What is a possible way to track the movement of one of the spokes?

I am asking this because I don't have any experience with video processing. So any advice would be helpful! What am I tracking? From what I have read, usually I would have to detect the object I want to track first. And I am using a corner detection algorithm for this such as goodfeaturestotrack. But how do I make sure I detect the correct spoke, etc. ?

Some additional information: The framerate of the video is 30fps. The wheel rotates in clockwise-direction only. And when I click through the video frame by frame it is pretty obvious that a spoke does not move by more than half of the angle between two spokes (from frame to frame).
Also: The radius of the wheel is 5cm.

I have now tried out Mark's answer. I have logged Tmax and the timestamp of the frame in a txt-file and then wrote the following code to compute the corresponding velocity:

ListOfVelocities = []
for idx in range(1,len(ListOfAngles)):
    if ListOfAngles[idx] < ListOfAngles[idx-1]:
        rotation = (360-ListOfAngles[idx]) + ListOfAngles[idx-1]
    else:
        rotation = ListOfAngles[idx] - ListOfAngles[idx-1]
    timePassed = VideoTimestamp[idx]-VideoTimestamp[idx-1]
    velocity = 2*np.pi/360 * rotation * RADIUS * timePassed
    ListOfVelocities.append(velocity)


问:
What is the difference between supervised learning and unsupervised learning?
In terms of artificial intelligence and machine learning, what is the difference between supervised and unsupervised learning?
Can you provide a basic, easy explanation with an example? </p>

答:
There are many answers already which explain the differences in detail. I found these gifs on codeacademy and they often help me explain the differences effectively.

Supervised Learning

Notice that the training images have labels here and that the model is learning the names of the images.

Unsupervised Learning

Notice that what's being done here is just grouping(clustering) and that the model doesn't know anything about any image.


问:
Colab not rendering mathjax sympy output
Google Colab is not rendering Mathjax output of python cell's generated with sympy. Instead of getting a graphic output I'm getting the markdown commands that would generate the ouput.

For instance, the code below:

```<code>import numpy as np
import sympy as sp
x1 = np.array([1,1,1,1]).reshape(-1,1)
x2 = np.array([2,3,4,5]).reshape(-1,1)
x3 = np.array([3,4,5,6]).reshape(-1,1)
A = np.concatenate([x1,x2,x3],axis=1)
A = sp.Matrix(A)
x = sp.Matrix([1,1,1])
sp.init_printing(use_latex='mathjax')
A,x
</code>```

gives me as output the string:

$\displaystyle \left( \left[\begin{matrix}1 & 2 & 3\1 & 3 & 4\1 & 4 & 5\1 & 5 & 6\end{matrix}\right], \ \left[\begin{matrix}1\1\1\end{matrix}\right]\right)$

instead of the rendered image itself.

答:
this works for me (from an older post https://stackoverflow.com/a/49584891/2417833 - won't work with mathjax from colab) :</p>

```<code>import numpy as np
import sympy as sp
from google.colab.output._publish import javascript
javascript(url="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.3/latest.js?config=default")
x1 = np.array([1,1,1,1]).reshape(-1,1)
x2 = np.array([2,3,4,5]).reshape(-1,1)
x3 = np.array([3,4,5,6]).reshape(-1,1)
A = np.concatenate([x1,x2,x3],axis=1)
A = sp.Matrix(A)
x = sp.Matrix([1,1,1])
sp.init_printing(use_latex='mathjax')
A,x
</code>```

Body:
Google Colab is not rendering Mathjax output of python cell's generated with sympy. Instead of getting a graphic output I'm getting the markdown commands that would generate the ouput.

For instance, the code below:

import numpy as np
import sympy as sp
x1 = np.array([1,1,1,1]).reshape(-1,1)
x2 = np.array([2,3,4,5]).reshape(-1,1)
x3 = np.array([3,4,5,6]).reshape(-1,1)
A = np.concatenate([x1,x2,x3],axis=1)
A = sp.Matrix(A)
x = sp.Matrix([1,1,1])
sp.init_printing(use_latex='mathjax')
A,x

gives me as output the string:

$\displaystyle \left( \left[\begin{matrix}1 & 2 & 3\1 & 3 & 4\1 & 4 & 5\1 & 5 & 6\end{matrix}\right], \ \left[\begin{matrix}1\1\1\end{matrix}\right]\right)$

instead of the rendered image itself.

Body:
this works for me (from an older post https://stackoverflow.com/a/49584891/2417833 - won't work with mathjax from colab) :

import numpy as np
import sympy as sp
from google.colab.output._publish import javascript
javascript(url="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.3/latest.js?config=default")
x1 = np.array([1,1,1,1]).reshape(-1,1)
x2 = np.array([2,3,4,5]).reshape(-1,1)
x3 = np.array([3,4,5,6]).reshape(-1,1)
A = np.concatenate([x1,x2,x3],axis=1)
A = sp.Matrix(A)
x = sp.Matrix([1,1,1])
sp.init_printing(use_latex='mathjax')
A,x


问:
Use Git as an undo-redo manager?
I'm trying to use Git as an undo-redo manager for changes made to a directory.

I essentially want the following:

An undo command, that resets the contents of the directory to the state of the previous commit (only if there was a previous commit)

```<code>State
-----
 -> * 3b1e4d8 F
    * fb2c608 E
    * cdd8ac5 D
    * aefe3ee C
    * 458bb4f B
    * 17fa95e A
currently "active" commit: F  (represented by ->)

Undo
----

    * 3b1e4d8 F
 -> * fb2c608 E
    * cdd8ac5 D
    * aefe3ee C
    * 458bb4f B
    * 17fa95e A

Note that F is still visible and not lost

Undo
----

    * 3b1e4d8 F
    * fb2c608 E
 -> * cdd8ac5 D
    * aefe3ee C
    * 458bb4f B
    * 17fa95e A
</code>```

A redo command, which undo's the undo, that is, resets the contents of the directory to the state of the next commit.

```<code>Redo
----

    * 3b1e4d8 F
 -> * fb2c608 E
    * cdd8ac5 D
    * aefe3ee C
    * 458bb4f B
    * 17fa95e A
</code>```

No commits should be lost. That is, no commits should become "dangling", and must always be reachable, and must always show up in git log.

```<code>Change G
----

 -> * f12ea02 G
    |  * 3b1e4d8 F
    | /
    * fb2c608 E
    * cdd8ac5 D
    * aefe3ee C
    * 458bb4f B
    * 17fa95e A

Note that the commit F is not lost from history/log
</code>```

Ability to push and pull the repo from a remote.

How do I accomplish this behavior?

I can implement undo using reset HEAD^, but that causes the latest commit to be lost. (The latest commit can still be reached by the commit hash, but the git log doesn't show it, and pushing the repo causes the commit to be lost forever).

So, that doesn't work.

I can instead got a checkout HEAD^ for undo, but now I'm in a detached head state and can't push to remote. Also, if I make any changes from a detached head state, the branch doesn't follow the head.

答:
So, first of all, pushing after a reset does not mean that the commit is "lost forever'.  You may feel this is beside the point, because there are other reasons why simply resetting won't behave as you want in general, but it you want to devise your own use cases for git, you need to start by having a correct conceptual knowledge of how it manages information.

And, as you have noticed, there aren't simple git commands that map to your "undo' and "redo" operations - because what you describe is not what git was designed to do.  That doesn't mean it can't do it - it's very flexible.  But it does mean that you're trying to devise your own use case.

So there's not a simple solution.  You're going to have to design through the edge cases, and the cases you've glossed over (when you've diverged after an undo, you've said you want the old state you undid to still be reachable and visible - but how do you want it shown, and how do you want to refer to it?

And once you've done that design work, you'll have to build the software to implement it.  Maybe you'll find git's functionality to provide a good foundation for that, in which case you can write scripts that string together git commands.  But it won't just be "run this one command", and it will probably involve commands that are less commonly used by end users (plumbing commands).

As is hopefully clear by now, a detailed step-by-step answer is beyond the scope of a Stack Overflow Q&A.  So that brings me back to the beginning - you need to begin by having a detailed understanding of how git handles the data you commit to it.  If you have specific questions along those lines, and if the (pretty good, albeit sometimes poorly-phrased) git documentation does not clarify matters, you then might have a question we can reasonably answer.

Title: Use Git as an undo-redo manager?

Body:
I'm trying to use Git as an undo-redo manager for changes made to a directory.

I essentially want the following:

An undo command, that resets the contents of the directory to the state of the previous commit (only if there was a previous commit)

State
-----
 -> * 3b1e4d8 F
    * fb2c608 E
    * cdd8ac5 D
    * aefe3ee C
    * 458bb4f B
    * 17fa95e A
currently "active" commit: F  (represented by ->)

Undo
----

    * 3b1e4d8 F
 -> * fb2c608 E
    * cdd8ac5 D
    * aefe3ee C
    * 458bb4f B
    * 17fa95e A

Note that F is still visible and not lost

Undo
----

    * 3b1e4d8 F
    * fb2c608 E
 -> * cdd8ac5 D
    * aefe3ee C
    * 458bb4f B
    * 17fa95e A

A redo command, which undo's the undo, that is, resets the contents of the directory to the state of the next commit.

Redo
----

    * 3b1e4d8 F
 -> * fb2c608 E
    * cdd8ac5 D
    * aefe3ee C
    * 458bb4f B
    * 17fa95e A

No commits should be lost. That is, no commits should become "dangling", and must always be reachable, and must always show up in git log.

Change G
----

 -> * f12ea02 G
    |  * 3b1e4d8 F
    | /
    * fb2c608 E
    * cdd8ac5 D
    * aefe3ee C
    * 458bb4f B
    * 17fa95e A

Note that the commit F is not lost from history/log

Ability to push and pull the repo from a remote.

How do I accomplish this behavior?

I can implement undo using reset HEAD^, but that causes the latest commit to be lost. (The latest commit can still be reached by the commit hash, but the git log doesn't show it, and pushing the repo causes the commit to be lost forever).

So, that doesn't work.

I can instead got a checkout HEAD^ for undo, but now I'm in a detached head state and can't push to remote. Also, if I make any changes from a detached head state, the branch doesn't follow the head.


问:
How can I convert columns to rows in Pandas?
I have something like this:

```<code>Values     Time
  22        0
  45        1
  65        2
  78        0
  12        1
  45        2
</code>```

and I want this:

```<code>Time    0    1    2
Val1    22   45   65
Val2    78   12   45
</code>```

How can I do it?

答:
If your time-delta is constant, ordered and has no missing values:

```<code>DELTA = 3
new_values = [df['Values'].iloc[i*DELTA:i*DELTA+DELTA].values.transpose() for i in range(int(len(df)/DELTA))]
df_new = pd.DataFrame(new_values , index=['Val'+str(i+1) for i in range(len(new_values ))])

print(df_new)
         0   1   2
Val1    22  45  65
Val2    78  12  45
</code>```

Not a pretty solution, but maybe it helps. :-)

Body:
I have something like this:

Values     Time
  22        0
  45        1
  65        2
  78        0
  12        1
  45        2

and I want this:

Time    0    1    2
Val1    22   45   65
Val2    78   12   45

How can I do it?

Body:
If your time-delta is constant, ordered and has no missing values:

DELTA = 3
new_values = [df['Values'].iloc[i*DELTA:i*DELTA+DELTA].values.transpose() for i in range(int(len(df)/DELTA))]
df_new = pd.DataFrame(new_values , index=['Val'+str(i+1) for i in range(len(new_values ))])

print(df_new)
         0   1   2
Val1    22  45  65
Val2    78  12  45

Not a pretty solution, but maybe it helps. :-)


问:
How to make my wpf app wait for 3 minutes before re-loading data?
I am using VS2010 - WPF - C#

in my application I fetch data from a web server and view it on my interface
the problem is that I want to keep fetching data and keep refreshing my interface every 3 minutes but I don't know how to do that...

I tried (Thread.Sleep(18000)) and it didn't work because my interface wouldn't show at all

I don't know how to use the Timer for such reason and I couldn't find what I'm looking for elsewhere

Please can you help me with it ?

Best Regards

答: Use a DispatcherTimer, there are also examples how to use it on the given link</p>


答:
I think about some simplier way:

```<code>some_dict = {}
for idt, txt in line: #~ For line use your id, info reader.
    some_dict[idt] = some_dict.get(idt, "") + txt
</code>```

It should create your dream structure without imports, and i hope most efficient way.
Just to understand, get have secound argument, what must return if something isn't finded in dict. Then create empty string and add text, if some was finded, then add text to that.

@Edit:

Here is complete example with reader :). Try to replace correctly variable instead of reader entry, which shows how to do it :)

```<code>some_dict = {}
with open('file.csv') as f:
    reader = csv.reader(f)
    for idt, info in reader:
        temp = some_dict.get(idt, "")
        some_dict[idt] = temp+" "+txt if temp else txt
print(some_dict)
df = pd.Series(some_dict).to_frame("Title of your column")
</code>```

This is full program which should work for you.
But, it won't work if you got more than 2 columns in file, then u can just replace idt, info with row, and use indexes for first and secound element.

@Next Edit:

For more then 2 columns:

```<code>some_dict = {}
with open('file.csv') as f:
    reader = csv.reader(f)
    for row in reader:
        temp = some_dict.get(row[0], "")
        some_dict[row[0]] = temp+" "+row[1] if temp else row[1]
        #~ There you can add something with another columns if u want.
        #~ Example: another_dict[row[2]] = another_dict.get(row[2], "") + row[3]
print(some_dict)
df = pd.Series(some_dict).to_frame("Title of your column")
</code>```

Title: How to merge and combine rows with same id (index) in python?

Body:
I think about some simplier way:

some_dict = {}
for idt, txt in line: #~ For line use your id, info reader.
    some_dict[idt] = some_dict.get(idt, "") + txt

It should create your dream structure without imports, and i hope most efficient way.
Just to understand, get have secound argument, what must return if something isn't finded in dict. Then create empty string and add text, if some was finded, then add text to that.

@Edit:

Here is complete example with reader :). Try to replace correctly variable instead of reader entry, which shows how to do it :)

some_dict = {}
with open('file.csv') as f:
    reader = csv.reader(f)
    for idt, info in reader:
        temp = some_dict.get(idt, "")
        some_dict[idt] = temp+" "+txt if temp else txt
print(some_dict)
df = pd.Series(some_dict).to_frame("Title of your column")

This is full program which should work for you.
But, it won't work if you got more than 2 columns in file, then u can just replace idt, info with row, and use indexes for first and secound element.

@Next Edit:

For more then 2 columns:

some_dict = {}
with open('file.csv') as f:
    reader = csv.reader(f)
    for row in reader:
        temp = some_dict.get(row[0], "")
        some_dict[row[0]] = temp+" "+row[1] if temp else row[1]
        #~ There you can add something with another columns if u want.
        #~ Example: another_dict[row[2]] = another_dict.get(row[2], "") + row[3]
print(some_dict)
df = pd.Series(some_dict).to_frame("Title of your column")


问:
How can I use varible from another function?
For printing the value of factorial, I want to use the value of fact in the facto() function. How can I achieve this?

I have tried declaring variables i and fact in the facto() function.

```<code>public class Factorial {
    int fact=1;
    int n=5,i=1;

    void facto()
    {

        for(i=n;i>=1;i--)
        {
            fact=fact*i;
        }

    }

    public static void main(String args[])
    {
        Factorial obj1= new Factorial();
        System.out.println(obj1.fact);
    }
}
</code>```

The answer I'm getting is what it gets the value from the class and is initialized with 1. I want to get 120 as the solution.

答:
Don't use fields. Use a parameter and a return value.</p>

```<code>public class Factorial {
    private int facto(int n) {
        int fact = 1;
        for (int i = n; i >= 1; i--) {
            fact = fact * i;
        }
        return fact;
    }

    public static void main(String args[]) {
        Factorial obj1 = new Factorial();
        System.out.println(obj1.facto(5));
    }
}
</code>```

Body:
For printing the value of factorial, I want to use the value of fact in the facto() function. How can I achieve this?

I have tried declaring variables i and fact in the facto() function.

public class Factorial {
    int fact=1;
    int n=5,i=1;

    void facto()
    {

        for(i=n;i>=1;i--)
        {
            fact=fact*i;
        }

    }

    public static void main(String args[])
    {
        Factorial obj1= new Factorial();
        System.out.println(obj1.fact);
    }
}

The answer I'm getting is what it gets the value from the class and is initialized with 1. I want to get 120 as the solution.

Body:
Don't use fields. Use a parameter and a return value.

public class Factorial {
    private int facto(int n) {
        int fact = 1;
        for (int i = n; i >= 1; i--) {
            fact = fact * i;
        }
        return fact;
    }

    public static void main(String args[]) {
        Factorial obj1 = new Factorial();
        System.out.println(obj1.facto(5));
    }
}


问:
How to get the List Index of a List Tuple element
I have created a List Tuple String int like this:

```<code>public static List<Tuple<string, int>> myGrid = new List<Tuple<string, int>>();

myGrid.Add(new Tuple<string, int>("Alpha", 159));
</code>```

I have done so, because I need to work with index in my code.

How to get the List index of Tuple Item1 or Item2?

答:
```<code>var indexByItem1 = myGrid.FindIndex(0, t => t.Item1 == "Alpha");
var indexByItem2 = myGrid.FindIndex(0, t => t.Item2 == 159);
</code>```

See this interactive fiddle.

Body:
I have created a List Tuple String int like this:

public static List<Tuple<string, int>> myGrid = new List<Tuple<string, int>>();

myGrid.Add(new Tuple<string, int>("Alpha", 159));

I have done so, because I need to work with index in my code.

How to get the List index of Tuple Item1 or Item2?

Body:
var indexByItem1 = myGrid.FindIndex(0, t => t.Item1 == "Alpha");
var indexByItem2 = myGrid.FindIndex(0, t => t.Item2 == 159);

See this interactive fiddle.


问:
Extract Character from Filename with RegEx in Excel VBA
My strings are filenames like this:

Filename 1 (A12 V1.1)

Filename 1 (V2) Text (A9 V2.3 8.99)

Filename V2 Text (A34 8.3 V4)

How do I extract only the numbers which start with the 'V', contained within the last brackets only, and excluding the 'V'?

i.e. - 1.1, 2.3, 4

The following Regex UDF was provided by YasserKhalil (Previous Post Here)

However, the UDF is returning on filenames like:

IPV32_20.dll which returns V32-20

IMV1.dll which returns V1.

These filenames do not contain brackets, so they should not be returning anything.

How to modify this UDF?

答:
I'm guessing that we might want to capture digits after V:

```<code>(?:.+V)([0-9.]+)(?:.+|$)
</code>```

We are adding a left and right boundary here using two non-capturing groups (?:.+V) and (?:.+|$) and in the middle, ([0-9.]+), we are capturing our desired number.

DEMO

Body:
I'm guessing that we might want to capture digits after V:

(?:.+V)([0-9.]+)(?:.+|$)

We are adding a left and right boundary here using two non-capturing groups (?:.+V) and (?:.+|$) and in the middle, ([0-9.]+), we are capturing our desired number.

DEMO


问:
resource for practical javascript exercise
I am beginner to webprogramming &  Javascript. I have went through few tutorials and learned the basics. Could someone suggest me the best resource with practical exercise with solutions.

I found "pagetutor.com" which has practical javascript exercises, but it's paid! Please
suggest any paid sites too which is really worth for practical learning.

答: I would have to say that http://javascript.crockford.com/ is one of the most important resources when learning (correct) JavaScript. Perhaps not as the first stop, but definitely when you've gotten the hang of the basics.</p>


问:
Command "make:factory" is not defined
[Symfony\Component\Console\Exception\CommandNotFoundException]
  Command "make:factory" is not defined.

php artisan make:factory PostFactory

[Symfony\Component\Console\Exception\CommandNotFoundException]
  Command "make:factory" is not defined.

答:
I think you have old versions of PHP and / or Laravel. Try upgrading with the following command:</p>

```<code>$ composer update
</code>```

Title: Command "make:factory" is not defined

Body:
I think you have old versions of PHP and / or Laravel. Try upgrading with the following command:

$ composer update


问:
android studio compare date child from firebase with date device
How can I compare the day and month that the user registered when registering with the day and month (firebase child: Cumpleaños) of the device used? this is what i tried

```<code>   protected void onStart() {
       super.onStart();
       CumpleañosRef = FirebaseDatabase.getInstance().getReference().child("Usuarios").child(CurrentUserID);
       Calendar calendar = Calendar.getInstance();

       final SimpleDateFormat currentDate = new SimpleDateFormat("dd-MMM", Locale.getDefault());
       saveCurrentDate = currentDate.format(calendar.getTime());
       CumpleañosRef.addListenerForSingleValueEvent(new ValueEventListener() {
           @Override
           public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
               if (dataSnapshot.child("Cumpleaños").equals(currentDate))
               {
                relativeLayout.setBackgroundColor(Color.parseColor("#dd89d7"));
               }
               else
               {
                   relativeLayout.setBackgroundColor(Color.parseColor("#ffffff"));
               }
           }

           @Override
           public void onCancelled(@NonNull DatabaseError databaseError) {

           }
       });
   }
</code>```

need that when the dates of firebase child and device coincide (day and month) change the color of the background.  Thanks

答:
You can always get the value of your child by calling getValue() (check for null to avoid NullPointerExceptions)

```<code>String dateAsStringFromDB = dataSnapshot.child("Cumpleaños").getValue();
</code>```

After you got the String value ("09-Nov" for example) currentDate to parse the dates

```<code>Date realtimeDate = currentDate.parse(saveCurrentDate);
Date dateFromDB = currentDate.parse(dateAsStringFromDB);
</code>```

Then comparing the dates using compareTo() method

```<code>if(realtimeDate.compareTo(dateFromDB) == 0 ){
 // do stuff ..

 }
</code>```

Don't forget to avoid null pointer and cast exceptions

Body:
How can I compare the day and month that the user registered when registering with the day and month (firebase child: Cumpleaños) of the device used? this is what i tried

   protected void onStart() {
       super.onStart();
       CumpleañosRef = FirebaseDatabase.getInstance().getReference().child("Usuarios").child(CurrentUserID);
       Calendar calendar = Calendar.getInstance();

       final SimpleDateFormat currentDate = new SimpleDateFormat("dd-MMM", Locale.getDefault());
       saveCurrentDate = currentDate.format(calendar.getTime());
       CumpleañosRef.addListenerForSingleValueEvent(new ValueEventListener() {
           @Override
           public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
               if (dataSnapshot.child("Cumpleaños").equals(currentDate))
               {
                relativeLayout.setBackgroundColor(Color.parseColor("#dd89d7"));
               }
               else
               {
                   relativeLayout.setBackgroundColor(Color.parseColor("#ffffff"));
               }
           }

           @Override
           public void onCancelled(@NonNull DatabaseError databaseError) {

           }
       });
   }

need that when the dates of firebase child and device coincide (day and month) change the color of the background.  Thanks

Body:
You can always get the value of your child by calling getValue() (check for null to avoid NullPointerExceptions)

String dateAsStringFromDB = dataSnapshot.child("Cumpleaños").getValue();

After you got the String value ("09-Nov" for example) currentDate to parse the dates

Date realtimeDate = currentDate.parse(saveCurrentDate);
Date dateFromDB = currentDate.parse(dateAsStringFromDB);

Then comparing the dates using compareTo() method

if(realtimeDate.compareTo(dateFromDB) == 0 ){
 // do stuff ..

 }

Don't forget to avoid null pointer and cast exceptions


问:
Webpack not working for simple project with npm start
This is my package file and webpack configuration.  I'm learning the technology but this isn't working.  I receive the following error for a blank canvas project.  Is there something I'm doing wrong?

Many thanks,

Error message

```<code>ERROR in ./src/index.js 6:16
Module parse failed: Unexpected token (6:16)
You may need an appropriate loader to handle this file type.
| import App from './App';
|
> ReactDOM.render(<App />, document.getElementById('root'));
</code>```

package.json

```<code>{
  "name": "boilerplate",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "webpack --mode development --watch",
    "build": "webpack --mode production"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "babel-core": "^6.26.3",
    "babel-loader": "^8.0.6",
    "babel-preset-env": "^1.7.0",
    "babel-preset-react": "^6.24.1",
    "css-loader": "^2.1.1",
    "html-webpack-plugin": "^3.2.0",
    "style-loader": "^0.23.1",
    "webpack": "^4.32.2",
    "webpack-cli": "^3.3.2"
  },
  "dependencies": {
    "react": "^16.8.6",
    "react-dom": "^16.8.6"
  }
}
</code>```

webpack.config.js

```<code>var HtmlWebpackPlugin = require('html-webpack-plugin');
var path = require('path');

module.exports = {
  entry: './src/index.js',
  output: {
    path: path.join(__dirname, './dist'),
    filename: 'index_bundle.js'
  },
  plugins: [new HtmlWebpackPlugin()]
};
</code>```

App.js

```<code>import React, { Component } from 'react';

class App extends Component {
    render() {
        return (
            <div>
                <h1>hello</h1>
            </div>
        )
    }
}
</code>```

I now have the following webpack.config.js

Update - complete file

```<code>var HtmlWebpackPlugin = require('html-webpack-plugin');
var path = require('path');

module.exports = {
  entry: './src/index.js',
  output: {
    path: path.join(__dirname, './dist'),
    filename: 'index_bundle.js'
  },
  resolve: {
    extensions: ['', '.js', '.jsx']
  },
  module: {
    loaders: [
      {
        test: /\.jsx?$/,
        loader: 'babel',
        exclude: /node_modules/,
        query: {
          cacheDirectory: true,
          presets: ['react', 'es2015']
        }
      }
    ]
  },
  plugins: [new HtmlWebpackPlugin()]
};
</code>```

After this change and after running npm install I get the following error when running npm start

```<code>Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
 - configuration.module has an unknown property 'loaders'. These properties are valid:
   object { defaultRules?, exprContextCritical?, exprContextRecursive?, exprContextRegExp?, exprContextRequest?, noParse?, rules?, strictExportPrese
nce?, strictThisContextOnImports?, unknownContextCritical?, unknownContextRecursive?, unknownContextRegExp?, unknownContextRequest?, unsafeCache?, w
rappedContextCritical?, wrappedContextRecursive?, wrappedContextRegExp? }
   -> Options affecting the normal modules (`NormalModuleFactory`).
 - configuration.resolve.extensions[0] should be an non-empty string.
   -> A non-empty string
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! boilerplate@1.0.0 start: `webpack --mode development --watch`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the boilerplate@1.0.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
</code>```

Update 2

```<code>var HtmlWebpackPlugin = require('html-webpack-plugin');
var path = require('path');

module.exports = {
  entry: './src/index.js',
  output: {
    path: path.join(__dirname, './dist'),
    filename: 'index_bundle.js'
  },
  resolve: {
    extensions: ['.js', '.jsx']
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
            loader: "babel-loader"
        }
      }
    ]
  },
  plugins: [new HtmlWebpackPlugin()]
};
</code>```

Error received with this version of the file

```<code>[./src/index.js] 3.16 KiB {main} [not cacheable] [built] [failed] [1 error]

ERROR in ./src/index.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
Error: Cannot find module '@babel/core'
 babel-loader@8 requires Babel 7.x (the package '@babel/core'). If you'd like to use Babel 6.x ('babel-core'), you should install 'babel-loader@7'.
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:613:15)
</code>```

答:
Add this in your webpack
...your code in webpack ...

```<code>,resolve: {
    extensions: ['', '.js', '.jsx']
  },
  module: {
    loaders: [
      {
        test: /\.jsx?$/,
        loader: 'babel',
        exclude: /node_modules/,
        query: {
          cacheDirectory: true,
          presets: ['react', 'es2015']
        }
      }
    ]
  }
</code>```

try npm install in your folder after that again use npm start

Body:
This is my package file and webpack configuration.  I'm learning the technology but this isn't working.  I receive the following error for a blank canvas project.  Is there something I'm doing wrong?

Many thanks,

Error message

ERROR in ./src/index.js 6:16
Module parse failed: Unexpected token (6:16)
You may need an appropriate loader to handle this file type.
| import App from './App';
|
> ReactDOM.render(<App />, document.getElementById('root'));

package.json

{
  "name": "boilerplate",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "webpack --mode development --watch",
    "build": "webpack --mode production"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "babel-core": "^6.26.3",
    "babel-loader": "^8.0.6",
    "babel-preset-env": "^1.7.0",
    "babel-preset-react": "^6.24.1",
    "css-loader": "^2.1.1",
    "html-webpack-plugin": "^3.2.0",
    "style-loader": "^0.23.1",
    "webpack": "^4.32.2",
    "webpack-cli": "^3.3.2"
  },
  "dependencies": {
    "react": "^16.8.6",
    "react-dom": "^16.8.6"
  }
}

webpack.config.js

var HtmlWebpackPlugin = require('html-webpack-plugin');
var path = require('path');

module.exports = {
  entry: './src/index.js',
  output: {
    path: path.join(__dirname, './dist'),
    filename: 'index_bundle.js'
  },
  plugins: [new HtmlWebpackPlugin()]
};

App.js

import React, { Component } from 'react';

class App extends Component {
    render() {
        return (

hello

        )
    }
}

I now have the following webpack.config.js

Update - complete file

var HtmlWebpackPlugin = require('html-webpack-plugin');
var path = require('path');

module.exports = {
  entry: './src/index.js',
  output: {
    path: path.join(__dirname, './dist'),
    filename: 'index_bundle.js'
  },
  resolve: {
    extensions: ['', '.js', '.jsx']
  },
  module: {
    loaders: [
      {
        test: /\.jsx?$/,
        loader: 'babel',
        exclude: /node_modules/,
        query: {
          cacheDirectory: true,
          presets: ['react', 'es2015']
        }
      }
    ]
  },
  plugins: [new HtmlWebpackPlugin()]
};

After this change and after running npm install I get the following error when running npm start

Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
 - configuration.module has an unknown property 'loaders'. These properties are valid:
   object { defaultRules?, exprContextCritical?, exprContextRecursive?, exprContextRegExp?, exprContextRequest?, noParse?, rules?, strictExportPrese
nce?, strictThisContextOnImports?, unknownContextCritical?, unknownContextRecursive?, unknownContextRegExp?, unknownContextRequest?, unsafeCache?, w
rappedContextCritical?, wrappedContextRecursive?, wrappedContextRegExp? }
   -> Options affecting the normal modules (`NormalModuleFactory`).
 - configuration.resolve.extensions[0] should be an non-empty string.
   -> A non-empty string
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! boilerplate@1.0.0 start: `webpack --mode development --watch`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the boilerplate@1.0.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

Update 2

var HtmlWebpackPlugin = require('html-webpack-plugin');
var path = require('path');

module.exports = {
  entry: './src/index.js',
  output: {
    path: path.join(__dirname, './dist'),
    filename: 'index_bundle.js'
  },
  resolve: {
    extensions: ['.js', '.jsx']
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
            loader: "babel-loader"
        }
      }
    ]
  },
  plugins: [new HtmlWebpackPlugin()]
};

Error received with this version of the file

[./src/index.js] 3.16 KiB {main} [not cacheable] [built] [failed] [1 error]

ERROR in ./src/index.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
Error: Cannot find module '@babel/core'
 babel-loader@8 requires Babel 7.x (the package '@babel/core'). If you'd like to use Babel 6.x ('babel-core'), you should install 'babel-loader@7'.
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:613:15)

Body:
Add this in your webpack
...your code in webpack ...

,resolve: {
    extensions: ['', '.js', '.jsx']
  },
  module: {
    loaders: [
      {
        test: /\.jsx?$/,
        loader: 'babel',
        exclude: /node_modules/,
        query: {
          cacheDirectory: true,
          presets: ['react', 'es2015']
        }
      }
    ]
  }

try npm install in your folder after that again use npm start


问:
Exclude beforeShowDay when determining maxDate
I'm "attempting" to create a system at work that allows my students to book equipment. I have two date inputs, for Date of Borrow, and Date of Return. Currently how it is setup, I have a bunch of dates, and the weekends disabled, and, students can't return the gear the day of borrow. The next step I'm attempting is to only offer students a return of the next available day

For instance, a student wants to borrow gear for the weekend but it is also a pupil free day on the Monday, so the Date of Return needs to only be Tuesday.

maxDate: 1 //doesn't take into account all the dates I have disabled from BeforeShowDay

I hope that made sense, here is my current, messy code.

< script type = "text/javascript" >
  jQuery(document).ready(function($) {
      $(function() {

        var publicd = ["4,3", "3,6", ];
        var term1 = ["15,4", "16,4", "17,4", "18,4", "19,4", "22,4", "23,4", "24,4", "25,4", "26,4", ];
        var term2 = ["7,7", "8,7", "9,7", "10,7", "11,7", "12,7", "15,7", "16,7", "17,7", "18,7", "19,7", ];
        var term3 = ["29,9", "30,9", "1,10", "2,10", "3,10", "4,10", "7,10", "8,10", "9,10", "10,10", "11,10"];
        var chrissy = ["2,12", "3,12", "4,12", "5,12", "6,12", "9,12", "10,12", "11,12", "12,12", "13,12", "16,12", "17,12", "18,12", "19,12", "20,12", "23,12", "24,12", "25,12", "26,12", "27,12", "30,12", "31,12", "1,1", "2,1", "3,1", "6,1", "7,1", "8,1", "9,1", "10,1", "13,1", "14,1", "15,1", "16,1", "17,1", "20,1", "21,1", "22,1", "23,1", "24,1", "27,1", "28,1", "29,1", "30,1", "31,1"];
        var pupil = ["8,3", "22,7", "15,11", "9,4", "27,5"];

        var combinedholidays = publicd.concat(term1, term2, term3, chrissy, pupil);

        function TotalHolidays(date) {
          var m = date.getMonth();
          var d = date.getDate();
          var currentdate = d + "," + (m + 1);
          for (var i = 0; i < combinedholidays.length; i++) {
            if ($.inArray(currentdate, combinedholidays) != -1) {
              return [false];
            }
          }
          var noWeekend = $.datepicker.noWeekends(date);
          return !noWeekend[0] ? noWeekend : [true];
        }

        $("#field_borrow").datepicker({
          dateFormat: 'yy/mm/dd',
          minDate: new Date(),
          beforeShowDay: TotalHolidays,
          showOn: "button",
          buttonImage: "https://jccamediaarts.edublogs.org/files/2018/06/if_calendar_285670-copy-2c5zvzr-2o5mcij-e1529025491810.png",
          buttonImageOnly: true,
          buttonText: "Select date",
          onSelect: function(date) {

            var selectedDate = new Date(date);
            var msecsInADay = 86400000;

            var endDate = new Date(selectedDate.getTime() + msecsInADay);

            $("#field_return").datepicker("option", "minDate", endDate);

          }
        });

        $("#field_return").datepicker({
          dateFormat: 'yy/mm/dd',
          beforeShowDay: TotalHolidays,
          showOn: "button",
          buttonImage: "https://jccamediaarts.edublogs.org/files/2018/06/if_calendar_285670-copy-2c5zvzr-2o5mcij-e1529025491810.png",
          buttonImageOnly: true,
          buttonText: "Select date"
        });

      }); <
      /script>```

Body:
I don't see any specific issues with the code you shown. I have updated it a bit and it seems to work as expected.

$(function() {
  var publicd = ["4,3", "3,6"];
  var term1 = ["15,4", "16,4", "17,4", "18,4", "19,4", "22,4", "23,4", "24,4", "25,4", "26,4", ];
  var term2 = ["7,7", "8,7", "9,7", "10,7", "11,7", "12,7", "15,7", "16,7", "17,7", "18,7", "19,7", ];
  var term3 = ["29,9", "30,9", "1,10", "2,10", "3,10", "4,10", "7,10", "8,10", "9,10", "10,10", "11,10"];
  var chrissy = ["2,12", "3,12", "4,12", "5,12", "6,12", "9,12", "10,12", "11,12", "12,12", "13,12", "16,12", "17,12", "18,12", "19,12", "20,12", "23,12", "24,12", "25,12", "26,12", "27,12", "30,12", "31,12", "1,1", "2,1", "3,1", "6,1", "7,1", "8,1", "9,1", "10,1", "13,1", "14,1", "15,1", "16,1", "17,1", "20,1", "21,1", "22,1", "23,1", "24,1", "27,1", "28,1", "29,1", "30,1", "31,1"];
  var pupil = ["8,3", "22,7", "15,11", "9,4", "27,5"];
  var dtFt = 'yy/mm/dd';

  var combinedHolidays = publicd.concat(term1, term2, term3, chrissy, pupil);

  function isHoliday(day, holidays) {
    var result = false;
    if ($.inArray(day, holidays) >= 0) {
      result = true;
    };
    return result;
  }

  function isWeekend(dt) {
    var result = $.datepicker.noWeekends(dt);
    return !result[0];
  }

  function TotalHolidays(date) {
    var m = date.getMonth();
    var d = date.getDate();
    var currentDate = d + "," + (m + 1);
    var result = [true, "weekDay"];
    if (isHoliday(currentDate, combinedHolidays) || isWeekend(date)) {
      result = [false, ""];
    }
    return result;
  }

  $("#borrow, #return").datepicker({
    dateFormat: dtFt,
    beforeShowDay: TotalHolidays,
    showOn: "button",
    buttonImage: "https://jccamediaarts.edublogs.org/files/2018/06/if_calendar_285670-copy-2c5zvzr-2o5mcij-e1529025491810.png",
    buttonImageOnly: true,
    buttonText: "Select date"
  });

  $("#borrow").datepicker("option", {
    minDate: new Date(),
    onSelect: function(date) {
      var selectedDate = new Date(date);
      var msecsInADay = 86400000;
      var endDate = new Date(selectedDate.getTime() + msecsInADay);
      $("#return").datepicker("option", "minDate", endDate);
    }
  });
});

<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<p>Borrow Date: <input type="text" id="borrow" /></p>
<p>Return Date: <input type="text" id="return" /></p>

Hope that helps.


问:
How to calculate yearly stock beta
I have 33 years of weekly data of a particular stock and S&P500 index return.
I want to calculate 33 yearly stock betas based on 52 weekly observations of stock return.

I know that beta can be calculated using covarience and varience. I have found that pandas has a function pd.rolling.cov, but it does not work.
module 'pandas' has no attribute 'rolling'

```<code>import pandas as pd
import numpy as np
stock=pd.read_excel(r"C:\01.xlsx", '2') #read second sheet of excel file
stock['stockreturn']=np.log(stock.AdjCloseStock / stock.AdjCloseStock.shift(1)) #stock ln return
stock['SP500return']=np.log(stock.AdjCloseSP500 / [enter image description here][1]stock.AdjCloseSP500.shift(1)) #SP500 ln return
stock = stock.iloc[1:] #delete first row in dataframe
stock['beta'] = pd.rolling.cov(stock['stockreturn'], stock['SP500return'],
window=52) / pd.rolling.var(stock['SP500return'], window=52)
</code>```

Frankly speaking I do not know how to get 33 yearly betas out of 33 52-weeks observation. Any help is appreciated.

print screen of my data frame

答:
You were looking for pd.core.window.Rolling.cov.
To spell the method name correctly,
we ask that you Read The Fine Manual,

cf Create rolling covariance matrix in pandas

Title: How to calculate yearly stock beta

Body:
I have 33 years of weekly data of a particular stock and S&P500 index return.
I want to calculate 33 yearly stock betas based on 52 weekly observations of stock return.

I know that beta can be calculated using covarience and varience. I have found that pandas has a function pd.rolling.cov, but it does not work.
module 'pandas' has no attribute 'rolling'

import pandas as pd
import numpy as np
stock=pd.read_excel(r"C:\01.xlsx", '2') #read second sheet of excel file
stock['stockreturn']=np.log(stock.AdjCloseStock / stock.AdjCloseStock.shift(1)) #stock ln return
stock['SP500return']=np.log(stock.AdjCloseSP500 / [enter image description here][1]stock.AdjCloseSP500.shift(1)) #SP500 ln return
stock = stock.iloc[1:] #delete first row in dataframe
stock['beta'] = pd.rolling.cov(stock['stockreturn'], stock['SP500return'],
window=52) / pd.rolling.var(stock['SP500return'], window=52)

Frankly speaking I do not know how to get 33 yearly betas out of 33 52-weeks observation. Any help is appreciated.

print screen of my data frame


问:
monitor a program's memory usage in Linux
Are there any tools available in Linux which graphically or textually display memory usage for a program?  For example, if I write a C++ program and would like to verify that objects are being allocated and deallocated properly in memory, are there applications available that would visually show the objects being instantiated and deleted?  When I used to program in Visual Studio, I remember stepping through a program and using a debug pane to monitor memory usage and am looking for something similar to that in Linux.  </p>

答: It's not exactly what you are looking for, but have a look at Valgrind.</p>

OwnerDisplayName: Chris

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Nathan Fellman

OwnerDisplayName: UncleZeiv


答:
you could try http://www.w3schools.com/js/default.asp. it's a very basic intro to the language.

Also I would recommend JavaScript: The Definitive Guide

very nice book, describes the language in details.

Also Douglas Crockford's JavaScript: The Good Parts

And probably some good blogs:

http://www.catswhocode.com/blog/

http://net.tutsplus.com/

http://www.webappers.com/

for exercise I would recommend jsFiddle

Title: resource for practical javascript exercise

Body:
I am beginner to webprogramming &  Javascript. I have went through few tutorials and learned the basics. Could someone suggest me the best resource with practical exercise with solutions.

I found "pagetutor.com" which has practical javascript exercises, but it's paid! Please
suggest any paid sites too which is really worth for practical learning.


问:
How to extract an ID number from a string?
How do I retrieve the middle value using regex or preg_match?

```<code>$str = 'fxs_124024574287414=base_domain=.example.com; datr=KWHazxXEIkldzBaVq_of--syv5; csrftoken=szcwad; ds_user_id=219132; mid=XN4bpAAEAAHOyBRR4V17xfbaosyN; sessionid=14811313756%12fasda%3A27; rur=VLL;'
</code>```

How do I only get values from ds_user_id using regex or preg_match?

答:
Use preg_match to match ds_user_id=, then forget those matched characters with \K, then match one or more digits.  No capture groups, no lookarounds, no parsing all the key-value pairs, no exploding.

Code: (Demo)

```<code>$str = 'fxs_124024574287414=base_domain=.example.com; datr=KWHazxXEIkldzBaVq_of--syv5; csrftoken=szcwad; ds_user_id=219132; mid=XN4bpAAEAAHOyBRR4V17xfbaosyN; sessionid=14811313756%12fasda%3A27; rur=VLL;';
echo preg_match('~ds_user_id=\K\d+~', $str, $out) ? $out[0] : 'no match';
</code>```

Output:

```<code>219132
</code>```

Body:
How do I retrieve the middle value using regex or preg_match?

$str = 'fxs_124024574287414=base_domain=.example.com; datr=KWHazxXEIkldzBaVq_of--syv5; csrftoken=szcwad; ds_user_id=219132; mid=XN4bpAAEAAHOyBRR4V17xfbaosyN; sessionid=14811313756%12fasda%3A27; rur=VLL;'

How do I only get values from ds_user_id using regex or preg_match?

Body:
Use preg_match to match ds_user_id=, then forget those matched characters with \K, then match one or more digits.  No capture groups, no lookarounds, no parsing all the key-value pairs, no exploding.

Code: (Demo)

$str = 'fxs_124024574287414=base_domain=.example.com; datr=KWHazxXEIkldzBaVq_of--syv5; csrftoken=szcwad; ds_user_id=219132; mid=XN4bpAAEAAHOyBRR4V17xfbaosyN; sessionid=14811313756%12fasda%3A27; rur=VLL;';
echo preg_match('~ds_user_id=\K\d+~', $str, $out) ? $out[0] : 'no match';

Output:

219132


问:
How to convert multiple rows into one row to get sum quantity
I will need to combine multiple rows into one row to get the total of number. My table looks like this

```<code>Sublot_Number Lot_Number Qty Pallet_ID
------------- ---------- --- ---------
 S1             L1        1    P1
 S2             L2        1    P1
 S3             L3        3    P1
</code>```

My result should looks like this

```<code>Sublot_Number  Lot_Num1 Lot_Num2 Lot_Num3 Qty_Sum Pallet_ID
-------------  -------- -------- -------- ------- ---------
Random Number    L1       L2        L3      5        P1
</code>```

I tried Pivot, but no luck. There may be more than 3 sublot will be used for the same Pallet, but I only will pick any three Sublot as Lot_Num1, Lot_Num2 and Lot_Num3

What would be a solution in this situation.

答:
You can use conditional aggregation (or pivot), but the key is row_number():

```<code>select rand(checksum(newid())) as sublot_number,
       pallet_id,
       max(case when seqnum = 1 then lot_number end) as lot_num1,
       max(case when seqnum = 2 then lot_number end) as lot_num2,
       max(case when seqnum = 3 then lot_number end) as lot_num3,
       sum(qty)
from (select t.*,
             row_number() over (partition by pallet_id order by (select null)) as seqnum
      from t
     ) t
group by pallet_id;
</code>```

If you want the sum of the quantity to only be for the three chosen lots, then add where seqnum <= 3 to the outer query.

If you have some sort of prioritization -- such as the largest quantities -- then use that for the order by.

Body:
I will need to combine multiple rows into one row to get the total of number. My table looks like this

Sublot_Number Lot_Number Qty Pallet_ID
------------- ---------- --- ---------
 S1             L1        1    P1
 S2             L2        1    P1
 S3             L3        3    P1

My result should looks like this

Sublot_Number  Lot_Num1 Lot_Num2 Lot_Num3 Qty_Sum Pallet_ID
-------------  -------- -------- -------- ------- ---------
Random Number    L1       L2        L3      5        P1

I tried Pivot, but no luck. There may be more than 3 sublot will be used for the same Pallet, but I only will pick any three Sublot as Lot_Num1, Lot_Num2 and Lot_Num3

What would be a solution in this situation.

Body:
You can use conditional aggregation (or pivot), but the key is row_number():

select rand(checksum(newid())) as sublot_number,
       pallet_id,
       max(case when seqnum = 1 then lot_number end) as lot_num1,
       max(case when seqnum = 2 then lot_number end) as lot_num2,
       max(case when seqnum = 3 then lot_number end) as lot_num3,
       sum(qty)
from (select t.*,
             row_number() over (partition by pallet_id order by (select null)) as seqnum
      from t
     ) t
group by pallet_id;

If you want the sum of the quantity to only be for the three chosen lots, then add where seqnum <= 3 to the outer query.

If you have some sort of prioritization -- such as the largest quantities -- then use that for the order by.


问:
Sum of certain items in a list
I'm working on a probability-related problem. I need to sum only specific items on a certain list.

I've tried using "for" functions and it hasn't worked. I'm looking for a way to select items based on their positions on the list, and summing them.

答:
You can use operator.itemgetter to select only certian index’s in a list or keys in a dict.

```<code>from operator import itemgetter

data = [1, 2, 3, 4, 5, 6, 7, 8]
get_indexes = itemgetter(2, 5, 7)
#this will return indexes 2, 5, 7 from a sequence
sum(get_indexes(data)) #3+6+8
#returns 17
</code>```

That example is for lists but you can use itemgetter for dict keys too just use itemgetter('key2', 'key5', 'key7')({some_dict})

To get only even or odd indexes use slicing not enumerate and a loop it’s much more efficient and easier to read:

```<code>even = sum(data[::2])
odd = sum(data[1::2])
</code>```

You can also use filter but I wouldn’t suggest this for getting by index:

```<code>sum(filter(lambda n: data.index(n) % 2 == 0, data))
</code>```

Title: Sum of certain items in a list

Body:
You can use operator.itemgetter to select only certian index’s in a list or keys in a dict.

from operator import itemgetter

data = [1, 2, 3, 4, 5, 6, 7, 8]
get_indexes = itemgetter(2, 5, 7)
#this will return indexes 2, 5, 7 from a sequence
sum(get_indexes(data)) #3+6+8
#returns 17

That example is for lists but you can use itemgetter for dict keys too just use itemgetter('key2', 'key5', 'key7')({some_dict})

To get only even or odd indexes use slicing not enumerate and a loop it’s much more efficient and easier to read:

even = sum(data[::2])
odd = sum(data[1::2])

You can also use filter but I wouldn’t suggest this for getting by index:

sum(filter(lambda n: data.index(n) % 2 == 0, data))


问:
How to include spaces in req.body variables
Let's say I have a variable:

```<code>var name = "Joe Smith"
</code>```

That I want to include in a POST request via form + option so that I add Joe Smith to my database.

I have already created my form and options and verified that it sends over the name to my controllers/middleware.

I would expect that when I send over the name in the POST request, a call to:

```<code>req.body.name
</code>```

on the server side would return:

```<code>Joe Smith
</code>```

However, for some reason white spaces are ignored and req.body.name evaluates to:

```<code>Joe
</code>```

Similar variables with white spaces in their names/values have this error and as a result I cannot look up these objects in the database and update properly. How can I resolve this issue?

Thank you!

EDIT: Here is my script code--I used jQuery to populate options in a select with the names of people in my database

```<code>$(function() {

  var $people = $("#people");
     $.ajax({
        type: 'GET',
        url: '/getAllPeopleData',
        success: function(people) {
            $.each(people, function(i, person) {
               $people.append('<option value=' + person.name + '>' +
               person.name + '</option');
              });
            }
         });
     });
</code>```

My form allows the user to select one person's name and adds it to the database:

```<code>    <form action="/addPerson" method="POST">
        Select a Person: <br>
        <select id="people" name="name"></select> <br>
        <input type="submit" value="Submit"> <br>
    </form?
</code>```

答:
If you can share your html form it can be helpful to answer. I can blindly guess you have to use it in a form as a variable. I should have commented but I'm not yet level 50.

I ran this sample code and it worked:

```<code><form action="/" method="POST">
 <% var name = 'Joe Smith' %>
 <input type="text" name="name" value="<%= name %>">
 <button type="submit">Submit</button>
</form>
</code>```

In the post route, I console logged it out and it came like:

```<code>POST / 200 1.094 ms - 5
GET / 200 2.202 ms - 352
Joe Smith
</code>```

Body:
Let's say I have a variable:

var name = "Joe Smith"

That I want to include in a POST request via form + option so that I add Joe Smith to my database.

I have already created my form and options and verified that it sends over the name to my controllers/middleware.

I would expect that when I send over the name in the POST request, a call to:

req.body.name

on the server side would return:

Joe Smith

However, for some reason white spaces are ignored and req.body.name evaluates to:

Joe

Similar variables with white spaces in their names/values have this error and as a result I cannot look up these objects in the database and update properly. How can I resolve this issue?

Thank you!

EDIT: Here is my script code--I used jQuery to populate options in a select with the names of people in my database

$(function() {

  var $people = $("#people");
     $.ajax({
        type: 'GET',
        url: '/getAllPeopleData',
        success: function(people) {
            $.each(people, function(i, person) {
               $people.append('<option value=' + person.name + '>' +
               person.name + '</option');
              });
            }
         });
     });

My form allows the user to select one person's name and adds it to the database:

    <form action="/addPerson" method="POST">
        Select a Person:

        <select id="people" name="name"></select>

        <input type="submit" value="Submit">

    </form?

Body:
If you can share your html form it can be helpful to answer. I can blindly guess you have to use it in a form as a variable. I should have commented but I'm not yet level 50.

I ran this sample code and it worked:

<form action="/" method="POST">
 <% var name = 'Joe Smith' %>
 <input type="text" name="name" value="<%= name %>">
 <button type="submit">Submit</button>
</form>

In the post route, I console logged it out and it came like:

POST / 200 1.094 ms - 5
GET / 200 2.202 ms - 352
Joe Smith


问:
lodash: Get duplicate values from an array
Say I have an array like this: [1, 1, 2, 2, 3]

I want to get the duplicates which are in this case: [1, 2]

Does lodash support this? I want to do it in the shortest way possible.

答:
Here is another concise solution:

let data = [1, 1, 2, 2, 3]

let result = _.uniq(_.filter(data, (v, i, a) => a.indexOf(v) !== i))

console.log(result)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script></code>```

_.uniq takes care of the dubs which _.filter comes back with.

Same with ES6 and Set:

let data = [1, 1, 2, 2, 3]

let result = new Set(data.filter((v, i, a) => a.indexOf(v) !== i))

console.log(Array.from(result))```

Body:
Here is another concise solution:

let data = [1, 1, 2, 2, 3]

let result = _.uniq(_.filter(data, (v, i, a) => a.indexOf(v) !== i))

console.log(result)

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

_.uniq takes care of the dubs which _.filter comes back with.

Same with ES6 and Set:

let data = [1, 1, 2, 2, 3]

let result = new Set(data.filter((v, i, a) => a.indexOf(v) !== i))

console.log(Array.from(result))


答:
Void function means the function that does not return any value, so it is wrong to use void function.

If you want to get a value from the method. You should use a method that can return a value as following :

```<code>public class Factorial {

    public int facto()
    {
    int fact=1;
    int n=5,i=1;

        for(i=n;i>=1;i--)
        {
            fact=fact*i;
        }
     return fact;
    }

    public static void main(String args[])
    {
        Factorial obj1= new Factorial();
        System.out.println(obj1.facto());
    }
}
</code>```

ps : I have changed the place of variables to scope of facto() method with warning of @Idle_Mind.
Because  this has a slight side effect in that if you call facto() more than once you'll get different results. To "fix" this you could re-initialize "fact" to 1 inside facto()

Title: How can I use varible from another function?

Body:
For printing the value of factorial, I want to use the value of fact in the facto() function. How can I achieve this?

I have tried declaring variables i and fact in the facto() function.

public class Factorial {
    int fact=1;
    int n=5,i=1;

    void facto()
    {

        for(i=n;i>=1;i--)
        {
            fact=fact*i;
        }

    }

    public static void main(String args[])
    {
        Factorial obj1= new Factorial();
        System.out.println(obj1.fact);
    }
}

The answer I'm getting is what it gets the value from the class and is initialized with 1. I want to get 120 as the solution.

Body:
Void function means the function that does not return any value, so it is wrong to use void function.

If you want to get a value from the method. You should use a method that can return a value as following :

public class Factorial {

    public int facto()
    {
    int fact=1;
    int n=5,i=1;

        for(i=n;i>=1;i--)
        {
            fact=fact*i;
        }
     return fact;
    }

    public static void main(String args[])
    {
        Factorial obj1= new Factorial();
        System.out.println(obj1.facto());
    }
}

ps : I have changed the place of variables to scope of facto() method with warning of @Idle_Mind.
Because  this has a slight side effect in that if you call facto() more than once you'll get different results. To "fix" this you could re-initialize "fact" to 1 inside facto()


问:
How to save the date and time when a Core Data object is created
I want to save & retrieve the timestamp of when the note was created in Core Data

Please guide me on how I can do this.

答:
Just to keep this question up-to-date with Swift, in the xcdatamodelid click the entity you wish to create a default date. Under the Data Model Inspector change Codegen from "Class Definition" to "Manual/None":

Then from the menu bar click Editor -> Create NSManagedObject Subclass... and create the two Swift classes: Note+CoreDataClass.swift and Note+CoreDataProperties.swift

Open the Note+CoreDataClass.swift file and add the following code:

```<code>import Foundation
import CoreData

@objc(Note)
public class Note: NSManagedObject {
    override public func awakeFromInsert() {
        super.awakeFromInsert()
        self.creationDate = Date() as NSDate
    }
}
</code>```

Now the creationDate will get a default date of the current date/time.

Body:
Just to keep this question up-to-date with Swift, in the xcdatamodelid click the entity you wish to create a default date. Under the Data Model Inspector change Codegen from "Class Definition" to "Manual/None":

Then from the menu bar click Editor -> Create NSManagedObject Subclass... and create the two Swift classes: Note+CoreDataClass.swift and Note+CoreDataProperties.swift

Open the Note+CoreDataClass.swift file and add the following code:

import Foundation
import CoreData

@objc(Note)
public class Note: NSManagedObject {
    override public func awakeFromInsert() {
        super.awakeFromInsert()
        self.creationDate = Date() as NSDate
    }
}

Now the creationDate will get a default date of the current date/time.