问:
For loop for array in Pharo Smalltalk
I'm trying to make an array with random numbers (just 0 or 1), but when I run it, it just prints this:  End of statement list encountered ->

This is my code:

```<code>GenList
 | lista |
  lista := Array new: 31.
  1 to: 30 do: [ :i | lista at: i put: 2 atRandom - 1]
  ^lista
</code>```

What can I do?

答:
Some interesting things to consider:

1. The method selector doesn't start with a lowercase letter

It is a tradition for selectors to start with a lowercase letter. In this sense, genLista would be more correct than GenLista.

2. The method selector includes the abbreviated word 'gen'

For instance, genLista could be renamed to genereLista o listaAlAzar (if you decide to use Spanish)

3. The Array named lista has 31 elements, not 30

The result of Array new: 31 is an array of 31 elements. However, the code below it only fills 30 of them, leaving the last one uninitialized (i.e., nil). Possible solution: lista := Array new: 30.

4. A dot is missing causing a compilation error

The code

```<code>  1 to: 30 do: [ :i | lista at: i put: 2 atRandom - 1]
  ^lista
</code>```

does not compile because there is no dot indicating the separation between the two sentences. Note that the error happens at compilation time (i.e., when you save the method) because the return token ^ must start a statement (i.e., it cannot be inlined inside a statement).

There are other cases where a missing dot will not prevent the code from compiling. Instead, an error will happen at runtime. Here is a (typical) example:

```<code>1 to: 10 do: [:i | self somethingWith: i]     "<- missing dot here"
self somethingElse
</code>```

the missing dot will generate the runtime error self not understood by block.

5. There is a more expressive way of generating 0s and 1s at random

The calculation 2 atRandom - 1 is ok. However, it forces the reader to mentally do the math. A better way to reveal your intention would have been

```<code>#(0 1) atRandom
</code>```

6. When playing with random numbers don't forget to save the seed

While it is ok to use atRandom, such a practice should only be used with "toy" code. If you are developing a system or a library, the recommended practice is to save the seed somewhere before generating any random data. This will allow you to reproduce the generation of random quantities later on for the sake of debugging or confirmation. (Note however, that this will not suffice for making your program deterministically reproducible because unordered (e.g. hashed) collections could form differently in successive executions.)

Title: For loop for array in Pharo Smalltalk

Body:
I'm trying to make an array with random numbers (just 0 or 1), but when I run it, it just prints this:  End of statement list encountered ->

This is my code:

GenList
 | lista |
  lista := Array new: 31.
  1 to: 30 do: [ :i | lista at: i put: 2 atRandom - 1]
  ^lista

What can I do?

Body:
Some interesting things to consider:

1. The method selector doesn't start with a lowercase letter

It is a tradition for selectors to start with a lowercase letter. In this sense, genLista would be more correct than GenLista.

2. The method selector includes the abbreviated word 'gen'

For instance, genLista could be renamed to genereLista o listaAlAzar (if you decide to use Spanish)

3. The Array named lista has 31 elements, not 30

The result of Array new: 31 is an array of 31 elements. However, the code below it only fills 30 of them, leaving the last one uninitialized (i.e., nil). Possible solution: lista := Array new: 30.

4. A dot is missing causing a compilation error

The code

  1 to: 30 do: [ :i | lista at: i put: 2 atRandom - 1]
  ^lista

does not compile because there is no dot indicating the separation between the two sentences. Note that the error happens at compilation time (i.e., when you save the method) because the return token ^ must start a statement (i.e., it cannot be inlined inside a statement).

There are other cases where a missing dot will not prevent the code from compiling. Instead, an error will happen at runtime. Here is a (typical) example:

1 to: 10 do: [:i | self somethingWith: i]     "<- missing dot here"
self somethingElse

the missing dot will generate the runtime error self not understood by block.

5. There is a more expressive way of generating 0s and 1s at random

The calculation 2 atRandom - 1 is ok. However, it forces the reader to mentally do the math. A better way to reveal your intention would have been

#(0 1) atRandom

6. When playing with random numbers don't forget to save the seed

While it is ok to use atRandom, such a practice should only be used with "toy" code. If you are developing a system or a library, the recommended practice is to save the seed somewhere before generating any random data. This will allow you to reproduce the generation of random quantities later on for the sake of debugging or confirmation. (Note however, that this will not suffice for making your program deterministically reproducible because unordered (e.g. hashed) collections could form differently in successive executions.)


来源: stackexchange

问:
Parent POM with Multiple - Multiple Modules having dependency
We had a relative flat project structure in CVS and post migration to Git we encountered a issue due to how Git repository were checkout. A CVS repository was never checkout, but with Git on Eclipse we see a repository folder under which projects are checkout. This has caused issue with our Maven script.

The new structure is:

I added the pom.xml file under idml and leancore that refer to parent pom.xml. the project below idml refers the intermediate idml parent pom.xml and leancore refer intermediate leancore parent pom.xml.

How do I define the dependency between 2 Multiple Modules project?

What will go into the parent POM to support this kind of structure?

How can AdjHubCore refer to a dependency in idml - idmlj2eert?

We would like to build all the module and war file from the root parent pom.xml file.

答:
Your idmlj2eert POM looks like:

```<code>  ...
  <groupId>idml</groupId>
  <artifactId>idmlj2eert<artifactId>
  <version>0.0.1-SNAPSHOT<>version>
  ...
</code>```

Then your AdjHubCore looks like:

```<code>    ...
    <dependency>
      <groupId>idml</groupId>
      <artifactId>idmlj2eert<artifactId>
      <version>0.0.1-SNAPSHOT<>version>
    </dependency>
   ...
</code>```

An alternative is to use <dependencyManagement> in your root POM, such avoiding having to declare a dependency's version in child POMs. Your root POM has to be a <parent> POM, direct or transitive across multiple levels, of such a child POM then.

So, that's not different to any other dependency. The Maven Reactor takes care of the proper build order according to (intra-)dependencies inside a multi-module project at the beginning of the build.

Remember, aggregation (multi-module) and inheritance (parent/child relationships) are different things. A project can use either of them and it can use both, too. See POM Reference, Inheritance v. Aggregation and Maven: The Complete Reference, 3.6.2. Multi-module vs. Inheritance.

ContentLicense: CC BY-SA 3.0

Body:
Your idmlj2eert POM looks like:

  ...
  <groupId>idml</groupId>
  <artifactId>idmlj2eert<artifactId>
  <version>0.0.1-SNAPSHOT<>version>
  ...

Then your AdjHubCore looks like:

    ...
    <dependency>
      <groupId>idml</groupId>
      <artifactId>idmlj2eert<artifactId>
      <version>0.0.1-SNAPSHOT<>version>
    </dependency>
   ...

An alternative is to use <dependencyManagement> in your root POM, such avoiding having to declare a dependency's version in child POMs. Your root POM has to be a <parent> POM, direct or transitive across multiple levels, of such a child POM then.

So, that's not different to any other dependency. The Maven Reactor takes care of the proper build order according to (intra-)dependencies inside a multi-module project at the beginning of the build.

Remember, aggregation (multi-module) and inheritance (parent/child relationships) are different things. A project can use either of them and it can use both, too. See POM Reference, Inheritance v. Aggregation and Maven: The Complete Reference, 3.6.2. Multi-module vs. Inheritance.


问:
Can json.loads ignore trailing commas?
As mentioned in this StackOverflow question, you are not allowed to have any trailing commas in json. For example, this

```<code>{
    "key1": "value1",
    "key2": "value2"
}
</code>```

is fine, but this

```<code>{
    "key1": "value1",
    "key2": "value2",
}
</code>```

is invalid syntax.

For reasons mentioned in this other StackOverflow question, using a trailing comma is legal (and perhaps encouraged?) in Python code. I am working with both Python and JSON, so I would love to be able to be consistent across both types of files. Is there a way to have json.loads ignore trailing commas?

答:
You can wrap python's json parser with jsoncomment

JSON Comment allows to parse JSON files or strings with:

Single and Multi line comments

Multi line data strings

Trailing commas in objects and arrays, after the last item

Example usage:

```<code>import json
from jsoncomment import JsonComment

with open(filename) as data_file:
    parser = JsonComment(json)
    data = parser.load(data_file)
</code>```

Title: Can json.loads ignore trailing commas?

Body:
As mentioned in this StackOverflow question, you are not allowed to have any trailing commas in json. For example, this

{
    "key1": "value1",
    "key2": "value2"
}

is fine, but this

{
    "key1": "value1",
    "key2": "value2",
}

is invalid syntax.

For reasons mentioned in this other StackOverflow question, using a trailing comma is legal (and perhaps encouraged?) in Python code. I am working with both Python and JSON, so I would love to be able to be consistent across both types of files. Is there a way to have json.loads ignore trailing commas?

Body:
You can wrap python's json parser with jsoncomment

JSON Comment allows to parse JSON files or strings with:

Single and Multi line comments

Multi line data strings

Trailing commas in objects and arrays, after the last item

Example usage:

import json
from jsoncomment import JsonComment

with open(filename) as data_file:
    parser = JsonComment(json)
    data = parser.load(data_file)


问:
Ajax call in cakePhp does not execute the requested php code in controller
I was handed a project written with cakePhp framework and needed to add some additional function. I tried to follow the existing syntax but somehow couldn't get the new function to work.

The original view file has the following script portion (after the html stuff):

```<code><script type="text/javascript">

function printorderpage() {
    window.print();
}

</script>
</code>```

What I wanted to do is to perform certain database operation (mark a record as locked down so it can no longer be edited) when user prints the page.

Here's what I added to the view file:

```<code>(function() {
    var beforePrint = function() {
        //console.log('Functionality to run before printing.');
        //alert('before print test');
    };
    var afterPrint = function() {
        //console.log('Functionality to run after printing');
        alert('lock'+<?=$order_id?>);

        $.ajax({
            url: "/Workorder/ajaxLockOrder/<?=$order_id?>?debug=false",
            type: "post",
            dataType: "json",
            data: post_data
        }).done(function(e) {
            alert(e.message);
        });

        alert('done?');

    };

    if (window.matchMedia) {
        var mediaQueryList = window.matchMedia('print');
        mediaQueryList.addListener(function(mql) {
            if (mql.matches) {
                beforePrint();
            } else {
                afterPrint();
            }
        });
    }

    window.onbeforeprint = beforePrint;
    window.onafterprint = afterPrint;
}());
</code>```

Basically the afterPrint function is called whenever user prints the page, and this in turn calls the controller function "ajaxLockOrder" to perform some database operations in the backend. By using the alert box, I could verify that the afterPrint function is executed (the alert pop-up successfully showed the $order_id that needs to be locked, in my test case, order_id is "18", alert box showed "lock18"). But then the ajaxLockOrder was not called?

