问:
Using PHP array in the JS code in PDO
I'm trying to use a PHP array in the JS but encountered the error I don't know how to fix.

I was using this example (in my case - it's PDO, not mysqli.): Inserting MYSQL results from PHP into Javascript Array

```<code>$pdo = new PDO('mysql:host=localhost; dbname=' . $db_name . '; charset=utf8mb4', $db_user, $db_password);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$type_zagon = 1;
$id_kurat = 1;
$usid = 78;

$stmt1 = $pdo->prepare("SELECT num FROM tb_zagon_id WHERE status = :status
    AND type = :type AND zagon_id = :zagon_id AND user_id = :usid ORDER BY num");
$num = $stmt1->fetchColumn();
$stmt1->execute(array(
    ':status' => 1,
    ':type' => $type_zagon,
    ':zagon_id' => $id_kurat,
    ':usid' => $usid
));

    $gyvuliu_array = array();

    while ($stmt1->fetch(PDO::FETCH_ASSOC)) {
        $gyvuliu_array[] = $num;
    }

    $array_encode = json_encode($gyvuliu_array);
?>
    <script>
        $('.surinkti_produkcija_paserti_gyvulius').click(function() {
            var gyvuliai_fermoje = '<?php echo $array_encode; ?>';
            var gyvuliu_array = [1,2,3,4,5,6,7,8,9];

            for (var i=0, l=gyvuliu_array.length; i<l; i++) { // WORKS
                console.log(gyvuliu_array[i]);
            }

            // DOESN'T WORK (console returns f,a,l,s,e,f,a,l,s,e and so on..)
            for (var i=0, l=gyvuliai_fermoje.length; i<l; i++) {
                console.log(gyvuliai_fermoje[i]);
            }
        });
    </script>
</code>```

I guess something is bad with the $num variable but I'm not sure.

EDIT:
I've changed the second for loop and it looks like it's working:

```<code>for (var i=0, l=gyvuliai_fermoje.length; i<l; i++) {
    console.log(gyvuliai_fermoje[i]);
}
</code>```

But I'm not sure if it's ok they aren't in the same row.
http://prntscr.com/ft4i9m

EDIT 2 After rickdenhaan's comment, it looks exactly how first for loop. Is it ok? Am I done?

答:
Problem solved! :) For future visitors, combined all this stuff you guys said, we have this code:

```<code>// PDO Connection
$pdo = new PDO('mysql:host=localhost; dbname=' . $db_name . ';
    charset=utf8mb4', $db_user, $db_password);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// Prepared statement with placeholders
$stmt1 = $pdo->prepare("SELECT num FROM tb_zagon_id WHERE status = :status
    AND type = :type AND zagon_id = :zagon_id AND user_id = :usid ORDER BY num");

// Binding query result to the $num variable (1 is the first column)
$stmt1->bindColumn(1, $num);

// Executing query and replacing placeholders with some variables
$stmt1->execute(array(
    ':status' => 1,
    ':type' => $type_zagon,
    ':zagon_id' => $id_kurat,
    ':usid' => $usid
));

// Creating a PHP array
$gyvuliu_array = array();

// Fetching through the array and inserting query results using $num variable ((int) makes sure a value is an integer)
while ($stmt1->fetch(PDO::FETCH_ASSOC)) {
    $gyvuliu_array[] = (int)$num;
}

// Encoding PHP array so we will be able to use it in the JS code
$array_encode = json_encode($gyvuliu_array);
?>
<script>
    var gyvuliai_fermoje = <?php echo $array_encode; ?>;

    for (var i = 0; i < gyvuliai_fermoje.length; i++) {
        // Stuff you would like to do with this array, access elements using gyvuliai_fermoje[i]
    }
</script>
</code>```

I hope it will help you to understand how to use a PHP array in the JS code in PDO :)

Title: Using PHP array in the JS code in PDO

Body:
I'm trying to use a PHP array in the JS but encountered the error I don't know how to fix.

I was using this example (in my case - it's PDO, not mysqli.): Inserting MYSQL results from PHP into Javascript Array

$pdo = new PDO('mysql:host=localhost; dbname=' . $db_name . '; charset=utf8mb4', $db_user, $db_password);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$type_zagon = 1;
$id_kurat = 1;
$usid = 78;

$stmt1 = $pdo->prepare("SELECT num FROM tb_zagon_id WHERE status = :status
    AND type = :type AND zagon_id = :zagon_id AND user_id = :usid ORDER BY num");
$num = $stmt1->fetchColumn();
$stmt1->execute(array(
    ':status' => 1,
    ':type' => $type_zagon,
    ':zagon_id' => $id_kurat,
    ':usid' => $usid
));

    $gyvuliu_array = array();

    while ($stmt1->fetch(PDO::FETCH_ASSOC)) {
        $gyvuliu_array[] = $num;
    }

    $array_encode = json_encode($gyvuliu_array);
?>

I guess something is bad with the $num variable but I'm not sure.

EDIT:
I've changed the second for loop and it looks like it's working:

for (var i=0, l=gyvuliai_fermoje.length; i<l; i++) {
    console.log(gyvuliai_fermoje[i]);
}

But I'm not sure if it's ok they aren't in the same row.
http://prntscr.com/ft4i9m

EDIT 2 After rickdenhaan's comment, it looks exactly how first for loop. Is it ok? Am I done?

Body:
Problem solved! :) For future visitors, combined all this stuff you guys said, we have this code:

// PDO Connection
$pdo = new PDO('mysql:host=localhost; dbname=' . $db_name . ';
    charset=utf8mb4', $db_user, $db_password);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// Prepared statement with placeholders
$stmt1 = $pdo->prepare("SELECT num FROM tb_zagon_id WHERE status = :status
    AND type = :type AND zagon_id = :zagon_id AND user_id = :usid ORDER BY num");

// Binding query result to the $num variable (1 is the first column)
$stmt1->bindColumn(1, $num);

// Executing query and replacing placeholders with some variables
$stmt1->execute(array(
    ':status' => 1,
    ':type' => $type_zagon,
    ':zagon_id' => $id_kurat,
    ':usid' => $usid
));

// Creating a PHP array
$gyvuliu_array = array();

// Fetching through the array and inserting query results using $num variable ((int) makes sure a value is an integer)
while ($stmt1->fetch(PDO::FETCH_ASSOC)) {
    $gyvuliu_array[] = (int)$num;
}

// Encoding PHP array so we will be able to use it in the JS code
$array_encode = json_encode($gyvuliu_array);
?>
<script>
    var gyvuliai_fermoje = <?php echo $array_encode; ?>;

    for (var i = 0; i < gyvuliai_fermoje.length; i++) {
        // Stuff you would like to do with this array, access elements using gyvuliai_fermoje[i]
    }
</script>

I hope it will help you to understand how to use a PHP array in the JS code in PDO :)


来源: stackexchange

问:
Get output from database on server, but not on php script
I have an very nasty issue....

My usage for this code: I wanna get through AJAX, just 5 records everytime i click on the further-button. I´m not so far yet....

This script just have to get me 5 records from a specific user.

The Problem:

So the sql queries run without any problems on the Database. But when i wanna  do it in PHP-script, i get ONLY from the first query the counter() AND the second query gives me an empty array from the PDO-Statement.

CODE:

```<code>if (empty($_SESSION['counter']) || ($_SESSION['counter'] < 0)) {

      $sql = 'SELECT count(record.record_id) AS counter FROM record
              LEFT JOIN recordbook ON record.record_id = recordbook.record
              WHERE user = ?';

              $sth = $this->dbc->prepare($sql);
              $sth->execute(array($u_id['user_id']));
              $count = $sth->fetch();

              $_SESSION['counter'] = $count['counter'];
              var_dump($_SESSION);
          }
          $_SESSION['counter'] = $_SESSION['counter'] - 5;

          $sql = 'SELECT record.record_id, status, place, record.record AS records, comment, recorddate
                  FROM record LEFT JOIN recordbook ON record.record_id = recordbook.record
                  WHERE user = ? ORDER BY record.record_id DESC LIMIT ?,5';
          $sth = $this->dbc->prepare($sql);
          $sth->execute(array($u_id['user_id'],
                                $_SESSION['counter']));

          $output = $sth->fetchAll();
}
</code>```

HOPE someone know how to solve this...

table structure

```<code>Field | Type | Null | Key | Default | Extra
record_id | int(10) unsigned | NO | PRI NULL | auto_increment
status | varchar(200) | YES | NULL |
place | varchar(200) | YES | NULL
record | longtext | YES NULL
comment | longtext | YES | NULL
recorddate | timestamp | YES | CURRENT_TIMESTAMP
attachment_id | int(10) unsigned | YES | MUL | NULL
</code>```

答:
ok, done! No error....

need to bind the variables to the query. Seems so, that only with prepare and execute, is it not clear enough. So add bindParam(for integer) or bindValue(for Strings) to code, than it goes nice and smoothly :)

Have seen that on PHP.net and with debugDumpParams() on PDOStatement you can see, how your Query is working with the Params you setted.

Here the manual http://php.net/manual/de/pdostatement.debugdumpparams.php

ContentLicense: CC BY-SA 3.0

Body:
I have an very nasty issue....

My usage for this code: I wanna get through AJAX, just 5 records everytime i click on the further-button. I´m not so far yet....

This script just have to get me 5 records from a specific user.

The Problem:

So the sql queries run without any problems on the Database. But when i wanna  do it in PHP-script, i get ONLY from the first query the counter() AND the second query gives me an empty array from the PDO-Statement.

CODE:

if (empty($_SESSION['counter']) || ($_SESSION['counter'] < 0)) {

      $sql = 'SELECT count(record.record_id) AS counter FROM record
              LEFT JOIN recordbook ON record.record_id = recordbook.record
              WHERE user = ?';

              $sth = $this->dbc->prepare($sql);
              $sth->execute(array($u_id['user_id']));
              $count = $sth->fetch();

              $_SESSION['counter'] = $count['counter'];
              var_dump($_SESSION);
          }
          $_SESSION['counter'] = $_SESSION['counter'] - 5;

          $sql = 'SELECT record.record_id, status, place, record.record AS records, comment, recorddate
                  FROM record LEFT JOIN recordbook ON record.record_id = recordbook.record
                  WHERE user = ? ORDER BY record.record_id DESC LIMIT ?,5';
          $sth = $this->dbc->prepare($sql);
          $sth->execute(array($u_id['user_id'],
                                $_SESSION['counter']));

          $output = $sth->fetchAll();
}

HOPE someone know how to solve this...

table structure

Field | Type | Null | Key | Default | Extra
record_id | int(10) unsigned | NO | PRI NULL | auto_increment
status | varchar(200) | YES | NULL |
place | varchar(200) | YES | NULL
record | longtext | YES NULL
comment | longtext | YES | NULL
recorddate | timestamp | YES | CURRENT_TIMESTAMP
attachment_id | int(10) unsigned | YES | MUL | NULL


问:
How to change more extensions in .htaccess with mod_rewrite?
Now I have this and rewrite index.php to index

```<code>RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.])$ $1.php [NC,L]
</code>```

But I want also that the file names about.html change to about without the .html
How do i do that?

答:
See This

FOR REMOVE .PHP

```<code>RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php
</code>```

FOR REMOVE .HTML

```<code>RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.html -f
RewriteRule ^(.*)$ $1.html
</code>```

Body:
Now I have this and rewrite index.php to index

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.])$ $1.php [NC,L]

But I want also that the file names about.html change to about without the .html
How do i do that?

