问:
Sublime Text: common "folder_exclude_patterns" for all folder paths in a project
How can we set common "folder_exclude_patterns" for all folder paths in a project.

For example, in the following project configuration, the folder_exclude_patterns has to be repeated for each of the folder path.  Can we have it at a common single place in the configuration, instead of specifying under each of the path setting?

{
"folders":
[
    {
        "follow_symlinks": true,
        "path": "/path/to/folder/1",
        "folder_exclude_patterns": ["node_modules", "target", ".sass-cache"]

    },
    {
        "follow_symlinks": true,
        "path": "/path/to/folder/2",
        "folder_exclude_patterns": ["node_modules", "target", ".sass-cache"]
    },
    {
        "follow_symlinks": true,
        "path": "/path/to/folder/3",
        "folder_exclude_patterns": ["node_modules", "target", ".sass-cache"]
    }
]
}
```

答:
You are making adjustment in Project settings. Use User settings instead.

Probably this is what you trying to do:

Go to

Preferences > settings

Look at "folder_exclude_patterns" property below I added "node_modules" to hide those folders from sublime you can go ahead and also add "target" and ".sass-cache" folders to hide them.

```<code>{
    "binary_file_patterns":
    [
        "*.dds",
        "*.eot",
        "*.gif",
        "*.ico",
        "*.jar",
        "*.jpeg",
        "*.jpg",
        "*.pdf",
        "*.png",
        "*.swf",
        "*.tga",
        "*.ttf",
        "*.zip",
        "node_modules/**"
    ],
    "color_scheme": "Packages/Material Theme/schemes/Material-Theme.tmTheme",
    "file_exclude_patterns":
    [
        "*.pyc",
        "*.pyo",
        "*.exe",
        "*.dll",
        "*.obj",
        "*.o",
        "*.a",
        "*.lib",
        "*.so",
        "*.dylib",
        "*.ncb",
        "*.sdf",
        "*.suo",
        "*.pdb",
        "*.idb",
        ".DS_Store",
        "*.class",
        "*.psd",
        "*.db",
        "*.sublime-workspace"
    ],
    "folder_exclude_patterns":
    [
        "*.phpintel",
        ".svn",
        ".git",
        ".hg",
        "CVS",
        "node_modules",
    ],
    "font_size": 12,
    "ignored_packages":
    [
        "Vintage"
    ],
    "ignored_words":
    [
        "autoload",
        "config",
        "php"
    ],
    "show_encoding": true,
    "spell_check": false,
    "tab_size": 2,
    "translate_tabs_to_spaces": true,
    "word_wrap": false
}
</code>```

Body:
You are making adjustment in Project settings. Use User settings instead.

Probably this is what you trying to do:

Go to

Preferences > settings

Look at "folder_exclude_patterns" property below I added "node_modules" to hide those folders from sublime you can go ahead and also add "target" and ".sass-cache" folders to hide them.

{
    "binary_file_patterns":
    [
        "*.dds",
        "*.eot",
        "*.gif",
        "*.ico",
        "*.jar",
        "*.jpeg",
        "*.jpg",
        "*.pdf",
        "*.png",
        "*.swf",
        "*.tga",
        "*.ttf",
        "*.zip",
        "node_modules/**"
    ],
    "color_scheme": "Packages/Material Theme/schemes/Material-Theme.tmTheme",
    "file_exclude_patterns":
    [
        "*.pyc",
        "*.pyo",
        "*.exe",
        "*.dll",
        "*.obj",
        "*.o",
        "*.a",
        "*.lib",
        "*.so",
        "*.dylib",
        "*.ncb",
        "*.sdf",
        "*.suo",
        "*.pdb",
        "*.idb",
        ".DS_Store",
        "*.class",
        "*.psd",
        "*.db",
        "*.sublime-workspace"
    ],
    "folder_exclude_patterns":
    [
        "*.phpintel",
        ".svn",
        ".git",
        ".hg",
        "CVS",
        "node_modules",
    ],
    "font_size": 12,
    "ignored_packages":
    [
        "Vintage"
    ],
    "ignored_words":
    [
        "autoload",
        "config",
        "php"
    ],
    "show_encoding": true,
    "spell_check": false,
    "tab_size": 2,
    "translate_tabs_to_spaces": true,
    "word_wrap": false
}


来源: stackexchange

问:
swift function return multiple values
Below is a function that I am trying to create that will get the values in JSON data based on the key value entered. The problem I am having is I need Need to be able to use all the rates in another calculation. I am not sure how to get each rate saved to a global variable. At this point, the function is giving me an error - "Missing Return in a function expecting to return a string". Any ideas how to solve this problem </p>

```<code>   func getLenderData(selectedLenderKey: String) -> String
    {

        let url = ""
        var request = URLRequest(url: URL(string: url)!)
        request.httpMethod = "GET"

        let configuration = URLSessionConfiguration.default
        let session = URLSession(configuration: configuration, delegate: nil, delegateQueue: OperationQueue.main)

        let task = session.dataTask(with: request) { (data, response, error) in
            if error != nil {
                print("Error")
            }
            else{

                do{
                    //let fetchedData = try JSONSerialization.jsonObject(with: data!, options: .mutableLeaves) as! NSArray
                    //print(fecthdata)

                    let swiftyJSON = try JSON(data:data!)
                    let lenderName = swiftyJSON["lenders"][selectedLenderKey]["financial_institution"].stringValue
                    let oneYear = swiftyJSON["lenders"][selectedLenderKey]["one_year"].stringValue
                    let twoYear = swiftyJSON["lenders"][selectedLenderKey]["two_year"].stringValue
                    let threeYear = swiftyJSON["lenders"][selectedLenderKey]["three_year"].stringValue
                    let fourYear = swiftyJSON["lenders"][selectedLenderKey]["four_year"].stringValue
                    let fiveYear = swiftyJSON["lenders"][selectedLenderKey]["five_year"].stringValue

                    print(lenderName)
                    print(oneYear)
                    print(twoYear)
                    print(threeYear)
                    print(fourYear)
                    print(fiveYear)

                }

                catch{
                    print("Error 2")
                }
            }

        }
        task.resume()
    }// end function