The controller file is named "workorder_controller.php", and here's the ajaxLockOrder function inside the controller:

```<code>function ajaxLockOrder($order_id) {
    //once the order is printed, lock the order so it can not be changed
    error_log("executed", 3, "lockerr.log");
    $this->Order->updateActivityStream($order_id, 5); //data operation
}
</code>```

By using the error_log function, I could verify that this function was not executed since the log file was not created.

On the other hand, when I tried to directly type in this function address (http://myurl/Workorder/ajaxLockOrder/18) in browser window, it worked and generated the log file in the backend and updated the database record for order#18. WHY?

Thanks in advance for any help.

答:
```<code>$.ajax({
        url: "<?php echo $this->Html->url(array('controller'=>'Workorder','action'=>'ajaxLockOrder',$order_id));?>",
        type: "post",
        dataType: "json",
        data: post_data
    }).done(function(e) {
        alert(e.message);
    });
</code>```

Body:
I was handed a project written with cakePhp framework and needed to add some additional function. I tried to follow the existing syntax but somehow couldn't get the new function to work.

The original view file has the following script portion (after the html stuff):

What I wanted to do is to perform certain database operation (mark a record as locked down so it can no longer be edited) when user prints the page.

Here's what I added to the view file:

(function() {
    var beforePrint = function() {
        //console.log('Functionality to run before printing.');
        //alert('before print test');
    };
    var afterPrint = function() {
        //console.log('Functionality to run after printing');
        alert('lock'+<?=$order_id?>);

        $.ajax({
            url: "/Workorder/ajaxLockOrder/<?=$order_id?>?debug=false",
            type: "post",
            dataType: "json",
            data: post_data
        }).done(function(e) {
            alert(e.message);
        });

        alert('done?');

    };

    if (window.matchMedia) {
        var mediaQueryList = window.matchMedia('print');
        mediaQueryList.addListener(function(mql) {
            if (mql.matches) {
                beforePrint();
            } else {
                afterPrint();
            }
        });
    }

    window.onbeforeprint = beforePrint;
    window.onafterprint = afterPrint;
}());

Basically the afterPrint function is called whenever user prints the page, and this in turn calls the controller function "ajaxLockOrder" to perform some database operations in the backend. By using the alert box, I could verify that the afterPrint function is executed (the alert pop-up successfully showed the $order_id that needs to be locked, in my test case, order_id is "18", alert box showed "lock18"). But then the ajaxLockOrder was not called?

The controller file is named "workorder_controller.php", and here's the ajaxLockOrder function inside the controller:

function ajaxLockOrder($order_id) {
    //once the order is printed, lock the order so it can not be changed
    error_log("executed", 3, "lockerr.log");
    $this->Order->updateActivityStream($order_id, 5); //data operation
}

By using the error_log function, I could verify that this function was not executed since the log file was not created.

On the other hand, when I tried to directly type in this function address (http://myurl/Workorder/ajaxLockOrder/18) in browser window, it worked and generated the log file in the backend and updated the database record for order#18. WHY?

Thanks in advance for any help.


问:
MySQLi Update Query works manually but no in script
I'm making an script that pings to IP and X value is saved in a MySQL db for statistic purposes.

If I take the echo (of the update data, in the mid of function) and execute directly in PHPMyAdmin works perfectly, but no the same query in the PHP code, I've checked all and I dont see the error, lol.

This is the code:

```<code>    /*
    ID  Primary int(11)         No  None        AUTO_INCREMENT   Change Change   Drop Drop
More
    2   ip  text    latin1_swedish_ci       No  None             Change Change   Drop Drop
More
    3   timeping    text    latin1_swedish_ci       No  None             Change Change   Drop Drop
More
    4   jsondata    text    latin1_swedish_ci       No  None             Change Change   Drop Drop
More
    5   timeop  text    latin1_swedish_ci
    */

$db = new mysqli ("127.0.0.1", "R_status", "PASSHIDDEN", "R_status");
//$totalIP = $db->query("SELECT COUNT(*) FROM data");
//$resultado = $totalIP->fetch_array();
//print($resultado[0]);
$prepare = $db->query("SELECT * FROM data WHERE timeping='0' LIMIT 1");
$ars = $prepare->fetch_array();
//echo($prepare-num_rows);
function pingAddress($ip) {
    $pingresult = exec("/bin/ping -c 3 $ip", $outcome, $status);
    $status++;
    global $ars;
    // 0 = NO COMPROBADO
    // 1 = EN LINEA
    // 2 = CAIDO
    echo("UPDATE data SET `timeping`='$status' WHERE ID=".$ars[0]."");
    $db->query("UPDATE data SET `timeping`='$status' WHERE ID=".$ars[0]."");
    die();
}
print_r($ars);
pingAddress($ars[1]);

?>
</code>```

Here's one output of this code:

```<code>Array ( [0] => 2 [ID] => 2 [1] => 77.26.0.2 [ip] => 77.26.0.2 [2] => 0 [timeping] => 0 [3] => 0 [jsondata] => 0 [4] => 0 [timeop] => 0 )

UPDATE data SET `timeping`='1' WHERE ID=2
</code>```

That update string works in PhpMyAdmin but no directly in the PHP script, stranger for me, because I didn't found a solution in google.

答:
As suggested in the comments, your current way of doing the query.. even with the added global $db; is highly insecure and is sensible to SQL-Injection attacks.

I suggest you do your update query as follows, to avoid the risk of SQL-Injections happening. However private you intend this to be or not, ignorance is no excuse in safety!

```<code>// $db is your database connection
$query = "UPDATE `data` SET `timeping`=? WHERE `ID`=?"; // the query
$stmt = mysqli_prepare($db, $query); // prepares the query for params
mysqli_stmt_bind_param($stmt, 'ii', $status, $ars[0]); // bind two ints -> 'ii' -> passing the args behind it
mysqli_stmt_execute($stmt); // run the stmt
// use following to check the number of affected rows:
// mysqli_stmt_affected_rows($stmt) // highly recommended to check for any malicious activity!
mysqli_stmt_close($stmt); // close it -> just to do it neatly
</code>```

An additional check through preg_match is advised to prevent any malicious code from beeing inserted when this does accidentaly get into the wrong hands. Doing mysqli_real_escape_string, stripping the tags and trimming might be good ideas aswell.

Body:
I'm making an script that pings to IP and X value is saved in a MySQL db for statistic purposes.

If I take the echo (of the update data, in the mid of function) and execute directly in PHPMyAdmin works perfectly, but no the same query in the PHP code, I've checked all and I dont see the error, lol.

This is the code:

    /*
    ID  Primary int(11)         No  None        AUTO_INCREMENT   Change Change   Drop Drop
More
    2   ip  text    latin1_swedish_ci       No  None             Change Change   Drop Drop
More
    3   timeping    text    latin1_swedish_ci       No  None             Change Change   Drop Drop
More
    4   jsondata    text    latin1_swedish_ci       No  None             Change Change   Drop Drop
More
    5   timeop  text    latin1_swedish_ci
    */

$db = new mysqli ("127.0.0.1", "R_status", "PASSHIDDEN", "R_status");
//$totalIP = $db->query("SELECT COUNT(*) FROM data");
//$resultado = $totalIP->fetch_array();
//print($resultado[0]);
$prepare = $db->query("SELECT * FROM data WHERE timeping='0' LIMIT 1");
$ars = $prepare->fetch_array();
//echo($prepare-num_rows);
function pingAddress($ip) {
    $pingresult = exec("/bin/ping -c 3 $ip", $outcome, $status);
    $status++;
    global $ars;
    // 0 = NO COMPROBADO
    // 1 = EN LINEA
    // 2 = CAIDO
    echo("UPDATE data SET `timeping`='$status' WHERE ID=".$ars[0]."");
    $db->query("UPDATE data SET `timeping`='$status' WHERE ID=".$ars[0]."");
    die();
}
print_r($ars);
pingAddress($ars[1]);

?>

Here's one output of this code:

Array ( [0] => 2 [ID] => 2 [1] => 77.26.0.2 [ip] => 77.26.0.2 [2] => 0 [timeping] => 0 [3] => 0 [jsondata] => 0 [4] => 0 [timeop] => 0 )

UPDATE data SET `timeping`='1' WHERE ID=2

That update string works in PhpMyAdmin but no directly in the PHP script, stranger for me, because I didn't found a solution in google.

Body:
As suggested in the comments, your current way of doing the query.. even with the added global $db; is highly insecure and is sensible to SQL-Injection attacks.

I suggest you do your update query as follows, to avoid the risk of SQL-Injections happening. However private you intend this to be or not, ignorance is no excuse in safety!

// $db is your database connection
$query = "UPDATE `data` SET `timeping`=? WHERE `ID`=?"; // the query
$stmt = mysqli_prepare($db, $query); // prepares the query for params
mysqli_stmt_bind_param($stmt, 'ii', $status, $ars[0]); // bind two ints -> 'ii' -> passing the args behind it
mysqli_stmt_execute($stmt); // run the stmt
// use following to check the number of affected rows:
// mysqli_stmt_affected_rows($stmt) // highly recommended to check for any malicious activity!
mysqli_stmt_close($stmt); // close it -> just to do it neatly

An additional check through preg_match is advised to prevent any malicious code from beeing inserted when this does accidentaly get into the wrong hands. Doing mysqli_real_escape_string, stripping the tags and trimming might be good ideas aswell.


问:
CPP - strlen is not outputting entire length for multiple words [C-Strings Only]
the code below is only outputting the length of the first word that I typed. I thought strlen would give me the length of multiple words, but it doesn't.

For example, the string "hello sir" gives me the output of 5 and not 8. Why is that?

```<code>#include <iostream>
#include <string>

void ReadString(char * c, int maxLength);
void GetStringLength(char * c, int * length);

int main()
{

    int length = 0;
    const int SIZE = 20;
    char cpoint[SIZE];
    char *refC = cpoint;

    ReadString(refC, SIZE);
    GetStringLength(refC, &length);
    system("pause");

}

void ReadString(char * c, int maxLength)
{
    std::cout << "Enter a string " << maxLength << " characters." << std::endl;
    std::cin >> c;

}

void GetStringLength(char * c, int * length)
{
    int sizeOfArray = std::strlen(c);
    *length = sizeOfArray;
    std::cout << sizeOfArray;
}
</code>```

答:
he string "hello sir" gives me the output of 5 and not 8. Why is that?

You are using

```<code>std::cin >> c;
</code>```

to read input into c. That will stop reading at the first whitespace. Hence, only "hello" is read into c, not "hello sir".

If you want to read the entire line, you can use std::string for c, instead of char*, and then use std::getline.

```<code>getline(cin, c);
</code>```

If you must use char*, I can think of the following options.

You can use istream::read.

```<code>cin.read(c, maxLength);
</code>```

and then, null-terminate c.

```<code>c[cin.gcount()] = '\0';
</code>```

You can use istream::getline.

```<code>cin.getline(c, maxLength);
</code>```

Body:
the code below is only outputting the length of the first word that I typed. I thought strlen would give me the length of multiple words, but it doesn't.

For example, the string "hello sir" gives me the output of 5 and not 8. Why is that?

#include <iostream>
#include <string>

void ReadString(char * c, int maxLength);
void GetStringLength(char * c, int * length);

int main()
{

    int length = 0;
    const int SIZE = 20;
    char cpoint[SIZE];
    char *refC = cpoint;

    ReadString(refC, SIZE);
    GetStringLength(refC, &length);
    system("pause");

}

void ReadString(char * c, int maxLength)
{
    std::cout << "Enter a string " << maxLength << " characters." << std::endl;
    std::cin >> c;

}

void GetStringLength(char * c, int * length)
{
    int sizeOfArray = std::strlen(c);
    *length = sizeOfArray;
    std::cout << sizeOfArray;
}

Body:
he string "hello sir" gives me the output of 5 and not 8. Why is that?

You are using

std::cin >> c;

to read input into c. That will stop reading at the first whitespace. Hence, only "hello" is read into c, not "hello sir".

If you want to read the entire line, you can use std::string for c, instead of char*, and then use std::getline.

getline(cin, c);

If you must use char*, I can think of the following options.

You can use istream::read.

cin.read(c, maxLength);

and then, null-terminate c.

c[cin.gcount()] = '\0';

You can use istream::getline.

cin.getline(c, maxLength);


问:
egrep search for whitespace
I'm trying to use egrep with a regex pattern to match whitespace.

I've used RegEx with Perl and C# before and they both support the pattern \s to search for whitespace. egrep (or at least the version I'm using) does not seem to support this pattern.

In a few articles online I've come across a shorthand [[:space:]], but this does not seem to work. Any help is appreciated.

Using: SunOS 5.10

答:
If you're using 'degraded' versions of grep (I quote the term because most UNIX'es I work on still use the original REs, not those fancy ones with "\s" or "[[:space:]]" :-), you can just revert to the lowest form of RE.