Body:
See This

FOR REMOVE .PHP

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php

FOR REMOVE .HTML

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.html -f
RewriteRule ^(.*)$ $1.html


问:
How to set range of separate cells in DataSeriesValues PHPExcel RadarChart
I can't make radar chart with PHPExcel. I need to add to DataSeriesValues range of separate cells

```<code>$xAxisTickValues = [
        new \PHPExcel_Chart_DataSeriesValues('String', $sn.'!$B$5', NULL, 1),
        new \PHPExcel_Chart_DataSeriesValues('String', $sn.'!$B$10', NULL, 1),
        new \PHPExcel_Chart_DataSeriesValues('String', $sn.'!$B$14', NULL, 1),
        new \PHPExcel_Chart_DataSeriesValues('String', $sn.'!$B$17', NULL, 1),
]; //This works fine

$xAxisTickValues = [
        new \PHPExcel_Chart_DataSeriesValues('String', $sn.'!$B$5:$B$10', NULL, 1),
];//This works too
</code>```

I need something like this:

```<code>    $xAxisTickValues = [
        new \PHPExcel_Chart_DataSeriesValues('String', $sn.'!$B$5;'.$sn.'!$A$15', NULL, 1),
    ]; //but this won't work
</code>```

答:
I've not tried it myself; but have you tried using a , separator for the ranges rather than a ;? PHPExcel expects US/UK "syntax", and the separator for cell ranges in US/UK is the ,

```<code>$xAxisTickValues = [
    new \PHPExcel_Chart_DataSeriesValues('String', $sn.'!$B$5,'.$sn.'!$A$15', NULL, 1),
];
</code>```

Body:
I can't make radar chart with PHPExcel. I need to add to DataSeriesValues range of separate cells

$xAxisTickValues = [
        new \PHPExcel_Chart_DataSeriesValues('String', $sn.'!$B$5', NULL, 1),
        new \PHPExcel_Chart_DataSeriesValues('String', $sn.'!$B$10', NULL, 1),
        new \PHPExcel_Chart_DataSeriesValues('String', $sn.'!$B$14', NULL, 1),
        new \PHPExcel_Chart_DataSeriesValues('String', $sn.'!$B$17', NULL, 1),
]; //This works fine

$xAxisTickValues = [
        new \PHPExcel_Chart_DataSeriesValues('String', $sn.'!$B$5:$B$10', NULL, 1),
];//This works too

I need something like this:

    $xAxisTickValues = [
        new \PHPExcel_Chart_DataSeriesValues('String', $sn.'!$B$5;'.$sn.'!$A$15', NULL, 1),
    ]; //but this won't work

Body:
I've not tried it myself; but have you tried using a , separator for the ranges rather than a ;? PHPExcel expects US/UK "syntax", and the separator for cell ranges in US/UK is the ,

$xAxisTickValues = [
    new \PHPExcel_Chart_DataSeriesValues('String', $sn.'!$B$5,'.$sn.'!$A$15', NULL, 1),
];


问:
How can I bound a type parameter for Tuples without relying on Product?
I'm trying to declare a function with a type parameter that I want to bound so that only instances of TupleN are accepted. However, I don't want to bound on Product as instances of case classes, for example, should not be accepted. For instance, if the function is named foo:

case class Foo(a: Int, b: String)
foo(Foo(1, "str")) // should not compile
foo((1, "str"))    // should compile
```

I can achieve this by enumerating all TupleN instances for a custom type class and then using a context bound on the type parameter, but I'd prefer to avoid it.

Is it possible to do that in a simpler way?

答:
If you're OK with depending on shapeless, you can rely on the IsTuple type class to provide evidence that a given type is a Scala tuple:

import shapeless._

def foo[A: IsTuple](v: A) = ???
foo((1, "str")) // compiles
foo(Foo(1, "str")) // does not compile due to lack of evidence
```

Body:
I'm trying to declare a function with a type parameter that I want to bound so that only instances of TupleN are accepted. However, I don't want to bound on Product as instances of case classes, for example, should not be accepted. For instance, if the function is named foo:

case class Foo(a: Int, b: String)
foo(Foo(1, "str")) // should not compile
foo((1, "str"))    // should compile

I can achieve this by enumerating all TupleN instances for a custom type class and then using a context bound on the type parameter, but I'd prefer to avoid it.

Is it possible to do that in a simpler way?


问:
What does this php code means
Hello I am new to PHP and I don't know exactaly what does this code means

```<code>$de = array('Ä'=>'ae','ä'=>'ae','Ü'=>'ue','ü'=>'ue', 'Ö'=>'oe', 'ö'=>'oe', 'ß'=>'ss');
 strtr($str, ${$de});
</code>```

The only thing that I need to know is what does ${$de} mean?

答:
Known as Variables Variable

http://php.net/manual/en/language.variables.variable.php

Title: What does this php code means

Body:
Hello I am new to PHP and I don't know exactaly what does this code means

$de = array('Ä'=>'ae','ä'=>'ae','Ü'=>'ue','ü'=>'ue', 'Ö'=>'oe', 'ö'=>'oe', 'ß'=>'ss');
 strtr($str, ${$de});

The only thing that I need to know is what does ${$de} mean?


问:
Thymeleaf th:value
Using SpringMVC  + Thymeleaf, how does one bind an integer based model attribute, to an input field in a form using th:value or th:field, without having a value of '0' show in the field itself.  </p>

答: Just remove th:field attribute and write id and name attributes with corresponding logical name.</p>

Title: Thymeleaf th:value


问:
object reference error in gridview find control
i am getting error of Object reference not set to an instance of an object.

the error is coming on the following line

```<code>cmd.Parameters.AddWithValue("empname", empname);
</code>```

and this is how i did the coding of findcontrol

```<code>    GridViewRow grdupd = grdemp.Rows[e.RowIndex];
    studentclass std = new studentclass();
    Label empid = (Label)grdupd.FindControl("lblempid");
    TextBox empname = (TextBox)grdupd.FindControl("txtname");
</code>```

and here is my gridview

```<code>            <asp:TemplateField HeaderText="Employee Name">
                <ItemTemplate>
                    <asp:Label ID="lblname" runat="server" Text='<%#Eval("empname") %>'></asp:Label>
                </ItemTemplate>
                <EditItemTemplate>
                    <asp:TextBox ID="txtname" runat="server" Text='<%#Eval("empname") %>'></asp:TextBox>
                </EditItemTemplate>
            </asp:TemplateField>
</code>```

what is wrong in my code and why i am  getting the error of null reference and why i am not able to pass data from gridview to backend

答:
If the error is in below line as you say then definitely you haven't declared SqlCommand object saying SqlCommand cmd = new SqlCommand(...)and so the error

```<code>cmd.Parameters.AddWithValue("empname", empname);
</code>```

Also, as commented by Steen; you are actually adding the TextBox control as parameter whereas you should use the Text property to do so like

```<code>cmd.Parameters.AddWithValue("empname", empname.Text);
</code>```

Body:
i am getting error of Object reference not set to an instance of an object.

the error is coming on the following line

cmd.Parameters.AddWithValue("empname", empname);

and this is how i did the coding of findcontrol

    GridViewRow grdupd = grdemp.Rows[e.RowIndex];
    studentclass std = new studentclass();
    Label empid = (Label)grdupd.FindControl("lblempid");
    TextBox empname = (TextBox)grdupd.FindControl("txtname");

and here is my gridview

            <asp:TemplateField HeaderText="Employee Name">
                <ItemTemplate>
                    <asp:Label ID="lblname" runat="server" Text='<%#Eval("empname") %>'></asp:Label>
                </ItemTemplate>
                <EditItemTemplate>
                    <asp:TextBox ID="txtname" runat="server" Text='<%#Eval("empname") %>'></asp:TextBox>
                </EditItemTemplate>
            </asp:TemplateField>

what is wrong in my code and why i am  getting the error of null reference and why i am not able to pass data from gridview to backend

Body:
If the error is in below line as you say then definitely you haven't declared SqlCommand object saying SqlCommand cmd = new SqlCommand(...)and so the error

cmd.Parameters.AddWithValue("empname", empname);

Also, as commented by Steen; you are actually adding the TextBox control as parameter whereas you should use the Text property to do so like

cmd.Parameters.AddWithValue("empname", empname.Text);


问:
How do you get your path in Octave (on Windows)?
I used addpath(pwd) to get my .m files working in my projects directory. When I close the window and start a new window, the path I just added is gone. But the files still run.

Is it in my path or not? How do I see the directories I have added to my path?

Also, . is the first entry I see from path. Does that mean I don't need to add any directories because it will always search the current directory first?

Thanks.

答:
I think there is a bug in Octave (I use version 4.0.3 on Windows). When I create a new file in current path, this can't be called by Octave ("error: 'foo' undefined near line 1 column 1"). If I restart Octave, it works. This addpath(pwd) trick helps me a lot (before I unsuccessfully tried rehash() and cd elsewhere and back again).

If you had the same problem, the reason for the symptom might be:

Start Octave.

Create newfile.m.

Call newfile - fails since Octave did not register its existence.

addpath(pwd) - causes Octave to register it.

Close Octave

Start Octave - now pwd is gone from path, but newfile.m is registered at startup.

call newfile - works


问:
Weird multiprocessing block importing Numba function

Environment

GNU/Linux (Fedora 25).

Conda environment.

Python 3.6.1.

Numba 0.33.0 (np112py36_0).

Initial setup (works fine)

Two files main.py and numbamodule.py:

main.py

Which spawns 2 processes to run the execute_numba function.

```<code>import time
from importlib import import_module
from multiprocessing import Process

def execute_numba(name):
    # Import the function
    importfunction = 'numbamodule.numba_function'
    module = import_module(importfunction.split('.')[0])
    function = getattr(module, importfunction.split('.')[-1])
    while True:
        print(str(name) + ' - executing Numba function...')
        # Execute the function
        function(10)
        time.sleep(0.1)

if __name__ == '__main__':
    processes = [Process(target=execute_numba, args=(i,)) for i in range(2)]
    [p.start() for p in processes]
    time.sleep(1)
    [p.terminate() for p in processes]
</code>```

numbamodule.py

Which defines a simple function numba_function:

```<code>import numba

@numba.jit()
def numba_function(x):
    total = 0
    for i in range(x):
        total += i
    return total
</code>```

I can run the main.py script and see both processes printing:

```<code>$ python main.py
0 - executing Numba function...
1 - executing Numba function...
0 - executing Numba function...
1 - executing Numba function...
0 - executing Numba function...
1 - executing Numba function...
[...]
</code>```

Breaking it

The way I break it is a bit weird, but this is what I stumbled upon when trying to minimize a reproducible test case. Please, tell me if you can reproduce the same behavior too.

In main.py I just add one of the proposed (bellow) imports after the last Process import (i.e.: uncomment one line and try):

```<code>import time
from importlib import import_module
from multiprocessing import Process

#
# Adding one of the import lines bellow results in a block...
# (you may need to install the packages first in the virtual environment)
#
#import matplotlib
#import Pyro4
#import scipy
#import dill

def execute_numba(name):
# [...]
</code>```

Then one process may block at execute_numba function (in particular at the import_module() call):

```<code>$ python main.py
1 - executing Numba function...
1 - executing Numba function...
1 - executing Numba function...
1 - executing Numba function...
1 - executing Numba function...
1 - executing Numba function...
[...]
</code>```

For me, matplotlib and Pyro4 imports "work" the best. I cannot even get the block a 100% of the runs... :-/