</code>```

答:
You probably want to use Promise for this sort of implementation. Look into PromiseKit. Your code would become something like this

```<code>func getLenderData(selectedLenderKey: String) -> Promise<String> {
    return Promise { fulfill, reject in
        let url = ""
    var request = URLRequest(url: URL(string: url)!)
    request.httpMethod = "GET"

    let configuration = URLSessionConfiguration.default
    let session = URLSession(configuration: configuration, delegate: nil, delegateQueue: OperationQueue.main)

    let task = session.dataTask(with: request) { (data, response, error) in
        if error != nil {
            print("Error")
            reject({ERROR})
        }
        else{

            do{
                //let fetchedData = try JSONSerialization.jsonObject(with: data!, options: .mutableLeaves) as! NSArray
                //print(fecthdata)

                let swiftyJSON = try JSON(data:data!)
                let lenderName = swiftyJSON["lenders"][selectedLenderKey]["financial_institution"].stringValue
                let oneYear = swiftyJSON["lenders"][selectedLenderKey]["one_year"].stringValue
                let twoYear = swiftyJSON["lenders"][selectedLenderKey]["two_year"].stringValue
                let threeYear = swiftyJSON["lenders"][selectedLenderKey]["three_year"].stringValue
                let fourYear = swiftyJSON["lenders"][selectedLenderKey]["four_year"].stringValue
                let fiveYear = swiftyJSON["lenders"][selectedLenderKey]["five_year"].stringValue

                print(lenderName)
                print(oneYear)
                print(twoYear)
                print(threeYear)
                print(fourYear)
                print(fiveYear)

                fulfill({STRING})

            }

            catch{
                print("Error 2")
                reject({ERROR})
            }
        }

    }
    task.resume()
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: swift function return multiple values

Body:
Below is a function that I am trying to create that will get the values in JSON data based on the key value entered. The problem I am having is I need Need to be able to use all the rates in another calculation. I am not sure how to get each rate saved to a global variable. At this point, the function is giving me an error - "Missing Return in a function expecting to return a string". Any ideas how to solve this problem

   func getLenderData(selectedLenderKey: String) -> String
    {

        let url = ""
        var request = URLRequest(url: URL(string: url)!)
        request.httpMethod = "GET"

        let configuration = URLSessionConfiguration.default
        let session = URLSession(configuration: configuration, delegate: nil, delegateQueue: OperationQueue.main)

        let task = session.dataTask(with: request) { (data, response, error) in
            if error != nil {
                print("Error")
            }
            else{

                do{
                    //let fetchedData = try JSONSerialization.jsonObject(with: data!, options: .mutableLeaves) as! NSArray
                    //print(fecthdata)

                    let swiftyJSON = try JSON(data:data!)
                    let lenderName = swiftyJSON["lenders"][selectedLenderKey]["financial_institution"].stringValue
                    let oneYear = swiftyJSON["lenders"][selectedLenderKey]["one_year"].stringValue
                    let twoYear = swiftyJSON["lenders"][selectedLenderKey]["two_year"].stringValue
                    let threeYear = swiftyJSON["lenders"][selectedLenderKey]["three_year"].stringValue
                    let fourYear = swiftyJSON["lenders"][selectedLenderKey]["four_year"].stringValue
                    let fiveYear = swiftyJSON["lenders"][selectedLenderKey]["five_year"].stringValue

                    print(lenderName)
                    print(oneYear)
                    print(twoYear)
                    print(threeYear)
                    print(fourYear)
                    print(fiveYear)

                }

                catch{
                    print("Error 2")
                }
            }

        }
        task.resume()
    }// end function

Body:
You probably want to use Promise for this sort of implementation. Look into PromiseKit. Your code would become something like this

func getLenderData(selectedLenderKey: String) -> Promise<String> {
    return Promise { fulfill, reject in
        let url = ""
    var request = URLRequest(url: URL(string: url)!)
    request.httpMethod = "GET"

    let configuration = URLSessionConfiguration.default
    let session = URLSession(configuration: configuration, delegate: nil, delegateQueue: OperationQueue.main)

    let task = session.dataTask(with: request) { (data, response, error) in
        if error != nil {
            print("Error")
            reject({ERROR})
        }
        else{

            do{
                //let fetchedData = try JSONSerialization.jsonObject(with: data!, options: .mutableLeaves) as! NSArray
                //print(fecthdata)

                let swiftyJSON = try JSON(data:data!)
                let lenderName = swiftyJSON["lenders"][selectedLenderKey]["financial_institution"].stringValue
                let oneYear = swiftyJSON["lenders"][selectedLenderKey]["one_year"].stringValue
                let twoYear = swiftyJSON["lenders"][selectedLenderKey]["two_year"].stringValue
                let threeYear = swiftyJSON["lenders"][selectedLenderKey]["three_year"].stringValue
                let fourYear = swiftyJSON["lenders"][selectedLenderKey]["four_year"].stringValue
                let fiveYear = swiftyJSON["lenders"][selectedLenderKey]["five_year"].stringValue

                print(lenderName)
                print(oneYear)
                print(twoYear)
                print(threeYear)
                print(fourYear)
                print(fiveYear)

                fulfill({STRING})

            }

            catch{
                print("Error 2")
                reject({ERROR})
            }
        }

    }
    task.resume()
    }
}


问:
Calling same plsql Procedure more than once in a package parallely
Have one plsql package "OMX_BEACON_MIG" where am calling

```<code>PROCEDURE handle_NR_Site(
    i_old_plan_inst_id NUMBER,
    i_new_plan_inst_id NUMBER,
    i_old_act_id       NUMBER,
    i_new_act_id       NUMBER )
</code>```

To process action ids i.e., if i have 4 action id's then i am calling this procedure 4 times since " i_old_plan_inst_id" , "i_new_plan_inst_id","i_old_act_id","i_new_act_id" are different for every action.

Is there any solution where i can call this procedure only once  and all the 4 actions are processed ate once?

Or is there anyway to carry out calling this function parallely instead of calling one by one?
Please guide.

答:
Oracle has a very nice utility dbms_scheduler to run jobs in parallel . You can call the below function four times with different parameters to execute them in parallel.

```<code>dbms_scheduler.create_job(job_name => dbms_scheduler.generate_job_name('MY_JOB_'),
   job_type => 'PLSQL_BLOCK',
   job_action => 'begin  handle_NR_Site(i_old_plan_inst_id => param1, i_new_plan_inst_id => param2, i_old_act_id => param3, i_new_act_id => param4 ); end;',
   comments => 'Thread 1 descriptionn',
   enabled => true,
   auto_drop => true);
</code>```

The jobs will run in background. Query the table DBA_SCHEDULER_JOB_RUN_DETAILS to get the execution status.

For more detailed explanation check the link:
https://oracle-base.com/articles/10g/scheduler-10g

Body:
Have one plsql package "OMX_BEACON_MIG" where am calling

PROCEDURE handle_NR_Site(
    i_old_plan_inst_id NUMBER,
    i_new_plan_inst_id NUMBER,
    i_old_act_id       NUMBER,
    i_new_act_id       NUMBER )

To process action ids i.e., if i have 4 action id's then i am calling this procedure 4 times since " i_old_plan_inst_id" , "i_new_plan_inst_id","i_old_act_id","i_new_act_id" are different for every action.

Is there any solution where i can call this procedure only once  and all the 4 actions are processed ate once?

Or is there anyway to carry out calling this function parallely instead of calling one by one?
Please guide.

Body:
Oracle has a very nice utility dbms_scheduler to run jobs in parallel . You can call the below function four times with different parameters to execute them in parallel.

dbms_scheduler.create_job(job_name => dbms_scheduler.generate_job_name('MY_JOB_'),
   job_type => 'PLSQL_BLOCK',
   job_action => 'begin  handle_NR_Site(i_old_plan_inst_id => param1, i_new_plan_inst_id => param2, i_old_act_id => param3, i_new_act_id => param4 ); end;',
   comments => 'Thread 1 descriptionn',
   enabled => true,
   auto_drop => true);

The jobs will run in background. Query the table DBA_SCHEDULER_JOB_RUN_DETAILS to get the execution status.

For more detailed explanation check the link:
https://oracle-base.com/articles/10g/scheduler-10g


问:
How we do Testing on migrated data from RDBMS to HDFS using SQoop?

How a tester test if the data is moved from RDBMS to HDFS? Please explain only from testing perspective.

What is the difference between moving data from RDBMS to HDFS and Moving Data from RDBMS to HIVE? As i know HIVE is not a database then why moving data to HIVE?

答:
The topic is quite big. I will try to answer in simple terms.

How a tester test if the data is moved from RDBMS to HDFS? Please
  explain only from testing perspective.

This is what we did, in the past. Once the migration activity happened. We wrote bunch of test script where we polled the RDBMS with a good amount of random records. Prepared primary keys out of each records and then searched those PK on the hive tables and did head  to head match of both result-sets.

What is the difference between moving data from RDBMS to HDFS and Moving Data from RDBMS to HIVE? As i know HIVE is not a database then why moving data to HIVE

When you move data to HDFS, you store the entire dataset into FS (that is file system). Hive is nothing but a Sql Wrapper which use the same files and give you an Sql interface to read/write the same data.
Hive is not an actual database but it can be used as a database.

Consider you underlying file is a simple csv. Hive while creating a Hive table you provide the delimeter, file name, column information and couple of other parameters and Hive will represent the same file as if it is a table.

After this you can add/delete/update records from the hive table or directly editing the CSV.


问:
z3 quantifiers elimination in SMTLIB syntax
I have the following example of quantifiers elimination using z3py below. However I would like to rewrite it using SMTLIB syntax (code below python code). Somehow I did not get the same output like what I got from python which are formulas. I wonder if anyone could point me out the problem.

    from z3 import *
    a, five = Ints('a five')
    cmp = Bool('cmp')

    j = Goal()
    j.add(Exists([five, cmp],   And(five == a,
                                cmp == (five < 1000),
                                False == cmp)))

    t = Tactic('qe')
    print(t(j))    # output [[1000 <= a]]

    (declare-fun five () Int)
    (declare-fun a () Int)
    (declare-fun cmp () Bool)
    (assert (exists ((five Int) (cmp Bool)) (and (= five a)
                                        (= cmp (< five 1000))
                                        (= cmp false)  )))
    (apply (then qe smt))

output
(goals
(goal
  :precision precise :depth 1)
)

答:
I asked the question too quickly. After more searching (Quantifier Elimination - More questions), I found a solution below.

    (declare-fun five () Int)
    (declare-fun a () Int)
    (declare-fun cmp () Bool)
    (assert (exists ((five Int) (cmp Bool)) (and (= five a)
                                            (= cmp (< five 1000))
                                            (= cmp false)  )))
    (apply (using-params qe :qe-nonlinear true))


问:
Fetching MySQL records: Warning: Illegal offset type
I've been charged with updating a site to php7 as the hosting company is upgrading the server soon. I never wrote the original code and it's so dated i'm having an issue with the below code.

After updating mysql_num_fields, mysql_fetch_array, and mysql_field_name to the new mysqli functions I'm now getting the error

Warning: Illegal offset type.

I've looked at the other answers for this but none match the code. I'm totally lost.

```<code>$fieldCount = mysqli_num_fields($result);
$k = 0;
while ($record = mysqli_fetch_array($result)) {
    for ($i = 0; $i < $fieldCount; $i++) {
        $fieldName = mysqli_fetch_field_direct($result, $i);
        $arrRecords[$k][$fieldName] = $record[$fieldName];
    }
    $k++;
}
</code>```

答:
I hope the below code will help you to get you desired output.</p>

```<code>//$fieldCount = mysqli_num_fields($result);
$k = 0;
$arrRecords = array();
while ($record = mysqli_fetch_array($result)) {
    foreach ($record as $key=>$val) {
        $arrRecords[$k][$key] = $val;
    }
    $k++;
}
print_r($arrRecords);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I've been charged with updating a site to php7 as the hosting company is upgrading the server soon. I never wrote the original code and it's so dated i'm having an issue with the below code.

After updating mysql_num_fields, mysql_fetch_array, and mysql_field_name to the new mysqli functions I'm now getting the error

Warning: Illegal offset type.

I've looked at the other answers for this but none match the code. I'm totally lost.

$fieldCount = mysqli_num_fields($result);
$k = 0;
while ($record = mysqli_fetch_array($result)) {
    for ($i = 0; $i < $fieldCount; $i++) {
        $fieldName = mysqli_fetch_field_direct($result, $i);
        $arrRecords[$k][$fieldName] = $record[$fieldName];
    }
    $k++;
}

Body:
I hope the below code will help you to get you desired output.

//$fieldCount = mysqli_num_fields($result);
$k = 0;
$arrRecords = array();
while ($record = mysqli_fetch_array($result)) {
    foreach ($record as $key=>$val) {
        $arrRecords[$k][$key] = $val;
    }
    $k++;
}
print_r($arrRecords);


问:
how to convert a list into a list of tuples?
Here's what I have in the text file:

1712 Albert
1703 Benny
1799 Henry
1735 Jessica
1722 Lucas
1701 Luke
1757 William
1777 Jenny
1783 Lucia
1764 Venus
1718 Felicitas
```

<p>Here's what I have done to read the file but I have no idea how to put them into a list of tuples</p>

```def readRecords(filepath):
    file = open('Students1.txt', 'r')
    filecontent = file.readlines()
    file.close()
    return filecontent
```

Here's what the output is supposed to be:

答:
```<code>def readRecords(filepath):
   rst = []
   with open(filepath) as f:
        data = f.read().splitlines()
        rst = [(int(x.split(' ')[0]), x.split(' ')[1]) for x in data]
   return rst
</code>```

Body:
Here's what I have in the text file:

1712 Albert
1703 Benny
1799 Henry
1735 Jessica
1722 Lucas
1701 Luke
1757 William
1777 Jenny
1783 Lucia
1764 Venus
1718 Felicitas

Here's what I have done to read the file but I have no idea how to put them into a list of tuples

def readRecords(filepath):
    file = open('Students1.txt', 'r')
    filecontent = file.readlines()
    file.close()
    return filecontent

Here's what the output is supposed to be:


问:
Memory leak in debug mode only
I have this code:

```<code>using (var memoryStream = new MemoryStream())
{
    using (var streamWriter = new StreamWriter(memoryStream))
    {
        var list = new List<Actor>();
        for (var i = 0; i < 1000000; i++)
        {
            list.Add(new Actor("lorem ipsum"));
        }

        using (var serializedContent = new MemoryStream())
        {
            streamWriter.WriteLine(JsonConvert.SerializeObject(list));
            streamWriter.Flush();
            serializedContent.Seek(0, SeekOrigin.Begin);
            using (ZipFile zip = new ZipFile())
            {
                zip.AddEntry("message.txt", serializedContent);
                zip.Save("Archive.zip");
            }
        }
    }
}

while (true)
{
    GC.Collect();
    GC.WaitForPendingFinalizers();
    GC.WaitForFullGCComplete();
    GC.Collect();
    Console.WriteLine("completed");
    Console.ReadKey();
}
</code>```

The problem is that a memory leak only appears in debug version, while in release it fully cleans after itself. Any ideas why could this be happening?

Edit.
I noticed that the problem disappears if I remove that part where I try to add files to zip archive. What could be the difference between debug and release versions with this code? I can't see the problem, because archiving part is executed within the using statement.

答:
Try wrapping your code into a function.

Take a look at this blogpost:

The tricky point is that a variable is eligible to be dead once it’s
  not used anymore. However, it’s up to JIT to determine whether it
  really wants to report the variable to be dead. In fact, for
  debuggable code, JIT extends lifetime for every variable to end of the
  function.

This means your variable will not be collected, by GC.Collect, because your variable is in the same function and at debugtime still in scope.

Remember: The garbage collector only removes variable that are not used (not in scope). using is only calling Dispose on an object.

Title: Memory leak in debug mode only

Body:
I have this code:

using (var memoryStream = new MemoryStream())
{
    using (var streamWriter = new StreamWriter(memoryStream))
    {
        var list = new List<Actor>();
        for (var i = 0; i < 1000000; i++)
        {
            list.Add(new Actor("lorem ipsum"));
        }

        using (var serializedContent = new MemoryStream())
        {
            streamWriter.WriteLine(JsonConvert.SerializeObject(list));
            streamWriter.Flush();
            serializedContent.Seek(0, SeekOrigin.Begin);
            using (ZipFile zip = new ZipFile())
            {
                zip.AddEntry("message.txt", serializedContent);
                zip.Save("Archive.zip");
            }
        }
    }
}

while (true)
{
    GC.Collect();
    GC.WaitForPendingFinalizers();
    GC.WaitForFullGCComplete();
    GC.Collect();
    Console.WriteLine("completed");
    Console.ReadKey();
}

The problem is that a memory leak only appears in debug version, while in release it fully cleans after itself. Any ideas why could this be happening?

Edit.
I noticed that the problem disappears if I remove that part where I try to add files to zip archive. What could be the difference between debug and release versions with this code? I can't see the problem, because archiving part is executed within the using statement.


问:
Google Spread Sheet Api | Invalid Application name Parameter name: ApplicationName
I have followed the Google APi Tutorial for Dot net. But on executing the code with same steps, mentions in the tutorial at the following code, the Invalid application name exception showed.</p>

```<code>var service = new SheetsService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = ApplicationName,
                });
</code>```

答:
It appears the quickstart has a bug. ApplicationName doesn't appear to accept spaces. Changing the line 21 to:

```<code>    static string ApplicationName = "Google-Sheets-API-Quickstart";
</code>```

worked for me.

Body:
I have followed the Google APi Tutorial for Dot net. But on executing the code with same steps, mentions in the tutorial at the following code, the Invalid application name exception showed.

var service = new SheetsService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = ApplicationName,
                });