For example, if :space: is defined as spaces and tabs, just use:

```<code>egrep '[ ^I]' file
</code>```

That ^I is an actual tab character, not the two characters ^ and I.

This is assuming :space: is defined as tabs and spaces, otherwise adjust the choices within the [] characters.

The advantage of using degraded REs is that they should work on all platforms (at least for ASCII; Unicode or non-English languages may have different rules but I rarely find a need).

Title: egrep search for whitespace

Body:
If you're using 'degraded' versions of grep (I quote the term because most UNIX'es I work on still use the original REs, not those fancy ones with "\s" or "[[:space:]]" :-), you can just revert to the lowest form of RE.

For example, if :space: is defined as spaces and tabs, just use:

egrep '[ ^I]' file

That ^I is an actual tab character, not the two characters ^ and I.

This is assuming :space: is defined as tabs and spaces, otherwise adjust the choices within the [] characters.

The advantage of using degraded REs is that they should work on all platforms (at least for ASCII; Unicode or non-English languages may have different rules but I rarely find a need).

OwnerDisplayName: Pax

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Jonathan Leffler


问:
Python & Sqlite3 - Uploading text file to SQL database keeps breaking
I have a text file, containing around 662,000 lines. I want to move each line in this text file into my database using sqlite3. Each line has two components, a key and a company name. Company name goes in one column, and a key in another.

Code below:

```<code>def input_txt_to_db():
    with open(our_txt_file) as f:
        for line in f:
            # Format each line
            curr_comp_name = str(line.rsplit(':')[0])
            curr_comp_key = str(line.rsplit(':')[-2])
            # Create object of the line
            curr_comp = Company(curr_comp_name, curr_comp_key)
            # Insert company is a self-made method, listed below
            insert_company(curr_comp)

def insert_company(comp):
    """

    :param comp: Company (object)
    :return: None
    """
    with conn:
        conn_cursor.execute("INSERT INTO companies VALUES "
                            "(:name, :key)",
                            {'name': comp.name,
                             'key': comp.key
                             })
</code>```

Now this all works, and I've check the db to see, and it uploaded properly. However, once it gets to say 60k lines, it crashes. It gives me some error like, OS error, or something like that. Also note, I have more than enough space for this db.

答:
This does not seem to be the most efficient way to upload data anyway. How about uploading data portion by portion with executemany?

```<code>def insert_companies(comps):
    with conn:
        conn_cursor.executemany("INSERT INTO companies VALUES (?, ?)", comps)
</code>```

We have to redefine the main function a bit. Let's get rid of the objects, we don't need them now anyway, right?

```<code>def input_txt_to_db():
    with open(our_txt_file) as f:
        batch = list()
        # How many companies do we dump to db at once?
        batch_size = 2000
        for line in f:
            # Format each line
            curr_comp_name = str(line.rsplit(':')[0])  # why str? it should be string as it is
            curr_comp_key = str(line.rsplit(':')[-2])
            # Create object of the line
            batch.append((curr_comp_name, curr_comp_name))
            # Insert company is a self-made method, listed below
            if len(batch) == batch_size:
                 insert_companies(batch)
                 batch = list()
        # something may be still pending
        if batch:
            insert_companies(batch)
</code>```

Try it, it should work. If you give some more information on the error that occurs, it might help as well, because now there isn't enough context to definitively answer your question.

Body:
I have a text file, containing around 662,000 lines. I want to move each line in this text file into my database using sqlite3. Each line has two components, a key and a company name. Company name goes in one column, and a key in another.

Code below:

def input_txt_to_db():
    with open(our_txt_file) as f:
        for line in f:
            # Format each line
            curr_comp_name = str(line.rsplit(':')[0])
            curr_comp_key = str(line.rsplit(':')[-2])
            # Create object of the line
            curr_comp = Company(curr_comp_name, curr_comp_key)
            # Insert company is a self-made method, listed below
            insert_company(curr_comp)

def insert_company(comp):
    """

    :param comp: Company (object)
    :return: None
    """
    with conn:
        conn_cursor.execute("INSERT INTO companies VALUES "
                            "(:name, :key)",
                            {'name': comp.name,
                             'key': comp.key
                             })

Now this all works, and I've check the db to see, and it uploaded properly. However, once it gets to say 60k lines, it crashes. It gives me some error like, OS error, or something like that. Also note, I have more than enough space for this db.

Body:
This does not seem to be the most efficient way to upload data anyway. How about uploading data portion by portion with executemany?

def insert_companies(comps):
    with conn:
        conn_cursor.executemany("INSERT INTO companies VALUES (?, ?)", comps)

We have to redefine the main function a bit. Let's get rid of the objects, we don't need them now anyway, right?

def input_txt_to_db():
    with open(our_txt_file) as f:
        batch = list()
        # How many companies do we dump to db at once?
        batch_size = 2000
        for line in f:
            # Format each line
            curr_comp_name = str(line.rsplit(':')[0])  # why str? it should be string as it is
            curr_comp_key = str(line.rsplit(':')[-2])
            # Create object of the line
            batch.append((curr_comp_name, curr_comp_name))
            # Insert company is a self-made method, listed below
            if len(batch) == batch_size:
                 insert_companies(batch)
                 batch = list()
        # something may be still pending
        if batch:
            insert_companies(batch)

Try it, it should work. If you give some more information on the error that occurs, it might help as well, because now there isn't enough context to definitively answer your question.


问:
Refering DBI functions in package - which to use?
When developing package using DBI extension (e.g. RJDBC, RSQLite) which package should I refer to?

```<code>connect_my_db <- function() DBI::dbConnect(RSQLite::SQLite(), "my_db.sqlite")
</code>```

or

```<code>connect_my_db <- function() RSQLite::dbConnect(RSQLite::SQLite(), "my_db.sqlite")
</code>```

?

First method force me to use DBI in Imports, so I prefer second one. But on other side I should call virtual function and let R to decide what to call.

答:
The DBI spec do require all backends to re-export all of DBI's methods, so both notations (RSQLite::dbConnect() vs. DBI::dbConnect()) are identical for all practical purposes:

identical(DBI::dbConnect, RSQLite::dbConnect)
#> [1] TRUE
```

The DBI:: notation expresses that you're using a DBI function, but if your package only uses RSQLite it seems fine to use that prefix from a code style point of view.

Body:
When developing package using DBI extension (e.g. RJDBC, RSQLite) which package should I refer to?

connect_my_db <- function() DBI::dbConnect(RSQLite::SQLite(), "my_db.sqlite")

or

connect_my_db <- function() RSQLite::dbConnect(RSQLite::SQLite(), "my_db.sqlite")

?

First method force me to use DBI in Imports, so I prefer second one. But on other side I should call virtual function and let R to decide what to call.

Body:
The DBI spec do require all backends to re-export all of DBI's methods, so both notations (RSQLite::dbConnect() vs. DBI::dbConnect()) are identical for all practical purposes:

identical(DBI::dbConnect, RSQLite::dbConnect)
#> [1] TRUE

The DBI:: notation expresses that you're using a DBI function, but if your package only uses RSQLite it seems fine to use that prefix from a code style point of view.


问:
How may I dynamically insert a string into a large javascript template string in python?
Suppose a template javascript string like this:

```<code>js_string = u'function hello() { alert({0}); } function goodbye() { alert({1}); }'
</code>```

I would like to get following result:

```<code>function hello() { alert('Hello!'); } function goodbye() { alert('Goodbye!'); }
</code>```

My initial idea was to use the .format() method, which resulted in a KeyError due to the arbitrary curly braces. I then had a look at this question and replaced said curly braces with double curly braces. Although this produces the desired result, I cannot use it, as I'm working with a rather large javascript template and am not up for changing each and every single curly brace.

I have also tried the .replace() function:

```<code>js_string.replace("{0}", repr("Hello!")).replace("{1}", repr("Goodbye!"))
</code>```

However, calling .replace() more than once seems inconvenient to me, which is why I am asking if there is any straightforward alternative for this problem.

答:
You could do the replacement with one call to sub by supplying a callback function that reads the number inside braces, and grabs the corresponding replacement word from a list:

```<code>re.sub(r'\{(\d+)\}', lambda m: ["'hello'", "'Goodbye!'"][int(m.group(1))], js_string)
</code>```

Body:
Suppose a template javascript string like this:

js_string = u'function hello() { alert({0}); } function goodbye() { alert({1}); }'

I would like to get following result:

function hello() { alert('Hello!'); } function goodbye() { alert('Goodbye!'); }

My initial idea was to use the .format() method, which resulted in a KeyError due to the arbitrary curly braces. I then had a look at this question and replaced said curly braces with double curly braces. Although this produces the desired result, I cannot use it, as I'm working with a rather large javascript template and am not up for changing each and every single curly brace.

I have also tried the .replace() function:

js_string.replace("{0}", repr("Hello!")).replace("{1}", repr("Goodbye!"))

However, calling .replace() more than once seems inconvenient to me, which is why I am asking if there is any straightforward alternative for this problem.

Body:
You could do the replacement with one call to sub by supplying a callback function that reads the number inside braces, and grabs the corresponding replacement word from a list:

re.sub(r'\{(\d+)\}', lambda m: ["'hello'", "'Goodbye!'"][int(m.group(1))], js_string)


问:
Remove white space at the top and the bottom in h3
h3 with white space at the top and the bottom

I have some white space around my h3. To align it the same as some pictures I want to delete the white space at the top and the bottom of the h3. The margin is 0, but there is still space between the top and the bottom of the text. How do I solve this?

this is my code:

```<code><html>
 <head>
 </head>
 <body>
  <h3>title</h3>
 </body>