Note that I am simply adding a single import line, not actually using the package. Some other external imports result in a block as well, but I have found that the ones proposed above "work" best (block the most).

What is happening?

First of all, can you reproduce the same behavior? (specially interested in non-virtualized GNU/Linux machines)

I don't know how to debug this or why could this be happening. Any ideas?

The fact that adding one random import xxx triggers the block scares me and makes little sense to me. Could this be dependent on timing/delays and that is why some imports break it and some others do not?

Notes

As you can see there is no traceback, the process just blocks.

If I remove the import numba and @numba.jit from numbamodule.py, then it will always work, so maybe it has something to do with Numba?

I can reproduce the same behavior also with older Numba/Python versions. Tried with Numba 0.25.0 and 0.22.1 (both with Python 3.5.3).

Updates

2017-07-03: Just to make it clear, I am not looking for a workaround (I already have one in the real code). I am genuinely interested in knowing how to proceed in a case like this. Understand what is going on and learn how to debug and find the problem in order to report it if it is a broken package/build/environment. How would you proceed?

2017-07-10: The block occurs in particular at the import_module() call.

2017-07-11: Numba issue acknowledged.

答:
This only applies to matplotlib debugging and is really guessing but might help you a bit to narrow down the problem.

You can start your program, when including matplotlib, with:

```<code>python main.py --verbose-helpful
</code>```

which shows you debug output on the matplotlib initialization. Since it sounded like an issue that is only present on your particular system, there might be some configuartion issue with matplotlibrc configured in such a way that it starts in interactive mode.

Here is an overview on the available debug modes:
https://matplotlib.org/users/customizing.html

Body:
Environment

GNU/Linux (Fedora 25).

Conda environment.

Python 3.6.1.

Numba 0.33.0 (np112py36_0).

Initial setup (works fine)

Two files main.py and numbamodule.py:

main.py

Which spawns 2 processes to run the execute_numba function.

import time
from importlib import import_module
from multiprocessing import Process

def execute_numba(name):
    # Import the function
    importfunction = 'numbamodule.numba_function'
    module = import_module(importfunction.split('.')[0])
    function = getattr(module, importfunction.split('.')[-1])
    while True:
        print(str(name) + ' - executing Numba function...')
        # Execute the function
        function(10)
        time.sleep(0.1)

if __name__ == '__main__':
    processes = [Process(target=execute_numba, args=(i,)) for i in range(2)]
    [p.start() for p in processes]
    time.sleep(1)
    [p.terminate() for p in processes]

numbamodule.py

Which defines a simple function numba_function:

import numba

@numba.jit()
def numba_function(x):
    total = 0
    for i in range(x):
        total += i
    return total

I can run the main.py script and see both processes printing:

$ python main.py
0 - executing Numba function...
1 - executing Numba function...
0 - executing Numba function...
1 - executing Numba function...
0 - executing Numba function...
1 - executing Numba function...
[...]

Breaking it

The way I break it is a bit weird, but this is what I stumbled upon when trying to minimize a reproducible test case. Please, tell me if you can reproduce the same behavior too.

In main.py I just add one of the proposed (bellow) imports after the last Process import (i.e.: uncomment one line and try):

import time
from importlib import import_module
from multiprocessing import Process

#
# Adding one of the import lines bellow results in a block...
# (you may need to install the packages first in the virtual environment)
#
#import matplotlib
#import Pyro4
#import scipy
#import dill

def execute_numba(name):
# [...]

Then one process may block at execute_numba function (in particular at the import_module() call):

$ python main.py
1 - executing Numba function...
1 - executing Numba function...
1 - executing Numba function...
1 - executing Numba function...
1 - executing Numba function...
1 - executing Numba function...
[...]

For me, matplotlib and Pyro4 imports "work" the best. I cannot even get the block a 100% of the runs... :-/

Note that I am simply adding a single import line, not actually using the package. Some other external imports result in a block as well, but I have found that the ones proposed above "work" best (block the most).

What is happening?

First of all, can you reproduce the same behavior? (specially interested in non-virtualized GNU/Linux machines)

I don't know how to debug this or why could this be happening. Any ideas?

The fact that adding one random import xxx triggers the block scares me and makes little sense to me. Could this be dependent on timing/delays and that is why some imports break it and some others do not?

Notes

As you can see there is no traceback, the process just blocks.

If I remove the import numba and @numba.jit from numbamodule.py, then it will always work, so maybe it has something to do with Numba?

I can reproduce the same behavior also with older Numba/Python versions. Tried with Numba 0.25.0 and 0.22.1 (both with Python 3.5.3).

Updates

2017-07-03: Just to make it clear, I am not looking for a workaround (I already have one in the real code). I am genuinely interested in knowing how to proceed in a case like this. Understand what is going on and learn how to debug and find the problem in order to report it if it is a broken package/build/environment. How would you proceed?

2017-07-10: The block occurs in particular at the import_module() call.

2017-07-11: Numba issue acknowledged.

Body:
This only applies to matplotlib debugging and is really guessing but might help you a bit to narrow down the problem.

You can start your program, when including matplotlib, with:

python main.py --verbose-helpful

which shows you debug output on the matplotlib initialization. Since it sounded like an issue that is only present on your particular system, there might be some configuartion issue with matplotlibrc configured in such a way that it starts in interactive mode.

Here is an overview on the available debug modes:
https://matplotlib.org/users/customizing.html


问:
How can I make Bootstrap 4 columns have a height of 100%?
how can I make a column take up 100% height of the browser w bootstrap 4?

See the following: https://codepen.io/johnpickly/pen/dRqxjV

Note the yellow div, I need this div/column to take up a height of 100%... Is there way to make this happen without having to make all parent div's have a height of 100%?

Thank you

html:

```<code><div class="container-fluid">
  <div class="row justify-content-center">

    <div class="col-4 hidden-md-down" id="yellow">
      XXXX
    </div>

    <div class="col-10 col-sm-10 col-md-10 col-lg-8 col-xl-8">
      Form Goes Here
    </div>
  </div>
</div>
</code>```

答:
Use the Bootstrap 4 h-100 class for height:100%;

```<code><div class="container-fluid h-100">
  <div class="row justify-content-center h-100">
    <div class="col-4 hidden-md-down" id="yellow">
      XXXX
    </div>
    <div class="col-10 col-sm-10 col-md-10 col-lg-8 col-xl-8">
      Form Goes Here
    </div>
  </div>
</div>
</code>```

https://www.codeply.com/go/zxd6oN1yWp

You'll also need ensure any parent(s) are also 100% height (or have a defined height)...

```<code>html,body {
  height: 100%;
}
</code>```

Note: 100% height is not the same as "remaining" height.

Related: Bootstrap 4: How to make the row stretch remaining height?

ContentLicense: CC BY-SA 4.0

Body:
how can I make a column take up 100% height of the browser w bootstrap 4?

See the following: https://codepen.io/johnpickly/pen/dRqxjV

Note the yellow div, I need this div/column to take up a height of 100%... Is there way to make this happen without having to make all parent div's have a height of 100%?

Thank you

html:

      XXXX

      Form Goes Here

Body:
Use the Bootstrap 4 h-100 class for height:100%;

<div class="container-fluid h-100">
  <div class="row justify-content-center h-100">
    <div class="col-4 hidden-md-down" id="yellow">
      XXXX
    </div>
    <div class="col-10 col-sm-10 col-md-10 col-lg-8 col-xl-8">
      Form Goes Here
    </div>
  </div>
</div>

https://www.codeply.com/go/zxd6oN1yWp

You'll also need ensure any parent(s) are also 100% height (or have a defined height)...

html,body {
  height: 100%;
}

Note: 100% height is not the same as "remaining" height.

Related: Bootstrap 4: How to make the row stretch remaining height?


问:
Invoking a generic function with a type variable conforming to a protocol
In a generic function, I want to test if a given object conforming to a certain protocol is of a given type. It works great if a concrete class type is passed as a parameter to the checking function. However, when I use a variable for the type (using ternary operator), I get an error:

Cannot invoke 'isObject' with an argument list of type '(AnyObject, of: P.Type)'

Casting additionally the type variable to P.Protocol doesn't help either, since:

In argument type 'P.Protocol', 'P' does not conform to expected type 'P'

```<code>protocol P {
    static var descr: String {get}
}

class A: P {
    static let descr = "class A"
}

class B: P {
    static let descr = "class B"
}

class Test {
    func isObject<T:P>(_ object: AnyObject, of type: T.Type) -> Bool {
        print("descr: \(type.descr)")
        return object is T
    }
}

let a = A()
let type = (false ? A.self : B.self) as P.Type //as! P.Protocol
let test = Test()

test.isObject(a, of: type)
</code>```

答:
The problem is that with a generic placeholder T, when T is a protocol type P, T.Type is P.Protocol not P.Type. In other words, it takes a metatype that describes the protocol itself rather than a metatype that describes a type that conforms to the protocol. This distinction is important because protocols don't conform to themselves.

One solution in your case is to introduce a wrapper around a P.Type metatype which uses a generic placeholder in the initialiser in order to store a closure to perform the is check for you.

```<code>struct AnyPType {

    let base: P.Type
    private let _isInstance: (Any) -> Bool

    /// Creates a new AnyType wrapper from a given metatype.
    /// The passed metatype's value **must** match its static value, i.e `T.self == base`.
    init<T : P>(_ base: T.Type) {
        precondition(T.self == base, "The static value \(T.self) and dynamic value \(base) of the passed metatype do not match")
        self.base = T.self
        self._isInstance = { $0 is T }
    }

    func isInstance(_ instance: Any) -> Bool {
        return _isInstance(instance)
    }
}
</code>```