Body:
It appears the quickstart has a bug. ApplicationName doesn't appear to accept spaces. Changing the line 21 to:

    static string ApplicationName = "Google-Sheets-API-Quickstart";

worked for me.


问:
Install two apks of different versions of application
I have two versions of the same Android application that I would like to have simultaneously on my Android device for easier testing. Is there a way to install both apk files such that they coexist on the same device?</p>

答:
You can create a new user in your device and install another instance of the app in that user.

Or

You can download Parallel Space from play store and run multiple instance or installation of an application.


问:
How can I start / stop a request stream with node.js?
I have

```<code>return request({
  method: "POST",
  url: response.stream.url,
  json: true,
  forever: true,
  body: {
    sessionid: response.stream.sessionid,
    symbols: symbolParams
  }
}).on("data", onData)
</code>```

That gives me data whenever it comes through. But what if I want to STOP listening on that stream, how can I do that?

答:
You can also abort it:</p>

```<code>var req = request('http://google.com')...
...
req.abort();
</code>```

Body:
I have

return request({
  method: "POST",
  url: response.stream.url,
  json: true,
  forever: true,
  body: {
    sessionid: response.stream.sessionid,
    symbols: symbolParams
  }
}).on("data", onData)

That gives me data whenever it comes through. But what if I want to STOP listening on that stream, how can I do that?

Body:
You can also abort it:

var req = request('http://google.com')...
...
req.abort();


问:
compare string with array to find a match
can I compare individual string with complete array. In the below case i am not able to satisfy the condition may be due to improper regex due to case sensitive, I want to match any word.

eg. MOVE 1-2 STEPS should match 1-2 Steps,MOVE 8-10 STEPS should match 8-10 Steps so on .

```<code>my @db_description=("MOVE 1-2 STEPS TO GB FIXTURE","WITHIN REACH TO CHECK","GET BEAM","PUSH/PULL ( >= 30 CM)","BEAM 2-3 TIMES","MOVE 8-10 STEPS TO HOIST");
my @steps_name = ("1-2 Steps", "5-7 Steps", "8-10 Steps", "11-15 Steps");

    for(my $i=0;$i<@db_description;$i++)
    {
                if (grep { /(?i)\Q$db_description[$i]\E/ } @steps_name)
                    {
                         print "<br><h1>Element '$db_description' found !</h1></br>" ;
                    }

                    else
                    {
                         print "<br>$db_description not found </br>"
                    }
    }
</code>```

答:
His question is valid.. Try following code</p>

```<code>my @db_description=("MOVE 1-2 STEPS TO GB FIXTURE","WITHIN REACH TO CHECK","GET BEAM","PUSH/PULL ( >= 30 CM)","BEAM 2-3 TIMES","MOVE 8-10 STEPS TO HOIST");
my @steps_name = ("1-2 Steps", "5-7 Steps", "8-10 Steps", "11-15 Steps");
my $testString1;
my $testString2;

my @abc;
my @xyz;

for(my $i=0;$i<$#db_description;$i++)
    {
    @abc = split (/ /,$db_description[$i]);
    for(my $j=0;$j<$#steps_name;$j++)
     {
         @xyz = split (/ /, $steps_name[$j]);
         for (my $i1=0; $i1<$#abc; $i1++)
            {
            for (my $j1=0; $j1<$#xyz; $j1++)
            {
                if ($abc[$i1] eq $xyz[$j1])
                {
                 print "$db_description[$i]  :: found $abc[$i1] == $xyz[$j1]\n";
                 }
             }

         }
     }
    }
</code>```

Body:
can I compare individual string with complete array. In the below case i am not able to satisfy the condition may be due to improper regex due to case sensitive, I want to match any word.

eg. MOVE 1-2 STEPS should match 1-2 Steps,MOVE 8-10 STEPS should match 8-10 Steps so on .

my @db_description=("MOVE 1-2 STEPS TO GB FIXTURE","WITHIN REACH TO CHECK","GET BEAM","PUSH/PULL ( >= 30 CM)","BEAM 2-3 TIMES","MOVE 8-10 STEPS TO HOIST");
my @steps_name = ("1-2 Steps", "5-7 Steps", "8-10 Steps", "11-15 Steps");

    for(my $i=0;$i<@db_description;$i++)
    {
                if (grep { /(?i)\Q$db_description[$i]\E/ } @steps_name)
                    {
                         print "

Element '$db_description' found !

" ;
                    }

                    else
                    {
                         print "
$db_description not found
"
                    }
    }

Body:
His question is valid.. Try following code

my @db_description=("MOVE 1-2 STEPS TO GB FIXTURE","WITHIN REACH TO CHECK","GET BEAM","PUSH/PULL ( >= 30 CM)","BEAM 2-3 TIMES","MOVE 8-10 STEPS TO HOIST");
my @steps_name = ("1-2 Steps", "5-7 Steps", "8-10 Steps", "11-15 Steps");
my $testString1;
my $testString2;

my @abc;
my @xyz;