</html>
</code>```

答:
Just Remove The Browser Default Margin and Padding Apply Top Of Your Css.

```<code><style>

* {
  margin: 0;
  padding: 0;
}

</style>
</code>```

NOTE:

Try to Reset all the html elements before writing your css.

OR [ Use In Your Case ]

```<code><style>

  *{
        margin: 0px;
        padding: 0px;
    }

h3 {
        margin-top: 0px;
    }

</style>
</code>```

DEMO:

```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
 <head>
 </head>
 <body>
  <h3>title</h3>
 </body>
</html></code>```

Body:
h3 with white space at the top and the bottom

I have some white space around my h3. To align it the same as some pictures I want to delete the white space at the top and the bottom of the h3. The margin is 0, but there is still space between the top and the bottom of the text. How do I solve this?

this is my code:

title

Body:
Just Remove The Browser Default Margin and Padding Apply Top Of Your Css.

<style>

* {
  margin: 0;
  padding: 0;
}

</style>

NOTE:

Try to Reset all the html elements before writing your css.

OR [ Use In Your Case ]

<style>

  *{
        margin: 0px;
        padding: 0px;
    }

h3 {
        margin-top: 0px;
    }

</style>

DEMO:

<style>

  *{
        margin: 0px;
        padding: 0px;
    }

h3 {
        margin-top: 0px;
    }

</style>

<html>
 <head>
 </head>
 <body>
  <h3>title</h3>
 </body>
</html>


问:
How do I retrieve an image from the cursor in android? getImageView?
I'm new to Android development and I'm trying to build a music player. To add the song data in the RecyclerView I created an ArrayList (thisList) which contains the song data including the album art but I can't figure out how to add the image to the list :( </p>

```<code> if(musicCursor!=null && musicCursor.moveToFirst()){
        //get columns
        int titleColumn = musicCursor.getColumnIndex
                (android.provider.MediaStore.Audio.Media.TITLE);
        int idColumn = musicCursor.getColumnIndex
                (android.provider.MediaStore.Audio.Media._ID);
        int artistColumn = musicCursor.getColumnIndex
                (android.provider.MediaStore.Audio.Media.ARTIST);
        int albumColumn = musicCursor.getColumnIndex
                (MediaStore.Audio.Media.ALBUM);

        int albumArtColumn = musicCursor.getColumnIndex
                (android.provider.MediaStore.Audio.Albums.ALBUM_ART);

        //add songs to list
        do {
            long thisId = musicCursor.getLong(idColumn);
            String thisTitle = musicCursor.getString(titleColumn);
            String thisArtist = musicCursor.getString(artistColumn);
            String thisAlbum = musicCursor.getString(albumColumn);

        //ImageView thisAlbumArt = musicCursor. ????

        theList.add(newSong(thisId,thisTitle,
                      thisArtist,thisAlbum,thisAlbumArt));
        }
        while (musicCursor.moveToNext());
    }
</code>```

答:
Try this:</p>

```<code>Cursor artCursor = context.getContentResolver().query(
    MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI,
    new String[] {MediaStore.Audio.AlbumColumns.ALBUM_ART},
    MediaStore.Audio.Media._ID+" =?",
    new String[]{String.valueOf(albumId)},
    null);
String albumArt;
if(artCursor.moveToNext()) {
    albumArt = "file://"+artCursor.getString(0);
} else {
    albumArt = null;
}
artCursor.close();

if(albumArt != null) {
    BitmapFactory.decodeFile(new File(albumArt));
}
</code>```

Body:
I'm new to Android development and I'm trying to build a music player. To add the song data in the RecyclerView I created an ArrayList (thisList) which contains the song data including the album art but I can't figure out how to add the image to the list :(

 if(musicCursor!=null && musicCursor.moveToFirst()){
        //get columns
        int titleColumn = musicCursor.getColumnIndex
                (android.provider.MediaStore.Audio.Media.TITLE);
        int idColumn = musicCursor.getColumnIndex
                (android.provider.MediaStore.Audio.Media._ID);
        int artistColumn = musicCursor.getColumnIndex
                (android.provider.MediaStore.Audio.Media.ARTIST);
        int albumColumn = musicCursor.getColumnIndex
                (MediaStore.Audio.Media.ALBUM);

        int albumArtColumn = musicCursor.getColumnIndex
                (android.provider.MediaStore.Audio.Albums.ALBUM_ART);

        //add songs to list
        do {
            long thisId = musicCursor.getLong(idColumn);
            String thisTitle = musicCursor.getString(titleColumn);
            String thisArtist = musicCursor.getString(artistColumn);
            String thisAlbum = musicCursor.getString(albumColumn);

        //ImageView thisAlbumArt = musicCursor. ????

        theList.add(newSong(thisId,thisTitle,
                      thisArtist,thisAlbum,thisAlbumArt));
        }
        while (musicCursor.moveToNext());
    }

Body:
Try this:

Cursor artCursor = context.getContentResolver().query(
    MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI,
    new String[] {MediaStore.Audio.AlbumColumns.ALBUM_ART},
    MediaStore.Audio.Media._ID+" =?",
    new String[]{String.valueOf(albumId)},
    null);
String albumArt;
if(artCursor.moveToNext()) {
    albumArt = "file://"+artCursor.getString(0);
} else {
    albumArt = null;
}
artCursor.close();

if(albumArt != null) {
    BitmapFactory.decodeFile(new File(albumArt));
}


问:
Fetching reviews and ratings from Shopify API
I need to get latest reviews from Shopify and it's ratings.
I found official Shopify reviews app with code snippet
which needs to be placed in theme template file, but there seems
to be no way to get these reviews through API or through webhooks.

Is there any other app for reviews in Shopify with open API?

答:
I asked Shopify to create a webhook for their review app but the response was that they do not integrate with third party apps, unfortunately.

I'm not sure about getting historical reviews, but you can capture reviews that are created in the review form by adding an additional submit event handler in your script tag and submitting the data to your server via XHR.


问:
How can I validate a copy constructor's parameter?
```<code>public class Rectangle {

  int width, height;

  public Rectangle(int width, int height) {
    this.width = width;
    this.height = height;
  }

  public Rectangle(Rectangle source) {
    this(source.width, source.height);
  }
}
</code>```

Let's say I have a class with multiple constructors, one of which is a copy-constructor (to copy an object).

Is there any way I can make check if source is null in the copy-constructor and throw an IllegalArgumentException if it is? Because the other constructor call has to be the first statement in my constructor.

答:
If you have this method somewhere in your codebase:

```<code>public static <T, R> R getIfNotNull(T instance, Function<T, R> extractor) {
    if (instance == null) throw new IllegalArgumentException();
    return extractor.apply(instance);
}
</code>```

You could use it to throw an IllegalArgumentException from within your constructor:

```<code>public class Rectangle {

    int width, height;

    public Rectangle(int width, int height) {
        this.width = width;
        this.height = height;
    }

    public Rectangle(Rectangle source) {
        this(getIfNotNull(source, s -> s.width), source.height);
    }
}
</code>```

Disclaimer: all this would be needed just to throw an IllegalArgumentException, which is less idiomatic than a NullPointerException. In general, it's considered good practice to throw a NullPointerException if some non-nullable argument is null. And your original code was already doing this when attempting to dereference the argument.

Body:
public class Rectangle {

  int width, height;

  public Rectangle(int width, int height) {
    this.width = width;
    this.height = height;
  }

  public Rectangle(Rectangle source) {
    this(source.width, source.height);
  }
}

Let's say I have a class with multiple constructors, one of which is a copy-constructor (to copy an object).

Is there any way I can make check if source is null in the copy-constructor and throw an IllegalArgumentException if it is? Because the other constructor call has to be the first statement in my constructor.

Body:
If you have this method somewhere in your codebase:

public static <T, R> R getIfNotNull(T instance, Function<T, R> extractor) {
    if (instance == null) throw new IllegalArgumentException();
    return extractor.apply(instance);
}

You could use it to throw an IllegalArgumentException from within your constructor:

public class Rectangle {

    int width, height;

    public Rectangle(int width, int height) {
        this.width = width;
        this.height = height;
    }

    public Rectangle(Rectangle source) {
        this(getIfNotNull(source, s -> s.width), source.height);
    }
}

Disclaimer: all this would be needed just to throw an IllegalArgumentException, which is less idiomatic than a NullPointerException. In general, it's considered good practice to throw a NullPointerException if some non-nullable argument is null. And your original code was already doing this when attempting to dereference the argument.


问:
How to set scroll position with jQuery?
I found a solution to a similar problem I am having HERE. However I can't get it to work for myself. The problem I encountered was when trying to lock vertical scroll while the mobile menu was opened on a site I am working on. Locking the scroll caused the page to jump to the top each time the menu was opened.

jQuery:

```<code>timber.openDrawerMenu = function () {
    var tempScrollTop = $(window).scrollTop();
    var $mobileMenu = $('.nav-bar'),
    $mobileMenuButton = $('#menu-opener'),
    $body = $('body');
    $mobileMenuButton.addClass('opened');
    $mobileMenu.addClass('opened');
    $body.addClass('opened-drawer');

  // Make drawer a11y accessible
  timber.cache.$navBar.attr('aria-hidden', 'false');

  // Set focus on drawer
  timber.trapFocus({
     $container: timber.cache.$navBar,
     namespace: 'drawer_focus'
  });

  // Escape key closes menu
  timber.cache.$html.on('keyup.drawerMenu', function(evt) {
    if (evt.keyCode == 27) {
      timber.closeDrawerMenu();
    }
  });
  console.log(tempScrollTop);
  $(window).scrollTop(tempScrollTop);
}
</code>```

I added the console.log() statement in order to see if the script was caputuring the proper scrollTop value and in fact it is. For some reason it is not setting the scroll position though and I am not able to figure out why exactly. Any help here is greatly appreciated.

答:
I see that this is a mobile specific problem.

I have 1 thought on that:

Try explicitly setting position: relative on the body tag.

If that doesn't work, I have a more hacky thought:

Try explicitly resetting the scroll location just before closing the menu.

Hope those work, if not, leave a comment :)

Title: How to set scroll position with jQuery?

Body:
I found a solution to a similar problem I am having HERE. However I can't get it to work for myself. The problem I encountered was when trying to lock vertical scroll while the mobile menu was opened on a site I am working on. Locking the scroll caused the page to jump to the top each time the menu was opened.

jQuery:

timber.openDrawerMenu = function () {
    var tempScrollTop = $(window).scrollTop();
    var $mobileMenu = $('.nav-bar'),
    $mobileMenuButton = $('#menu-opener'),
    $body = $('body');
    $mobileMenuButton.addClass('opened');
    $mobileMenu.addClass('opened');
    $body.addClass('opened-drawer');

  // Make drawer a11y accessible
  timber.cache.$navBar.attr('aria-hidden', 'false');

  // Set focus on drawer
  timber.trapFocus({
     $container: timber.cache.$navBar,
     namespace: 'drawer_focus'
  });

  // Escape key closes menu
  timber.cache.$html.on('keyup.drawerMenu', function(evt) {
    if (evt.keyCode == 27) {
      timber.closeDrawerMenu();
    }
  });
  console.log(tempScrollTop);
  $(window).scrollTop(tempScrollTop);
}

I added the console.log() statement in order to see if the script was caputuring the proper scrollTop value and in fact it is. For some reason it is not setting the scroll position though and I am not able to figure out why exactly. Any help here is greatly appreciated.


问:
Silent Dropbox removal
I use the following script in Npackd to uninstall Dropbox. It works on XP and Vista, but fails on Windows 7/64. Instead of showing the taskbar (the one that is normally at the bottom of the screen) it shows a Windows Explorer window with the content of C:/. This is not Dropbox related as removing other packages with DLL based shell extensions also shows the same effect.

```<code>Uninstall.exe /S _?=%CD%
taskkill /f /fi "IMAGENAME eq explorer.exe"
del DropboxExt.13.dll
del DropboxExt64.13.dll
rem start explorer from the root directory so it does not lock this one
start "" /D\ explorer.exe
</code>```

What is wrong with the script? How can it be modified to work correctly on Windows 7 too?

Thanks

EDIT: I am really tired of this problem. The following batch file works either started as a normal user or "As Administrator":

```<code>taskkill /f /fi "IMAGENAME eq explorer.exe"
ping -n 5 127.0.0.1
pushd \
rem runas /trustlevel:0x20000
start "" /D\ explorer.exe
popd
</code>```

Here is the code that starts the .bat from my program (path="Uninstall.bat", only 2 new environment variables are defined):

```<code>QDir d = this->getDirectory();
QProcess p(0);
p.setProcessChannelMode(QProcess::MergedChannels);
QStringList params;
p.setWorkingDirectory(d.absolutePath());
QString exe = d.absolutePath() + "\\" + path;
for (int i = 0; i < env.count(); i += 2) {
    p.processEnvironment().insert(env.at(i), env.at(i + 1));
}
p.start(exe, params);
</code>```

The corresponding code in Qt/qprocess_win.cpp:

```<code>DWORD dwCreationFlags = CREATE_NO_WINDOW;
dwCreationFlags |= CREATE_UNICODE_ENVIRONMENT;
STARTUPINFOW startupInfo = { sizeof( STARTUPINFO ), 0, 0, 0,
                             (ulong)CW_USEDEFAULT, (ulong)CW_USEDEFAULT,
                             (ulong)CW_USEDEFAULT, (ulong)CW_USEDEFAULT,
                             0, 0, 0,
                             STARTF_USESTDHANDLES,
                             0, 0, 0,
                             stdinChannel.pipe[0], stdoutChannel.pipe[1], stderrChannel.pipe[1]
};
success = CreateProcess(0, (wchar_t*)args.utf16(),
                        0, 0, TRUE, dwCreationFlags,
                        environment.isEmpty() ? 0 : envlist.data(),
                        workingDirectory.isEmpty() ? 0 : (wchar_t*)QDir::toNativeSeparators(workingDirectory).utf16(),
                        &startupInfo, pid);