This is a specialised version of the wrapper that I show in my answer to this Q&A, in which I also show how to lift the limitation of T.self == base on Apple platforms (but this limitation shouldn't be a problem in your case).

You can now use the wrapper like so:

```<code>class Test {
    func isObject(_ object: Any, of type: AnyPType) -> Bool {
        print("descr: \(type.base.descr)")
        return type.isInstance(object)
    }
}

let type = AnyPType(A.self) // or AnyPType(B.self)

print(Test().isObject(A(), of: type))

// descr: class A
// true
</code>```

Body:
In a generic function, I want to test if a given object conforming to a certain protocol is of a given type. It works great if a concrete class type is passed as a parameter to the checking function. However, when I use a variable for the type (using ternary operator), I get an error:

Cannot invoke 'isObject' with an argument list of type '(AnyObject, of: P.Type)'

Casting additionally the type variable to P.Protocol doesn't help either, since:

In argument type 'P.Protocol', 'P' does not conform to expected type 'P'

protocol P {
    static var descr: String {get}
}

class A: P {
    static let descr = "class A"
}

class B: P {
    static let descr = "class B"
}

class Test {
    func isObject<T:P>(_ object: AnyObject, of type: T.Type) -> Bool {
        print("descr: \(type.descr)")
        return object is T
    }
}

let a = A()
let type = (false ? A.self : B.self) as P.Type //as! P.Protocol
let test = Test()

test.isObject(a, of: type)

Body:
The problem is that with a generic placeholder T, when T is a protocol type P, T.Type is P.Protocol not P.Type. In other words, it takes a metatype that describes the protocol itself rather than a metatype that describes a type that conforms to the protocol. This distinction is important because protocols don't conform to themselves.

One solution in your case is to introduce a wrapper around a P.Type metatype which uses a generic placeholder in the initialiser in order to store a closure to perform the is check for you.

struct AnyPType {

    let base: P.Type
    private let _isInstance: (Any) -> Bool

    /// Creates a new AnyType wrapper from a given metatype.
    /// The passed metatype's value **must** match its static value, i.e `T.self == base`.
    init<T : P>(_ base: T.Type) {
        precondition(T.self == base, "The static value \(T.self) and dynamic value \(base) of the passed metatype do not match")
        self.base = T.self
        self._isInstance = { $0 is T }
    }

    func isInstance(_ instance: Any) -> Bool {
        return _isInstance(instance)
    }
}

This is a specialised version of the wrapper that I show in my answer to this Q&A, in which I also show how to lift the limitation of T.self == base on Apple platforms (but this limitation shouldn't be a problem in your case).

You can now use the wrapper like so:

class Test {
    func isObject(_ object: Any, of type: AnyPType) -> Bool {
        print("descr: \(type.base.descr)")
        return type.isInstance(object)
    }
}

let type = AnyPType(A.self) // or AnyPType(B.self)

print(Test().isObject(A(), of: type))

// descr: class A
// true


问:
Change directory via cmd.exe doesn't work
I am trying to change directory via

```<code>cd d:
</code>```

Doesn't work. I tried other variations of same process but doesn't work.
As if command prompt doesn't recognize D drive.

答:
The short answer

The correct way to go from a random place on your C: drive to the root of your D: drive, is the following command :

```<code>cd /d d:\
</code>```

More details

If you're somewhere random on your D:\ drive, and you want to go to the root of your drive, you can use this command :

```<code>cd d:\
</code>```

If you're somewhere random on your D:\ drive, and you want to go to a specific folder on your drive, you can use this command :

```<code>cd d:\path\to\my\folder
</code>```

If you're on a different drive, and you want to go to the root of your D:\ drive, you can use this command :

```<code>cd /d d:\
</code>```

If you're on a different drive, and you want to go to a specific folder on your D: drive, you can use this command :

```<code>cd /d d:\path\to\my\folder
</code>```

If you're on a different drive, and you want to go to the last open folder of you D: drive, you can use this command :

```<code>cd /d d:
</code>```

As a shorthand for cd /d d:, you can also use this command :

```<code>d:
</code>```

Body:
I am trying to change directory via

cd d:

Doesn't work. I tried other variations of same process but doesn't work.
As if command prompt doesn't recognize D drive.

Body:
The short answer

The correct way to go from a random place on your C: drive to the root of your D: drive, is the following command :

cd /d d:\

More details

If you're somewhere random on your D:\ drive, and you want to go to the root of your drive, you can use this command :

cd d:\

If you're somewhere random on your D:\ drive, and you want to go to a specific folder on your drive, you can use this command :

cd d:\path\to\my\folder

If you're on a different drive, and you want to go to the root of your D:\ drive, you can use this command :

cd /d d:\

If you're on a different drive, and you want to go to a specific folder on your D: drive, you can use this command :

cd /d d:\path\to\my\folder

If you're on a different drive, and you want to go to the last open folder of you D: drive, you can use this command :

cd /d d:

As a shorthand for cd /d d:, you can also use this command :

d:


问:
Running statistics on multiple lines in bash
I have multiple HTTP headers in one giant file, separated with one empty line.

```<code>Host
Connection
Accept
From
User-Agent
Accept-Encoding

Host
Connection
Accept
From
User-Agent
Accept-Encoding
X-Forwarded-For

cookie
Cache-Control
referer
x-fb-sim-hni
Host
Accept
user-agent
x-fb-net-sid
x-fb-net-hni
X-Purpose
accept-encoding
x-fb-http-engine
Connection

User-Agent
Host
Connection
Accept-Encoding
</code>```

I have approximately 10,000,000 of headers separated with an empty line.
If I want to discover trends, like header order, I want to do aggregate headers to a one-liner (how I can aggregate lines ending with an empty line and do that separately for all headers?):

Host,Connection,Accept,From,User-Agent,Accept-Encoding

and follow with: uniq -c|sort -nk1,
so I could receive:

```<code>197897 Host,Connection,Accept,From,User-Agent,Accept-Encoding
8732233 User-Agent,Host,Connection,Accept-Encoding
</code>```

What would be the best approach and most effective one to parse that massive file and get that data?

Thanks for hints.

答:
If you have enough memory (10M records, in your sample about 80 chars per record, 800MB, and if you're counting them, I assume a lot of duplicates) you could hash the records to memory and count while hashing:

```<code>$ awk 'BEGIN{ RS=""; OFS=","}
{
    b=""                       # reset buffer b
    for(i=1;i<=NF;i++)         # for every header element in record
        b=b (b==""?"":OFS) $i  # buffer them and comma separate
    a[b]++                     # hash to a, counting
}
END {                          # in the end
    for(i in a)                # go thru the a hash
        print a[i] " " i}      # print counts and records
' file
1 Host,Connection,Accept,From,User-Agent,Accept-Encoding
1 cookie,Cache-Control,referer,x-fb-sim-hni,Host,Accept,user-agent,x-fb-net-sid,x-fb-net-hni,X-Purpose,accept-encoding,x-fb-http-engine,Connection
1 User-Agent,Host,Connection,Accept-Encoding
1 Host,Connection,Accept,From,User-Agent,Accept-Encoding,X-Forwarded-For
</code>```

Output order is random due to the nature of i in a so order the output afterwards as pleases.

Edit:

As @dawg kindly pointed out in the comments, $1=$1 is enough to rebuild the record to comma-separated form:

```<code>$ awk 'BEGIN{ RS=""; OFS=","}
{
    $1=$1                      # rebuild the record
    a[$0]++                    # hash $0 to a, counting
}
END {                          # in the end
    for(i in a)                # go thru the a hash
        print a[i] " " i}      # print counts and records
' file
</code>```

Body:
I have multiple HTTP headers in one giant file, separated with one empty line.

Host
Connection
Accept
From
User-Agent
Accept-Encoding

Host
Connection
Accept
From
User-Agent
Accept-Encoding
X-Forwarded-For

cookie
Cache-Control
referer
x-fb-sim-hni
Host
Accept
user-agent
x-fb-net-sid
x-fb-net-hni
X-Purpose
accept-encoding
x-fb-http-engine
Connection

User-Agent
Host
Connection
Accept-Encoding

I have approximately 10,000,000 of headers separated with an empty line.
If I want to discover trends, like header order, I want to do aggregate headers to a one-liner (how I can aggregate lines ending with an empty line and do that separately for all headers?):

Host,Connection,Accept,From,User-Agent,Accept-Encoding

and follow with: uniq -c|sort -nk1,
so I could receive:

197897 Host,Connection,Accept,From,User-Agent,Accept-Encoding
8732233 User-Agent,Host,Connection,Accept-Encoding

What would be the best approach and most effective one to parse that massive file and get that data?

Thanks for hints.

Body:
If you have enough memory (10M records, in your sample about 80 chars per record, 800MB, and if you're counting them, I assume a lot of duplicates) you could hash the records to memory and count while hashing:

$ awk 'BEGIN{ RS=""; OFS=","}
{
    b=""                       # reset buffer b
    for(i=1;i<=NF;i++)         # for every header element in record
        b=b (b==""?"":OFS) $i  # buffer them and comma separate
    a[b]++                     # hash to a, counting
}
END {                          # in the end
    for(i in a)                # go thru the a hash
        print a[i] " " i}      # print counts and records
' file
1 Host,Connection,Accept,From,User-Agent,Accept-Encoding
1 cookie,Cache-Control,referer,x-fb-sim-hni,Host,Accept,user-agent,x-fb-net-sid,x-fb-net-hni,X-Purpose,accept-encoding,x-fb-http-engine,Connection
1 User-Agent,Host,Connection,Accept-Encoding
1 Host,Connection,Accept,From,User-Agent,Accept-Encoding,X-Forwarded-For

Output order is random due to the nature of i in a so order the output afterwards as pleases.

Edit:

As @dawg kindly pointed out in the comments, $1=$1 is enough to rebuild the record to comma-separated form:

$ awk 'BEGIN{ RS=""; OFS=","}
{
    $1=$1                      # rebuild the record
    a[$0]++                    # hash $0 to a, counting
}
END {                          # in the end
    for(i in a)                # go thru the a hash
        print a[i] " " i}      # print counts and records
' file


问:
Find the URL of an image in java using Selenium from any given website
I'm new to using Selenium Web Driver, however I'm currently undergoing a project that would make me need to save an image of a person from a website using just their name. Many solutions I've found online don't seem to work at least in my case scenario. The main issue I need assistance with is singling out specific images from a webpage. For example if I were to use the link https://www.squarespace.com/about/team/ I would need to be able to download images, or at least get the link of an image of solely one person based on their name. Any information would help, thanks!</p>

答:
Here is the Answer to your Question:

You can use the following code block to retrieve the name of all the Team Members and the link of the image of solely one person based on their name:

```<code>    import java.util.ArrayList;
    import java.util.List;

    import org.openqa.selenium.By;
    import org.openqa.selenium.JavascriptExecutor;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.chrome.ChromeDriver;
    import org.openqa.selenium.chrome.ChromeOptions;

    public class Q44980374_url_of_an_image
    {

        public static void main(String[] args)
        {

            System.setProperty("webdriver.chrome.driver", "C:\\Utility\\BrowserDrivers\\chromedriver.exe");
            ChromeOptions options = new ChromeOptions();
            options.addArguments("start-maximized");
            options.addArguments("disable-infobars");
            WebDriver driver=new ChromeDriver(options);
            driver.get("https://www.squarespace.com/about/team/");
            JavascriptExecutor jse = (JavascriptExecutor) driver;
            jse.executeScript("window.scrollBy(0,1000)", "");
            //Get the Name of the Members
            List<WebElement> team_member = driver.findElements(By.xpath("//main[@id='content']//div[@class='team-members']/div[@class='team-member']/div[@class='team-member-text']/h3"));
            List<String> mem_name_list = new ArrayList<String>();
            for (WebElement member:team_member)
            {
                    String memeber_name = member.getAttribute("innerHTML");
                    mem_name_list.add(memeber_name);
            }
            List<WebElement> team_member_images = driver.findElements(By.xpath("//main[@id='content']//div[@class='team-members']/div[@class='team-member']/div[@class='team-member-portrait']/img"));
            List<String> mem_image_list = new ArrayList<String>();
            for (WebElement image_link:team_member_images)
            {
                    String memebr_image = image_link.getAttribute("src");
                    mem_image_list.add(memebr_image);
            }
            for(int i=0;i<team_member.size();i++)
            {
                System.out.println(mem_name_list.get(i)+"'s image link is : "+mem_image_list.get(i) );
            }
        }

    }
</code>```

The Output of this code block is:

```<code>Anthony Casalena's image link is : https://static1.squarespace.com/static/ta/5134cbefe4b0c6fb04df8065/9025/assets/pages/about/team/executive-team/anthony-casalena-300w.jpg
Nicole Anasenes's image link is : https://static1.squarespace.com/static/ta/5134cbefe4b0c6fb04df8065/9025/assets/pages/about/team/executive-team/nicole-anasenes-300w.jpg
Andrew Bartholomew's image link is : https://static1.squarespace.com/static/ta/5134cbefe4b0c6fb04df8065/9025/assets/pages/about/team/executive-team/andrew-bartholomew-300w.jpg
John Colton's image link is : https://static1.squarespace.com/static/ta/5134cbefe4b0c6fb04df8065/9025/assets/pages/about/team/executive-team/john-colton-300w.jpg
Raphael Fontes's image link is : https://static1.squarespace.com/static/ta/5134cbefe4b0c6fb04df8065/9025/assets/pages/about/team/executive-team/raphael-fontes-300w.jpg
David Lee's image link is : https://static1.squarespace.com/static/ta/5134cbefe4b0c6fb04df8065/9025/assets/pages/about/team/executive-team/david-lee-300w.jpg
Kinjil Mathur's image link is : https://static1.squarespace.com/static/ta/5134cbefe4b0c6fb04df8065/9025/assets/pages/about/team/executive-team/kinjil-mathur-300w.jpg
Roberta Meo's image link is : https://static1.squarespace.com/static/ta/5134cbefe4b0c6fb04df8065/9025/assets/pages/about/team/executive-team/roberta-meo-300w.jpg
Kris Passet's image link is : https://static1.squarespace.com/static/ta/5134cbefe4b0c6fb04df8065/9025/assets/pages/about/team/executive-team/kris-passet-300w.jpg
</code>```

Let me know if this Answers your Question.

Body:
Here is the Answer to your Question:

You can use the following code block to retrieve the name of all the Team Members and the link of the image of solely one person based on their name:

    import java.util.ArrayList;
    import java.util.List;

    import org.openqa.selenium.By;
    import org.openqa.selenium.JavascriptExecutor;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.chrome.ChromeDriver;
    import org.openqa.selenium.chrome.ChromeOptions;

    public class Q44980374_url_of_an_image
    {

        public static void main(String[] args)
        {

            System.setProperty("webdriver.chrome.driver", "C:\\Utility\\BrowserDrivers\\chromedriver.exe");
            ChromeOptions options = new ChromeOptions();
            options.addArguments("start-maximized");
            options.addArguments("disable-infobars");
            WebDriver driver=new ChromeDriver(options);
            driver.get("https://www.squarespace.com/about/team/");
            JavascriptExecutor jse = (JavascriptExecutor) driver;
            jse.executeScript("window.scrollBy(0,1000)", "");
            //Get the Name of the Members
            List<WebElement> team_member = driver.findElements(By.xpath("//main[@id='content']//div[@class='team-members']/div[@class='team-member']/div[@class='team-member-text']/h3"));
            List<String> mem_name_list = new ArrayList<String>();
            for (WebElement member:team_member)
            {
                    String memeber_name = member.getAttribute("innerHTML");
                    mem_name_list.add(memeber_name);
            }
            List<WebElement> team_member_images = driver.findElements(By.xpath("//main[@id='content']//div[@class='team-members']/div[@class='team-member']/div[@class='team-member-portrait']/img"));
            List<String> mem_image_list = new ArrayList<String>();
            for (WebElement image_link:team_member_images)
            {
                    String memebr_image = image_link.getAttribute("src");
                    mem_image_list.add(memebr_image);
            }
            for(int i=0;i<team_member.size();i++)
            {
                System.out.println(mem_name_list.get(i)+"'s image link is : "+mem_image_list.get(i) );
            }
        }

    }

The Output of this code block is:

Anthony Casalena's image link is : https://static1.squarespace.com/static/ta/5134cbefe4b0c6fb04df8065/9025/assets/pages/about/team/executive-team/anthony-casalena-300w.jpg
Nicole Anasenes's image link is : https://static1.squarespace.com/static/ta/5134cbefe4b0c6fb04df8065/9025/assets/pages/about/team/executive-team/nicole-anasenes-300w.jpg
Andrew Bartholomew's image link is : https://static1.squarespace.com/static/ta/5134cbefe4b0c6fb04df8065/9025/assets/pages/about/team/executive-team/andrew-bartholomew-300w.jpg
John Colton's image link is : https://static1.squarespace.com/static/ta/5134cbefe4b0c6fb04df8065/9025/assets/pages/about/team/executive-team/john-colton-300w.jpg
Raphael Fontes's image link is : https://static1.squarespace.com/static/ta/5134cbefe4b0c6fb04df8065/9025/assets/pages/about/team/executive-team/raphael-fontes-300w.jpg
David Lee's image link is : https://static1.squarespace.com/static/ta/5134cbefe4b0c6fb04df8065/9025/assets/pages/about/team/executive-team/david-lee-300w.jpg
Kinjil Mathur's image link is : https://static1.squarespace.com/static/ta/5134cbefe4b0c6fb04df8065/9025/assets/pages/about/team/executive-team/kinjil-mathur-300w.jpg
Roberta Meo's image link is : https://static1.squarespace.com/static/ta/5134cbefe4b0c6fb04df8065/9025/assets/pages/about/team/executive-team/roberta-meo-300w.jpg
Kris Passet's image link is : https://static1.squarespace.com/static/ta/5134cbefe4b0c6fb04df8065/9025/assets/pages/about/team/executive-team/kris-passet-300w.jpg

Let me know if this Answers your Question.


问:
I tried using a handler, but it said 'cannot resolve symbol"Handler"'
What do i do to be able to use a handler to update my TextView every 2 secs because right now it comes up with 'cannot resolve symbol"Handler"'</p>

```<code>int noStart = 20;
int minus = 5;

public void number(View view) {
    final TextView tx = (TextView) findViewById(R.id.number);

    if(noStart<0){
        new Handler().postDelayed(new Runnable() {
            public void run() {
                noStart -= minus;
                tx.setText(String.valueOf(noStart));
            }
        }, 2000);
    }
}
</code>```

答:
Check your activity imports and add this line to the class:</p>

```<code>import android.os.*
</code>```

Body:
What do i do to be able to use a handler to update my TextView every 2 secs because right now it comes up with 'cannot resolve symbol"Handler"'

int noStart = 20;
int minus = 5;

public void number(View view) {
    final TextView tx = (TextView) findViewById(R.id.number);

    if(noStart<0){
        new Handler().postDelayed(new Runnable() {
            public void run() {
                noStart -= minus;
                tx.setText(String.valueOf(noStart));
            }
        }, 2000);
    }
}

Body:
Check your activity imports and add this line to the class:

import android.os.*


问:
MySQL update column value where else update another column value (single query)
I would like to link these two queries together rather than executing them both at different times.

```<code>UPDATE `table` SET `column_one` = @value WHERE `column_one_key` = @key LIMIT 1;
</code>```

and also this query;

```<code>UPDATE `table` SET `column_two` = @value WHERE `column_two_key` = @key LIMIT 1;
</code>```

Something like this but can't seem to get it to work

```<code>UPDATE `table` (SET `column_one` = @value WHERE `column_one_key` = @key) || (SET `column_two` = @value WHERE `column_two_key` = @key) LIMIT 1;
</code>```

Some additional information

column_one_key and column_two_key are never the same which is why you can use OR.

答:
Try something like this:</p>

```<code>UPDATE `table` SET `column_one` = @value, `column_two` = @value  WHERE `column_one_key` = @key AND `column_two_key` = @key LIMIT 1;
</code>```

Body:
I would like to link these two queries together rather than executing them both at different times.

UPDATE `table` SET `column_one` = @value WHERE `column_one_key` = @key LIMIT 1;

and also this query;

UPDATE `table` SET `column_two` = @value WHERE `column_two_key` = @key LIMIT 1;

Something like this but can't seem to get it to work

UPDATE `table` (SET `column_one` = @value WHERE `column_one_key` = @key) || (SET `column_two` = @value WHERE `column_two_key` = @key) LIMIT 1;

Some additional information

column_one_key and column_two_key are never the same which is why you can use OR.

Body:
Try something like this:

UPDATE `table` SET `column_one` = @value, `column_two` = @value  WHERE `column_one_key` = @key AND `column_two_key` = @key LIMIT 1;


问:
Type date default sysdate in Mysql
I have seen this question before but it is not answered, so here it goes:

When creating a table, I have a column with the type Date. I want that the default value is the system date, (Sysdate), but for some reason it does not work and it gives an error (in syntax, which is strange because I am following the Mysql syntax).

```<code>create table students(
id integer(10),
name varchar (21) NOT NULL,
surname varchar(30),
grade integer check(grade in(1,2,3),
enrollment date default sysdate,
primary key(id) );
</code>```

And it gives an error in syntax just at the "sysdate". I have tried with sys_date, sys-date, and it is the same.

答:
Instead of sysdate, try CURRENT_TIMESTAMP like:

```<code>CREATE TABLE foo (
    creation_time      DATETIME DEFAULT   CURRENT_TIMESTAMP,
    modification_time  DATETIME ON UPDATE CURRENT_TIMESTAMP
)
</code>```

Title: Type date default sysdate in Mysql

Body:
I have seen this question before but it is not answered, so here it goes:

When creating a table, I have a column with the type Date. I want that the default value is the system date, (Sysdate), but for some reason it does not work and it gives an error (in syntax, which is strange because I am following the Mysql syntax).

create table students(
id integer(10),
name varchar (21) NOT NULL,
surname varchar(30),
grade integer check(grade in(1,2,3),
enrollment date default sysdate,
primary key(id) );

And it gives an error in syntax just at the "sysdate". I have tried with sys_date, sys-date, and it is the same.

Body:
Instead of sysdate, try CURRENT_TIMESTAMP like:

CREATE TABLE foo (
    creation_time      DATETIME DEFAULT   CURRENT_TIMESTAMP,
    modification_time  DATETIME ON UPDATE CURRENT_TIMESTAMP
)


问:
for loop with print in functional programming style python
How can I change the following program in Python to functional style?

```<code>from itertools import permutations
for p in permutations(range(1, int(input()) + 1)):
    print(*p, sep='')
</code>```

I know about map, but

```<code>map(lambda p: print(*p, sep=''), permutations(range(1, int(input()) + 1)))
</code>```

doesn't produce the expected output.

I wonder if it is possible to do so without 'redefining' the for loop.

答:
map should not be used for side-effects functions.
The print function is returning None so you are building a list (or generator in python3) that will contain as many Nones as items in the collection you are iterating, completly useless.
You can use a while loop:

```<code>def printFrom(col):
    i = iter(col)
    while True:
        try:
            print(next(i))
        except StopIteration:
            break
</code>```

As functional style, you can use recursion:

```<code>def printFrom(col):
    it = iter(col)
    def printit(i):
        try:
            print(next(i))
            printit(i)
        except StopIteration:
            return
    printit(it)
</code>```

Or also just this:

```<code>print(" ".join(map(lambda x: " ".join(map(str, x)),permutations(range(1, 10)))))
</code>```

The idea of this last solutions is that you build the actual final string before printing it with just one call.

Body:
How can I change the following program in Python to functional style?

from itertools import permutations
for p in permutations(range(1, int(input()) + 1)):
    print(*p, sep='')

I know about map, but

map(lambda p: print(*p, sep=''), permutations(range(1, int(input()) + 1)))

doesn't produce the expected output.

I wonder if it is possible to do so without 'redefining' the for loop.

Body:
map should not be used for side-effects functions.
The print function is returning None so you are building a list (or generator in python3) that will contain as many Nones as items in the collection you are iterating, completly useless.
You can use a while loop:

def printFrom(col):
    i = iter(col)
    while True:
        try:
            print(next(i))
        except StopIteration:
            break

As functional style, you can use recursion:

def printFrom(col):
    it = iter(col)
    def printit(i):
        try:
            print(next(i))
            printit(i)
        except StopIteration:
            return
    printit(it)

Or also just this:

print(" ".join(map(lambda x: " ".join(map(str, x)),permutations(range(1, 10)))))

The idea of this last solutions is that you build the actual final string before printing it with just one call.


问:
Javascript can't find element by id?
```<code><html>
<head>
    <title>Test javascript</title>

    <script type="text/javascript">
        var e = document.getElementById("db_info");
        e.innerHTML='Found you';
    </script>
</head>
<body>
    <div id="content">
        <div id="tables">

        </div>
        <div id="db_info">
        </div>
    </div>
</body>
</html>
</code>```

If I use alert(e); it turns up null.... and obviously I don't get any "found you" on screen. What am I doing wrong?

答:
Script is called before element exists.

You should try one of the following:

wrap code into a function and use a body onload event to call it.

put script at the end of document

use defer attribute into script tag declaration

ContentLicense: CC BY-SA 2.5

Title: Javascript can't find element by id?

Body:
    <title>Test javascript</title>

If I use alert(e); it turns up null.... and obviously I don't get any "found you" on screen. What am I doing wrong?


问:
PHP Excel save only one sheet as pdf
i'm using phpoffice/phpexcel an have a problem.

I have a excel file with 9 sheets

I open 6 of this 9 sheets ($objReader->setLoadSheetsOnly([...])) do set some values and calculate

I save this new excel file with 6 sheets

Info: one of the 6 steets is a overview site which have some references to the other sheets

I there any method to save only the overview sheet as PDF?

My Lines:

```<code>require_once dirname(__FILE__) . '/PHPExcel/IOFactory.php';

if (!file_exists("orginal.xls")) {
    exit("Please create orginal.xls first." . EOL);
}

PHPExcel_Settings::setCacheStorageMethod(PHPExcel_CachedObjectStorageFactory::cache_in_memory);

echo date('H:i:s') , " Load from Excel2007 file" , EOL;

$objReader = PHPExcel_IOFactory::createReader('Excel5');

$objReader->setLoadSheetsOnly(array("Dateneingabe", "Leistungen EK", "Flugliste", "Sprachen", "Buchungsübersicht", "Verkaufspreise", "Offerte", "Transferdauer"));

$objPHPExcel = $objReader->load("orginal.xls");

$objPHPExcel->setActiveSheetIndexByName('Dateneingabe');
$objPHPExcel->getActiveSheet()->SetCellValue('D102', '220');
$objPHPExcel->getActiveSheet()->SetCellValue('F102', '220');

$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
//$objWriter->setPreCalculateFormulas(false);
$objWriter->setOffice2003Compatibility(true);
$objWriter->save(str_replace('.php', '.xls', __FILE__));

 //SAVE AS PDF

$objReader = PHPExcel_IOFactory::createReader('Excel2007');

$objReader->setReadDataOnly(true);

$objReader->setLoadSheetsOnly(array("Dateneingabe", "Leistungen EK", "Flugliste", "Sprachen", "Buchungsübersicht", "Verkaufspreise", "Offerte", "Transferdauer"));

$objPHPExcel = $objReader->load("index.xls");

$objPHPExcel->setActiveSheetIndexByName('Offerte');

$rendererName = PHPExcel_Settings::PDF_RENDERER_DOMPDF;

$rendererLibrary = dirname(__FILE__).'/dompdf/dompdf/';

PHPExcel_Settings::setPdfRenderer($rendererName, $rendererLibrary);

$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'PDF');

$objWriter->setPreCalculateFormulas(false);

$objWriter->save(str_replace('.php', '.pdf', __FILE__));
</code>```

答:
use mpdf tool like below code

use mpdf tool to convert your data into pdf formate .

Title: PHP Excel save only one sheet as pdf

Body:
i'm using phpoffice/phpexcel an have a problem.

I have a excel file with 9 sheets

I open 6 of this 9 sheets ($objReader->setLoadSheetsOnly([...])) do set some values and calculate

I save this new excel file with 6 sheets

Info: one of the 6 steets is a overview site which have some references to the other sheets

I there any method to save only the overview sheet as PDF?

My Lines:

require_once dirname(__FILE__) . '/PHPExcel/IOFactory.php';

if (!file_exists("orginal.xls")) {
    exit("Please create orginal.xls first." . EOL);
}

PHPExcel_Settings::setCacheStorageMethod(PHPExcel_CachedObjectStorageFactory::cache_in_memory);

echo date('H:i:s') , " Load from Excel2007 file" , EOL;

$objReader = PHPExcel_IOFactory::createReader('Excel5');

$objReader->setLoadSheetsOnly(array("Dateneingabe", "Leistungen EK", "Flugliste", "Sprachen", "Buchungsübersicht", "Verkaufspreise", "Offerte", "Transferdauer"));

$objPHPExcel = $objReader->load("orginal.xls");

$objPHPExcel->setActiveSheetIndexByName('Dateneingabe');
$objPHPExcel->getActiveSheet()->SetCellValue('D102', '220');
$objPHPExcel->getActiveSheet()->SetCellValue('F102', '220');

$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
//$objWriter->setPreCalculateFormulas(false);
$objWriter->setOffice2003Compatibility(true);
$objWriter->save(str_replace('.php', '.xls', __FILE__));

 //SAVE AS PDF

$objReader = PHPExcel_IOFactory::createReader('Excel2007');

$objReader->setReadDataOnly(true);

$objReader->setLoadSheetsOnly(array("Dateneingabe", "Leistungen EK", "Flugliste", "Sprachen", "Buchungsübersicht", "Verkaufspreise", "Offerte", "Transferdauer"));

$objPHPExcel = $objReader->load("index.xls");

$objPHPExcel->setActiveSheetIndexByName('Offerte');

$rendererName = PHPExcel_Settings::PDF_RENDERER_DOMPDF;

$rendererLibrary = dirname(__FILE__).'/dompdf/dompdf/';

PHPExcel_Settings::setPdfRenderer($rendererName, $rendererLibrary);

$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'PDF');

$objWriter->setPreCalculateFormulas(false);

$objWriter->save(str_replace('.php', '.pdf', __FILE__));


问:
How to check for null in Scala.js?
How can we check for null in Scala.js?
I'm working with JavaScript library and have method that can return object or null. I've tried to use js.undefined like this

```<code>if(node != js.undefined){
  global.console.log("node is object")
} else global.alert("Please select node.")
</code>```

But this doesn't work

答:
According to the docs, you can simply do:

```<code>if (node != null) {
  global.console.log("node is object")
} else global.alert("Please select node.")
</code>```

Check all the available types here: https://www.scala-js.org/doc/interoperability/types.html

Title: How to check for null in Scala.js?

Body:
How can we check for null in Scala.js?
I'm working with JavaScript library and have method that can return object or null. I've tried to use js.undefined like this

if(node != js.undefined){
  global.console.log("node is object")
} else global.alert("Please select node.")

But this doesn't work

Body:
According to the docs, you can simply do:

if (node != null) {
  global.console.log("node is object")
} else global.alert("Please select node.")

Check all the available types here: https://www.scala-js.org/doc/interoperability/types.html


问:
Add conditional css to bundleconfig
I have 2 css files. and both of them are for all pages except that one of them is the fix for right to left languages and it will exist in all pages when a right to left culture is selected, and will be in none of them otherwise.

Current definition in Layout file:

```<code><environment names="Development">
    <link rel="stylesheet" href="~/css/site.css" />
</environment>
<environment names="Staging,Production">
    <link rel="stylesheet" href="~/css/site.min.css" asp-append-version="true" />
</environment>
</code>```

bundleconfig.json:

```<code>{
    "outputFileName": "wwwroot/css/site.min.css",
    // An array of relative input file paths. Globbing patterns supported
    "inputFiles": [
      "wwwroot/css/site.css"
    ]
  },
  {
    "outputFileName": "wwwroot/js/site.min.js",
    "inputFiles": [
      "wwwroot/js/site.js"
    ],
    // Optionally specify minification options
    "minify": {
      "enabled": true,
      "renameLocals": true
    },
    // Optionally generate .map file
    "sourceMap": false
  }
</code>```

Is there any way to include it in the bundling when needed? I don't want to include it separately.

答:
I solved the problem.

In bundleconfig.json I choose to create 2 different minified css, one with rtl patch and one without it:

```<code>[
  {
    "outputFileName": "wwwroot/css/site.min.css",
    // An array of relative input file paths. Globbing patterns supported
    "inputFiles": [
      "wwwroot/css/site.css"
    ]
  },
  {
    "outputFileName": "wwwroot/css/sitertl.min.css",
    // An array of relative input file paths. Globbing patterns supported
    "inputFiles": [
      "wwwroot/css/site.css",
      "wwwroot/css/rtl.css"
    ]
  },
  {
    "outputFileName": "wwwroot/js/site.min.js",
    "inputFiles": [
      "wwwroot/js/site.js"
    ],
    // Optionally specify minification options
    "minify": {
      "enabled": true,
      "renameLocals": true
    },
    // Optionally generate .map file
    "sourceMap": false
  }
]
</code>```

And in layout I add a condition like this:

```<code>    <environment names="Development">
            <link rel="stylesheet" href="~/css/site.css" />
           @if (CultureInfo.CurrentUICulture.Name.ToLower() == "fa-ir")
           { <link href="~/css/rtl.css" rel="stylesheet" />}
        </environment>
        <environment names="Staging,Production">
@if(CultureInfo.CurrentUICulture.Name.ToLower()=="fa-ir"){
            <link rel="stylesheet" href="~/css/sitertl.min.css" asp-append-version="true"  />}
else{
<link rel="stylesheet" href="~/css/site.min.css" asp-append-version="true"  />
}
        </environment>
</code>```

Title: Add conditional css to bundleconfig

Body:
I have 2 css files. and both of them are for all pages except that one of them is the fix for right to left languages and it will exist in all pages when a right to left culture is selected, and will be in none of them otherwise.

Current definition in Layout file:

<environment names="Development">
    <link rel="stylesheet" href="~/css/site.css" />
</environment>
<environment names="Staging,Production">
    <link rel="stylesheet" href="~/css/site.min.css" asp-append-version="true" />
</environment>

bundleconfig.json:

{
    "outputFileName": "wwwroot/css/site.min.css",
    // An array of relative input file paths. Globbing patterns supported
    "inputFiles": [
      "wwwroot/css/site.css"
    ]
  },
  {
    "outputFileName": "wwwroot/js/site.min.js",
    "inputFiles": [
      "wwwroot/js/site.js"
    ],
    // Optionally specify minification options
    "minify": {
      "enabled": true,
      "renameLocals": true
    },
    // Optionally generate .map file
    "sourceMap": false
  }

Is there any way to include it in the bundling when needed? I don't want to include it separately.

Body:
I solved the problem.

In bundleconfig.json I choose to create 2 different minified css, one with rtl patch and one without it:

[
  {
    "outputFileName": "wwwroot/css/site.min.css",
    // An array of relative input file paths. Globbing patterns supported
    "inputFiles": [
      "wwwroot/css/site.css"
    ]
  },
  {
    "outputFileName": "wwwroot/css/sitertl.min.css",
    // An array of relative input file paths. Globbing patterns supported
    "inputFiles": [
      "wwwroot/css/site.css",
      "wwwroot/css/rtl.css"
    ]
  },
  {
    "outputFileName": "wwwroot/js/site.min.js",
    "inputFiles": [
      "wwwroot/js/site.js"
    ],
    // Optionally specify minification options
    "minify": {
      "enabled": true,
      "renameLocals": true
    },
    // Optionally generate .map file
    "sourceMap": false
  }
]

And in layout I add a condition like this:

    <environment names="Development">
            <link rel="stylesheet" href="~/css/site.css" />
           @if (CultureInfo.CurrentUICulture.Name.ToLower() == "fa-ir")
           { <link href="~/css/rtl.css" rel="stylesheet" />}
        </environment>
        <environment names="Staging,Production">
@if(CultureInfo.CurrentUICulture.Name.ToLower()=="fa-ir"){
            <link rel="stylesheet" href="~/css/sitertl.min.css" asp-append-version="true"  />}
else{
<link rel="stylesheet" href="~/css/site.min.css" asp-append-version="true"  />
}
        </environment>


问:
CSS not linked to HTML page
Good morning guys,

I am playing around building a small website. In the html I have my link to my CSS file but for some reason the CSS is not being shown on the page.

The link tag looks as follows:

```<code><link rel="stylesheet" href="./styles/style.css" type="text/css">
</code>```

The site does not contain any styles that I have built. Am I doing something wrong here?

答:
Folder Structure 1

index.html

styles (folder)

style.css

If this the folder structure then your link tag should be

```<code><link rel="stylesheet" href="styles/style.css" type="text/css" />
</code>```

Folder Structure 2

index.html

style.css

If your folder structure is like the above then the link tag should be

```<code><link rel="stylesheet" href="style.css" type="text/css" />
</code>```

Folder Structure 3

HTML (folder)

index.html

styles (folder)

style.css

If your folder structure is like above then the link tag should be

```<code><link rel="stylesheet" href="../styles/style.css" type="text/css" />
</code>```

This might help you. For any error check the browser console.

Title: CSS not linked to HTML page

Body:
Good morning guys,

I am playing around building a small website. In the html I have my link to my CSS file but for some reason the CSS is not being shown on the page.

The link tag looks as follows:

<link rel="stylesheet" href="./styles/style.css" type="text/css">

The site does not contain any styles that I have built. Am I doing something wrong here?

Body:
Folder Structure 1

index.html

styles (folder)

style.css

If this the folder structure then your link tag should be

<link rel="stylesheet" href="styles/style.css" type="text/css" />

Folder Structure 2

index.html

style.css

If your folder structure is like the above then the link tag should be

<link rel="stylesheet" href="style.css" type="text/css" />

Folder Structure 3

HTML (folder)

index.html

styles (folder)

style.css

If your folder structure is like above then the link tag should be

<link rel="stylesheet" href="../styles/style.css" type="text/css" />

This might help you. For any error check the browser console.


问:
Upload images to temporary image folder
I have a hosted website and i want to upload my images to image directory and link the image to mysql database .

What i did:

Creating form as :

```<code><form method=POST align=center enctype="multipart/form-data">
<input type=file name=image>
</code>```

Php code :

```<code>$uploaddir = 'images/';
     // echo $uploaddir;
        $target = "$uploaddir".basename($_FILES['image']['name']);
              echo $target;

        $image = $_FILES['image']['name'];
    $sql="insert into News2(image_News2)
    values($image)";
    $res=mysqli_query($con,$sql);
    copy($_FILES['tmp_name']['name'],$target,true);
</code>```

What this code actually do is only inserting the image into the database not copying the image into the images folder.

What i searched for and found :

You shouldn't specify a http:// URL as $uploaddir but a path relative to the path where the php script is running from.

So i what i really wanted to do is :

1- Copying the image into image folder directory on website.
2- Linking the copied image to the database.

答:
you're missing the name ïmage"
not:

copy($_FILES['tmp_name']['name'],$target,true);

but:

move_uploaded_file($_FILES['image']['tmp_name'], $target);

And maybe you should try the move first, before inserting it in the database, should that action fail (or filesize = 0) etc.

do check on both the file actions and the db actions, should they fail: rollback

extra:

is only 1 column present in your database table?
is it wise to use the uploaded file's name? Duplicates can happen.
I would after checking the file insert the original name into the database. Get the autoincrement id of that record. rename the file to ./1234.jpg

through the database you can then later use the original name. But this numbering might go too var for a simple application

Title: Upload images to temporary image folder

Body:
I have a hosted website and i want to upload my images to image directory and link the image to mysql database .

What i did:

Creating form as :

<form method=POST align=center enctype="multipart/form-data">
<input type=file name=image>

Php code :

$uploaddir = 'images/';
     // echo $uploaddir;
        $target = "$uploaddir".basename($_FILES['image']['name']);
              echo $target;

        $image = $_FILES['image']['name'];
    $sql="insert into News2(image_News2)
    values($image)";
    $res=mysqli_query($con,$sql);
    copy($_FILES['tmp_name']['name'],$target,true);

What this code actually do is only inserting the image into the database not copying the image into the images folder.

What i searched for and found :

You shouldn't specify a http:// URL as $uploaddir but a path relative to the path where the php script is running from.

So i what i really wanted to do is :

1- Copying the image into image folder directory on website.
2- Linking the copied image to the database.


问:
Parsing string to DateTime with TryParseExact with other language culture and format
I have tried to parse a string that represents a date in Spanish (Chile) when meaningful data is missing -- the year. I hoped that the DateTime class will know how to find the latest date that match. Any suggestions?      </p>

```<code>  public void TestDateParsing()
    {
        string strDate = "MIE 25";
        CultureInfo cl = new CultureInfo("es-CL");
        DateTime date= new DateTime();
        if (DateTime.TryParseExact(strDate,"ddd d",cl,DateTimeStyles.None, out date))
        {
            //print the variable date...
        }
    }
</code>```

答:
It's been a while and I forgot about that question. After going over your answers (2 years ago Haha) I found that there is a way to parse a date according to the current year calendar.
According to 2017 "Martes 21 de marzo" (Tuesday, March 21) is a valid data and the code below will work, but if you will change it to "Martes 24 de marzo" for example, exception (format exception that says "String was not recognized as a valid DateTime because the day of week was incorrect." to be more accurate) will be raised cause that date doesn't exist at the current year.
I must mention that I used that code to parse dates in scrappers that I used to build and I assumed that the dates that I'm receiving are valid dates.
I hope that that piece of code will help someone somehow.</p>

```<code>string strDate ="Martes 21 de marzo";
CultureInfo cl = new CultureInfo("es-CO");
DateTime date = DateTime.Parse(strDate, cl, DateTimeStyles.None);
</code>```

Body:
I have tried to parse a string that represents a date in Spanish (Chile) when meaningful data is missing -- the year. I hoped that the DateTime class will know how to find the latest date that match. Any suggestions?

  public void TestDateParsing()
    {
        string strDate = "MIE 25";
        CultureInfo cl = new CultureInfo("es-CL");
        DateTime date= new DateTime();
        if (DateTime.TryParseExact(strDate,"ddd d",cl,DateTimeStyles.None, out date))
        {
            //print the variable date...
        }
    }

Body:
It's been a while and I forgot about that question. After going over your answers (2 years ago Haha) I found that there is a way to parse a date according to the current year calendar.
According to 2017 "Martes 21 de marzo" (Tuesday, March 21) is a valid data and the code below will work, but if you will change it to "Martes 24 de marzo" for example, exception (format exception that says "String was not recognized as a valid DateTime because the day of week was incorrect." to be more accurate) will be raised cause that date doesn't exist at the current year.
I must mention that I used that code to parse dates in scrappers that I used to build and I assumed that the dates that I'm receiving are valid dates.
I hope that that piece of code will help someone somehow.

string strDate ="Martes 21 de marzo";
CultureInfo cl = new CultureInfo("es-CO");
DateTime date = DateTime.Parse(strDate, cl, DateTimeStyles.None);


问:
Mongoose custom validator: check if value exists in database
I am currently trying to add a custom validator to my schema. For some reason I cannot query the database. Does anyone know a solution for my problem?

This is the schema:

```<code>var Portfolio = new Schema({
    title: {
        type: String,
        required: [true, 'Title is required']
    },
    thumbnail: {
        type: String,
        required: [true, 'Thumbnail is required'],
    },
    description: String,
    date: Date,
    images: [String],
    categories: [Schema.Types.ObjectId],
    order: Number,
    slug: {
        type: String,
        validate: {
            validator: slugExists,
            message: 'Slug already exists, choose a different title',
        }
    }
}, options);
</code>```

This is the method that checks whether the data exists:

```<code>function slugExists(value) {
    this.model.count({slug: value}, function(err, count) {
        if (error) {
            return err;
        }
        return count > 0;
    });
}
</code>```

When I run the application I get the following error message:

```<code>TypeError: this.model.count is not a function
</code>```

I have also tried to use the following:

```<code>mongoose.model['portfolio'].count(...)
</code>```

but the result is the same.

I have been trying to fix the problem for two hours now, even tried different approaches (for example the pre hook). But adding the custom validation directly to the Schema feels like the cleanest entry.

Hope you have a solution for me. Many thanks in advance!

Jeffrey

答:
While I was testing the different solutions I found a post that answered my question (https://stackoverflow.com/a/26268156/8267696).

This was the solution I was looking for:

```<code>function slugExists(value, callback) {
    this.constructor.count({slug: value}, function(err, count) {
        if (err) {
            next(err);
        }
        callback(count === 0);
    });
}

Portfolio.pre('validate', function(next) {
    this.slug = slugify(this.title);
    next();
});
</code>```

Side note: The slug will be generated based on the title. That is why I had to use a 'validate' pre hook so that the slug is already set before validation (otherwise the validator would be ignored, because it doesn't have any value and it's not required)

Body:
I am currently trying to add a custom validator to my schema. For some reason I cannot query the database. Does anyone know a solution for my problem?

This is the schema:

var Portfolio = new Schema({
    title: {
        type: String,
        required: [true, 'Title is required']
    },
    thumbnail: {
        type: String,
        required: [true, 'Thumbnail is required'],
    },
    description: String,
    date: Date,
    images: [String],
    categories: [Schema.Types.ObjectId],
    order: Number,
    slug: {
        type: String,
        validate: {
            validator: slugExists,
            message: 'Slug already exists, choose a different title',
        }
    }
}, options);

This is the method that checks whether the data exists:

function slugExists(value) {
    this.model.count({slug: value}, function(err, count) {
        if (error) {
            return err;
        }
        return count > 0;
    });
}

When I run the application I get the following error message:

TypeError: this.model.count is not a function

I have also tried to use the following:

mongoose.model['portfolio'].count(...)

but the result is the same.

I have been trying to fix the problem for two hours now, even tried different approaches (for example the pre hook). But adding the custom validation directly to the Schema feels like the cleanest entry.

Hope you have a solution for me. Many thanks in advance!

Jeffrey

Body:
While I was testing the different solutions I found a post that answered my question (https://stackoverflow.com/a/26268156/8267696).

This was the solution I was looking for:

function slugExists(value, callback) {
    this.constructor.count({slug: value}, function(err, count) {
        if (err) {
            next(err);
        }
        callback(count === 0);
    });
}

Portfolio.pre('validate', function(next) {
    this.slug = slugify(this.title);
    next();
});

Side note: The slug will be generated based on the title. That is why I had to use a 'validate' pre hook so that the slug is already set before validation (otherwise the validator would be ignored, because it doesn't have any value and it's not required)


问:
"Unidentified character <" error when using Vue.js inside PyCharm
I am working on a Python Django project in which in one of the app, I have to do a lot of DOM manipulations. Earlier, I was using jQuery for this purpose but I want to use VueJS because of its virtual DOM. I am using PyCharm Pro. I am not able to use .vue files inside PyCharm. Somehow, I mistakenly set the 'language setting' for .vue file to React RxJS (since Vue also supports RxJS). I then installed Vue plugin for PyCharm and restarted it. Still, I get the same error "Unidentified character <" in the template portion of Vue file. I found that VueJS is now supported with a plugin in PyCharm Pro (https://twitter.com/pycharm/status/848978918120058880).

Can someone tell me what I am missing? What changes in the project or PyCharm settings do I need to make?

Edit: If someone can, please provide any suggestions/alternative solutions to handle DOM manipulations other than jQuery.

答:
Consider setting .vue files in PyCharm to be recognized as HTML files.

I'm currently using PyCharm for a Flask / Vue.js project.

This is what my 'File Types' settings look like for .vue files:

And this is what a .vue file looks like in PyCharm for me:

When you attempt to add the *.vue pattern as an HTML file type, you should be forced by PyCharm to reassign it from the React JSX file type, so you shouldn't need to worry about manually removing the *.vue pattern from the React JSX file type.


问:
WARNING Illegal string offset 'file' on line number 19
simple array giving error.

WARNING Illegal string offset 'file' on line number 19

any help will be great

```<code><?php
  //    $someffdd is output of print_r

$someffdd="Array
(
    [file] => Array
        (
            [name] => 2Pcs-font-b-Mini-b-font-font-b-Couple-b-font-Lover-Animal-DIY-Resin-Fairy-32-185x215.jpg
            [type] => application/octet-stream
            [tmp_name] => /tmp/phpwhglrk
            [error] => 0
            [size] => 8713
        )

)";

            foreach((array) $someffdd as $value ) {

    $jkgkgff=$value['file'];

echo $jkgkgff;
}

?>
</code>```

tried all sort of combination but nothing is error free . i want to output name value

答:
Not sure where this array comes from, but when the array has proper string values it works without issue by simply calling on the key value parent/child:
*Your array in its current state is not properly configured.</p>

```<code>$someffdd = Array (
    "file" => Array (
        "name" => "2Pcs-font-b-Mini-b-font-font-b-Couple-b-font-Lover-Animal-DIY-Resin-Fairy-32-185x215.jpg",
        "type" => "application/octet-stream",
        "tmp_name" => "/tmp/phpwhglrk",
        "error" => 0,
        "size" => 8713
    )

);
//with proper array getting name is simple:
var_dump($someffdd["file"]["name"]);
</code>```

Body:
simple array giving error.

WARNING Illegal string offset 'file' on line number 19

any help will be great

<?php
  //    $someffdd is output of print_r

$someffdd="Array
(
    [file] => Array
        (
            [name] => 2Pcs-font-b-Mini-b-font-font-b-Couple-b-font-Lover-Animal-DIY-Resin-Fairy-32-185x215.jpg
            [type] => application/octet-stream
            [tmp_name] => /tmp/phpwhglrk
            [error] => 0
            [size] => 8713
        )

)";

            foreach((array) $someffdd as $value ) {

    $jkgkgff=$value['file'];

echo $jkgkgff;
}

?>

tried all sort of combination but nothing is error free . i want to output name value

Body:
Not sure where this array comes from, but when the array has proper string values it works without issue by simply calling on the key value parent/child:
*Your array in its current state is not properly configured.

$someffdd = Array (
    "file" => Array (
        "name" => "2Pcs-font-b-Mini-b-font-font-b-Couple-b-font-Lover-Animal-DIY-Resin-Fairy-32-185x215.jpg",
        "type" => "application/octet-stream",
        "tmp_name" => "/tmp/phpwhglrk",
        "error" => 0,
        "size" => 8713
    )

);
//with proper array getting name is simple:
var_dump($someffdd["file"]["name"]);


问:
What is this technique called in javascript?
After I add a link (facebook.com) on Google plus, it shows me:

I want to do same thing on my page but I don't know what it is (Enter url location -> connect to the page and get some informations (logo, name, title...) -> display).

p/s: Sorry for javascript tag, I'm not sure it can be done with javascript or jquery or something else.

答:
This is basically done with Meta tags of the page you're targeting. Google Plus (and Facebook for example) fetch this metadata from the page you're linking to, parse it and show what they want to show.

It's not an actual iframe or embed.

Take a look at The Open Graph protocol: http://ogp.me/

For example if you look at the DOM of the OGP page you'll find some meta tags like:

<meta property="og:description" content="The Open Graph protocol enables any web page to become a rich object in a social graph.">

Now if you're paste that link (http://ogp.me/) into Facebook, that's exactly what will be displayed there. Google Plus doesn't fetch this description for example, it just takes og:image and og:title.

If you want to know how to grab these information of the specified page you should search for questions about that directly, for example here: How can I retrieve og/meta attributes of a resource?

Hope it helps.


问:
Make sql query simpler shorter ( Laravel )
is there any way to make these queries shorter or simpler? or maybe get the result in 1 query rather than 3.??
any advise appreciated</p>

```<code>        $room_single = \DB::table('book_room')
        ->leftJoin('book_tour', 'book_room.bookingID', '=', 'book_tour.bookingID')
        ->where('tourdateID', '=', $id)
        ->where('roomtype','=',1)
        ->where('book_room.status','=',1)
        ->count();

    $room_double = \DB::table('book_room')
        ->leftJoin('book_tour', 'book_room.bookingID', '=', 'book_tour.bookingID')
        ->where('tourdateID', '=', $id)
        ->where('roomtype','=',2)
        ->where('book_room.status','=',1)
        ->count();

    $room_triple = \DB::table('book_room')
        ->leftJoin('book_tour', 'book_room.bookingID', '=', 'book_tour.bookingID')
        ->where('tourdateID', '=', $id)
        ->where('roomtype','=',3)
        ->where('book_room.status','=',1)
        ->count();
    $total= $room_single+($room_double*2)+($room_triple*3) ;
</code>```

答:
You can do it in more simple way.

one is,

```<code>$query = \DB::table('book_room')
         ->leftJoin('book_tour', 'book_room.bookingID', '=', 'book_tour.bookingID')
         ->where('tourdateID', '=', $id)
         ->where('book_room.status','=',1);

$room_single = $query->where('roomtype','=',1)->count();
$room_double = $query->where('roomtype','=',2)->count();
$room_triple = $query->where('roomtype','=',3)->count();
</code>```

And then add these as you want. This is just reducing your lines of code.

Another and better way is following.

```<code>$all_type = \DB::table('book_room')
            ->leftJoin('book_tour', 'book_room.bookingID', '=', 'book_tour.bookingID')
            ->where('tourdateID', '=', $id)
            ->where('book_room.status','=',1)
            ->select('roomtype',\DB::raw('COUNT(bookingID) as count'))
            ->groupBy('roomtype')
            ->get();
</code>```

With this query you will get three count for each room type.
Hope you understand.

Body:
is there any way to make these queries shorter or simpler? or maybe get the result in 1 query rather than 3.??
any advise appreciated

        $room_single = \DB::table('book_room')
        ->leftJoin('book_tour', 'book_room.bookingID', '=', 'book_tour.bookingID')
        ->where('tourdateID', '=', $id)
        ->where('roomtype','=',1)
        ->where('book_room.status','=',1)
        ->count();

    $room_double = \DB::table('book_room')
        ->leftJoin('book_tour', 'book_room.bookingID', '=', 'book_tour.bookingID')
        ->where('tourdateID', '=', $id)
        ->where('roomtype','=',2)
        ->where('book_room.status','=',1)
        ->count();

    $room_triple = \DB::table('book_room')
        ->leftJoin('book_tour', 'book_room.bookingID', '=', 'book_tour.bookingID')
        ->where('tourdateID', '=', $id)
        ->where('roomtype','=',3)
        ->where('book_room.status','=',1)
        ->count();
    $total= $room_single+($room_double*2)+($room_triple*3) ;

Body:
You can do it in more simple way.

one is,

$query = \DB::table('book_room')
         ->leftJoin('book_tour', 'book_room.bookingID', '=', 'book_tour.bookingID')
         ->where('tourdateID', '=', $id)
         ->where('book_room.status','=',1);

$room_single = $query->where('roomtype','=',1)->count();
$room_double = $query->where('roomtype','=',2)->count();
$room_triple = $query->where('roomtype','=',3)->count();

And then add these as you want. This is just reducing your lines of code.

Another and better way is following.

$all_type = \DB::table('book_room')
            ->leftJoin('book_tour', 'book_room.bookingID', '=', 'book_tour.bookingID')
            ->where('tourdateID', '=', $id)
            ->where('book_room.status','=',1)
            ->select('roomtype',\DB::raw('COUNT(bookingID) as count'))
            ->groupBy('roomtype')
            ->get();

With this query you will get three count for each room type.
Hope you understand.


问:
Select Same Element on Second List By Order of Second List
I have a two list of character arrays:

```<code>char[] charA = new char[] { 'a', 'd', 'd', 'b', 'y', 'c', 'a' };
char[] charB = new char[] { 'a', 'b', 'c', 'd'};
</code>```

Now I want to get all the same element and get the same arrangement like on second list (arrangement is a, b, c, d):

```<code>var final = charA.Where(x => charB.Any(y => y == x)).ToArray();
</code>```

The result of this is:

```<code>'a', 'd', 'd', 'b', 'c', 'a'
</code>```

But what I want is the arrangement on the second list using LINQ:

```<code>'a', 'a', 'b', 'c', 'd', 'd'
</code>```

答:
Using method syntax:

```<code>char[] charA = new char[] { 'a', 'd', 'd', 'b', 'y', 'c', 'a' };
char[] charB = new char[] { 'a', 'b', 'c', 'd' };
var result = charA.Where(x => charB.Contains(x)).OrderBy(x => Array.IndexOf(charB, x));
</code>```

Firstly, Where is used to filter out values that are not in charB. Without this, elements that are not in charB would end up at the beginning of result. Then, the remaining collection is simply sorted by using Array.IndexOf which returns the index of each element of charA in charB. This is not optimal, but a really short solution.

Body:
I have a two list of character arrays:

char[] charA = new char[] { 'a', 'd', 'd', 'b', 'y', 'c', 'a' };
char[] charB = new char[] { 'a', 'b', 'c', 'd'};

Now I want to get all the same element and get the same arrangement like on second list (arrangement is a, b, c, d):

var final = charA.Where(x => charB.Any(y => y == x)).ToArray();

The result of this is:

'a', 'd', 'd', 'b', 'c', 'a'

But what I want is the arrangement on the second list using LINQ:

'a', 'a', 'b', 'c', 'd', 'd'

Body:
Using method syntax:

char[] charA = new char[] { 'a', 'd', 'd', 'b', 'y', 'c', 'a' };
char[] charB = new char[] { 'a', 'b', 'c', 'd' };
var result = charA.Where(x => charB.Contains(x)).OrderBy(x => Array.IndexOf(charB, x));

Firstly, Where is used to filter out values that are not in charB. Without this, elements that are not in charB would end up at the beginning of result. Then, the remaining collection is simply sorted by using Array.IndexOf which returns the index of each element of charA in charB. This is not optimal, but a really short solution.


问:
sending large JSON data from android to php server can I compress?
i am sending large datasets in JSON format from my android device to my server (using PHP). I want to keep bandwidth costs down. I am wondering:
should I gzip compress the JSON data server side before sending the data?
is there a javascript gzip uncompression library in php side and what i do in android side?</p>

答:
You can compress your JSON output in this way from PHP server.

```<code>echo gzencode(json_encode($data));
</code>```

And for android side you can use "gzip decoder"

Body:
You can compress your JSON output in this way from PHP server.

echo gzencode(json_encode($data));

And for android side you can use "gzip decoder"