for(my $i=0;$i<$#db_description;$i++)
    {
    @abc = split (/ /,$db_description[$i]);
    for(my $j=0;$j<$#steps_name;$j++)
     {
         @xyz = split (/ /, $steps_name[$j]);
         for (my $i1=0; $i1<$#abc; $i1++)
            {
            for (my $j1=0; $j1<$#xyz; $j1++)
            {
                if ($abc[$i1] eq $xyz[$j1])
                {
                 print "$db_description[$i]  :: found $abc[$i1] == $xyz[$j1]\n";
                 }
             }

         }
     }
    }


问:
integrating 2 lists and a data farme in RR
Please could you advise on the R code I could use in order to do the    following operation :

I have 2 lists of "genome coordinates" : a list is composed by numbers that represent genome coordinates;

let's say list N:

```<code>n1
n2
n3
n4
</code>```

and a list M:

```<code>m1
m2
m3
m4
m5
</code>```

and a dataframe C, where for some pairs of coordinates (n,m)    from the lists above, we have a numerical intensity;

for example:

```<code>n1; m1; 100
n1; m2; 300
</code>```

The question would be : what is the most efficient R code I could use in order to integrate the list N, the list M, and the   dataframe C, in order to obtain a dataframe with:

list N as the columns names

list M as the rows names

the values in the cells of N * M, corresponding to the numerical values in the data frame C.

A little example would be :

```<code>     n1  n2  n3 n4
m1  100  -   -   -
m2  300  -   -   -
m3   -   -   -   -
m4   -   -   -   -
m5   -   -   -   -
</code>```

答:
I'm sure someone has a cleaner way to implement the following, and I would be happy to know. Your data is not really MWE ready: see How to make a great R Reproducible Example. However, given the data "as-is" and assuming you don't really want the first row titled 'n1'. The following solution requires reshape2 package:

```<code>N=c('n1','n2','n3','n4')
M=c('m1','m2','m3','m4','m5')
C=data.frame(
  X1=c('n1','n1'),
  X2=c('m1','m2'),
  C=c(100, 300)
)
</code>```

We've defined the data as above. Now let's merge it together.

```<code>X = merge(N, M)
</code>```

Let's add NAs to the data.frame so that it will be blanked when we define the items.

```<code>C$C <- NA

C$C <- C[which(C$X1 %in% N & C$X2 %in% M),'C']

D = merge(N, M, all=TRUE)
names(D) <- c('X1','X2')
names(X) <- c('X1','X2')

E = merge(D, C, all = TRUE, by=c('X1', 'X2'))

library(reshape2)
reshape2::dcast(E, X2 + C ~ X1, drop=FALSE, value.var='C')
</code>```

Hopefully this will help you out until someone else can explain it a little better.

EDIT: Since @Lamia beat me to it, I compared the system.time values for the examples. . . and @Lamia's answer is 0.01 +/- 0.032 over ten reps on my machine.

Body:
Please could you advise on the R code I could use in order to do the    following operation :

I have 2 lists of "genome coordinates" : a list is composed by numbers that represent genome coordinates;

let's say list N:

n1
n2
n3
n4

and a list M:

m1
m2
m3
m4
m5

and a dataframe C, where for some pairs of coordinates (n,m)    from the lists above, we have a numerical intensity;

for example:

n1; m1; 100
n1; m2; 300

The question would be : what is the most efficient R code I could use in order to integrate the list N, the list M, and the   dataframe C, in order to obtain a dataframe with:

list N as the columns names

list M as the rows names

the values in the cells of N * M, corresponding to the numerical values in the data frame C.

A little example would be :

     n1  n2  n3 n4
m1  100  -   -   -
m2  300  -   -   -
m3   -   -   -   -
m4   -   -   -   -
m5   -   -   -   -

Body:
I'm sure someone has a cleaner way to implement the following, and I would be happy to know. Your data is not really MWE ready: see How to make a great R Reproducible Example. However, given the data "as-is" and assuming you don't really want the first row titled 'n1'. The following solution requires reshape2 package:

N=c('n1','n2','n3','n4')
M=c('m1','m2','m3','m4','m5')
C=data.frame(
  X1=c('n1','n1'),
  X2=c('m1','m2'),
  C=c(100, 300)
)

We've defined the data as above. Now let's merge it together.

X = merge(N, M)

Let's add NAs to the data.frame so that it will be blanked when we define the items.

C$C <- NA

C$C <- C[which(C$X1 %in% N & C$X2 %in% M),'C']

D = merge(N, M, all=TRUE)
names(D) <- c('X1','X2')
names(X) <- c('X1','X2')

E = merge(D, C, all = TRUE, by=c('X1', 'X2'))

library(reshape2)
reshape2::dcast(E, X2 + C ~ X1, drop=FALSE, value.var='C')

Hopefully this will help you out until someone else can explain it a little better.

EDIT: Since @Lamia beat me to it, I compared the system.time values for the examples. . . and @Lamia's answer is 0.01 +/- 0.032 over ten reps on my machine.


问:
How to run scripts in django context from pycharm
How to run an arbitrary script in the django context while using pycharm?

Running an arbirtary script in the django context makes it easy to develop background tasks or do ad-hoc queries. The standard answer is to add the script to custom commands, however, I'm not used to that workflow and it seems an unnecessary step if you don't intend it to be exposed like this.

This is a question-and-answer post since I can't find this technique anywhere in StackOverflow and I thought it would help. I wanted an answer in my third hour of learning Django.

答:
I've just started with django. There may be better ways but I'm developing some tasks which will eventually be sent to celery and while developing them I find it convenient to quickly run them in the django context. I use pycharm

To do this:

set up a standard python run environment and make the script the script you want to execute.
add an environment variable DJANGO_SETTINGS_MODULE and set it to the python import path for your settings.py. Eg if you settings.py is in a directory called myapp:
 DJANGO_SETTINGS_MODULE = myapp.settings

make the working directory your project root
leave the  "Add content roots" & "Add source roots" checkboxes ticked.

In the script, add these two lines at the top:

```<code>from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
</code>```

and now you can use

```<code>if __name__ == "__main__":
</code>```

and you're off and running.

or run tests or whatever.

It's easy then to run a script which needs Django context:

```<code> PYTHONPATH=${PYTHONPATH}:. DJANGO_SETTINGS_MODULE=project.settings python dir1/dir2/myscript.py
</code>```

Run that from the normal django root directory.

Credit to: Stavros Korokithakis https://www.stavros.io/ from this post: https://www.stavros.io/posts/standalone-django-scripts-definitive-guide/

Body:
I've just started with django. There may be better ways but I'm developing some tasks which will eventually be sent to celery and while developing them I find it convenient to quickly run them in the django context. I use pycharm

To do this:

set up a standard python run environment and make the script the script you want to execute.
add an environment variable DJANGO_SETTINGS_MODULE and set it to the python import path for your settings.py. Eg if you settings.py is in a directory called myapp:
 DJANGO_SETTINGS_MODULE = myapp.settings

make the working directory your project root
leave the  "Add content roots" & "Add source roots" checkboxes ticked.

In the script, add these two lines at the top:

from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()

and now you can use

if __name__ == "__main__":

and you're off and running.

or run tests or whatever.

It's easy then to run a script which needs Django context:

 PYTHONPATH=${PYTHONPATH}:. DJANGO_SETTINGS_MODULE=project.settings python dir1/dir2/myscript.py

Run that from the normal django root directory.

Credit to: Stavros Korokithakis https://www.stavros.io/ from this post: https://www.stavros.io/posts/standalone-django-scripts-definitive-guide/


问:
How to make a shortcut to do batch processing in Visual Studio 2010?
I want to

publish my Asp.Net MVC project to my local IIS and

launch my default browser pointing to the site/application.

I know Visual Studio can do the same thing but using a different scenario, i.e.,

launching built-in web server and web browser, or

launching web browser pointing to the project associated with local iis virtual directory.

How can I create a shortcut to do batch processing as mentioned above?

答:
To script publishing the site you'll need to call MSbuild and ask that to publish the site. See http://codingcockerel.co.uk/2008/05/18/how-to-publish-a-web-site-with-msbuild/ for details on this.

You can lauch the site from a script with a line like:

```<code>start iexplore "http://localhost:12345/"
</code>```

ContentLicense: CC BY-SA 2.5

Body:
To script publishing the site you'll need to call MSbuild and ask that to publish the site. See http://codingcockerel.co.uk/2008/05/18/how-to-publish-a-web-site-with-msbuild/ for details on this.

You can lauch the site from a script with a line like:

start iexplore "http://localhost:12345/"


问:
Managing access from a Console App to a Web API on Azure
I have an Angular application deployed on Azure secured with Azure Active Directory. To achieve that, I have followed this guide : https://learn.microsoft.com/en-us/azure/active-directory/develop/active-directory-devquickstarts-angular.

So, in order to query the website's Web API, the user needs to be authenticated on Azure Active Directory. So far, everything works great.

Now, we have a internal service, not deployed on Azure, that needs to query a method of that Web API, which is already secured as previously mentioned.

Is there a way, without using the Api Management service, to give access to the internal service in order to call the secured Web API without having the need to use a AAD username / password?

I tried using ADAL librairy, but all the example that I have seen prompt an AAD username password login.

答:
To call the web API which protected by Azure AD without interaction to provide username and password, we can use the Client Credentials flow( refer this document).

And there is the code to use the azure-activedirectory-library-for-dotnet for your reference:

```<code>string authority = "https://login.microsoftonline.com/{tenantId}";
string clientId = "";
string secret = "";
string resource = "";

var credential = new ClientCredential(clientId, secret);
AuthenticationContext authContext = new AuthenticationContext(authority);
var token = authContext.AcquireTokenAsync(resource, credential).Result.AccessToken;

Console.WriteLine(token);
</code>```

Body:
To call the web API which protected by Azure AD without interaction to provide username and password, we can use the Client Credentials flow( refer this document).

And there is the code to use the azure-activedirectory-library-for-dotnet for your reference:

string authority = "https://login.microsoftonline.com/{tenantId}";
string clientId = "";
string secret = "";
string resource = "";

var credential = new ClientCredential(clientId, secret);
AuthenticationContext authContext = new AuthenticationContext(authority);
var token = authContext.AcquireTokenAsync(resource, credential).Result.AccessToken;

Console.WriteLine(token);


问:
How to set the MaxDequeueCount at the Queue Level
I have an Azure WebJob listening to multiple queues...

I can specify the MaxDequeueCount at the job level...

```<code>    config.UseTimers();
    config.Queues.BatchSize = 32;
    config.Queues.MaxDequeueCount = 6;
</code>```

What the best way to set MaxDequeueCounts at the queue level? I know I can get the actual dequeue count and send it to the poison queue "manually" but I was wondering if this can be done in a better way...

答:
If you want to set different configuration for different queue trigger functions, you could implement your own QueueProcessorFactory and reset some configurations of context based on the queue name.

```<code>public class MyQueueProcessorFactory : IQueueProcessorFactory
{
    public  QueueProcessor Create(QueueProcessorFactoryContext context)
    {
        if (context == null)
        {
            throw new ArgumentNullException("context");
        }
        if (context.Queue.Name == "queue1")
        {
            context.MaxDequeueCount = 2;
        }
        else if (context.Queue.Name == "queue2")
        {
            context.MaxDequeueCount = 4;
        }
        return new QueueProcessor(context);
    }
}
</code>```

To use the custom QueueProcessorFactory, we need to set the QueueProcessorFactory property as following.

```<code>JobHostConfiguration config = new JobHostConfiguration();
config.Queues.QueueProcessorFactory = new MyQueueProcessorFactory();
JobHost host = new JobHost(config);
</code>```

Body:
I have an Azure WebJob listening to multiple queues...

I can specify the MaxDequeueCount at the job level...

    config.UseTimers();
    config.Queues.BatchSize = 32;
    config.Queues.MaxDequeueCount = 6;

What the best way to set MaxDequeueCounts at the queue level? I know I can get the actual dequeue count and send it to the poison queue "manually" but I was wondering if this can be done in a better way...

Body:
If you want to set different configuration for different queue trigger functions, you could implement your own QueueProcessorFactory and reset some configurations of context based on the queue name.

public class MyQueueProcessorFactory : IQueueProcessorFactory
{
    public  QueueProcessor Create(QueueProcessorFactoryContext context)
    {
        if (context == null)
        {
            throw new ArgumentNullException("context");
        }
        if (context.Queue.Name == "queue1")
        {
            context.MaxDequeueCount = 2;
        }
        else if (context.Queue.Name == "queue2")
        {
            context.MaxDequeueCount = 4;
        }
        return new QueueProcessor(context);
    }
}

To use the custom QueueProcessorFactory, we need to set the QueueProcessorFactory property as following.

JobHostConfiguration config = new JobHostConfiguration();
config.Queues.QueueProcessorFactory = new MyQueueProcessorFactory();
JobHost host = new JobHost(config);


问:
Highlight cell in colA if cells B-J on row are empty
I have a simple spreadsheet in a Google Drive spreadsheet that contains in colA a list of names. ColB thru ColJ are fill in the blank cells.

I want to change the background color of the cell in ColA when there is no data entered in ColB thru ColJ but I do not see a way to do this.

答:
Clear formatting from ColumnA, select ColumnA and Format, Conditional formatting..., Format cells if... Custom formula is and:

```<code>=and(A1<>"",counta(B1:J1)=0)
</code>```

Then select fill of choice and Done.

Body:
Clear formatting from ColumnA, select ColumnA and Format, Conditional formatting..., Format cells if... Custom formula is and:

=and(A1<>"",counta(B1:J1)=0)

Then select fill of choice and Done.


问:
OpencCV: calcOpticalFlowSF function
I try to use the calcOpticalFlowSF() function, but when I launch it, the programm doesn't repond, here the part of the code that use it:

```<code>frame1 = cv::imread("frame10.png");
frame2 = cv::imread("frame11.png");

if (frame1.empty()) {
   cout<<"could not read image oldori"<<endl;

  return;
}

if (frame2.empty()) {
   cout<<"could not read image ori"<<endl;
  return;
}

if (frame1.rows != frame2.rows && frame1.cols != frame2.cols) {
     cout<<"images should be of equal sizes "endl;
  return;
}

if (frame1.type() != 16 || frame2.type() != 16) {
     cout<<"images should be of equal type CV_8UC3")endl;
  return;
}

cv::Mat flow;

cv::calcOpticalFlowSF(frame1, frame2, flow, 2, 2, 4);
// calcOpticalFlowSF(frame1, frame1,  // doesn't work too.
//                    flow,
//                    3, 2, 4, 4.1, 25.5, 18, 55.0, 25.5, 0.35, 18, 55.0, 25.5, 10);
</code>```

I know that the error come from the function calcOpticalFlowSF, because if I comment it, the programm works. I use the same pictures as they use in the SimpleFlow demo. If you look here:How to get cv::calcOpticalFlowSF to work? it seems that he got no problem with the function itself...

Do you have an idea why it doesn't work?

thanks,

best regards.

答:
make sure the image is 3-channel, is better to see the docs here</p>

```<code>#if 1
#define _CRT_SECURE_NO_WARNINGS

#include <cstdio>
#include <cstdlib>
#include <vector>
#include <stdlib.h>
#include <opencv2/opencv.hpp>
#include "opencv2/optflow.hpp"
#include "opencv2/highgui.hpp"

using namespace std;
using namespace cv;
using namespace cv::optflow;//calcOpticalFlowSF 's namespace
const size_t choice = 2 ;
// choice
// 1    2    3
// calcOpticalFlowFarneback   calcOpticalFlowSF   calcOpticalFlowPyrLK
void drawOptFlowMap(const Mat& flow, Mat& cflowmap, int step, const Scalar& color) {
    // cflowmap is the pre frame with the line of Optical Flow
    // flow is a xxx array, store float point
    //      store the delta of x,y
    // step is every step pixel
    for (int y = 0; y < cflowmap.rows; y += step)
        for (int x = 0; x < cflowmap.cols; x += step)
        {
            const Point2f& fxy = flow.at< Point2f>(y, x);
            line(cflowmap, Point(x, y), Point(cvRound(x + fxy.x), cvRound(y + fxy.y)),
                color);
            circle(cflowmap, Point(cvRound(x + fxy.x), cvRound(y + fxy.y)), 1, color, -1);
        }
}

void drawOptFlowMap(Mat& cflowmap, int step, const Scalar& color, vector<Point2f> &retPts) {
    // same as above, retPts is the next frame point
    auto it = retPts.begin();
    for (int y = 0; y < cflowmap.rows; y += step)
        for (int x = 0; x < cflowmap.cols; x += step)
        {
            line(cflowmap, Point(x, y), *it, color);
            circle(cflowmap, *it, 1, color, -1);
            it++;
        }
}

int main(int argc, char *argv[])
{
    Mat flow;//flow = aft - pre
    Mat pre = imread("1hf.png", IMREAD_COLOR);
    Mat aft = imread("2hf.png", IMREAD_COLOR);//           CV_LOAD_IMAGE_GRAYSCALE   gray ; IMREAD_COLOR   color
    if (pre.empty() || aft.empty()){
        printf("Unable to load the image");
        return 1;
    }

    Mat cflow = pre; Mat cflow2 = aft;// store the  3-channel mat of frame, cflow is for show color with line
    cvtColor(pre, pre, CV_BGR2GRAY);
    cvtColor(aft, aft, CV_BGR2GRAY);

    //below parameter of calcOpticalFlowPyrLK
    vector<Point2f> prePts;
    size_t step = 10;
    vector<Point2f> nextPts(pre.rows * pre.cols);
    vector<uchar> status;
    vector<float> err;
    TermCriteria termcrit(CV_TERMCRIT_ITER | CV_TERMCRIT_EPS, 20, 0.03);

    switch (choice)
    {
    case 1:// calcOpticalFlowFarneback
        calcOpticalFlowFarneback(pre, aft, flow, 0.5, 3, 15, 3, 5, 1.2, 0); // info in the flow; note that input mat should in 1-channel
        drawOptFlowMap(flow, cflow, 10, CV_RGB(0, 255, 0));  break;
    case 2:// calcOpticalFlowSF
        calcOpticalFlowSF(cflow, cflow2,
            flow,
            3, 2, 4, 4.1, 25.5, 18, 55.0, 25.5, 0.35, 18, 55.0, 25.5, 10);// info in the flow; note that input mat should in 3-channel

        drawOptFlowMap(flow, cflow, 10, CV_RGB(0, 255, 0)); break;
    case 3:// calcOpticalFlowPyrLK
        for (int y = 0; y < pre.rows; y += step)
            for (int x = 0; x < pre.cols; x += step)
            {
            prePts.push_back(Point(x, y));
            }

        // above get a point vector in step
        calcOpticalFlowPyrLK(pre, aft, prePts, nextPts, status, err, Size(31, 31), 3, termcrit, 0, 0.001);// info in the flow; note that input mat should in 1-channel
        drawOptFlowMap(cflow, step, CV_RGB(0, 255, 0), nextPts);
        break;
    default:
        break;
    }

    imshow("pre", pre);
    imshow("after", aft);
    //cflow is the pre with OpticalFlow line
    imshow("pre with OpticalFlow line", cflow);
    waitKey(0);
    return 0;
}
#endif
</code>```

Title: OpencCV: calcOpticalFlowSF function

Body:
I try to use the calcOpticalFlowSF() function, but when I launch it, the programm doesn't repond, here the part of the code that use it:

frame1 = cv::imread("frame10.png");
frame2 = cv::imread("frame11.png");

if (frame1.empty()) {
   cout<<"could not read image oldori"<<endl;

  return;
}

if (frame2.empty()) {
   cout<<"could not read image ori"<<endl;
  return;
}

if (frame1.rows != frame2.rows && frame1.cols != frame2.cols) {
     cout<<"images should be of equal sizes "endl;
  return;
}

if (frame1.type() != 16 || frame2.type() != 16) {
     cout<<"images should be of equal type CV_8UC3")endl;
  return;
}

cv::Mat flow;

cv::calcOpticalFlowSF(frame1, frame2, flow, 2, 2, 4);
// calcOpticalFlowSF(frame1, frame1,  // doesn't work too.
//                    flow,
//                    3, 2, 4, 4.1, 25.5, 18, 55.0, 25.5, 0.35, 18, 55.0, 25.5, 10);

I know that the error come from the function calcOpticalFlowSF, because if I comment it, the programm works. I use the same pictures as they use in the SimpleFlow demo. If you look here:How to get cv::calcOpticalFlowSF to work? it seems that he got no problem with the function itself...

Do you have an idea why it doesn't work?

thanks,

best regards.

Body:
make sure the image is 3-channel, is better to see the docs here

#if 1
#define _CRT_SECURE_NO_WARNINGS

#include <cstdio>
#include <cstdlib>
#include <vector>
#include <stdlib.h>
#include <opencv2/opencv.hpp>
#include "opencv2/optflow.hpp"
#include "opencv2/highgui.hpp"

using namespace std;
using namespace cv;
using namespace cv::optflow;//calcOpticalFlowSF 's namespace
const size_t choice = 2 ;
// choice
// 1    2    3
// calcOpticalFlowFarneback   calcOpticalFlowSF   calcOpticalFlowPyrLK
void drawOptFlowMap(const Mat& flow, Mat& cflowmap, int step, const Scalar& color) {
    // cflowmap is the pre frame with the line of Optical Flow
    // flow is a xxx array, store float point
    //      store the delta of x,y
    // step is every step pixel
    for (int y = 0; y < cflowmap.rows; y += step)
        for (int x = 0; x < cflowmap.cols; x += step)
        {
            const Point2f& fxy = flow.at< Point2f>(y, x);
            line(cflowmap, Point(x, y), Point(cvRound(x + fxy.x), cvRound(y + fxy.y)),
                color);
            circle(cflowmap, Point(cvRound(x + fxy.x), cvRound(y + fxy.y)), 1, color, -1);
        }
}

void drawOptFlowMap(Mat& cflowmap, int step, const Scalar& color, vector<Point2f> &retPts) {
    // same as above, retPts is the next frame point
    auto it = retPts.begin();
    for (int y = 0; y < cflowmap.rows; y += step)
        for (int x = 0; x < cflowmap.cols; x += step)
        {
            line(cflowmap, Point(x, y), *it, color);
            circle(cflowmap, *it, 1, color, -1);
            it++;
        }
}

int main(int argc, char *argv[])
{
    Mat flow;//flow = aft - pre
    Mat pre = imread("1hf.png", IMREAD_COLOR);
    Mat aft = imread("2hf.png", IMREAD_COLOR);//           CV_LOAD_IMAGE_GRAYSCALE   gray ; IMREAD_COLOR   color
    if (pre.empty() || aft.empty()){
        printf("Unable to load the image");
        return 1;
    }

    Mat cflow = pre; Mat cflow2 = aft;// store the  3-channel mat of frame, cflow is for show color with line
    cvtColor(pre, pre, CV_BGR2GRAY);
    cvtColor(aft, aft, CV_BGR2GRAY);

    //below parameter of calcOpticalFlowPyrLK
    vector<Point2f> prePts;
    size_t step = 10;
    vector<Point2f> nextPts(pre.rows * pre.cols);
    vector<uchar> status;
    vector<float> err;
    TermCriteria termcrit(CV_TERMCRIT_ITER | CV_TERMCRIT_EPS, 20, 0.03);

    switch (choice)
    {
    case 1:// calcOpticalFlowFarneback
        calcOpticalFlowFarneback(pre, aft, flow, 0.5, 3, 15, 3, 5, 1.2, 0); // info in the flow; note that input mat should in 1-channel
        drawOptFlowMap(flow, cflow, 10, CV_RGB(0, 255, 0));  break;
    case 2:// calcOpticalFlowSF
        calcOpticalFlowSF(cflow, cflow2,
            flow,
            3, 2, 4, 4.1, 25.5, 18, 55.0, 25.5, 0.35, 18, 55.0, 25.5, 10);// info in the flow; note that input mat should in 3-channel

        drawOptFlowMap(flow, cflow, 10, CV_RGB(0, 255, 0)); break;
    case 3:// calcOpticalFlowPyrLK
        for (int y = 0; y < pre.rows; y += step)
            for (int x = 0; x < pre.cols; x += step)
            {
            prePts.push_back(Point(x, y));
            }

        // above get a point vector in step
        calcOpticalFlowPyrLK(pre, aft, prePts, nextPts, status, err, Size(31, 31), 3, termcrit, 0, 0.001);// info in the flow; note that input mat should in 1-channel
        drawOptFlowMap(cflow, step, CV_RGB(0, 255, 0), nextPts);
        break;
    default:
        break;
    }

    imshow("pre", pre);
    imshow("after", aft);
    //cflow is the pre with OpticalFlow line
    imshow("pre with OpticalFlow line", cflow);
    waitKey(0);
    return 0;
}
#endif


问:
"Stratify" parameter from sklearn's train_test_split not working correctly?
I have a problem with the stratify parameter in the train_test_split() function of scikit-learn. This is a dummy example with the same problem that appears randomly on my data:

```<code>from sklearn.model_selection import train_test_split
a = [1, 0, 0, 0, 0, 0, 0, 1]
train_test_split(a, stratify=a, random_state=42)
</code>```

which returns:

```<code>[[1, 0, 0, 0, 0, 1], [0, 0]]
</code>```

Shouldn't it select a "1" also in the test subset? From how I expect train_test_split() with stratify to work it should return something like:

```<code>[[1, 0, 0, 0, 0, 0], [0, 1]]
</code>```

This happens with some values of random_state, while with other values it works correctly; but I cannot search for a "right" value of it every time I have to analyse data.

I have python 2.7 and scikit-learn 0.18.

答:
This question was asked 8 months ago but I guess an answer might still help readers in the future.

When using the stratify parameter, train_test_split actually relies on the StratifiedShuffleSplit function to do the split. As you see in the documentation, StratifiedShuffleSplit does aim to do the split by preserving the percentage of samples for each class, as you expected.

The problem is, in your example 25% (2 of 8 samples) are 1s, but the sample size is not large enough for you to see this proportion reflected on the test set. You have two options here:

A. Increase the size of the test set with the option test_size, which defaults to 0.25, to say 0.5. In this case, half of your samples will become your test set, and you'll see that 25% of them (i.e. 1 in 4) are 1.

```<code>>>> a = [1, 0, 0, 0, 0, 0, 0, 1]
>>> train_test_split(a, stratify=a, random_state=42, test_size=0.5)
[[1, 0, 0, 0], [0, 0, 1, 0]]
</code>```

B. Keep test_size to its default value and increase the size of your set a so that 25% of its samples amount to at least 4 elements. An a of 16 samples or more will do that for you.

```<code>>>> a = [1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1]
>>> train_test_split(a, stratify=a, random_state=42)
[[0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0], [0, 0, 1, 0]]
</code>```

Hope that helps.

Body:
I have a problem with the stratify parameter in the train_test_split() function of scikit-learn. This is a dummy example with the same problem that appears randomly on my data:

from sklearn.model_selection import train_test_split
a = [1, 0, 0, 0, 0, 0, 0, 1]
train_test_split(a, stratify=a, random_state=42)

which returns:

[[1, 0, 0, 0, 0, 1], [0, 0]]

Shouldn't it select a "1" also in the test subset? From how I expect train_test_split() with stratify to work it should return something like:

[[1, 0, 0, 0, 0, 0], [0, 1]]

This happens with some values of random_state, while with other values it works correctly; but I cannot search for a "right" value of it every time I have to analyse data.

I have python 2.7 and scikit-learn 0.18.

Body:
This question was asked 8 months ago but I guess an answer might still help readers in the future.

When using the stratify parameter, train_test_split actually relies on the StratifiedShuffleSplit function to do the split. As you see in the documentation, StratifiedShuffleSplit does aim to do the split by preserving the percentage of samples for each class, as you expected.

The problem is, in your example 25% (2 of 8 samples) are 1s, but the sample size is not large enough for you to see this proportion reflected on the test set. You have two options here:

A. Increase the size of the test set with the option test_size, which defaults to 0.25, to say 0.5. In this case, half of your samples will become your test set, and you'll see that 25% of them (i.e. 1 in 4) are 1.

>>> a = [1, 0, 0, 0, 0, 0, 0, 1]
>>> train_test_split(a, stratify=a, random_state=42, test_size=0.5)
[[1, 0, 0, 0], [0, 0, 1, 0]]

B. Keep test_size to its default value and increase the size of your set a so that 25% of its samples amount to at least 4 elements. An a of 16 samples or more will do that for you.

>>> a = [1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1]
>>> train_test_split(a, stratify=a, random_state=42)
[[0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0], [0, 0, 1, 0]]

Hope that helps.


问:
How to implement tuple unpacking for function parameters in Java?
I have created some tuple classes, and put them into Java collection. But I don't want to use tuple as function parameters directly when iterating collection.So I implemented tuple unpacking as the following code.

Basically it works, but the problem is that a type casting is needed:

map((Func2<Long, Long, Long>) (a, b) -> a + b)

Is there any way to remove the type casting here?

edit:

Maybe I didn't make it clear, not only tuple2, but also tuple3, tuple4... should be supported. @Flown's answer works greatly for Tuple2, but doesn't work for tuple2, tuple3, tuple4 in the meantime

```<code>package test;

import com.google.common.collect.Iterables;

import java.util.Arrays;
import java.util.function.Function;

import static test.TupleIterable.Tuple.tuple;

public interface TupleIterable<T> {

    Iterable<T> apply();

    static <E> TupleIterable<E> from(Iterable<E> iterable) {
        return () -> iterable;
    }

    default <E> TupleIterable<E> map(Function<? super T, ? extends E> op) {
        return () -> Iterables.transform(TupleIterable.this.apply(), op::apply);
    }

    interface Func2<T1, T2, R> extends Function<Tuple.Tuple2<T1, T2>, R> {

        R apply(T1 t1, T2 t2);

        @Override
        default R apply(Tuple.Tuple2<T1, T2> t) {
            return apply(t.t1, t.t2);
        }
    }

    interface Func3<T1, T2, T3, R> extends Function<Tuple.Tuple3<T1, T2, T3>, R> {

        R apply(T1 t1, T2 t2, T3 t3);

        @Override
        default R apply(Tuple.Tuple3<T1, T2, T3> t) {
            return apply(t.t1, t.t2, t.t3);
        }
    }

    interface Tuple {

        static <T1, T2> Tuple2<T1, T2> tuple(T1 t1, T2 t2) {
            return new Tuple2<>(t1, t2);
        }

        static <T1, T2, T3> Tuple3<T1, T2, T3> tuple(T1 t1, T2 t2, T3 t3) {
            return new Tuple3<>(t1, t2, t3);
        }

        class Tuple2<T1, T2> implements Tuple {

            public T1 t1;

            public T2 t2;

            public Tuple2(T1 t1, T2 t2) {
                this.t1 = t1;
                this.t2 = t2;
            }
        }

        class Tuple3<T1, T2, T3> implements Tuple {

            public T1 t1;

            public T2 t2;

            public T3 t3;

            public Tuple3(T1 t1, T2 t2, T3 t3) {
                this.t1 = t1;
                this.t2 = t2;
                this.t3 = t3;
            }
        }
    }

    public static void main(String[] args) {
        TupleIterable.from(Arrays.asList(1L, 2L))
                .map(x -> tuple(x, x)) // map long to tuple2
                .map((Func2<Long, Long, Tuple.Tuple3<Long, Long, Long>>) (a, b) -> tuple(a, b, a + b)) // map tuple2 to tuple3
                .map((Func3<Long, Long, Long, Long>) (a, b, c) -> a + b + c) // map tuple3 to Long
                .apply()
                .forEach(System.out::println);
    }
}
</code>```

答:
Instead of doing type casting, I created a unpack function to unpack tuples. It works like map(unpack((a, b) -> tuple(a, b, a + b))), though still not intuitive enough.

```<code>package test;

import com.google.common.collect.Iterables;

import java.util.Arrays;
import java.util.function.Function;

import static test.TupleIterable.Func.unpack;
import static test.TupleIterable.Tuple.tuple;

public interface TupleIterable<T> {

    Iterable<T> apply();

    static <E> TupleIterable<E> from(Iterable<E> iterable) {
        return () -> iterable;
    }

    default <E> TupleIterable<E> map(Function<? super T, E> op) {
        return () -> Iterables.transform(TupleIterable.this.apply(), op::apply);
    }

    interface Func {

        static <T1, T2, R> Function<Tuple.Tuple2<T1, T2>, R> unpack(Func2<T1, T2, R> f) {
            return t -> f.apply(t.t1, t.t2);
        }

        static <T1, T2, T3, R> Function<Tuple.Tuple3<T1, T2, T3>, R> unpack(Func3<T1, T2, T3, R> f) {
            return t -> f.apply(t.t1, t.t2, t.t3);
        }

        @FunctionalInterface
        interface Func2<T1, T2, R> {

            R apply(T1 t1, T2 t2);
        }

        @FunctionalInterface
        interface Func3<T1, T2, T3, R> {

            R apply(T1 t1, T2 t2, T3 t3);
        }
    }

    interface Tuple {

        static <T1, T2> Tuple2<T1, T2> tuple(T1 t1, T2 t2) {
            return new Tuple2<>(t1, t2);
        }

        static <T1, T2, T3> Tuple3<T1, T2, T3> tuple(T1 t1, T2 t2, T3 t3) {
            return new Tuple3<>(t1, t2, t3);
        }

        class Tuple2<T1, T2> implements Tuple {

            public T1 t1;

            public T2 t2;

            public Tuple2(T1 t1, T2 t2) {
                this.t1 = t1;
                this.t2 = t2;
            }
        }

        class Tuple3<T1, T2, T3> implements Tuple {

            public T1 t1;

            public T2 t2;

            public T3 t3;

            public Tuple3(T1 t1, T2 t2, T3 t3) {
                this.t1 = t1;
                this.t2 = t2;
                this.t3 = t3;
            }
        }
    }

    public static void main(String[] args) {
        TupleIterable.from(Arrays.asList(1L, 2L))
                .map(x -> tuple(x, x)) // map long to tuple2
                .map(unpack((a, b) -> tuple(a, b, a + b))) // map tuple2 to tuple3
                .map(unpack((a, b, c) -> a + b + c)) // map tuple3 to Long
                .apply()
                .forEach(System.out::println);
    }
}
</code>```

Body:
I have created some tuple classes, and put them into Java collection. But I don't want to use tuple as function parameters directly when iterating collection.So I implemented tuple unpacking as the following code.

Basically it works, but the problem is that a type casting is needed:

map((Func2<Long, Long, Long>) (a, b) -> a + b)

Is there any way to remove the type casting here?

edit:

Maybe I didn't make it clear, not only tuple2, but also tuple3, tuple4... should be supported. @Flown's answer works greatly for Tuple2, but doesn't work for tuple2, tuple3, tuple4 in the meantime

package test;

import com.google.common.collect.Iterables;

import java.util.Arrays;
import java.util.function.Function;

import static test.TupleIterable.Tuple.tuple;

public interface TupleIterable<T> {

    Iterable<T> apply();

    static <E> TupleIterable<E> from(Iterable<E> iterable) {
        return () -> iterable;
    }

    default <E> TupleIterable<E> map(Function<? super T, ? extends E> op) {
        return () -> Iterables.transform(TupleIterable.this.apply(), op::apply);
    }

    interface Func2<T1, T2, R> extends Function<Tuple.Tuple2<T1, T2>, R> {

        R apply(T1 t1, T2 t2);

        @Override
        default R apply(Tuple.Tuple2<T1, T2> t) {
            return apply(t.t1, t.t2);
        }
    }

    interface Func3<T1, T2, T3, R> extends Function<Tuple.Tuple3<T1, T2, T3>, R> {

        R apply(T1 t1, T2 t2, T3 t3);

        @Override
        default R apply(Tuple.Tuple3<T1, T2, T3> t) {
            return apply(t.t1, t.t2, t.t3);
        }
    }

    interface Tuple {

        static <T1, T2> Tuple2<T1, T2> tuple(T1 t1, T2 t2) {
            return new Tuple2<>(t1, t2);
        }

        static <T1, T2, T3> Tuple3<T1, T2, T3> tuple(T1 t1, T2 t2, T3 t3) {
            return new Tuple3<>(t1, t2, t3);
        }

        class Tuple2<T1, T2> implements Tuple {

            public T1 t1;

            public T2 t2;

            public Tuple2(T1 t1, T2 t2) {
                this.t1 = t1;
                this.t2 = t2;
            }
        }

        class Tuple3<T1, T2, T3> implements Tuple {

            public T1 t1;

            public T2 t2;

            public T3 t3;

            public Tuple3(T1 t1, T2 t2, T3 t3) {
                this.t1 = t1;
                this.t2 = t2;
                this.t3 = t3;
            }
        }
    }

    public static void main(String[] args) {
        TupleIterable.from(Arrays.asList(1L, 2L))
                .map(x -> tuple(x, x)) // map long to tuple2
                .map((Func2<Long, Long, Tuple.Tuple3<Long, Long, Long>>) (a, b) -> tuple(a, b, a + b)) // map tuple2 to tuple3
                .map((Func3<Long, Long, Long, Long>) (a, b, c) -> a + b + c) // map tuple3 to Long
                .apply()
                .forEach(System.out::println);
    }
}

Body:
Instead of doing type casting, I created a unpack function to unpack tuples. It works like map(unpack((a, b) -> tuple(a, b, a + b))), though still not intuitive enough.

package test;

import com.google.common.collect.Iterables;

import java.util.Arrays;
import java.util.function.Function;

import static test.TupleIterable.Func.unpack;
import static test.TupleIterable.Tuple.tuple;

public interface TupleIterable<T> {

    Iterable<T> apply();

    static <E> TupleIterable<E> from(Iterable<E> iterable) {
        return () -> iterable;
    }

    default <E> TupleIterable<E> map(Function<? super T, E> op) {
        return () -> Iterables.transform(TupleIterable.this.apply(), op::apply);
    }

    interface Func {

        static <T1, T2, R> Function<Tuple.Tuple2<T1, T2>, R> unpack(Func2<T1, T2, R> f) {
            return t -> f.apply(t.t1, t.t2);
        }

        static <T1, T2, T3, R> Function<Tuple.Tuple3<T1, T2, T3>, R> unpack(Func3<T1, T2, T3, R> f) {
            return t -> f.apply(t.t1, t.t2, t.t3);
        }

        @FunctionalInterface
        interface Func2<T1, T2, R> {

            R apply(T1 t1, T2 t2);
        }

        @FunctionalInterface
        interface Func3<T1, T2, T3, R> {

            R apply(T1 t1, T2 t2, T3 t3);
        }
    }

    interface Tuple {

        static <T1, T2> Tuple2<T1, T2> tuple(T1 t1, T2 t2) {
            return new Tuple2<>(t1, t2);
        }

        static <T1, T2, T3> Tuple3<T1, T2, T3> tuple(T1 t1, T2 t2, T3 t3) {
            return new Tuple3<>(t1, t2, t3);
        }

        class Tuple2<T1, T2> implements Tuple {

            public T1 t1;

            public T2 t2;

            public Tuple2(T1 t1, T2 t2) {
                this.t1 = t1;
                this.t2 = t2;
            }
        }

        class Tuple3<T1, T2, T3> implements Tuple {

            public T1 t1;

            public T2 t2;

            public T3 t3;

            public Tuple3(T1 t1, T2 t2, T3 t3) {
                this.t1 = t1;
                this.t2 = t2;
                this.t3 = t3;
            }
        }
    }

    public static void main(String[] args) {
        TupleIterable.from(Arrays.asList(1L, 2L))
                .map(x -> tuple(x, x)) // map long to tuple2
                .map(unpack((a, b) -> tuple(a, b, a + b))) // map tuple2 to tuple3
                .map(unpack((a, b, c) -> a + b + c)) // map tuple3 to Long
                .apply()
                .forEach(System.out::println);
    }
}


问:
Ruby's ||= (or equals) in JavaScript?
I love Ruby's ||= mechanism. If a variable doesn't exist or is nil, then create it and set it equal to something:

```<code>amount # is nil
amount ||= 0 # is 0
amount ||= 5 # is 0
</code>```

I need to do something similar in JavaScript now. What's the convention or proper way to do this? I know ||= is not valid syntax. 2 obvious ways to handle it are:

```<code>window.myLib = window.myLib || {};

// or

if (!window.myLib)
  window.myLib = {};
</code>```

答:
If you're working with objects, you can use destructuring (since ES6) like so:

```<code>({ myLib: window.myLib = {} } = window);
</code>```

...but you don't gain anything over the accepted answer except confusion.

Title: Ruby's ||= (or equals) in JavaScript?

Body:
I love Ruby's ||= mechanism. If a variable doesn't exist or is nil, then create it and set it equal to something:

amount # is nil
amount ||= 0 # is 0
amount ||= 5 # is 0

I need to do something similar in JavaScript now. What's the convention or proper way to do this? I know ||= is not valid syntax. 2 obvious ways to handle it are:

window.myLib = window.myLib || {};

// or

if (!window.myLib)
  window.myLib = {};

Body:
If you're working with objects, you can use destructuring (since ES6) like so:

({ myLib: window.myLib = {} } = window);

...but you don't gain anything over the accepted answer except confusion.


问:
Dynamically creating divs using Jquery with JSON data
so basically what I am trying to do is I have a bunch of data in an external JSON file. This JSON file can be edited by authorised people at any time so the number of data will keep on changing. Therefore, using the data in that file, I need to dynamically create divs so that the number of divs that I have will match the amount of data there is in the JSON file. And in the divs, the JSON data will be shown. I've done my research and I found out that it could be done through Jquery and Ajax but I did not manage to find something that was similar to my situation. Pardon me because I am quite a newbie when it comes to web development

This is how the divs are if it was hard-coded.

```<code><div class="container" id="TestCi">
<h3>Files</h3>
<div class="row">
  <div class="col-md-102 col-sm-12">

    <div class="col-md-4 col-sm-4">
      <div class="well">
        <h5>3G</h5>
         <a href="https://example.com" target="_blank"><img data-toggle="tooltip" data-placement="left" title="Click to open data" src="images/3GQoS.jpg" height="100%" width="100%"/> </a>
      </div>
    </div>

    <div class="col-md-4 col-sm-4">
      <div class="well">
        <h5>4G</h5>
        <a href="https://example.com" target="_blank"><img data-toggle="tooltip" data-placement="left" title="Click to open data" src="images/4GQoS.jpg" height="100%" width="100%"/></a>
      </div>
    </div>

  <div class="col-md-4 col-sm-4">
    <div class="well">
      <h5>Lorem Ipsum</h5>
      <p>Integer eget tortor justo. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia.</p>
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit Ut enim ad minim veniam, quis nostrud exercitation.</p>
    </div>
  </div>
</code>```

And this is my JSON file

```<code>[{"title":"3G","filePath":"https://example.com","imagePath":"images/3GQoS.jpg"}, {"title":"4G", "filePath":"https://example.com", "imagePath":"images/4GQoS.jpg"} ]
</code>```

Edit:
I need to read each item in the external JSON file and with each item, a div will be created and the data will be displayed in it. Here is an image of how the divs look like: Image

答:
You can try this.</p>

```<code>$.ajax({
    url : "url",
    type : "GET or POST", // whichever you like
    contentType:"application/json",
    success : function(list)
    {
        var divCol  = "<div class='col-sm-4 col-md-4'>";
        var divWell = "<div class='well'>";
        var divClose= "</div>";

        list.forEach(function(obj, index) {

            var title     = "<h5>"      + obj.title    + "</h5>";
            var linkStart = "<a href='" + obj.filePath + "' target='_blank'>";
            var image     = "<img data-toggle='tooltip' data-placement='left' title='Click to open data' src='" + obj.imagePath + "' height='100%' width='100%'/>"
            var linkEnd   = "</a>";

            var div = divCol    +
                        divWell     +
                            title       +
                            linkStart       +
                            image       +
                            linkEnd +
                        divClose +
                      divClose;

            $('.col-sm-12').append(div); // insert the div you've just created

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

Body:
so basically what I am trying to do is I have a bunch of data in an external JSON file. This JSON file can be edited by authorised people at any time so the number of data will keep on changing. Therefore, using the data in that file, I need to dynamically create divs so that the number of divs that I have will match the amount of data there is in the JSON file. And in the divs, the JSON data will be shown. I've done my research and I found out that it could be done through Jquery and Ajax but I did not manage to find something that was similar to my situation. Pardon me because I am quite a newbie when it comes to web development

This is how the divs are if it was hard-coded.

Files

3G

4G

Lorem Ipsum

Integer eget tortor justo. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia.

Lorem ipsum dolor sit amet, consectetur adipiscing elit Ut enim ad minim veniam, quis nostrud exercitation.

And this is my JSON file

[{"title":"3G","filePath":"https://example.com","imagePath":"images/3GQoS.jpg"}, {"title":"4G", "filePath":"https://example.com", "imagePath":"images/4GQoS.jpg"} ]

Edit:
I need to read each item in the external JSON file and with each item, a div will be created and the data will be displayed in it. Here is an image of how the divs look like: Image

Body:
You can try this.

$.ajax({
    url : "url",
    type : "GET or POST", // whichever you like
    contentType:"application/json",
    success : function(list)
    {
        var divCol  = "<div class='col-sm-4 col-md-4'>";
        var divWell = "<div class='well'>";
        var divClose= "</div>";

        list.forEach(function(obj, index) {

            var title     = "<h5>"      + obj.title    + "</h5>";
            var linkStart = "<a href='" + obj.filePath + "' target='_blank'>";
            var image     = "<img data-toggle='tooltip' data-placement='left' title='Click to open data' src='" + obj.imagePath + "' height='100%' width='100%'/>"
            var linkEnd   = "</a>";

            var div = divCol    +
                        divWell     +
                            title       +
                            linkStart       +
                            image       +
                            linkEnd +
                        divClose +
                      divClose;

            $('.col-sm-12').append(div); // insert the div you've just created

        })
    }
});


问:
How to get the avg values in front of the current position in a RDD with spark/scala
I have a RDD, I want to get the average values in front of the current position(including current position) in a RDD
for example：

```<code>inputRDD:
1,  2,   3,  4,   5,  6,   7,  8

output:
1,  1.5, 2,  2.5, 3,  3.5, 4,  4.5
</code>```

this is my try:

```<code>val rdd=sc.parallelize(List(1,2,3,4,5,6,7,8),4)
    var sum=0.0
    var index=0.0
    val partition=rdd.getNumPartitions
    rdd.zipWithIndex().collect().foreach(println)
    rdd.zipWithIndex().sortBy(x=>{x._2},true,1).mapPartitions(ite=>{
      var result=new ArrayBuffer[Tuple2[Double,Long]]()
      while (ite.hasNext){
        val iteNext=ite.next()
        sum+=iteNext._1
        index+=1
        var avg:Double=sum/index
        result.append((avg,iteNext._2))
      }
      result.toIterator
    }).sortBy(x=>{x._2},true,partition).map(x=>{x._1}).collect().foreach(println)
</code>```

I have to repartition to 1 then calculate it with a array,it's so inefficient.

Is there any cleaner solution without using array in 4 partitions?

答:
a simpler solution would be to use Spark-SQL.
here I am computing the running average for each row

```<code>val df = sc.parallelize(List(1,2,3,4,5,6,7,8)).toDF("col1")

df.createOrReplaceTempView("table1")

val result = spark.sql("""SELECT col1, sum(col1) over(order by col1 asc)/row_number() over(order by col1 asc) as avg FROM table1""")
</code>```

or alternatively if you want to use the DataFrames API.

```<code>import org.apache.spark.sql.expressions._
val result = df
 .withColumn("csum", sum($"col1").over(Window.orderBy($"col1")))
 .withColumn("rownum", row_number().over(Window.orderBy($"col1")))
 .withColumn("avg", $"csum"/$"rownum")
 .select("col1","avg")
</code>```

Output:

```<code>result.show()

+----+---+
|col1|avg|
+----+---+
|   1|1.0|
|   2|1.5|
|   3|2.0|
|   4|2.5|
|   5|3.0|
|   6|3.5|
|   7|4.0|
|   8|4.5|
+----+---+
</code>```

Body:
I have a RDD, I want to get the average values in front of the current position(including current position) in a RDD
for example：

inputRDD:
1,  2,   3,  4,   5,  6,   7,  8

output:
1,  1.5, 2,  2.5, 3,  3.5, 4,  4.5

this is my try:

val rdd=sc.parallelize(List(1,2,3,4,5,6,7,8),4)
    var sum=0.0
    var index=0.0
    val partition=rdd.getNumPartitions
    rdd.zipWithIndex().collect().foreach(println)
    rdd.zipWithIndex().sortBy(x=>{x._2},true,1).mapPartitions(ite=>{
      var result=new ArrayBuffer[Tuple2[Double,Long]]()
      while (ite.hasNext){
        val iteNext=ite.next()
        sum+=iteNext._1
        index+=1
        var avg:Double=sum/index
        result.append((avg,iteNext._2))
      }
      result.toIterator
    }).sortBy(x=>{x._2},true,partition).map(x=>{x._1}).collect().foreach(println)

I have to repartition to 1 then calculate it with a array,it's so inefficient.

Is there any cleaner solution without using array in 4 partitions?

Body:
a simpler solution would be to use Spark-SQL.
here I am computing the running average for each row

val df = sc.parallelize(List(1,2,3,4,5,6,7,8)).toDF("col1")

df.createOrReplaceTempView("table1")

val result = spark.sql("""SELECT col1, sum(col1) over(order by col1 asc)/row_number() over(order by col1 asc) as avg FROM table1""")

or alternatively if you want to use the DataFrames API.

import org.apache.spark.sql.expressions._
val result = df
 .withColumn("csum", sum($"col1").over(Window.orderBy($"col1")))
 .withColumn("rownum", row_number().over(Window.orderBy($"col1")))
 .withColumn("avg", $"csum"/$"rownum")
 .select("col1","avg")

Output:

result.show()

+----+---+
|col1|avg|
+----+---+
|   1|1.0|
|   2|1.5|
|   3|2.0|
|   4|2.5|
|   5|3.0|
|   6|3.5|
|   7|4.0|
|   8|4.5|
+----+---+


问:
Outputting emoji in python
I'm trying to output emoji in Telegram automatically using python library pyautogui but however i found it impossible to just typewrite it. I searched for libraries to help me solve my problem and i found pyemojify and emoji but in both cases i faced

```<code>UnicodeEncodeError: 'charmap' codec can't encode characters: character maps to <undefined>
</code>```

and the code is:

```<code>from pyemojify import emojify
print(emojify("Life is short :smile: , use :sparkles: Python :sparkles:"))
</code>```

and this:

```<code>import emoji
print(emoji.emojize('Python is :thumbs_up_sign:'))
</code>```

i searched here a lot but none of the answers finally worked for me.
Now i have two questions: is there any way to output an emoji in Telegram using python pyautogui or even using java Robot class? and the second question is how i should fix UnicodeEncodeError in my code? Thanks in advance :)

答:
```<code>from selenium import webdriver

b = webdriver.Firefox()
b.get('https://web.telegram.org')
....
....
b.find_elements_by_class_name('composer_rich_textarea')[0].send_keys('\U0001F422')
print('\U0001F422'.encode('utf-8'))
</code>```

Title: Outputting emoji in python

Body:
I'm trying to output emoji in Telegram automatically using python library pyautogui but however i found it impossible to just typewrite it. I searched for libraries to help me solve my problem and i found pyemojify and emoji but in both cases i faced

UnicodeEncodeError: 'charmap' codec can't encode characters: character maps to <undefined>

and the code is:

from pyemojify import emojify
print(emojify("Life is short :smile: , use :sparkles: Python :sparkles:"))

and this:

import emoji
print(emoji.emojize('Python is :thumbs_up_sign:'))

i searched here a lot but none of the answers finally worked for me.
Now i have two questions: is there any way to output an emoji in Telegram using python pyautogui or even using java Robot class? and the second question is how i should fix UnicodeEncodeError in my code? Thanks in advance :)


问:
Installed Google Cloud SDK but can't access gcloud
I am trying to install the Google Cloud SDK on OSX and do this node.js tutorial (https://cloud.google.com/nodejs/getting-started/hello-world) and keep running into a problem where the gcloud is not found. It might be just be something simple about setting in or where I'm in saving the file.

I've read a ton of other posts here but haven't been able to solve this problem. Here are all the steps/issues:

I already created a project in the dev console.

Install the cloud sdk

```<code>MacBook-Pro-2:~ nico$ curl https://sdk.cloud.google.com | bash
</code>```

Then go through the process

```<code>Directory to extract under (this will create a directory google-cloud-sdk) (/Users/nico):

Do you want to help improve the Google Cloud SDK (Y/n)?  y

Modify profile to update your $PATH and enable bash completion? (Y/n)? y

Enter path to an rc file to update, or leave blank to use [/Users/nico/.bash_profile]:
</code>```

Then I tried to authenticate:

```<code>MacBook-Pro-2:~ nico$ gcloud auth login
-bash: gcloud: command not found
</code>```

Then I went into a cloud sdk bin directory

```<code>MacBook-Pro-2:~ nico$ cd google-cloud-sdk/bin
MacBook-Pro-2:bin nico$ ./gcloud auth login
</code>```

Authentication was successful

```<code> MacBook-Pro-2:bin nico$ ./gcloud config set project helloworld-project
</code>```

Setting the project was successful

```<code>MacBook-Pro-2:bin nico$ ./gcloud components update app

ERROR: (gcloud.components.update) Your current working directory is inside the Cloud SDK install root: /Users/nico/google-cloud-sdk.
In order to perform this update, run the command from outside of this directory.
</code>```

So then I move out of that directory

```<code> MacBook-Pro-2:test_project nico$ gcloud components update app
-bash: gcloud: command not found
</code>```

And now it's not working, do I have to set gcloud somewhere so it can be access globally? How can I update it and access the gcloud command line tool?

答:
I had modified my

```<code>vi ~/.bash_profile
</code>```

and added one line to the end of it

```<code>source ~/.bashrc
</code>```

Then you can log out & logged in again or run:

source ~/.bash_profile

After you have added the line.

OS: Linux vagrant-ubuntu-trusty-64 3.13.0-116-generic #163-Ubuntu

Or Simply Run:

```<code>echo "source ~/.bashrc" >> ~/.bash_profile
source ~/.bash_profile
which gcloud
</code>```

Showed me

/home/myusername/google/google-cloud-sdk/bin/gcloud

Body:
I am trying to install the Google Cloud SDK on OSX and do this node.js tutorial (https://cloud.google.com/nodejs/getting-started/hello-world) and keep running into a problem where the gcloud is not found. It might be just be something simple about setting in or where I'm in saving the file.

I've read a ton of other posts here but haven't been able to solve this problem. Here are all the steps/issues:

I already created a project in the dev console.

Install the cloud sdk

MacBook-Pro-2:~ nico$ curl https://sdk.cloud.google.com | bash

Then go through the process

Directory to extract under (this will create a directory google-cloud-sdk) (/Users/nico):

Do you want to help improve the Google Cloud SDK (Y/n)?  y

Modify profile to update your $PATH and enable bash completion? (Y/n)? y

Enter path to an rc file to update, or leave blank to use [/Users/nico/.bash_profile]:

Then I tried to authenticate:

MacBook-Pro-2:~ nico$ gcloud auth login
-bash: gcloud: command not found

Then I went into a cloud sdk bin directory

MacBook-Pro-2:~ nico$ cd google-cloud-sdk/bin
MacBook-Pro-2:bin nico$ ./gcloud auth login

Authentication was successful

 MacBook-Pro-2:bin nico$ ./gcloud config set project helloworld-project

Setting the project was successful

MacBook-Pro-2:bin nico$ ./gcloud components update app

ERROR: (gcloud.components.update) Your current working directory is inside the Cloud SDK install root: /Users/nico/google-cloud-sdk.
In order to perform this update, run the command from outside of this directory.

So then I move out of that directory

 MacBook-Pro-2:test_project nico$ gcloud components update app
-bash: gcloud: command not found

And now it's not working, do I have to set gcloud somewhere so it can be access globally? How can I update it and access the gcloud command line tool?

Body:
I had modified my

vi ~/.bash_profile

and added one line to the end of it

source ~/.bashrc

Then you can log out & logged in again or run:

source ~/.bash_profile

After you have added the line.

OS: Linux vagrant-ubuntu-trusty-64 3.13.0-116-generic #163-Ubuntu

Or Simply Run:

echo "source ~/.bashrc" >> ~/.bash_profile
source ~/.bash_profile
which gcloud

Showed me

/home/myusername/google/google-cloud-sdk/bin/gcloud


答:
Sorry I dont use Scala and hope you could read it </p>

```<code>df = spark.createDataFrame(map(lambda x: (x,), range(1, 9)), ['val'])
df = df.withColumn('spec_avg',
                   f.avg('val').over(Window().orderBy('val').rowsBetween(start=Window.unboundedPreceding, end=0)))
</code>```

Title: How to get the avg values in front of the current position in a RDD with spark/scala

Body:
Sorry I dont use Scala and hope you could read it

df = spark.createDataFrame(map(lambda x: (x,), range(1, 9)), ['val'])
df = df.withColumn('spec_avg',
                   f.avg('val').over(Window().orderBy('val').rowsBetween(start=Window.unboundedPreceding, end=0)))


问:
Selenium: FirefoxProfile exception Can't load the profile. Python script called from PHP
My python script has the following code:

```<code>firefox_profile = webdriver.FirefoxProfile()
self.driver = webdriver.Firefox(firefox_profile=firefox_profile)
</code>```

When I execute the script from bash it works, but if I call the script from a PHP file, with the following command:

```<code>shell_exec("python path_to_the_script");
</code>```

I receive the exception:

```<code>selenium.common.exceptions.WebDriverException: Message: Can't load the profile. Profile Dir: /tmp/tmp7Ob0z6/webdriver-py-profilecopy If you specified a log_file in the FirefoxBinary constructor, check it for details.
</code>```

I've also tried to set the profile manually, like this:

```<code> firefox_profile = webdriver.FirefoxProfile(profile_directory='path_to_the_profile_dir')
</code>```

But nothing changed, while if I set the profile directory path like this:

```<code>firefox_profile = webdriver.FirefoxProfile(profile_directory='path_to_the_profile_dir')
firefox_profile.profile_dir = 'path_to_the_profile_dir'
</code>```

The exception error changes to this:

```<code>selenium.common.exceptions.WebDriverException: Message: Can't load the profile. Profile Dir: path_to_the_profile_dir If you specified a log_file in the FirefoxBinary constructor, check it for details.
</code>```

I've set the permissions to 777 for all the involved directories, and also tried to override the FirefoxBinary.launch_browser function so that it uses a greater timeout value, but id did not work.
I'm using Python 2.7, Selenium 2.53.6 and Firefox 46.0.1

Firefox is working in headless mode, through Xvfb and pyvirtualdisplay.

答:
If that didn't fix your issue check your firefox profile name

like this

```<code>fp = webdriver.FirefoxProfile('/home/YOUR_USERNAME/.mozilla/firefox/YOUR_PROFILE_NAME.default')
driver = webdriver.Firefox(firefox_profile=fp)
</code>```

To find your firefox profile name open your file browser and enable "show hidden files" go to "Home/.mozilla/firefox" and you'll see your firefox profile folder.

I hope that solved your issue

Body:
My python script has the following code:

firefox_profile = webdriver.FirefoxProfile()
self.driver = webdriver.Firefox(firefox_profile=firefox_profile)

When I execute the script from bash it works, but if I call the script from a PHP file, with the following command:

shell_exec("python path_to_the_script");

I receive the exception:

selenium.common.exceptions.WebDriverException: Message: Can't load the profile. Profile Dir: /tmp/tmp7Ob0z6/webdriver-py-profilecopy If you specified a log_file in the FirefoxBinary constructor, check it for details.

I've also tried to set the profile manually, like this:

 firefox_profile = webdriver.FirefoxProfile(profile_directory='path_to_the_profile_dir')

But nothing changed, while if I set the profile directory path like this:

firefox_profile = webdriver.FirefoxProfile(profile_directory='path_to_the_profile_dir')
firefox_profile.profile_dir = 'path_to_the_profile_dir'

The exception error changes to this:

selenium.common.exceptions.WebDriverException: Message: Can't load the profile. Profile Dir: path_to_the_profile_dir If you specified a log_file in the FirefoxBinary constructor, check it for details.

I've set the permissions to 777 for all the involved directories, and also tried to override the FirefoxBinary.launch_browser function so that it uses a greater timeout value, but id did not work.
I'm using Python 2.7, Selenium 2.53.6 and Firefox 46.0.1

Firefox is working in headless mode, through Xvfb and pyvirtualdisplay.

Body:
If that didn't fix your issue check your firefox profile name

like this

fp = webdriver.FirefoxProfile('/home/YOUR_USERNAME/.mozilla/firefox/YOUR_PROFILE_NAME.default')
driver = webdriver.Firefox(firefox_profile=fp)

To find your firefox profile name open your file browser and enable "show hidden files" go to "Home/.mozilla/firefox" and you'll see your firefox profile folder.

I hope that solved your issue


问:
Downloading Xcode 9 (or 9.1 Beta release)
I downloaded iOS 11 on my device and want to continue testing my projects on my device but it wont work because it says that ios 11.0 may not support the version of Xcode I have (which is 8.3.3). I am assuming this is because I need to use the Xcode 9 (or 9.1 beta release) but I can't seem to find where I can download this at.</p>

答:
To get the Xcode 9 beta:

Log in to member center

Click on downloads on the menu to the left

And you´ll find Xcode 9 beta

Downloads for Apple Developers here.

Download stable version here here.


问:
Unable to open the stream coming from google map api in android?
When i am using below url for drawing route on map on android:

```<code>StringBuilder urlString = new StringBuilder();
   urlString.append("http://maps.google.com/maps?f=d&hl=en");
   urlString.append("&saddr=");
   urlString.append(src);
   urlString.append("&daddr=");// to
   urlString.append(dest);
   urlString.append("&ie=UTF8&0&om=0&output=kml");
</code>```

Its throwing exception when urlConnection.getInputStream is called.

```<code>HttpURLConnection urlConnection=(HttpURLConnection)url.openConnection();
      urlConnection.setRequestMethod("GET");
      urlConnection.setDoOutput(true);
      urlConnection.setDoInput(true);
      urlConnection.connect();

      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
      DocumentBuilder db = dbf.newDocumentBuilder();
      doc = db.parse(urlConnection.getInputStream());
</code>```

New Code:

```<code>Document doc=null;

        try
        {

            String url = getUrl(p, q);
            DocumentBuilderFactory dbfAdd = DocumentBuilderFactory.newInstance();
            DocumentBuilder dbAdd = dbfAdd.newDocumentBuilder();
            doc = dbAdd.parse(url.toString());
</code>```

答:
IIRC Android's XML document parser cannot handle an InputStream which blocks. Better to use the version of parse() which does the download for you, i.e. :

```<code>DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
doc = db.parse(urlString.toString());
</code>```

Body:
When i am using below url for drawing route on map on android:

StringBuilder urlString = new StringBuilder();
   urlString.append("http://maps.google.com/maps?f=d&hl=en");
   urlString.append("&saddr=");
   urlString.append(src);
   urlString.append("&daddr=");// to
   urlString.append(dest);
   urlString.append("&ie=UTF8&0&om=0&output=kml");

Its throwing exception when urlConnection.getInputStream is called.

HttpURLConnection urlConnection=(HttpURLConnection)url.openConnection();
      urlConnection.setRequestMethod("GET");
      urlConnection.setDoOutput(true);
      urlConnection.setDoInput(true);
      urlConnection.connect();

      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
      DocumentBuilder db = dbf.newDocumentBuilder();
      doc = db.parse(urlConnection.getInputStream());

New Code:

Document doc=null;

        try
        {

            String url = getUrl(p, q);
            DocumentBuilderFactory dbfAdd = DocumentBuilderFactory.newInstance();
            DocumentBuilder dbAdd = dbfAdd.newDocumentBuilder();
            doc = dbAdd.parse(url.toString());

Body:
IIRC Android's XML document parser cannot handle an InputStream which blocks. Better to use the version of parse() which does the download for you, i.e. :

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
doc = db.parse(urlString.toString());


问:
If I run "rm -rf /* && dd if=/dev/zeros of=/dev/sdX" will the drive be overwritten with zeros?
I am wondering what the result of the above command will be. My goal is a command that will first delete all files on the disk and then overwrite the disk with zeros. However I am concerned that the rm part of the above command will delete the files necessary to run the dd command (such as /dev/sdX). What will the result of the above command be and if it does not do what I described how could it be improved?</p>

答:
You don't need the rm -rf / (read about page cache)

Just do the dd if=/dev/zero of=/dev/sdX bs=64k (with an appropriate X letter). Then reboot without sync

If you really are paranoid, do the dd from a live USB linux. If you are even more paranoid, destroy physically the disk afterwards (e.g. with a hammer).