</code>```

Why does the Explorer think there is already a taskbar?

EDIT2: I know what is wrong now. After the Explorer is killed a new is automatically started by an svchost.exe process with the following parameters: /factory,{682159d9-c321-47ca-b3f1-30e36b2ec8b9}. The GUID is for DesktopExplorerFactory. This is probably a crash-protection for a COM service. My calls to explorer.exe do not start a new Explorer as there is already one. After a minute or two this process will be automatically closed if no windows are opened. So I think Ben Voigt is right and "There's really no good way to unload the shell completely without logging off all users."

答:
What is wrong with the script is quite simple: The shell is loaded into many many applications besides just Windows Explorer.  Every application that uses the common open/save file dialogs hosts the shell.

To address your immediate question of how to control the working directory of Windows Explorer without passing arguments that open a window, just set the working directory:

```<code>pushd C:\
start explorer.exe
popd
</code>```

But this still will not let you reliably delete the extension.  There's really no good way to unload the shell completely without logging off all users.

EDIT: Is your script running at the same integrity level as the original explorer.exe you killed?  Same elevation level?  The shell runs with medium (normal) integrity level and unelevated token, you need to match this.

Title: Silent Dropbox removal

Body:
I use the following script in Npackd to uninstall Dropbox. It works on XP and Vista, but fails on Windows 7/64. Instead of showing the taskbar (the one that is normally at the bottom of the screen) it shows a Windows Explorer window with the content of C:/. This is not Dropbox related as removing other packages with DLL based shell extensions also shows the same effect.

Uninstall.exe /S _?=%CD%
taskkill /f /fi "IMAGENAME eq explorer.exe"
del DropboxExt.13.dll
del DropboxExt64.13.dll
rem start explorer from the root directory so it does not lock this one
start "" /D\ explorer.exe

What is wrong with the script? How can it be modified to work correctly on Windows 7 too?

Thanks

EDIT: I am really tired of this problem. The following batch file works either started as a normal user or "As Administrator":

taskkill /f /fi "IMAGENAME eq explorer.exe"
ping -n 5 127.0.0.1
pushd \
rem runas /trustlevel:0x20000
start "" /D\ explorer.exe
popd

Here is the code that starts the .bat from my program (path="Uninstall.bat", only 2 new environment variables are defined):

QDir d = this->getDirectory();
QProcess p(0);
p.setProcessChannelMode(QProcess::MergedChannels);
QStringList params;
p.setWorkingDirectory(d.absolutePath());
QString exe = d.absolutePath() + "\\" + path;
for (int i = 0; i < env.count(); i += 2) {
    p.processEnvironment().insert(env.at(i), env.at(i + 1));
}
p.start(exe, params);

The corresponding code in Qt/qprocess_win.cpp:

DWORD dwCreationFlags = CREATE_NO_WINDOW;
dwCreationFlags |= CREATE_UNICODE_ENVIRONMENT;
STARTUPINFOW startupInfo = { sizeof( STARTUPINFO ), 0, 0, 0,
                             (ulong)CW_USEDEFAULT, (ulong)CW_USEDEFAULT,
                             (ulong)CW_USEDEFAULT, (ulong)CW_USEDEFAULT,
                             0, 0, 0,
                             STARTF_USESTDHANDLES,
                             0, 0, 0,
                             stdinChannel.pipe[0], stdoutChannel.pipe[1], stderrChannel.pipe[1]
};
success = CreateProcess(0, (wchar_t*)args.utf16(),
                        0, 0, TRUE, dwCreationFlags,
                        environment.isEmpty() ? 0 : envlist.data(),
                        workingDirectory.isEmpty() ? 0 : (wchar_t*)QDir::toNativeSeparators(workingDirectory).utf16(),
                        &startupInfo, pid);

Why does the Explorer think there is already a taskbar?

EDIT2: I know what is wrong now. After the Explorer is killed a new is automatically started by an svchost.exe process with the following parameters: /factory,{682159d9-c321-47ca-b3f1-30e36b2ec8b9}. The GUID is for DesktopExplorerFactory. This is probably a crash-protection for a COM service. My calls to explorer.exe do not start a new Explorer as there is already one. After a minute or two this process will be automatically closed if no windows are opened. So I think Ben Voigt is right and "There's really no good way to unload the shell completely without logging off all users."

Body:
What is wrong with the script is quite simple: The shell is loaded into many many applications besides just Windows Explorer.  Every application that uses the common open/save file dialogs hosts the shell.

To address your immediate question of how to control the working directory of Windows Explorer without passing arguments that open a window, just set the working directory:

pushd C:\
start explorer.exe
popd

But this still will not let you reliably delete the extension.  There's really no good way to unload the shell completely without logging off all users.

EDIT: Is your script running at the same integrity level as the original explorer.exe you killed?  Same elevation level?  The shell runs with medium (normal) integrity level and unelevated token, you need to match this.


问:
Using regex to get numbers from a string using Python, incorrectly prints full string

Objective

I'm looking to use the regular expression \d+ to extract just the digits from the string, answer_40194.

Problem

I'm targeting a form element with Selenium and I'm printing the formID to the Terminal, but after the line re.findall('\d+', formID) I expect formID to be just the numbers 40194, but instead I'm getting the entire string answer_40194.

script.py

```<code>import selenium
import re

form = browser.find_element_by_tag_name('form')
formID = form.get_attribute('id')
re.findall('\d+', formID)
print formIDNumber
</code>```

答:
You need to assign the result to a variable, e.g.

```<code>var1 = re.findall('\d+', formID)
print(var1)
</code>```

This will generate a list, if you only want one result, use

```<code>var1 = re.search('\d+', formID)
print(var1.group(0))
</code>```

The latter is called a regular expression object, hence the .group(0), see the documentation on python.org for more information.

Body:
Objective

I'm looking to use the regular expression \d+ to extract just the digits from the string, answer_40194.

Problem

I'm targeting a form element with Selenium and I'm printing the formID to the Terminal, but after the line re.findall('\d+', formID) I expect formID to be just the numbers 40194, but instead I'm getting the entire string answer_40194.

script.py

import selenium
import re

form = browser.find_element_by_tag_name('form')
formID = form.get_attribute('id')
re.findall('\d+', formID)
print formIDNumber

Body:
You need to assign the result to a variable, e.g.

var1 = re.findall('\d+', formID)
print(var1)

This will generate a list, if you only want one result, use

var1 = re.search('\d+', formID)
print(var1.group(0))

The latter is called a regular expression object, hence the .group(0), see the documentation on python.org for more information.


问:
find duplicate addresses in database, stop users entering them early?
How do I find duplicate addresses in a database, or better stop people already when filling in the form ? I guess the earlier the better?

Is there any good way of abstracting street, postal code etc so that typos and simple attempts to get 2 registrations can be detected? like:

```<code>Quellenstrasse 66/11
Quellenstr. 66a-11
</code>```

I'm talking German addresses...
Thanks!

答:
Machine learning and AI has algorithms to find string similarities and duplicate measures.

Record linkage or the task of matching equivalent records
that differ syntactically—was first explored in the late 1950s
and 1960s.

You can represent every pair of records using a vector of
features that describe the similarity between individual record fields.

For example, Adaptive Duplicate Detection Using Learnable String
Similarity Measures. for example, read this doc

You can use generic or manually tuned distance metrics for estimating the similarity of potential duplicates.

You can use adaptive name matching algorithms, like Jaro metric, which is based on the number and order of common characters between two strings.

Token-based and hybrid distance. In such cases, we can convert the
strings s and t to token multisets (where each token is a word) and consider similarity metrics on these multisets.

OwnerDisplayName: Johannes

Body:
How do I find duplicate addresses in a database, or better stop people already when filling in the form ? I guess the earlier the better?

Is there any good way of abstracting street, postal code etc so that typos and simple attempts to get 2 registrations can be detected? like:

Quellenstrasse 66/11
Quellenstr. 66a-11

I'm talking German addresses...
Thanks!

LastEditorDisplayName: Remou


问:
google datastore custom key using nodejs
I am using @google-cloud/datastore to save data in my entity.I have created the entity with custom key name = id.
How can I have a custom UUID as the key of the entity? </p>

```<code>ds.save({
    id: <uuid>,
    data: Log
}).then(function () {
    console.log(entities.map(fromDatastore));
});
</code>```

答:
```<code>const dsKey = ds.key({
    namespace : namespace,// optional
    path      : ([kindName, id])
  })
</code>```

The key can be generated like this. The namespace is optional, if not provided the default namespace will be used. In the path kindname should be provided(if there is a parent kind for the provided kind, the path array value should begin from the root parent name and id) and the id can be any id you assign. If the id is not provided, datastore will generate a random id and assign it to the entity you inserted.

If you meant that you wanted the UUId as the complete key, that is not possible.

Body:
I am using @google-cloud/datastore to save data in my entity.I have created the entity with custom key name = id.
How can I have a custom UUID as the key of the entity?

ds.save({
    id: <uuid>,
    data: Log
}).then(function () {
    console.log(entities.map(fromDatastore));
});

Body:
const dsKey = ds.key({
    namespace : namespace,// optional
    path      : ([kindName, id])
  })

The key can be generated like this. The namespace is optional, if not provided the default namespace will be used. In the path kindname should be provided(if there is a parent kind for the provided kind, the path array value should begin from the root parent name and id) and the id can be any id you assign. If the id is not provided, datastore will generate a random id and assign it to the entity you inserted.

If you meant that you wanted the UUId as the complete key, that is not possible.


问:
Flex 3.5 Validator Error Message Repeats
Anybody have any idea why the error message repeats in Flex SDK 3.5 (but not in 3.4) and have a good way to make it stop repeating? See screenshots:

You can also see the different apps here:

http://www.flexdevelopers.com/examples/validator/3.4/Tester.html

http://www.flexdevelopers.com/examples/validator/3.5/Tester.html

[View source is enabled on both apps]

To make this happen, leave the textInput field empty and hit save multiple times. Then mouseover the textInput.

I can think of a couple of solutions but they seem pretty hacky.

Thanks,

Jeremy Mitchell

答:
Here's a hack to fix this in 3.5.

View the source of this file: http://www.flexdevelopers.com/examples/validator/3.5/Tester.html

Change the saveMessage() method to read like this:

```<code>public function saveMessage(event:Event):void
        {
            setupValidators();

            var failedValidations:Array = new Array();
            failedValidations = Validator.validateAll(_formValidators);

            if (failedValidations.length == 0)
            {
                Alert.show("save it");
            }
            else
            {
                for each (var validationResultEvent:ValidationResultEvent in failedValidations)
                {
                    hackForSDK35Bug22911ToRemoveRepeatingErrorMessages(validationResultEvent);
                }
            }
        }
</code>```

then add this method:

```<code>private function hackForSDK35Bug22911ToRemoveRepeatingErrorMessages(failedValidation:ValidationResultEvent):void
        {
            var uiComponent:UIComponent = failedValidation.target.source as UIComponent;
            var errorString:String = uiComponent.errorString as String;
            uiComponent.errorString = errorString.split("\n")[0];
        }
</code>```

that should remove the repeating error messages and leave just one...

Body:
Here's a hack to fix this in 3.5.

View the source of this file: http://www.flexdevelopers.com/examples/validator/3.5/Tester.html

Change the saveMessage() method to read like this:

public function saveMessage(event:Event):void
        {
            setupValidators();

            var failedValidations:Array = new Array();
            failedValidations = Validator.validateAll(_formValidators);

            if (failedValidations.length == 0)
            {
                Alert.show("save it");
            }
            else
            {
                for each (var validationResultEvent:ValidationResultEvent in failedValidations)
                {
                    hackForSDK35Bug22911ToRemoveRepeatingErrorMessages(validationResultEvent);
                }
            }
        }

then add this method:

private function hackForSDK35Bug22911ToRemoveRepeatingErrorMessages(failedValidation:ValidationResultEvent):void
        {
            var uiComponent:UIComponent = failedValidation.target.source as UIComponent;
            var errorString:String = uiComponent.errorString as String;
            uiComponent.errorString = errorString.split("\n")[0];
        }

that should remove the repeating error messages and leave just one...


问:
Get PEBS data linear address from perf
I'm now trying to using perf to measure L3_Miss(LLC Miss) with PEBS.

Here is the command: perf record -d -e cpu/event=0xd1,umask=0x20/ppu -c 1 test, and when the perf finished, I using perf script -F ip,sym,addr to check the result.

According to the SDM from intel, Vol. 3B Table 18-55. PEBS record contains a field named Data Linear Address, stands for address of load or destination of store, is what I need.

My question is, the field addr I specified in perf-script is same as Data Linear Address in PEBS record?
If not, how to retrieve this field? (and another related field such like CPU register R8~R15)

ps. I'm using i7-6700 CPU (Skylake Microarchitecture)

Thanks, and any suggestion will be appreciated.

答:
Yes, you are right. The addr field in perf script does, in fact, give you the data linear address in a PEBS record. This data linear address is associated with the source of the load or the destination of the store, as you correctly specified. The switch -d that you used in your command perf record -d helps to record the linear addresses of the data accessed or written to in memory.

This mechanism to record Data Linear Addresses has started from the processor microarchitecture name Haswell replacing precise-store events. It has carried on to Skylake as well.

If you want to see this in code, here you go.

Title: Get PEBS data linear address from perf


问:
Mixing properties of multiple records in one .tfrecords file
I have a dataset of around 1M examples. I each example to a separate .tfrecord file, which resulted in around 500GB sitting in some network location.

Reading multiple small files from this network location is extremely slow, so I'm thinking about grouping around 100 examples into one .tfrecord file.

I am worried though, that examples from the same .tfrecords file will always appear in the same minibatch (or one minibatch after each other), which is bad for the proper mixing of training data I want to have.

my input pipeline is the following:
I have a tf.train.string_input_producer(files, capacity=100000) for the filenames queue, using TFRecordReader.read to read from the filenames queue, and use tf.train.batch that creates an examples queue and returns a batch from it using dequeue_many.

I fear that once the filenames queue dequeues a filename, all examples from it will be read and enqueued into the examples FIFO queue created by tf.train.batch, which will result in the same examples being in the same minibatches over and over.

Is it really going to have the same examples in the same minibatch over and over? If so, should I create a Shuffle queue for examples, instead of using tf.train.batch?

答:
One of the points of TFRecord is to store many files in the same location to overcome the problem of opening/closing many files. So your approach of one tfrecord per one example does not make sense. You can put even all examples in one file or have 10k per file. Regarding shuffling: there are two types shuffling which serve different purposes and shuffle different things:

tf.train.string_input_producer shuffle: Boolean. If true, the strings are randomly shuffled within each epoch.. So if you have a few files ['file1', 'file2', ..., 'filen'] this randomly selects a file from this list. If case of false, the files follow one after each other.

tf.train.shuffle_batch Creates batches by randomly shuffling tensors. So it takes batch_size tensors from your queue (you will need to create a queue with tf.train.start_queue_runners ) and shuffles them.


问:
Applying bindingRedirect config to pythonnet
I have an application that relies on NuGet's <bindingRedirect> feature to ensure a single version of log4net.dll. Binding redirects are automatically added to the applications app.config file.

I'd like to load that application's assemblies into Python and call into its code, but because the binding redirects are application-specific, they're not being picked up by Pythonnet and the assembly fails to load:

```<code>LOG: Post-policy reference: log4net, Version=1.2.15.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a
[...snip...]
LOG: Assembly Name is: log4net, Version=2.0.8.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a
WRN: Comparing the assembly name resulted in the mismatch: Major Version
</code>```

Can I get pythonnet to refer to my application's app.config and use the <bindingRedirect> found there? Or can I apply a binding redirect after startup, without needing an app.config?

答:
Here is how to enable app.config with pythonnet when using .NET assemblies from CPython:

Place python.exe.config file next python.exe with the following configuration for detection later:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
        <sectionGroup name="customAppSettingsGroup">

        </sectionGroup>
    </configSections>
    <customAppSettingsGroup>
        <customAppSettings>
          <add key="Debugger" value="True"/>
        </customAppSettings>
    </customAppSettingsGroup>
   <startup useLegacyV2RuntimeActivationPolicy="true">
      <supportedRuntime version="v4.0"/>
   </startup>
</configuration>

Generate .NET assembly with the following code for testing and reading app.config settings:

```<code>using System;

using System.Collections.Specialized;
using System.Configuration;

namespace dotnet20
{
    public class Class1
    {
        public Class1()
        {
            NameValueCollection settings =
                ConfigurationManager.GetSection("customAppSettingsGroup/customAppSettings") as NameValueCollection;

            if (settings != null)
            {
                foreach (string key in settings.AllKeys)
                {
                    if ((key == "Debugger") && (settings[key] == "True"))
                    {
                        Console.WriteLine("Detected debugger mode");
                    }
                }
            }
        }
    }
}
</code>```

Now test that pythonnet is able to detect these custom settings from app.config:

```<code>python
Python 3.5.3 (v3.5.3:1880cb95a742, Jan 16 2017, 16:02:32) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import clr
>>> import sys
>>> sys.path.append(r"C:\pythonnet\dotnet2.0\bin\Debug")
>>> clr.AddReference("dotnet2.0")
<System.Reflection.RuntimeAssembly object at 0x000001A51626D630>
>>> from dotnet20 import Class1
>>> Class1()
Detected debugger mode
<dotnet20.Class1 object at 0x000001A51626D6A0>
>>>
</code>```

Body:
I have an application that relies on NuGet's <bindingRedirect> feature to ensure a single version of log4net.dll. Binding redirects are automatically added to the applications app.config file.

I'd like to load that application's assemblies into Python and call into its code, but because the binding redirects are application-specific, they're not being picked up by Pythonnet and the assembly fails to load:

LOG: Post-policy reference: log4net, Version=1.2.15.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a
[...snip...]
LOG: Assembly Name is: log4net, Version=2.0.8.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a
WRN: Comparing the assembly name resulted in the mismatch: Major Version

Can I get pythonnet to refer to my application's app.config and use the <bindingRedirect> found there? Or can I apply a binding redirect after startup, without needing an app.config?

Body:
Here is how to enable app.config with pythonnet when using .NET assemblies from CPython:

Place python.exe.config file next python.exe with the following configuration for detection later:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
        <sectionGroup name="customAppSettingsGroup">
          <section name="customAppSettings" type="System.Configuration.AppSettingsSection, System.Configuration" />
        </sectionGroup>
    </configSections>
    <customAppSettingsGroup>
        <customAppSettings>
          <add key="Debugger" value="True"/>
        </customAppSettings>
    </customAppSettingsGroup>
   <startup useLegacyV2RuntimeActivationPolicy="true">
      <supportedRuntime version="v4.0"/>
   </startup>
</configuration>

Generate .NET assembly with the following code for testing and reading app.config settings:

using System;

using System.Collections.Specialized;
using System.Configuration;

namespace dotnet20
{
    public class Class1
    {
        public Class1()
        {
            NameValueCollection settings =
                ConfigurationManager.GetSection("customAppSettingsGroup/customAppSettings") as NameValueCollection;

            if (settings != null)
            {
                foreach (string key in settings.AllKeys)
                {
                    if ((key == "Debugger") && (settings[key] == "True"))
                    {
                        Console.WriteLine("Detected debugger mode");
                    }
                }
            }
        }
    }
}

Now test that pythonnet is able to detect these custom settings from app.config:

python
Python 3.5.3 (v3.5.3:1880cb95a742, Jan 16 2017, 16:02:32) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import clr
>>> import sys
>>> sys.path.append(r"C:\pythonnet\dotnet2.0\bin\Debug")
>>> clr.AddReference("dotnet2.0")
<System.Reflection.RuntimeAssembly object at 0x000001A51626D630>
>>> from dotnet20 import Class1
>>> Class1()
Detected debugger mode
<dotnet20.Class1 object at 0x000001A51626D6A0>
>>>


问:
What is the best way to ingest data from Terdata into Hadoop with Informatica?
What is the best ways to parallel ingest data from Teradata database into Hadoop with parallel data moving?

If we create a job which is simple opens one session to Teradata database it will take a lot of time to load huge table.

if we create a set of sessions to load data in parallel, and also make Select in each of the sessions, than it will make a set of Full table scans Teradata to produce a data

What is the recommended best practice to load data in parallelised streams and make unnecessary workload to Teradata?

答:
If Tera data supports table partitioning like oracle, you could try reading the table based on partitioning points which will enable parallelism in read...

Other option you have is, split the table into multiple partitions like adding a where clause on indexed column. This will ensure index scan and you can avoid full table scan.


问:
Cut the date if there is overlapping
I have a List<Object[]> with two dates value and I have the 'filterFromDayStart' and filterToDayEnd which presente for example the following date  20.06.17 00:00:00 and 20.06.17 23:59:59

Now I want to cut row[15] or row[16] if there is overlapping with filterFromDayStart and filterToDayEnd; if there is no overlapping because the date/dates outside the area do not cut the dates.

filterToDayEnd: 20.06.17 00:00:00  filterToDayEnd: 20.06.17 23:59:59

date_1_start  : 19.06.17 22:00:00  date_1_end: 20.06.17 02:00:00

cut to -->

date_1_start  : 20.06.17 00:00:00  date_1_end: 20.06.17 02:00:00

date_2_start  : 19.06.17 22:00:00  date_2_end: 19.06.17 22:00:00

do not cut to!

date_3_start  : 20.06.17 22:00:00  date_3_end: 21.06.17 02:00:00

cut to -->

date_1_start  : 20.06.17 22:00:00  date_1_end: 20.06.17 23:59:59

besides other cases...

I have tired the code below but some times the date is being cut even if there is no overlapping. How can I manage that?

```<code>row[15] = row[15].before(filterFromDayStart) ? filterFromDayStart : row[15];
row[16] = row[16].after(filterToDayEnd) ? filterToDayEnd : row[16];
</code>```

Edit
Here is my example:

```<code>import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;

public class DateBeforeAfter {

    public static void main(String[] args) {
        try {
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            Date filterFrom = dateFormat.parse("2017-02-20 00:00:00.0");
            Date filterTo = dateFormat.parse("2017-02-20 23:59:59.0");

            Date date1 = dateFormat.parse("2017-02-20 16:10:00.0");
            Date date2 = dateFormat.parse("2017-02-21 16:50:00.0");

            Date date3 = dateFormat.parse("2017-02-19 19:42:00.0");
            Date date4 = dateFormat.parse("2017-02-20 19:46:00.0");

            Date date5 = dateFormat.parse("2017-02-19 19:42:00.0");
            Date date6 = dateFormat.parse("2017-02-19 19:46:00.0");

            ArrayList<Object[]> list = new ArrayList<Object[]>();
            Object[] element1 = { date1, date2 };
            list.add(element1);
            Object[] element2 = { date3, date4 };
            list.add(element2);
            Object[] element3 = { date5, date6 };
            list.add(element3);
            for (Object[] row : list) {
                row[0] = ((Date) row[0]).before(filterFrom) ? filterFrom : row[0];
                row[1] = ((Date) row[1]).after(filterTo) ? filterTo : row[1];

            }

            for (Object[] row : list) {
                System.out.println(Arrays.toString(row));

            }

        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}
</code>```

result

```<code>[Mon Feb 20 16:10:00 CET 2017, Mon Feb 20 23:59:59 CET 2017]
[Mon Feb 20 00:00:00 CET 2017, Mon Feb 20 19:46:00 CET 2017]
[Mon Feb 20 00:00:00 CET 2017, Sun Feb 19 19:46:00 CET 2017]
</code>```

How can I make it in the right way so that the third one is not being cut?

The right result would be:

```<code>[Mon Feb 20 16:10:00 CET 2017, Mon Feb 20 23:59:59 CET 2017]
[Mon Feb 20 00:00:00 CET 2017, Mon Feb 20 19:46:00 CET 2017]
[Sun Feb 19 19:42:00 CET 2017, Sun Feb 19 19:46:00 CET 2017]
</code>```

This part of code works for me:

```<code>    for (Object[] row : list) {
        if ((((Date) row[0]).before(filterFrom) && ((Date) row[1]).before(filterFrom))) {
            System.out.println("The record is before filterFrom: " + Arrays.toString(row));

        } else if ((((Date) row[0]).after(filterTo) && ((Date) row[1]).after(filterTo))) {
            System.out.println("The record is after filterFrom: " + Arrays.toString(row));

        } else {
            row[0] = ((Date) row[0]).before(filterFrom) ? filterFrom : row[0];
            row[1] = ((Date) row[1]).after(filterTo) ? filterTo : row[1];

        }

    }
</code>```

答:
You are only comparing row[0] with filterFrom, but in your third case, you must also check if row[1] is before filterFrom. Just change your for loop to:

```<code>for (Object[] row : list) {
    Date row0 = (Date) row[0];
    Date row1 = (Date) row[1];
    if (!row1.before(filterFrom)) {
        row[0] = row0.before(filterFrom) ? filterFrom : row[0];
        row[1] = row1.after(filterTo) ? filterTo : row[1];
    }
}
</code>```

If row[1] is not before filterFrom, then you apply your rule. Otherwise, no change is needed.

This will produce the output you want.

Title: Cut the date if there is overlapping

Body:
I have a List<Object[]> with two dates value and I have the 'filterFromDayStart' and filterToDayEnd which presente for example the following date  20.06.17 00:00:00 and 20.06.17 23:59:59

Now I want to cut row[15] or row[16] if there is overlapping with filterFromDayStart and filterToDayEnd; if there is no overlapping because the date/dates outside the area do not cut the dates.

filterToDayEnd: 20.06.17 00:00:00  filterToDayEnd: 20.06.17 23:59:59

date_1_start  : 19.06.17 22:00:00  date_1_end: 20.06.17 02:00:00

cut to -->

date_1_start  : 20.06.17 00:00:00  date_1_end: 20.06.17 02:00:00

date_2_start  : 19.06.17 22:00:00  date_2_end: 19.06.17 22:00:00

do not cut to!

date_3_start  : 20.06.17 22:00:00  date_3_end: 21.06.17 02:00:00

cut to -->

date_1_start  : 20.06.17 22:00:00  date_1_end: 20.06.17 23:59:59

besides other cases...

I have tired the code below but some times the date is being cut even if there is no overlapping. How can I manage that?

row[15] = row[15].before(filterFromDayStart) ? filterFromDayStart : row[15];
row[16] = row[16].after(filterToDayEnd) ? filterToDayEnd : row[16];

Edit
Here is my example:

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;

public class DateBeforeAfter {

    public static void main(String[] args) {
        try {
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            Date filterFrom = dateFormat.parse("2017-02-20 00:00:00.0");
            Date filterTo = dateFormat.parse("2017-02-20 23:59:59.0");

            Date date1 = dateFormat.parse("2017-02-20 16:10:00.0");
            Date date2 = dateFormat.parse("2017-02-21 16:50:00.0");

            Date date3 = dateFormat.parse("2017-02-19 19:42:00.0");
            Date date4 = dateFormat.parse("2017-02-20 19:46:00.0");

            Date date5 = dateFormat.parse("2017-02-19 19:42:00.0");
            Date date6 = dateFormat.parse("2017-02-19 19:46:00.0");

            ArrayList<Object[]> list = new ArrayList<Object[]>();
            Object[] element1 = { date1, date2 };
            list.add(element1);
            Object[] element2 = { date3, date4 };
            list.add(element2);
            Object[] element3 = { date5, date6 };
            list.add(element3);
            for (Object[] row : list) {
                row[0] = ((Date) row[0]).before(filterFrom) ? filterFrom : row[0];
                row[1] = ((Date) row[1]).after(filterTo) ? filterTo : row[1];

            }

            for (Object[] row : list) {
                System.out.println(Arrays.toString(row));

            }

        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

result

[Mon Feb 20 16:10:00 CET 2017, Mon Feb 20 23:59:59 CET 2017]
[Mon Feb 20 00:00:00 CET 2017, Mon Feb 20 19:46:00 CET 2017]
[Mon Feb 20 00:00:00 CET 2017, Sun Feb 19 19:46:00 CET 2017]

How can I make it in the right way so that the third one is not being cut?

The right result would be:

[Mon Feb 20 16:10:00 CET 2017, Mon Feb 20 23:59:59 CET 2017]
[Mon Feb 20 00:00:00 CET 2017, Mon Feb 20 19:46:00 CET 2017]
[Sun Feb 19 19:42:00 CET 2017, Sun Feb 19 19:46:00 CET 2017]

This part of code works for me:

    for (Object[] row : list) {
        if ((((Date) row[0]).before(filterFrom) && ((Date) row[1]).before(filterFrom))) {
            System.out.println("The record is before filterFrom: " + Arrays.toString(row));

        } else if ((((Date) row[0]).after(filterTo) && ((Date) row[1]).after(filterTo))) {
            System.out.println("The record is after filterFrom: " + Arrays.toString(row));

        } else {
            row[0] = ((Date) row[0]).before(filterFrom) ? filterFrom : row[0];
            row[1] = ((Date) row[1]).after(filterTo) ? filterTo : row[1];

        }

    }

Body:
You are only comparing row[0] with filterFrom, but in your third case, you must also check if row[1] is before filterFrom. Just change your for loop to:

for (Object[] row : list) {
    Date row0 = (Date) row[0];
    Date row1 = (Date) row[1];
    if (!row1.before(filterFrom)) {
        row[0] = row0.before(filterFrom) ? filterFrom : row[0];
        row[1] = row1.after(filterTo) ? filterTo : row[1];
    }
}

If row[1] is not before filterFrom, then you apply your rule. Otherwise, no change is needed.

This will produce the output you want.


问:
Is there any way to change char* value at any index?
As I know, if we declare char* in our program then it gives memory from read-only area, so we are not able to change a char at any position in the array.

```<code>char *ch = "sitaram";
ch[2] = 'y';
</code>```

The above code will not run properly, as we are changing read-only memory.

One approach is we can declare our char array as

```<code>char ch[] = "sitaram";
</code>```

and then we can change a value at an index.

Is there any way where I can change a char value at any index in a char*?

答:
When you say:

```<code>char *ch = "sitaram";
</code>```

The compiler does the following:

it allocates the string "sitaram" at program start (static storage duration). This string can be put into read-only memory.

when your program arrives at this line, it allocates the pointer ch, and makes this pointer to point to the statically allocated "sitaram" string.

if you do ch[2] = 'y', then you're trying to modify the 3rd character of the statically allocated string. Usually, you get a crash (because it is in read-only memory)

On the other hand, if you do the following:

```<code>char ch[] = "sitaram";
</code>```

When the program hit this line, it allocates memory for the array ch[] (for 8 chars), then copies the string "sitaram" into this memory. If you do ch[2] = 'y', then you modify this allocated memory, which is perfectly fine to do.

If you want to modify a string with char *, it should point to a memory which is modifiable. For example:

```<code>char ch[] = "sitaram";
char *xx = ch;
xx[2] = 'y'; // it is the same as ch[2] = 'y';
</code>```

Body:
As I know, if we declare char* in our program then it gives memory from read-only area, so we are not able to change a char at any position in the array.

char *ch = "sitaram";
ch[2] = 'y';

The above code will not run properly, as we are changing read-only memory.

One approach is we can declare our char array as

char ch[] = "sitaram";

and then we can change a value at an index.

Is there any way where I can change a char value at any index in a char*?

Body:
When you say:

char *ch = "sitaram";

The compiler does the following:

it allocates the string "sitaram" at program start (static storage duration). This string can be put into read-only memory.

when your program arrives at this line, it allocates the pointer ch, and makes this pointer to point to the statically allocated "sitaram" string.

if you do ch[2] = 'y', then you're trying to modify the 3rd character of the statically allocated string. Usually, you get a crash (because it is in read-only memory)

On the other hand, if you do the following:

char ch[] = "sitaram";

When the program hit this line, it allocates memory for the array ch[] (for 8 chars), then copies the string "sitaram" into this memory. If you do ch[2] = 'y', then you modify this allocated memory, which is perfectly fine to do.

If you want to modify a string with char *, it should point to a memory which is modifiable. For example:

char ch[] = "sitaram";
char *xx = ch;
xx[2] = 'y'; // it is the same as ch[2] = 'y';


问:
QtcpServer: Qt how to get python string to label
hello everyone I use python send a string to qt but i do not know how show the string on a label can anyone help me ???
my mainwindow.cpp is

```<code>MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    QTimer *timer=new QTimer(this);
    connect(timer,SIGNAL(timeout()),this,SLOT(showTime()));
    timer->start();

    tcpServer.listen(QHostAddress::Any,42207);
    //QByteArray Msg= tcpSocket->readAll();
    readMessage();
}

 void MainWindow::showTime()
{
   QTime time=QTime::currentTime();
   QString time_text=time.toString("hh:mm:ss");
   ui->Digital_clock->setText(time_text);

   QDateTime dateTime = QDateTime::currentDateTime();
   QString datetimetext=dateTime.toString();
   ui->date->setText(datetimetext);

}

void MainWindow::readMessage()
{

    ui->receivedata_2->setText("no connection yet");

    if(!tcpServer.listen(QHostAddress::Any,42207))
    ui->receivedata_2->setText("waitting!");
     //QByteArray Msg= tcpSocket->readAll();

}
</code>```

every time i try to put socket->readall()  it will get crashed when i debug

答:
The connection between sockets is not necessarily sequential, can occur at any time so that QtcpServer handles appropriate signals, when creating a new connection we must use the signal newConnection.

In the slot that connects to the previous signal we must use nextPendingConnection that returns a pending connection through a socket.

This socket issues the readyRead signal when there is pending information, and in that task you get the data you want.

Also when disconnected this emits the signal disconnected, in that slot we must eliminate the socket.

mainwindow.h

```<code>#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QTcpServer>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private slots:
    void newConnection();
    void readyRead();
    void disconnected();
private:
    Ui::MainWindow *ui;

    QTcpServer* tcpServer;
};

#endif // MAINWINDOW_H
</code>```

mainwindow.h

```<code>#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QDebug>
#include <QTcpSocket>
#include <QLabel>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    tcpServer = new QTcpServer(this);

    connect(tcpServer, &QTcpServer::newConnection, this, &MainWindow::newConnection);

    if(!tcpServer->listen(QHostAddress::Any,42207)){
        qDebug() << "Server could not start";
    }
    else{
        qDebug() << "Server started!";
    }
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::newConnection()
{
    QTcpSocket *socket = tcpServer->nextPendingConnection();
    connect(socket, &QTcpSocket::readyRead, this, &MainWindow::readyRead);
    connect(socket, &QTcpSocket::disconnected, this, &MainWindow::disconnected);
}

void MainWindow::readyRead()
{
    QTcpSocket* socket = qobject_cast<QTcpSocket *>(sender());
    ui->receivedata_2->setText(socket->readAll());
}

void MainWindow::disconnected()
{
    sender()->deleteLater();
}
</code>```

Body:
hello everyone I use python send a string to qt but i do not know how show the string on a label can anyone help me ???
my mainwindow.cpp is

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    QTimer *timer=new QTimer(this);
    connect(timer,SIGNAL(timeout()),this,SLOT(showTime()));
    timer->start();

    tcpServer.listen(QHostAddress::Any,42207);
    //QByteArray Msg= tcpSocket->readAll();
    readMessage();
}

 void MainWindow::showTime()
{
   QTime time=QTime::currentTime();
   QString time_text=time.toString("hh:mm:ss");
   ui->Digital_clock->setText(time_text);

   QDateTime dateTime = QDateTime::currentDateTime();
   QString datetimetext=dateTime.toString();
   ui->date->setText(datetimetext);

}

void MainWindow::readMessage()
{

    ui->receivedata_2->setText("no connection yet");

    if(!tcpServer.listen(QHostAddress::Any,42207))
    ui->receivedata_2->setText("waitting!");
     //QByteArray Msg= tcpSocket->readAll();

}

every time i try to put socket->readall()  it will get crashed when i debug

Body:
The connection between sockets is not necessarily sequential, can occur at any time so that QtcpServer handles appropriate signals, when creating a new connection we must use the signal newConnection.

In the slot that connects to the previous signal we must use nextPendingConnection that returns a pending connection through a socket.

This socket issues the readyRead signal when there is pending information, and in that task you get the data you want.

Also when disconnected this emits the signal disconnected, in that slot we must eliminate the socket.

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QTcpServer>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private slots:
    void newConnection();
    void readyRead();
    void disconnected();
private:
    Ui::MainWindow *ui;

    QTcpServer* tcpServer;
};

#endif // MAINWINDOW_H

mainwindow.h

#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QDebug>
#include <QTcpSocket>
#include <QLabel>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    tcpServer = new QTcpServer(this);

    connect(tcpServer, &QTcpServer::newConnection, this, &MainWindow::newConnection);

    if(!tcpServer->listen(QHostAddress::Any,42207)){
        qDebug() << "Server could not start";
    }
    else{
        qDebug() << "Server started!";
    }
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::newConnection()
{
    QTcpSocket *socket = tcpServer->nextPendingConnection();
    connect(socket, &QTcpSocket::readyRead, this, &MainWindow::readyRead);
    connect(socket, &QTcpSocket::disconnected, this, &MainWindow::disconnected);
}

void MainWindow::readyRead()
{
    QTcpSocket* socket = qobject_cast<QTcpSocket *>(sender());
    ui->receivedata_2->setText(socket->readAll());
}

void MainWindow::disconnected()
{
    sender()->deleteLater();
}