答:
The month parameter starts at 0, so if you want to put July you must write 6 instead of 7.

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Date

Body:
I am trying to use the "new Date()" function but my dates are not coming out correctly.

This date & time is correct if I use:

new Date(); //outputs Wed Jul 05 2017 13:16:31 GMT-0700 (Pacific Daylight Time)

When I try to change the date, it comes out incorrect:

new Date(2017,07,03,12,01,36); //outputs Thu Aug 03 2017 12:01:36 GMT-0700 (Pacific Daylight Time)

I'm not sure why it says "Aug" when it should be "Jul".

Thanks In Advance!


来源: stackexchange

问:
Why must accessor functions be const? Where is the vulnerability?
Professors hammered it into my head when I was in school, associates have jumped down my throat for it on code reviews, and it's in pretty much every C++ textbook out there: "accessor" (aka "selector" or "getter") methods must be marked const. If it doesn't change or mutate the data, then mark it const.

Why? How could the invocation of an accessor modify the private data?

In the following example, I have set up a simple class and one accessor. How can getBrand() be used to modify the private data? In my eyes, it can't; so why do we need to mark it const?

In other words, am I correct in saying that it is impossible for getBrand() to be used, in practice, to mutate a private property?

Example:

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

class Cheese {
public:
    Cheese(std::string brand):brand_(brand) {}
    std::string getBrand() { return brand_; } // Intentionally not marked const
private:
    std::string brand_;
};

int main() {
    Cheese cheddar("Cabot clothbound");
    std::cout << "Brand: " << cheddar.getBrand() << std::endl;
    return 0;
}
</code>```

答:
Strictly speaking the method you've written doesn't mutate class members. If you marked it const the compiler completely prevents it from mutating members. But let's dig a little deeper here.

Typically you write code once but read/review it many times. Marking a method const allows future readers to look at it and instantly know that the method can't change the class state because the compiler would catch it. For example if you accidentally write size_t empty() const { return size_ = 0; } (where size_ is a member variable) the compiler will catch your typo. If you hadn't marked the method const you would have a subtle bug.

But more importantly, const methods can only call other const methods. Consider if you have a method that takes the class state as input, does a bunch of work and returns a result. If the getter methods it uses to do its work are non-const then the long, complicated method also has to be non-const which then makes code comprehension much harder.

ContentLicense: CC BY-SA 3.0

Body:
Professors hammered it into my head when I was in school, associates have jumped down my throat for it on code reviews, and it's in pretty much every C++ textbook out there: "accessor" (aka "selector" or "getter") methods must be marked const. If it doesn't change or mutate the data, then mark it const.

Why? How could the invocation of an accessor modify the private data?

In the following example, I have set up a simple class and one accessor. How can getBrand() be used to modify the private data? In my eyes, it can't; so why do we need to mark it const?

In other words, am I correct in saying that it is impossible for getBrand() to be used, in practice, to mutate a private property?

Example:

#include <iostream>
#include <string>

class Cheese {
public:
    Cheese(std::string brand):brand_(brand) {}
    std::string getBrand() { return brand_; } // Intentionally not marked const
private:
    std::string brand_;
};

int main() {
    Cheese cheddar("Cabot clothbound");
    std::cout << "Brand: " << cheddar.getBrand() << std::endl;
    return 0;
}


问:
How would you separate a list into sublists of all the duplicates in the original?
```<code>l = [a, a, a, b, b, c]

desired1 = [a, a, a]

desired2 = [b, b]

desired3 = [c]
</code>```

desired could also be a list of all the lists above.

Body:
l = [a, a, a, b, b, c]

desired1 = [a, a, a]

desired2 = [b, b]

desired3 = [c]

desired could also be a list of all the lists above.

Body:
Slightly more straightforward dict approach

>>> l = [1,2,1,3,4,2,3,1,1,4]
>>> out = {}
>>> for i in set(l):
         out[i] = []
...
>>> for i in l:
...      out[i].append(i)
>>> out
{1: [1, 1, 1, 1], 2: [2, 2], 3: [3, 3], 4: [4, 4]}
>>> out.values()
[[1, 1, 1, 1], [2, 2], [3, 3], [4, 4]]


问:
ExecuteNonQuery() ERROR -> The conversion of the nvarchar value '3955811801' overflowed an int column.
My code is as shown below :

```<code>using (SqlConnection _conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DarmanConnectionString"].ToString()))
{
    using (SqlCommand _cmd = new SqlCommand("dbo.sp_Noskheh_SumOfTotalPay", _conn))
    {
        _cmd.CommandType = CommandType.StoredProcedure;
        _cmd.Parameters.Add(new SqlParameter("@Co_ID", int.Parse(Session["Co_ID"].ToString())));

        _cmd.Parameters.Add(new SqlParameter("@RETURN_VALUE", SqlDbType.NVarChar));
        _cmd.Parameters["@RETURN_VALUE"].Direction = ParameterDirection.ReturnValue;

        _conn.Open();
        _cmd.ExecuteNonQuery();

        Int64 result = Int64.Parse(_cmd.Parameters["@RETURN_VALUE"].Value.ToString());
        lblSumTotalPayShow.Text = result.ToString();

            _conn.Close();
        }
    }
</code>```

my SP is like this :

```<code>create Procedure [dbo].[sp_Noskheh_SumOfTotalPay]
    @Co_ID int
As
    -----------------
    Declare @Sum nvarchar(50)
    -----------------
BEGIN
    Select @Sum = convert(nvarchar(50), SUM(TotalPay))
    From Noskheh
    Where (Co_ID = @Co_ID)

    Return @Sum
END
</code>```

and the error is in line (_cmd.ExecuteNonQuery();):

Error:

Sys.WebForms.PageRequestManagerServerErrorException: The conversion of
  the nvarchar value '3955811801' overflowed an int column. The
  'sp_Noskheh_SumOfTotalPay' procedure attempted to return a status of
  NULL, which is not allowed. A status of 0 will be returned instead.

Would you please help me to figure out this problem?

答:
You are trying to convert a nvarchar value to a int

The Return statement must be an integer.

Try changing your approach and in your Stored Proc do

Select @Sum instead of return @sum

Then instead of using ExecuteNonQuery use ExecuteScalar

```<code>String result = (String)cmd.ExecuteScalar();
lblSumTotalPayShow.Text = result.ToString();
</code>```

Body:
My code is as shown below :

using (SqlConnection _conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DarmanConnectionString"].ToString()))
{
    using (SqlCommand _cmd = new SqlCommand("dbo.sp_Noskheh_SumOfTotalPay", _conn))
    {
        _cmd.CommandType = CommandType.StoredProcedure;
        _cmd.Parameters.Add(new SqlParameter("@Co_ID", int.Parse(Session["Co_ID"].ToString())));

        _cmd.Parameters.Add(new SqlParameter("@RETURN_VALUE", SqlDbType.NVarChar));
        _cmd.Parameters["@RETURN_VALUE"].Direction = ParameterDirection.ReturnValue;

        _conn.Open();
        _cmd.ExecuteNonQuery();

        Int64 result = Int64.Parse(_cmd.Parameters["@RETURN_VALUE"].Value.ToString());
        lblSumTotalPayShow.Text = result.ToString();

            _conn.Close();
        }
    }

my SP is like this :

create Procedure [dbo].[sp_Noskheh_SumOfTotalPay]
    @Co_ID int
As
    -----------------
    Declare @Sum nvarchar(50)
    -----------------
BEGIN
    Select @Sum = convert(nvarchar(50), SUM(TotalPay))
    From Noskheh
    Where (Co_ID = @Co_ID)

    Return @Sum
END

and the error is in line (_cmd.ExecuteNonQuery();):

Error:

Sys.WebForms.PageRequestManagerServerErrorException: The conversion of
  the nvarchar value '3955811801' overflowed an int column. The
  'sp_Noskheh_SumOfTotalPay' procedure attempted to return a status of
  NULL, which is not allowed. A status of 0 will be returned instead.

Would you please help me to figure out this problem?

Body:
You are trying to convert a nvarchar value to a int

The Return statement must be an integer.

Try changing your approach and in your Stored Proc do

Select @Sum instead of return @sum

Then instead of using ExecuteNonQuery use ExecuteScalar

String result = (String)cmd.ExecuteScalar();
lblSumTotalPayShow.Text = result.ToString();

ContentLicense: CC BY-SA 2.5


问:
fit size of parent layout
I have a simple linear layout and want to divide the screen into two equally sized parts.

In the upper one, I want to put a SurfaceView that has exactly the same size as its parent, i.e. half of the screen. Unfortunately, it always either takes all the screen or nothing (depending on the configuration).
Why is that and how can I change it?

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:weightSum="2"
    android:orientation="vertical">

    <LinearLayout android:id="@+id/layoutUpperDaw"
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:background="#192832">

        <com.example.MySurvfaceView
            android:id="@+id/id_mySurfaceView"
            android:layout_width="match_parent"

            android:layout_height="0pt"
            android:layout_weight="1"

            OR

            android:layout_height="match_parent"

            >

        </com.example.MySurvfaceView>

    </LinearLayout>

    <LinearLayout android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:background="#193222">

        ...
    </LinearLayout>
</LinearLayout>
</code>```

答:
When you provide weight you have to set height or weight to 0dp as below.

```<code><LinearLayout android:id="@+id/layoutUpperDaw"
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:background="#192832">
</code>```

and

```<code><com.example.MySurvfaceView
            android:id="@+id/id_mySurfaceView"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            >
</code>```

Update: Answer above is correct about weight usage, make sure either hight or width is 0dp at all places where you used weight.

You don't really need nested LinearLayout. Following should work.

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

        <com.example.MySurvfaceView
            android:id="@+id/id_mySurfaceView"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            >

        </com.example.MySurvfaceView>

    <LinearLayout android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:background="#193222">

    </LinearLayout>
</LinearLayout>
</code>```

Title: fit size of parent layout

Body:
I have a simple linear layout and want to divide the screen into two equally sized parts.

In the upper one, I want to put a SurfaceView that has exactly the same size as its parent, i.e. half of the screen. Unfortunately, it always either takes all the screen or nothing (depending on the configuration).
Why is that and how can I change it?

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:weightSum="2"
    android:orientation="vertical">

    <LinearLayout android:id="@+id/layoutUpperDaw"
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:background="#192832">

        <com.example.MySurvfaceView
            android:id="@+id/id_mySurfaceView"
            android:layout_width="match_parent"

            android:layout_height="0pt"
            android:layout_weight="1"

            OR

            android:layout_height="match_parent"

            >

        </com.example.MySurvfaceView>

    </LinearLayout>

    <LinearLayout android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:background="#193222">

        ...
    </LinearLayout>
</LinearLayout>

Body:
When you provide weight you have to set height or weight to 0dp as below.

<LinearLayout android:id="@+id/layoutUpperDaw"
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:background="#192832">

and

<com.example.MySurvfaceView
            android:id="@+id/id_mySurfaceView"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            >

Update: Answer above is correct about weight usage, make sure either hight or width is 0dp at all places where you used weight.

You don't really need nested LinearLayout. Following should work.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

        <com.example.MySurvfaceView
            android:id="@+id/id_mySurfaceView"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            >

        </com.example.MySurvfaceView>

    <LinearLayout android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:background="#193222">

    </LinearLayout>
</LinearLayout>


问:
Function that counts how often it call another function
I have a 'twice' function that return 2 of the argument passed into it. I also have another function 'runTwice' that counts the number of times it called the 'twice' function (the idea being that I want the 'twice' function to only run 'twice' no matter how often it is called via the 'runTwice' function). Can you please help?

Functions are given below:

var count = 1;

function twice(num){
  return num*2;
}

function runTwice(func){
  if (count<3){
    count++;
    return func;
  } else {
    return 'Function cannot run!';
  }
}

var myFunc = runTwice(twice)

var output = [];

for (var i = 0; i < 3; i++){
  output.push(myFunc(i));
}

console.log(output);```

I would like the output to be [0, 2, 'Function cannot run!'].

I can make this work if I count the 'twice' function directly but I am looking to understand why this doesn't work as presented above.

答:
Just for fun I'll make a generic expireAfter(invocable[, times[, message]]) function:

function expireAfter(invocable, times = 2, message = 'Function cannot run!') {
  return function expires() {
    if (times > 0) {
      times--;

      return invocable.apply(this, arguments);
    }

    return message;
  }
}

function twice(n) {
  return n * 2;
}

var myFunc = expireAfter(twice);

console.log(Array(3)
  .fill()
  .map((_, index) => myFunc(index))
);```

Body:
I have a 'twice' function that return 2 of the argument passed into it. I also have another function 'runTwice' that counts the number of times it called the 'twice' function (the idea being that I want the 'twice' function to only run 'twice' no matter how often it is called via the 'runTwice' function). Can you please help?

Functions are given below:

var count = 1;

function twice(num){
  return num*2;
}

function runTwice(func){
  if (count<3){
    count++;
    return func;
  } else {
    return 'Function cannot run!';
  }
}

var myFunc = runTwice(twice)

var output = [];

for (var i = 0; i < 3; i++){
  output.push(myFunc(i));
}

console.log(output);

I would like the output to be [0, 2, 'Function cannot run!'].

I can make this work if I count the 'twice' function directly but I am looking to understand why this doesn't work as presented above.


问:
Pass class type to a function in Scala
I have a function that has this signature;

```<code>def process[E: TypeTag : ClassTag](id: Int): E = {
</code>```

Normally I would call it like this:

```<code>process[Item](1)
</code>```

I need to call it from the place where the type of the item is stored in a variable.

```<code>tt.tpe.members.collect {
  case m if m.isMethod && m.asMethod.isCaseAccessor => m.asMethod
} foreach { member => {
  // member is a MethodSymbol that can be used to get a type
  // how to call process[??](id) from here?
</code>```

I assume that I have to use reflect or returnType, but how can I pass the generic type?

答:
You can pass typeTag and classTag to the method explicitly, it will infer the type parameter from that:

```<code>process(id)(typeTag, classTag)
</code>```

To figure out how to get TypeTag from Type, see here, and to get ClassTag from TypeTag, look here.
To get Type from member, use member.returnType

Title: Pass class type to a function in Scala

Body:
I have a function that has this signature;

def process[E: TypeTag : ClassTag](id: Int): E = {

Normally I would call it like this:

process[Item](1)

I need to call it from the place where the type of the item is stored in a variable.

tt.tpe.members.collect {
  case m if m.isMethod && m.asMethod.isCaseAccessor => m.asMethod
} foreach { member => {
  // member is a MethodSymbol that can be used to get a type
  // how to call process[??](id) from here?

I assume that I have to use reflect or returnType, but how can I pass the generic type?

Body:
You can pass typeTag and classTag to the method explicitly, it will infer the type parameter from that:

process(id)(typeTag, classTag)

To figure out how to get TypeTag from Type, see here, and to get ClassTag from TypeTag, look here.
To get Type from member, use member.returnType


问:
jQuery flying notifier
I have long page. I want show some info, so when user scroll page, this info will follow by the user.

Is any plugin?

Title: jQuery flying notifier

Body:
http://www.phpletter.com/Demo/Jquery-Floating-Box-Plugin/
http://roshanbh.com.np/examples/floating-message-jquery/
http://amirharel.com/labs/fo/float_demo.html
https://d2o0t5hpnwv4c1.cloudfront.net/018_Floating_Menu/demo/dhtml_float_menu_final_nettut.html


问:
Python convert txt file to JSON stripping and element ordering
I have a txt file that contains data split by spaces such as:

```<code>2017-05-16 00:44:36.151724381 +43.8187 -104.7669 -004.4 00.6 00.2 00.2 090 C
2017-05-16 00:44:36.246672534 +41.6321 -104.7834 +004.3 00.6 00.3 00.2 130 C
2017-05-16 00:44:36.356132768 +46.4559 -104.5989 -004.2 01.1 00.4 00.2 034 C
</code>```

and I would like to convert it into JSON data to something like:

```{"dataset": "Lightning","observation_date": "20170516004436151", "location": { "type": "point", "coordinates": [43.8187, -104.7669]}}
{"dataset": "Lightning","observation_date": "20170516004436246", "location": { "type": "point", "coordinates": [41.6321, -104.7834]}}
{"dataset": "Lightning","observation_date": "20170516004436356", "location": { "type": "point", "coordinates": [46.4559, -104.5989]}}```

where I have to append a 'dataset':'lightning' key/val pair, combine and strip the date and time, and combine the lat/lng into a dict before doing any json conversion.

But right now I still get the date and time elements without being stripped of the "-" and ":" characters like:

```{"observation_date": "2017-05-1600:44:36.151724381", "location": {"type": "point", "coordinates": ["+43.8187", "-104.7669"]}, "dataset": "Lightning"}
{"observation_date": "2017-05-1600:44:36.246672534", "location": {"type": "point", "coordinates": ["+41.6321", "-104.7834"]}, "dataset": "Lightning"}
{"observation_date": "2017-05-1600:44:36.356132768", "location": {"type": "point", "coordinates": ["+46.4559", "-104.5989"]}, "dataset": "Lightning"}```

What I coded so far:

```<code>import json
import sys
def convert(filename):
    dataDict = {}
    txtFile = filename[0]
    print "Opening TXT file: ",txtFile
    infile = open(txtFile, "r")
    for line in infile:
        lineStrip = line.strip()
        parts = [p.strip() for p in lineStrip.split()]
        date = parts[0].strip("-") #trying to get rid of "-" but not working
        time = parts[1].strip(":") #trying to get rid of ":" and "." but not working
        dataDict.update({"dataset":"Lightning"})
        dataDict.update({"observation_date": date + time})
        dataDict.update({"location": {"type":"point", "coordinates": [parts[2], parts[3]]}})
        json_filename = txtFile.split(".")[0]+".json"
        jsonf = open(json_filename,'a')
        data = json.dumps(dataDict)
        jsonf.write(data + "\n")
        print dataDict
    infile.close()
    jsonf.close()
if __name__=="__main__":
    convert(sys.argv[1:])
</code>```

But I'm not sure how to strip the "-", ".", and ":" as well as place the "dataset":"lightning" element in the front.

答:
Python dictionaries are unordered, so you can't specify the "dataset":"lightning" element to be first. For that I would use an OrderedDict instead or sort the json as others have mentioned.

In order to format the time correctly, I'd use a datetime object as such:

```<code>import datetime

date_string = parts[0] + parts[1]
format = "%Y-%d-%m%H:%M:%S.%f"
dt = datetime.strptime(date_string, format)
new_date_string = dt.strftime("%Y%d%m%H%M%S")
</code>```

Using a datetime object is helpful because it plays nicely with pandas and numpy if you continue to work on the data beyond spitting out the json. It also supports mathematical operations and time zone localization if you need it to.

Body:
I have a txt file that contains data split by spaces such as:

2017-05-16 00:44:36.151724381 +43.8187 -104.7669 -004.4 00.6 00.2 00.2 090 C
2017-05-16 00:44:36.246672534 +41.6321 -104.7834 +004.3 00.6 00.3 00.2 130 C
2017-05-16 00:44:36.356132768 +46.4559 -104.5989 -004.2 01.1 00.4 00.2 034 C

and I would like to convert it into JSON data to something like:

{"dataset": "Lightning","observation_date": "20170516004436151", "location": { "type": "point", "coordinates": [43.8187, -104.7669]}}
{"dataset": "Lightning","observation_date": "20170516004436246", "location": { "type": "point", "coordinates": [41.6321, -104.7834]}}
{"dataset": "Lightning","observation_date": "20170516004436356", "location": { "type": "point", "coordinates": [46.4559, -104.5989]}}

where I have to append a 'dataset':'lightning' key/val pair, combine and strip the date and time, and combine the lat/lng into a dict before doing any json conversion.

But right now I still get the date and time elements without being stripped of the "-" and ":" characters like:

{"observation_date": "2017-05-1600:44:36.151724381", "location": {"type": "point", "coordinates": ["+43.8187", "-104.7669"]}, "dataset": "Lightning"}
{"observation_date": "2017-05-1600:44:36.246672534", "location": {"type": "point", "coordinates": ["+41.6321", "-104.7834"]}, "dataset": "Lightning"}
{"observation_date": "2017-05-1600:44:36.356132768", "location": {"type": "point", "coordinates": ["+46.4559", "-104.5989"]}, "dataset": "Lightning"}

What I coded so far:

import json
import sys
def convert(filename):
    dataDict = {}
    txtFile = filename[0]
    print "Opening TXT file: ",txtFile
    infile = open(txtFile, "r")
    for line in infile:
        lineStrip = line.strip()
        parts = [p.strip() for p in lineStrip.split()]
        date = parts[0].strip("-") #trying to get rid of "-" but not working
        time = parts[1].strip(":") #trying to get rid of ":" and "." but not working
        dataDict.update({"dataset":"Lightning"})
        dataDict.update({"observation_date": date + time})
        dataDict.update({"location": {"type":"point", "coordinates": [parts[2], parts[3]]}})
        json_filename = txtFile.split(".")[0]+".json"
        jsonf = open(json_filename,'a')
        data = json.dumps(dataDict)
        jsonf.write(data + "\n")
        print dataDict
    infile.close()
    jsonf.close()
if __name__=="__main__":
    convert(sys.argv[1:])

But I'm not sure how to strip the "-", ".", and ":" as well as place the "dataset":"lightning" element in the front.

Body:
Python dictionaries are unordered, so you can't specify the "dataset":"lightning" element to be first. For that I would use an OrderedDict instead or sort the json as others have mentioned.

In order to format the time correctly, I'd use a datetime object as such:

import datetime

date_string = parts[0] + parts[1]
format = "%Y-%d-%m%H:%M:%S.%f"
dt = datetime.strptime(date_string, format)
new_date_string = dt.strftime("%Y%d%m%H%M%S")

Using a datetime object is helpful because it plays nicely with pandas and numpy if you continue to work on the data beyond spitting out the json. It also supports mathematical operations and time zone localization if you need it to.


问:
C# download file with resume (Content-Range)
Do we have some C# library or class which can download big file by parts and if connection fails resume download?

I have tried use some build-in WebClient class by it doesn't support resume downloading.

```<code>WebClient webClient = new WebClient();
webClient.DownloadFile(link, @"C:\Test\1.zip");
</code>```

Fail with an exception: "Received an unexpected EOF or 0 bytes from the transport stream".

答:
I made some code which download file with resume support.</p>

```<code>    static bool DownloadFileWithRange()
    {
        string link = "http://freelistenonline.com/"; //<- link to some big file
        string FilePath = @"C:\Test\1.zip";

        if (File.Exists(FilePath))
            File.Delete(FilePath);

        long totalBytesRead = 0;
        long MaxContentLength = 0;
        long RequestContentLength = 0;
        int i = 0;
        while (MaxContentLength == 0 || totalBytesRead < MaxContentLength)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(link);

            if (totalBytesRead > 0) request.AddRange(totalBytesRead);

            WebResponse response = request.GetResponse();

            Console.WriteLine("=============== Request #{0} ==================", ++i);
            foreach (var header in response.Headers)
            {
                if (header.ToSaveString().Contains("Content-Length") || header.ToSaveString().Contains("Content-Range"))
                    Console.WriteLine("{0}: {1}", header, response.Headers[header.ToString()]);
            }

            if (response.ContentLength > MaxContentLength)
                MaxContentLength = response.ContentLength;

            var ns = response.GetResponseStream();
            RequestContentLength = 0;
            try
            {
                using (var responseStream = response.GetResponseStream())
                {
                    using (FileStream localFileStream = new FileStream(FilePath, FileMode.Append))
                    {
                        var buffer = new byte[4096];
                        int bytesRead;

                        while ((bytesRead = responseStream.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            totalBytesRead += bytesRead;
                            RequestContentLength += bytesRead;
                            localFileStream.Write(buffer, 0, bytesRead);
                        }

                        Console.WriteLine("Got bytes: {0}", RequestContentLength);
                    }

                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Got bytes: {0}", RequestContentLength);
            }
        }

        if (MaxContentLength == totalBytesRead)
            return true;

        return false;
    }
</code>```

Body:
Do we have some C# library or class which can download big file by parts and if connection fails resume download?

I have tried use some build-in WebClient class by it doesn't support resume downloading.

WebClient webClient = new WebClient();
webClient.DownloadFile(link, @"C:\Test\1.zip");

Fail with an exception: "Received an unexpected EOF or 0 bytes from the transport stream".

Body:
I made some code which download file with resume support.

    static bool DownloadFileWithRange()
    {
        string link = "http://freelistenonline.com/"; //<- link to some big file
        string FilePath = @"C:\Test\1.zip";

        if (File.Exists(FilePath))
            File.Delete(FilePath);

        long totalBytesRead = 0;
        long MaxContentLength = 0;
        long RequestContentLength = 0;
        int i = 0;
        while (MaxContentLength == 0 || totalBytesRead < MaxContentLength)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(link);

            if (totalBytesRead > 0) request.AddRange(totalBytesRead);

            WebResponse response = request.GetResponse();

            Console.WriteLine("=============== Request #{0} ==================", ++i);
            foreach (var header in response.Headers)
            {
                if (header.ToSaveString().Contains("Content-Length") || header.ToSaveString().Contains("Content-Range"))
                    Console.WriteLine("{0}: {1}", header, response.Headers[header.ToString()]);
            }

            if (response.ContentLength > MaxContentLength)
                MaxContentLength = response.ContentLength;

            var ns = response.GetResponseStream();
            RequestContentLength = 0;
            try
            {
                using (var responseStream = response.GetResponseStream())
                {
                    using (FileStream localFileStream = new FileStream(FilePath, FileMode.Append))
                    {
                        var buffer = new byte[4096];
                        int bytesRead;

                        while ((bytesRead = responseStream.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            totalBytesRead += bytesRead;
                            RequestContentLength += bytesRead;
                            localFileStream.Write(buffer, 0, bytesRead);
                        }

                        Console.WriteLine("Got bytes: {0}", RequestContentLength);
                    }

                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Got bytes: {0}", RequestContentLength);
            }
        }

        if (MaxContentLength == totalBytesRead)
            return true;

        return false;
    }


问:
Optimizer Tuning in sklearn Gaussian Process Regressor
I'm attempting to use a GaussianProcessRegressor as part of scikit-learn 0.18.1

I'm training on 200 data points and using 13 input features for my kernel - one constant multiplied by a radial basis function with twelve elements.  The model runs without complaints, but if I run the same script several times I notice that I sometimes get different solutions.  It may be worth noting that several of the optimized parameters are running into the bounds I've provided them (I'm currently working out which features matter).

I've tried increasing the parameter n_restarts_optimizer to 50, and while this takes considerably longer to run it doesn't eliminate the element of apparent randomness.  It seems possible to change the optimizer itself, though I've had no luck.  From a quick scan it seems the most similar syntactically are scipy's fmin_tnc and fmin_slsqp (other optimizers do not include bounds).  However, using either of those cause other issues: for example, fmin_tnc does not return the value of the objective function at its minimum.

Are there any suggestions for how to have a more deterministic script?  Ideally I'd like it to print the same values regardless of iteration, because as it stands it feels a bit like a lottery (and therefore drawing any conclusions is questionable).

A snippet of the code I'm using:

```<code>from sklearn.gaussian_process import GaussianProcessRegressor as GPR
from sklearn.gaussian_process.kernels import RBF, ConstantKernel as C

lbound = 1e-2
rbound = 1e1
n_restarts = 50
n_features = 12 # Actually determined elsewhere in the code
kernel = C(1.0, (lbound,rbound)) * RBF(n_features*[10], (lbound,rbound))
gp = GPR(kernel=kernel, n_restarts_optimizer=n_restarts)
gp.fit(train_input, train_outputs)
test_model, sigma2_pred = gp.predict(test_input, return_std=True)
print gp.kernel_
</code>```

答:
This uses random values to initialize optimization:

As the LML may have multiple local optima, the optimizer can be
  started repeatedly by specifying n_restarts_optimizer.

As far as I understand, there will always be a random factor. Sometimes it will find local minima, which are the bounds you've mentioned.

If your data allows it (invertible X matrix) You can use normal equation if it suits your needs, no random factor there.

You can do (something like a random forest) sampling on top of this, where you run this algorithm several times and choose the best fit or the common value: You will have to weigh consistency versus accuracy.

Hope I understood your question correctly.

ContentLicense: CC BY-SA 4.0

Body:
I'm attempting to use a GaussianProcessRegressor as part of scikit-learn 0.18.1

I'm training on 200 data points and using 13 input features for my kernel - one constant multiplied by a radial basis function with twelve elements.  The model runs without complaints, but if I run the same script several times I notice that I sometimes get different solutions.  It may be worth noting that several of the optimized parameters are running into the bounds I've provided them (I'm currently working out which features matter).

I've tried increasing the parameter n_restarts_optimizer to 50, and while this takes considerably longer to run it doesn't eliminate the element of apparent randomness.  It seems possible to change the optimizer itself, though I've had no luck.  From a quick scan it seems the most similar syntactically are scipy's fmin_tnc and fmin_slsqp (other optimizers do not include bounds).  However, using either of those cause other issues: for example, fmin_tnc does not return the value of the objective function at its minimum.

Are there any suggestions for how to have a more deterministic script?  Ideally I'd like it to print the same values regardless of iteration, because as it stands it feels a bit like a lottery (and therefore drawing any conclusions is questionable).

A snippet of the code I'm using:

from sklearn.gaussian_process import GaussianProcessRegressor as GPR
from sklearn.gaussian_process.kernels import RBF, ConstantKernel as C

lbound = 1e-2
rbound = 1e1
n_restarts = 50
n_features = 12 # Actually determined elsewhere in the code
kernel = C(1.0, (lbound,rbound)) * RBF(n_features*[10], (lbound,rbound))
gp = GPR(kernel=kernel, n_restarts_optimizer=n_restarts)
gp.fit(train_input, train_outputs)
test_model, sigma2_pred = gp.predict(test_input, return_std=True)
print gp.kernel_


问:
Making grid triangular mesh quickly with Numpy
Consider a regular matrix that represents nodes numbered as shown in the figure:

I want to make a list with all the triangles represented in the figure. Which would result in the following 2 dimensional list:[[0,1,4],[1,5,4],[1,2,5],[2,6,5],...,[11,15,14]]

Assuming that the dimensions of the matrix are (NrXNc) ((4X4) in this case), I was able to achieve this result with the following code:

```<code>def MakeFaces(Nr,Nc):
    Nfaces=(Nr-1)*(Nc-1)*2
    Faces=np.zeros((Nfaces,3),dtype=np.int32)
    for r in range(Nr-1):
        for c in range(Nc-1):
            fi=(r*(Nc-1)+c)*2
            l1=r*Nc+c
            l2=l1+1
            l3=l1+Nc
            l4=l3+1
            Faces[fi]=[l1,l2,l3]
            Faces[fi+1]=[l2,l4,l3]
    return Faces
</code>```

However, the double loop operations make this approach quite slow. Is there a way of using numpy in a smart way to do this faster?

答:
We could play a multi-dimensional game based on slicing and multi-dim assignment that are perfect in NumPy environment on efficiency  -

```<code>def MakeFacesVectorized1(Nr,Nc):

    out = np.empty((Nr-1,Nc-1,2,3),dtype=int)

    r = np.arange(Nr*Nc).reshape(Nr,Nc)

    out[:,:, 0,0] = r[:-1,:-1]
    out[:,:, 1,0] = r[:-1,1:]
    out[:,:, 0,1] = r[:-1,1:]

    out[:,:, 1,1] = r[1:,1:]
    out[:,:, :,2] = r[1:,:-1,None]

    out.shape =(-1,3)
    return out
</code>```

Runtime test and verification -

```<code>In [226]: Nr,Nc = 100, 100

In [227]: np.allclose(MakeFaces(Nr, Nc), MakeFacesVectorized1(Nr, Nc))
Out[227]: True

In [228]: %timeit MakeFaces(Nr, Nc)
100 loops, best of 3: 11.9 ms per loop

In [229]: %timeit MakeFacesVectorized1(Nr, Nc)
10000 loops, best of 3: 133 µs per loop

In [230]: 11900/133.0
Out[230]: 89.47368421052632
</code>```

Around 90x speedup for Nr, Nc = 100, 100!

Body:
Consider a regular matrix that represents nodes numbered as shown in the figure:

I want to make a list with all the triangles represented in the figure. Which would result in the following 2 dimensional list:[[0,1,4],[1,5,4],[1,2,5],[2,6,5],...,[11,15,14]]

Assuming that the dimensions of the matrix are (NrXNc) ((4X4) in this case), I was able to achieve this result with the following code:

def MakeFaces(Nr,Nc):
    Nfaces=(Nr-1)*(Nc-1)*2
    Faces=np.zeros((Nfaces,3),dtype=np.int32)
    for r in range(Nr-1):
        for c in range(Nc-1):
            fi=(r*(Nc-1)+c)*2
            l1=r*Nc+c
            l2=l1+1
            l3=l1+Nc
            l4=l3+1
            Faces[fi]=[l1,l2,l3]
            Faces[fi+1]=[l2,l4,l3]
    return Faces

However, the double loop operations make this approach quite slow. Is there a way of using numpy in a smart way to do this faster?

Body:
We could play a multi-dimensional game based on slicing and multi-dim assignment that are perfect in NumPy environment on efficiency  -

def MakeFacesVectorized1(Nr,Nc):

    out = np.empty((Nr-1,Nc-1,2,3),dtype=int)

    r = np.arange(Nr*Nc).reshape(Nr,Nc)

    out[:,:, 0,0] = r[:-1,:-1]
    out[:,:, 1,0] = r[:-1,1:]
    out[:,:, 0,1] = r[:-1,1:]

    out[:,:, 1,1] = r[1:,1:]
    out[:,:, :,2] = r[1:,:-1,None]

    out.shape =(-1,3)
    return out

Runtime test and verification -

In [226]: Nr,Nc = 100, 100

In [227]: np.allclose(MakeFaces(Nr, Nc), MakeFacesVectorized1(Nr, Nc))
Out[227]: True

In [228]: %timeit MakeFaces(Nr, Nc)
100 loops, best of 3: 11.9 ms per loop

In [229]: %timeit MakeFacesVectorized1(Nr, Nc)
10000 loops, best of 3: 133 µs per loop

In [230]: 11900/133.0
Out[230]: 89.47368421052632

Around 90x speedup for Nr, Nc = 100, 100!


问:
Load Rss Feed from url
Have some problems while loading XMLDocument. When I try to load url it throws exception:

"System.Xml.XmlException: 'Ссылка на необъявленный объект подстановки "raquo"".

What`s wrong?

C# code:

```<code>XmlDocument rssXmlDoc = new XmlDocument();
rssXmlDoc.Load(sourceUrl);

XmlNodeList rssNodes = rssXmlDoc.SelectNodes("rss/channel/item");

foreach (XmlNode item in rssNodes)
{
    XmlNode rssSubNodeTitle = item.SelectSingleNode("title");
    string title = rssSubNodeTitle != null ? rssSubNodeTitle.InnerText : "";
    Console.WriteLine(title);
}
</code>```

答:
Making a few changes to your code and providing the correct URL RSS you can have these results:

```<code>String url = "https://keddr.com/feed/";
XmlReader reader = XmlReader.Create(url);
SyndicationFeed feed = SyndicationFeed.Load(reader);
reader.Close();

foreach (SyndicationItem item in feed.Items)
{
    Console.WriteLine("Title: " + item.Title.Text);
    Console.WriteLine("Publish Date:" + item.PublishDate.ToString("MM/dd/yyyy HH:mm:ss"));
    Console.WriteLine("Link: " + item.Links[0].GetAbsoluteUri().ToString());
    Console.WriteLine(item.Summary.Text");
}
</code>```

I'll show here only the first result, but, you'll get the idea:

```<code>Title: Собираем новый ПК – выпуск 1
Publish Date:  07/05/2017 17:10:10
Link: https://keddr.com/2017/07/sobiraem-novyiy-pk-vyipusk-1/
// This is the body of the feed:
А вот и новый многосерийный проект на Кеддре! На этот раз мы сняли САМУЮ геморную […]
</code>```

Title: Load Rss Feed from url

Body:
Have some problems while loading XMLDocument. When I try to load url it throws exception:

"System.Xml.XmlException: 'Ссылка на необъявленный объект подстановки "raquo"".

What`s wrong?

C# code:

XmlDocument rssXmlDoc = new XmlDocument();
rssXmlDoc.Load(sourceUrl);

XmlNodeList rssNodes = rssXmlDoc.SelectNodes("rss/channel/item");

foreach (XmlNode item in rssNodes)
{
    XmlNode rssSubNodeTitle = item.SelectSingleNode("title");
    string title = rssSubNodeTitle != null ? rssSubNodeTitle.InnerText : "";
    Console.WriteLine(title);
}

Body:
Making a few changes to your code and providing the correct URL RSS you can have these results:

String url = "https://keddr.com/feed/";
XmlReader reader = XmlReader.Create(url);
SyndicationFeed feed = SyndicationFeed.Load(reader);
reader.Close();

foreach (SyndicationItem item in feed.Items)
{
    Console.WriteLine("Title: " + item.Title.Text);
    Console.WriteLine("Publish Date:" + item.PublishDate.ToString("MM/dd/yyyy HH:mm:ss"));
    Console.WriteLine("Link: " + item.Links[0].GetAbsoluteUri().ToString());
    Console.WriteLine(item.Summary.Text");
}

I'll show here only the first result, but, you'll get the idea:

Title: Собираем новый ПК – выпуск 1
Publish Date:  07/05/2017 17:10:10
Link: https://keddr.com/2017/07/sobiraem-novyiy-pk-vyipusk-1/
// This is the body of the feed:
А вот и новый многосерийный проект на Кеддре! На этот раз мы сняли САМУЮ геморную [&#8230;]


问:
Enable and disable onkeydown event?
Hi I am trying to start off with the keys enable and then once a button is clicked to disable the event this so far works fine, then once the close button is pressed I want to enable the event again this part doesn't work I'd like to solve this using javascript if possible my close button is in another html (project1.html) file and is loaded via Ajax here is my code:

```<code>var enable_keydown = document.onkeydown;

$(".open-project").click(function(){
document.onkeydown = null;
});

$("#project_close").click(function(){
document.onkeydown = enable_keydown;
});

document.onkeydown = function(e) {
    switch (e.keyCode) {
        case 37:
             $.fn.fullpage.moveSectionUp();
            break;
        case 38:
             $.fn.fullpage.moveSectionUp();
            break;
        case 39:
             $.fn.fullpage.moveSectionDown();
            break;
        case 40:
             $.fn.fullpage.moveSectionDown();
            break;
    }
};
</code>```

Kind Regards

答:
To remove event listener your function can't be anonymous so that you can reference it later. So define your function:

```<code>function moveSection(e) {
    switch (e.keyCode) {
        case 37:
        case 38:
             $.fn.fullpage.moveSectionUp();
            break;
        case 39:
        case 40:
             $.fn.fullpage.moveSectionDown();
            break;
        default:
            break;
    }
}
</code>```

Add it to event listener:

```<code>$(".open-project").click(function(){
    document.addEventListener('keydown', moveSection);
});
</code>```

And remove it:

```<code>$("#project_close").click(function(){
    document.removeEventListener('keydown', moveSection);
});
</code>```

See https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener and https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener

What you are doing here

```<code>var enable_keydown = document.onkeydown;

$("#project_close").click(function(){
    document.onkeydown = enable_keydown;
});
</code>```

boils down to document.onkeydown = document.onkeydown which doesn't make sense.

Title: Enable and disable onkeydown event?

Body:
Hi I am trying to start off with the keys enable and then once a button is clicked to disable the event this so far works fine, then once the close button is pressed I want to enable the event again this part doesn't work I'd like to solve this using javascript if possible my close button is in another html (project1.html) file and is loaded via Ajax here is my code:

var enable_keydown = document.onkeydown;

$(".open-project").click(function(){
document.onkeydown = null;
});

$("#project_close").click(function(){
document.onkeydown = enable_keydown;
});

document.onkeydown = function(e) {
    switch (e.keyCode) {
        case 37:
             $.fn.fullpage.moveSectionUp();
            break;
        case 38:
             $.fn.fullpage.moveSectionUp();
            break;
        case 39:
             $.fn.fullpage.moveSectionDown();
            break;
        case 40:
             $.fn.fullpage.moveSectionDown();
            break;
    }
};

Kind Regards

Body:
To remove event listener your function can't be anonymous so that you can reference it later. So define your function:

function moveSection(e) {
    switch (e.keyCode) {
        case 37:
        case 38:
             $.fn.fullpage.moveSectionUp();
            break;
        case 39:
        case 40:
             $.fn.fullpage.moveSectionDown();
            break;
        default:
            break;
    }
}

Add it to event listener:

$(".open-project").click(function(){
    document.addEventListener('keydown', moveSection);
});

And remove it:

$("#project_close").click(function(){
    document.removeEventListener('keydown', moveSection);
});

See https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener and https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener

What you are doing here

var enable_keydown = document.onkeydown;

$("#project_close").click(function(){
    document.onkeydown = enable_keydown;
});

boils down to document.onkeydown = document.onkeydown which doesn't make sense.


问:
Java command line using classpath for Libraries and Manifest file for MainClass
I am able to achieve the following two things already.

Use ManifestFile to define classpath libraries and Main class as below.

manifest-Version: 1.0

Class-Path: lib/log4j-1.2.17.jar

Main-Class: FQNofMainClass

Pass the ClassPath libraries folder and MainClass from Command Line as below.

(java -cp my.jar;lib_folder/* FQNofMainClass)

But now my scenario is to run the .jar file with Classpath libraries in command line and MainClass details inside Manifest File. How do I achieve this?

答: Make your JAR executable (to your OS and user) and then java -jar /path/to/your.jar


问:
Flowplayer pauses at different times with cuepoint
Good morning. I have a Flowplayer video with cuepoints ex [5, 10]. Here, my video starts from 5th second and pauses at 10th second. So it works. However, video sometimes pauses at 9th second and sometimes on 10th second. So it looks like a flowplayer bug.

I'd appreciate a hint or solution, how I can make the video always pause at exact time everytime.

here is the code snippet

```<code>flowplayer(flowplayerObject, {
        hlsjs: {
          xhrSetup: function (xhr) {
            xhr.withCredentials = true;
          }
        },
        swf: ------,
        swfHls: -------,
        clip: {
          cuepoints:[videoStartTime,videoEndTime],
          sources: [
            {type: "application/x-mpegURL", src: -------l},
            {type: "video/mp4", src: -------}
          ]
        }
      }).one("ready", function (e, api, video){
        api.seek(parseInt(videoStartTime));
      }).on("cuepoint", function (e, api, cuepoint) {
         if (cuepoint.index === 1) {
          api.pause();
        };
      }) ;
</code>```

Thank you

答:
I have not used the cuepoints feature of Flowplayer before, but I am familiar with the seek() API function where you specify the time (in seconds) in the video that you would like to seek to.

For the seek function to work properly, your video needs to have a keyframe at every second of the video. I have a feeling cuepoints would have the same requirement.

If you are familiar with ffmpeg, you can use the "force_key_frames" parameter like this way to add a keyframe to every second of the video -

ffmpeg -i input_file_location -force_key_frames "expr:gte(t,n_forced*1)" other_ffmpeg_parameters -y output_file_location

The downside to adding additional keyframes is that your video will occupy more space on the disk, but if you need the video to pause (or) start consistently at the times specified, I can't think of any other way using the HTML5 version of Flowplayer.

Body:
Good morning. I have a Flowplayer video with cuepoints ex [5, 10]. Here, my video starts from 5th second and pauses at 10th second. So it works. However, video sometimes pauses at 9th second and sometimes on 10th second. So it looks like a flowplayer bug.

I'd appreciate a hint or solution, how I can make the video always pause at exact time everytime.

here is the code snippet

flowplayer(flowplayerObject, {
        hlsjs: {
          xhrSetup: function (xhr) {
            xhr.withCredentials = true;
          }
        },
        swf: ------,
        swfHls: -------,
        clip: {
          cuepoints:[videoStartTime,videoEndTime],
          sources: [
            {type: "application/x-mpegURL", src: -------l},
            {type: "video/mp4", src: -------}
          ]
        }
      }).one("ready", function (e, api, video){
        api.seek(parseInt(videoStartTime));
      }).on("cuepoint", function (e, api, cuepoint) {
         if (cuepoint.index === 1) {
          api.pause();
        };
      }) ;

Thank you


问:
Switch statement not processing
I'm attempting to use a switch statement to control flow in my PowerShell script, but the switch isn't being processed at all.  If I run it interactively (highlight + F8 in ISE), it works without a hitch.  I validate the argument, and have tested it thoroughly.  If(){} statements process properly.  Is there some kind of weird bug with switch statements?  Even the Default argument isn't being triggered.

```<code>[CmdletBinding()]
Param(
    [Parameter(Mandatory=$True)]
    [ValidateSet('Install','Uninstall','Verify','Enable','Disable')]
    [String]$Switch
)

**FUNCTIONS**

[Int]$R = 324
Start-Transcript 'Path\ESD.log' -Append -Force

Switch ($Switch)
{
    "VERIFY"    { $R = Verify;    Break }
    "INSTALL"   { $R = Install;   Break }
    "UNINSTALL" { $R = Uninstall; Break }
    "ENABLE"    { $R = Enable;    Break }
    "DISABLE"   { $R = Disable;   Break }
    Default { Write-Host "Unable to match: $Switch" -BackgroundColor Red }
}

Write-Host "Exiting with: $R"
Stop-Transcript
EXIT $R
</code>```

Output:

```<code>PS Path\EnterpriseSiteDiscovery> .\ESD verify
Transcript started, output file is Path\ESD.log
Exiting with: 324
Transcript stopped, output file is Path\ESD.log

PS Path\EnterpriseSiteDiscovery> $LASTEXITCODE
324
</code>```

Content of log:

```<code>**********************
Windows PowerShell transcript start
Start time: 20170705154435
**SYSTEMINFO**
**********************
Transcript started, output file is Path\ESD.log
Exiting with: 324
**********************
Windows PowerShell transcript end
End time: 20170705154436
**********************
</code>```

答:
It turns out when you are inside a Switch construct, the variable
  $Switch value is redefined (presumably by the switch construct itself)
  as an empty variable of type System.Collections.IEnumerator. The value
  is set to $null. This won’t be a problem if you’re not using a
  variable with the name $Switch. Unfortunately I was because I was
  working with a set to Virtual Switches so $Switch seemed like a fair
  choice of variable name.

https://dscottraynsford.wordpress.com/2015/09/08/powershell-dont-of-the-week-switch-in-a-swtich/

Title: Switch statement not processing

Body:
I'm attempting to use a switch statement to control flow in my PowerShell script, but the switch isn't being processed at all.  If I run it interactively (highlight + F8 in ISE), it works without a hitch.  I validate the argument, and have tested it thoroughly.  If(){} statements process properly.  Is there some kind of weird bug with switch statements?  Even the Default argument isn't being triggered.

[CmdletBinding()]
Param(
    [Parameter(Mandatory=$True)]
    [ValidateSet('Install','Uninstall','Verify','Enable','Disable')]
    [String]$Switch
)

**FUNCTIONS**

[Int]$R = 324
Start-Transcript 'Path\ESD.log' -Append -Force

Switch ($Switch)
{
    "VERIFY"    { $R = Verify;    Break }
    "INSTALL"   { $R = Install;   Break }
    "UNINSTALL" { $R = Uninstall; Break }
    "ENABLE"    { $R = Enable;    Break }
    "DISABLE"   { $R = Disable;   Break }
    Default { Write-Host "Unable to match: $Switch" -BackgroundColor Red }
}

Write-Host "Exiting with: $R"
Stop-Transcript
EXIT $R

Output:

PS Path\EnterpriseSiteDiscovery> .\ESD verify
Transcript started, output file is Path\ESD.log
Exiting with: 324
Transcript stopped, output file is Path\ESD.log

PS Path\EnterpriseSiteDiscovery> $LASTEXITCODE
324

Content of log:

**********************
Windows PowerShell transcript start
Start time: 20170705154435
**SYSTEMINFO**
**********************
Transcript started, output file is Path\ESD.log
Exiting with: 324
**********************
Windows PowerShell transcript end
End time: 20170705154436
**********************


问:
Triggering Two Instances of the Same Class - Javascript
I have a menu system where there are two hamburger menus.  I'm trying to work out how to have JS trigger both instances of these menu icons. They both have all have the same classes.

I've tried adding a for loop, to loop through anything with the instance of the classes, but this didn't seem to work, and I'm going around in endless circles now.

With the code below I've kept the index number of the three menu bars in the first hamburger men at zero[0] so that you can see the desired effect of what happens when you click on the top hamburger menu.

I'd like it so that when I click on either hamburger menu the animation of the bars happens on both icons and the state of the blue box changes.

Any help would be amazing.

Codepen link is here: https://codepen.io/emilychews/pen/jwwVam

Code is below.

JAVASCRIPT

```<code>var container = document.getElementsByClassName('container')[0],
    bar1 = document.getElementsByClassName('bar1')[0],
    bar2 = document.getElementsByClassName('bar2')[0],
    bar3 = document.getElementsByClassName('bar3')[0],
    box = document.getElementsByClassName('box')[0],
    openMenu = false; // used for toggle

container.onclick = function(){

  if(openMenu === false) {

    bar1.classList.add("bar1_open");
    bar2.classList.add("bar2_open");
    bar3.classList.add("bar3_open");

    box.classList.add("changeBackground");

    openMenu = true;

  } else {

    bar1.classList.remove("bar1_open");
    bar2.classList.remove("bar2_open");
    bar3.classList.remove("bar3_open");

    box.classList.remove("changeBackground");

    openMenu = false;
  }

};
</code>```

CSS

```<code>* {padding: 0; margin: 0;}
body {height: 200vh; font-family: arial;}
/* red square */
.container {
  margin: 10px;
  width: 100px;
  height: 100px;
  background: red;
  padding: 0px;
  position: relative;
}

/* properties for all menu bar lines */
.bar {
  position: absolute;
  height: 4px;
  width: 60px;
  background: blue;
  left: 20px;
}

/* 1st menu line */
.bar1 {
  position: absolute;
  top: 28px;
  margin: 0 auto;
  transform-origin: top right;
  transition: transform .5s;
}

/* 2nd menu line */
.bar2 {
  position: absolute;
  top: 48px;
  margin: 0 auto;
  transition: opacity 1s;
}

/* 3rd menu line */
.bar3 {
  position: absolute;
  top: 68px;
  margin: 0 auto;
  transform-origin: right bottom;
  transition: transform .5s;
}

.bar1_open{
  transform-origin: top right;
  transform: rotate(-45deg) translate(-7px, -7px);
  transition: transform .5s .1s ease-out ;
}

.bar2_open {
  opacity: 0;
  transition: opacity .2s ease-in;
}

.bar3_open {
  top: 69px;
  transform-origin: right bottom;
  transform: rotate(45deg)  translate(-7px, 7px);
  transition: transform .5s .1s ease-out;
}

.box {
  padding: 10px;
  width: 200px;
  height: 100px;
  background: blue;
  position: absolute;
  left: 300px;
  top: 30px;
  z-index: 99;
  color: white;
  display: flex;
  justify-content: center;
  align-items: center

}

.changeBackground {
  background: red;
}
</code>```

HTML

```<code><div class="container">
  <div class="bar bar1"></div>
  <div class="bar bar2"></div>
  <div class="bar bar3"></div>
</div>

<!-- second hamburger menu button that currently has no JS  -->
<div class="container">
  <div class="bar bar1"></div>
  <div class="bar bar2"></div>
  <div class="bar bar3"></div>
</div>

<div class="box"> This toggles after 1st hamburger menu is clicked</div>
</code>```

答:
I have refined your code to work how you want it, i set the variables to the array of DOM Elements instead of the single one and for loop through them.
EDIT: heres the updated codepen if you'd like to take a look https://codepen.io/anon/pen/LLBEeQ</p>

```<code>var container = document.getElementsByClassName('container'),
    bar1 = document.getElementsByClassName('bar1'),
    bar2 = document.getElementsByClassName('bar2'),
    bar3 = document.getElementsByClassName('bar3'),
    box = document.getElementsByClassName('box')[0],
    openMenu = false; // used for toggle

for(var i=0; i < container.length; i++){
container[i].onclick = function(){

  if(openMenu === false) {
    for(var j = 0;j<bar1.length;j++){
    bar1[j].classList.add("bar1_open");
    bar2[j].classList.add("bar2_open");
    bar3[j].classList.add("bar3_open");
    }
    box.classList.add("changeBackground");

    openMenu = true;

  } else {
  for(var j = 0;j<bar1.length;j++){
    bar1[j].classList.remove("bar1_open");
    bar2[j].classList.remove("bar2_open");
    bar3[j].classList.remove("bar3_open");
  }
    box.classList.remove("changeBackground");

    openMenu = false;
  }

}
};
</code>```

Body:
I have a menu system where there are two hamburger menus.  I'm trying to work out how to have JS trigger both instances of these menu icons. They both have all have the same classes.

I've tried adding a for loop, to loop through anything with the instance of the classes, but this didn't seem to work, and I'm going around in endless circles now.

With the code below I've kept the index number of the three menu bars in the first hamburger men at zero[0] so that you can see the desired effect of what happens when you click on the top hamburger menu.

I'd like it so that when I click on either hamburger menu the animation of the bars happens on both icons and the state of the blue box changes.

Any help would be amazing.

Codepen link is here: https://codepen.io/emilychews/pen/jwwVam

Code is below.

JAVASCRIPT

var container = document.getElementsByClassName('container')[0],
    bar1 = document.getElementsByClassName('bar1')[0],
    bar2 = document.getElementsByClassName('bar2')[0],
    bar3 = document.getElementsByClassName('bar3')[0],
    box = document.getElementsByClassName('box')[0],
    openMenu = false; // used for toggle

container.onclick = function(){

  if(openMenu === false) {

    bar1.classList.add("bar1_open");
    bar2.classList.add("bar2_open");
    bar3.classList.add("bar3_open");

    box.classList.add("changeBackground");

    openMenu = true;

  } else {

    bar1.classList.remove("bar1_open");
    bar2.classList.remove("bar2_open");
    bar3.classList.remove("bar3_open");

    box.classList.remove("changeBackground");

    openMenu = false;
  }

};

CSS

* {padding: 0; margin: 0;}
body {height: 200vh; font-family: arial;}
/* red square */
.container {
  margin: 10px;
  width: 100px;
  height: 100px;
  background: red;
  padding: 0px;
  position: relative;
}

/* properties for all menu bar lines */
.bar {
  position: absolute;
  height: 4px;
  width: 60px;
  background: blue;
  left: 20px;
}

/* 1st menu line */
.bar1 {
  position: absolute;
  top: 28px;
  margin: 0 auto;
  transform-origin: top right;
  transition: transform .5s;
}

/* 2nd menu line */
.bar2 {
  position: absolute;
  top: 48px;
  margin: 0 auto;
  transition: opacity 1s;
}

/* 3rd menu line */
.bar3 {
  position: absolute;
  top: 68px;
  margin: 0 auto;
  transform-origin: right bottom;
  transition: transform .5s;
}

.bar1_open{
  transform-origin: top right;
  transform: rotate(-45deg) translate(-7px, -7px);
  transition: transform .5s .1s ease-out ;
}

.bar2_open {
  opacity: 0;
  transition: opacity .2s ease-in;
}

.bar3_open {
  top: 69px;
  transform-origin: right bottom;
  transform: rotate(45deg)  translate(-7px, 7px);
  transition: transform .5s .1s ease-out;
}

.box {
  padding: 10px;
  width: 200px;
  height: 100px;
  background: blue;
  position: absolute;
  left: 300px;
  top: 30px;
  z-index: 99;
  color: white;
  display: flex;
  justify-content: center;
  align-items: center

}

.changeBackground {
  background: red;
}

HTML

 This toggles after 1st hamburger menu is clicked

Body:
I have refined your code to work how you want it, i set the variables to the array of DOM Elements instead of the single one and for loop through them.
EDIT: heres the updated codepen if you'd like to take a look https://codepen.io/anon/pen/LLBEeQ

var container = document.getElementsByClassName('container'),
    bar1 = document.getElementsByClassName('bar1'),
    bar2 = document.getElementsByClassName('bar2'),
    bar3 = document.getElementsByClassName('bar3'),
    box = document.getElementsByClassName('box')[0],
    openMenu = false; // used for toggle

for(var i=0; i < container.length; i++){
container[i].onclick = function(){

  if(openMenu === false) {
    for(var j = 0;j<bar1.length;j++){
    bar1[j].classList.add("bar1_open");
    bar2[j].classList.add("bar2_open");
    bar3[j].classList.add("bar3_open");
    }
    box.classList.add("changeBackground");

    openMenu = true;

  } else {
  for(var j = 0;j<bar1.length;j++){
    bar1[j].classList.remove("bar1_open");
    bar2[j].classList.remove("bar2_open");
    bar3[j].classList.remove("bar3_open");
  }
    box.classList.remove("changeBackground");

    openMenu = false;
  }

}
};


问:
Most efficient method to groupby on an array of objects
What is the most efficient way to groupby objects in an array?

For example, given this array of objects:

```<code>[
    { Phase: "Phase 1", Step: "Step 1", Task: "Task 1", Value: "5" },
    { Phase: "Phase 1", Step: "Step 1", Task: "Task 2", Value: "10" },
    { Phase: "Phase 1", Step: "Step 2", Task: "Task 1", Value: "15" },
    { Phase: "Phase 1", Step: "Step 2", Task: "Task 2", Value: "20" },
    { Phase: "Phase 2", Step: "Step 1", Task: "Task 1", Value: "25" },
    { Phase: "Phase 2", Step: "Step 1", Task: "Task 2", Value: "30" },
    { Phase: "Phase 2", Step: "Step 2", Task: "Task 1", Value: "35" },
    { Phase: "Phase 2", Step: "Step 2", Task: "Task 2", Value: "40" }
]
</code>```

I’m displaying this information in a table. I’d like to groupby different methods, but I want to sum the values.

I’m using Underscore.js for its groupby function, which is helpful, but doesn’t do the whole trick, because I don’t want them “split up” but “merged”, more like the SQL group by method.

What I’m looking for would be able to total specific values (if requested).

So if I did groupby Phase, I’d want to receive:

```<code>[
    { Phase: "Phase 1", Value: 50 },
    { Phase: "Phase 2", Value: 130 }
]
</code>```

And if I did groupy Phase / Step, I’d receive:

```<code>[
    { Phase: "Phase 1", Step: "Step 1", Value: 15 },
    { Phase: "Phase 1", Step: "Step 2", Value: 35 },
    { Phase: "Phase 2", Step: "Step 1", Value: 55 },
    { Phase: "Phase 2", Step: "Step 2", Value: 75 }
]
</code>```

Is there a helpful script for this, or should I stick to using Underscore.js, and then looping through the resulting object to do the totals myself?

答:
Lets generate a generic Array.prototype.groupBy() tool. Just for variety let's use ES6 fanciness the spread operator for some Haskellesque pattern matching on a recursive approach. Also let's make our Array.prototype.groupBy() to accept a callback which takes the item (e) the index (i) and the applied array (a) as arguments.

Array.prototype.groupBy = function(cb){
                            return function iterate([x,...xs], i = 0, r = [[],[]]){
                                     cb(x,i,[x,...xs]) ? (r[0].push(x), r)
                                                       : (r[1].push(x), r);
                                     return xs.length ? iterate(xs, ++i, r) : r;
                                   }(this);
                          };

var arr = [0,1,2,3,4,5,6,7,8,9],
    res = arr.groupBy(e => e < 5);
console.log(res);```

Body:
What is the most efficient way to groupby objects in an array?

For example, given this array of objects:

[
    { Phase: "Phase 1", Step: "Step 1", Task: "Task 1", Value: "5" },
    { Phase: "Phase 1", Step: "Step 1", Task: "Task 2", Value: "10" },
    { Phase: "Phase 1", Step: "Step 2", Task: "Task 1", Value: "15" },
    { Phase: "Phase 1", Step: "Step 2", Task: "Task 2", Value: "20" },
    { Phase: "Phase 2", Step: "Step 1", Task: "Task 1", Value: "25" },
    { Phase: "Phase 2", Step: "Step 1", Task: "Task 2", Value: "30" },
    { Phase: "Phase 2", Step: "Step 2", Task: "Task 1", Value: "35" },
    { Phase: "Phase 2", Step: "Step 2", Task: "Task 2", Value: "40" }
]

I’m displaying this information in a table. I’d like to groupby different methods, but I want to sum the values.

I’m using Underscore.js for its groupby function, which is helpful, but doesn’t do the whole trick, because I don’t want them “split up” but “merged”, more like the SQL group by method.

What I’m looking for would be able to total specific values (if requested).

So if I did groupby Phase, I’d want to receive:

[
    { Phase: "Phase 1", Value: 50 },
    { Phase: "Phase 2", Value: 130 }
]

And if I did groupy Phase / Step, I’d receive:

[
    { Phase: "Phase 1", Step: "Step 1", Value: 15 },
    { Phase: "Phase 1", Step: "Step 2", Value: 35 },
    { Phase: "Phase 2", Step: "Step 1", Value: 55 },
    { Phase: "Phase 2", Step: "Step 2", Value: 75 }
]

Is there a helpful script for this, or should I stick to using Underscore.js, and then looping through the resulting object to do the totals myself?


问:
Expected singleton odoo 9
After enter 2 and more new row in tree view and click on save get error

```<code>  raise ValueError("Expected singleton: %s" % self)
ValueError: Expected singleton: my.model(2116, 2117)
</code>```

My source code:

```<code>@api.depends('start', 'finish','stop')
def total_fun(self):
    time1 = datetime.strptime(self.start, "%Y-%m-%d %H:%M:%S")
    time2 = datetime.strptime(self.finish, "%Y-%m-%d %H:%M:%S")
    self.total = round(((time2 - time1).seconds / float(60*60) - self.stop))
</code>```

答:
As you can see in the error message Expected singleton: my.model(2116, 2117)

By default in odoo the self is always a recordSet (means it can contain more then one record.) so when you do self.getSomeField here odoo will be confused wich record you want to get the value from.

if you don't tell odoo that make sure that the self will always contain one record when you acces an attribute if the recordSet contains more than one record this error is raised.

Now how to tell odoo make sure there is always one record is by adding @api.one decorator to the method. but is not recommended because odoo in your case there is two record so he will loop and call the method for each record and pass a recordSet that have only that record. imagine that you execute a search or any communication with database.

so don't use @api.one only if you are sure of what you are doing because you can make 10000 method call and interact with database.

like this example using @api.one:

```<code>   # every call to this method you will execute a search.
   self.env['some.model'].search([('m2o_id' , '=', self.id)]
</code>```

you can do this before the loop:

```<code>  # one query for all record with one call to the method
  result = self.env['some.model'].search([('m2o_id' , 'in', self.ids)]
  for rec in self:
      # use result here
  # or here ..
</code>```

Title: Expected singleton odoo 9

Body:
After enter 2 and more new row in tree view and click on save get error

  raise ValueError("Expected singleton: %s" % self)
ValueError: Expected singleton: my.model(2116, 2117)

My source code:

@api.depends('start', 'finish','stop')
def total_fun(self):
    time1 = datetime.strptime(self.start, "%Y-%m-%d %H:%M:%S")
    time2 = datetime.strptime(self.finish, "%Y-%m-%d %H:%M:%S")
    self.total = round(((time2 - time1).seconds / float(60*60) - self.stop))

Body:
As you can see in the error message Expected singleton: my.model(2116, 2117)

By default in odoo the self is always a recordSet (means it can contain more then one record.) so when you do self.getSomeField here odoo will be confused wich record you want to get the value from.

if you don't tell odoo that make sure that the self will always contain one record when you acces an attribute if the recordSet contains more than one record this error is raised.

Now how to tell odoo make sure there is always one record is by adding @api.one decorator to the method. but is not recommended because odoo in your case there is two record so he will loop and call the method for each record and pass a recordSet that have only that record. imagine that you execute a search or any communication with database.

so don't use @api.one only if you are sure of what you are doing because you can make 10000 method call and interact with database.

like this example using @api.one:

   # every call to this method you will execute a search.
   self.env['some.model'].search([('m2o_id' , '=', self.id)]

you can do this before the loop:

  # one query for all record with one call to the method
  result = self.env['some.model'].search([('m2o_id' , 'in', self.ids)]
  for rec in self:
      # use result here
  # or here ..


问:
Difference between Graph Transform Tool and scripts in python/tools?
I want to deploy trained models for inference and need to convert tf.Variable into tf.constant, and strip any unused graph nodes.

What's the difference between these two toolsets? They look like they serve the same purpose. Which one should I rely on?

https://github.com/tensorflow/tensorflow/tree/master/tensorflow/tools/graph_transforms

https://github.com/tensorflow/tensorflow/tree/master/tensorflow/python/tools

答: The Graph Transform Tool is a more modern replacement for the older Python scripts.</p>


问:
Should the Bootstrap media queries be saved in a css file or a js file?
I am using media queries for screen sizing, and I need help embedding the file into my HTML document. So, help?</p>

```<code><link rel="stylesheet" href="style.css" /> //This?
<script src="style.js"></script> //Or This?
</code>```

答:
As indicate precedently, the media queries must be into a css file.

Documentation for media queries

For exemple for style a div element for responsive design :

```<code>@media (max-width: 700px){

    div{
      //For smartphone
    }
}
@media ( min-width: 701px and max-width: 900px{

    div{
        //For tablet
    }
}
@media ( min-width: 901px and max-width: 1200px{
    div{
        //For small destop
    }
}
@media ( min-width: 1201px){
    div{
        //For large desktop
    }
}
</code>```

Body:
I am using media queries for screen sizing, and I need help embedding the file into my HTML document. So, help?

<link rel="stylesheet" href="style.css" /> //This?
 //Or This?

Body:
As indicate precedently, the media queries must be into a css file.

Documentation for media queries

For exemple for style a div element for responsive design :

@media (max-width: 700px){

    div{
      //For smartphone
    }
}
@media ( min-width: 701px and max-width: 900px{

    div{
        //For tablet
    }
}
@media ( min-width: 901px and max-width: 1200px{
    div{
        //For small destop
    }
}
@media ( min-width: 1201px){
    div{
        //For large desktop
    }
}


问:
How would you separate a list into sublists of all the duplicates in the original?
```<code>l = [a, a, a, b, b, c]

desired1 = [a, a, a]

desired2 = [b, b]

desired3 = [c]
</code>```

desired could also be a list of all the lists above.

答:
Another option using Counter :)

```<code>from collections import Counter
l = ['a', 'a', 'a', 'b', 'b', 'c']
c = Counter(l)
result = [ [k]*v for k, v in c.items() ]
</code>```

Body:
l = [a, a, a, b, b, c]

desired1 = [a, a, a]

desired2 = [b, b]

desired3 = [c]

desired could also be a list of all the lists above.

Body:
Another option using Counter :)

from collections import Counter
l = ['a', 'a', 'a', 'b', 'b', 'c']
c = Counter(l)
result = [ [k]*v for k, v in c.items() ]


问:
When using cloud-init, is it possible to both specify a boot script and a data blob that can be queried from inside the instance?
I have some current instances that get some data by passing a json blob through the user data string. I would like to also pass a script to be run at boot time through the user data. Is there a way to do both of these things? I've looked at cloud-config, but setting an arbitrary value doesn't seem to be one of the options.</p>

答: Well, cloud-init supports multi-part MIME. With that in mind you could have your boot script as one part, then a custom mime part. Note that you would need to write a python handler that tells cloud-init what to do with that part (most likely moving it to wherever your app expects it). This handler code ends up in the handlers directory as described here.


问:
How to copy and paste a range from one workbook to another more efficiently in VBA?
I have figured out how to copy and paste from one workbook to another but it is not the most efficient. I want to copy a range from one workbook and paste it in cell A3 in a second workbook. Here is my code (I have set all my variables, I just did not include it in this question):

```<code>Dim wb1 As Workbook
Dim wb2 As Workbook
Dim wb1s1 As Worksheet
Dim wb1s2 As Worksheet
Dim wb2s1 As Worksheet
Dim wb2s2 As Worksheet

    wb1.Activate
       With wb1s1
        .Range(.Range("A14"), .Range("F" & .Rows.Count)).Copy
      End With

    wb2.Activate
        With wb2s1
       .Range("A3").PasteSpecial xlPasteAll
      End With

    wb1.Activate
      With wb1s2
        .Range(.Range("A14"), .Range("F" & .Rows.Count)).Copy
       End With

    wb2.Activate
       With wb2s2
       .Range("A3").PasteSpecial xlPasteAll
       End With
</code>```

Now, I have tried this line of code to increase its efficiency but it is not working for me.

```<code>wb1.wb1s1.Range("A14", ("F" & Rows.Count)).Copy Destination:=wb2.wb2s1.Range("A3")
</code>```

I get the error "Object doesn't support this Property or Method". Any help would be greatly appreciated.

答:
I guess you should not double reference the Worksheet.

try

```<code>wb1s1.Range("A14", ("F" & Rows.Count)).Copy Destination:=wb2s1.Range("A3")
</code>```

The workbook wb1 does not support the "Property or Method" wb1s1, nor does wb2 support wb2s1

Body:
I have figured out how to copy and paste from one workbook to another but it is not the most efficient. I want to copy a range from one workbook and paste it in cell A3 in a second workbook. Here is my code (I have set all my variables, I just did not include it in this question):

Dim wb1 As Workbook
Dim wb2 As Workbook
Dim wb1s1 As Worksheet
Dim wb1s2 As Worksheet
Dim wb2s1 As Worksheet
Dim wb2s2 As Worksheet

    wb1.Activate
       With wb1s1
        .Range(.Range("A14"), .Range("F" & .Rows.Count)).Copy
      End With

    wb2.Activate
        With wb2s1
       .Range("A3").PasteSpecial xlPasteAll
      End With

    wb1.Activate
      With wb1s2
        .Range(.Range("A14"), .Range("F" & .Rows.Count)).Copy
       End With

    wb2.Activate
       With wb2s2
       .Range("A3").PasteSpecial xlPasteAll
       End With

Now, I have tried this line of code to increase its efficiency but it is not working for me.

wb1.wb1s1.Range("A14", ("F" & Rows.Count)).Copy Destination:=wb2.wb2s1.Range("A3")

I get the error "Object doesn't support this Property or Method". Any help would be greatly appreciated.

Body:
I guess you should not double reference the Worksheet.

try

wb1s1.Range("A14", ("F" & Rows.Count)).Copy Destination:=wb2s1.Range("A3")

The workbook wb1 does not support the "Property or Method" wb1s1, nor does wb2 support wb2s1


问:
tkinter class composition not working
My intention is to create gui from several classes and as exercise I created small example. As can be seen in app self.greet should be button created from class Button, but what I get is generic button (without text and callback function).
Any suggestions?</p>

```<code>import tkinter as tk
import tkinter.ttk as ttk

class Button(ttk.Button):

    def __init__(self, parent):
        super().__init__(parent)

        self.item = ttk.Button(parent, text="Greet", command=self.greet)

    def greet(self):
        print("Greetings!")

class App():

    def __init__(self, parent):
        parent.title("A simple GUI")

        self.label = ttk.Label(parent, text="A label")
        self.greet = Button(parent)
        self.button = ttk.Button(parent, text="Close", command=parent.quit)

        self.label.grid(row=0, column=0, sticky=(tk.N, tk.S, tk.W, tk.E))
        self.greet.grid(row=1, column=0, sticky=(tk.N, tk.S, tk.W, tk.E))
        self.button.grid(row=2, column=0, sticky=(tk.N, tk.S, tk.W, tk.E))

        parent.grid_columnconfigure(0, weight=1)

    def greet(self):
        print("Greetings!")

if __name__ == "__main__":
    root = tk.Tk()
    app = App(root)
    root.mainloop()
</code>```

答:
Instances of your class Button are indeed just generic buttons with no text or callback.  Each one contains (via their self.item attribute) a fancier button, but that button is never actually visible to the user because you never pack or grid it.

Basically, the parameters you're passing to the ttk.Button() call should instead be passed in the super().__init__() call, so that they affect the Button object itself.

Title: tkinter class composition not working

Body:
My intention is to create gui from several classes and as exercise I created small example. As can be seen in app self.greet should be button created from class Button, but what I get is generic button (without text and callback function).
Any suggestions?

import tkinter as tk
import tkinter.ttk as ttk

class Button(ttk.Button):

    def __init__(self, parent):
        super().__init__(parent)

        self.item = ttk.Button(parent, text="Greet", command=self.greet)

    def greet(self):
        print("Greetings!")

class App():

    def __init__(self, parent):
        parent.title("A simple GUI")

        self.label = ttk.Label(parent, text="A label")
        self.greet = Button(parent)
        self.button = ttk.Button(parent, text="Close", command=parent.quit)

        self.label.grid(row=0, column=0, sticky=(tk.N, tk.S, tk.W, tk.E))
        self.greet.grid(row=1, column=0, sticky=(tk.N, tk.S, tk.W, tk.E))
        self.button.grid(row=2, column=0, sticky=(tk.N, tk.S, tk.W, tk.E))

        parent.grid_columnconfigure(0, weight=1)

    def greet(self):
        print("Greetings!")

if __name__ == "__main__":
    root = tk.Tk()
    app = App(root)
    root.mainloop()


问:
Php send 0 bytes excel file through echo
I am creating a very large table in a single string $output with the data from a MySQL database. In end of the php script, I send two headers:

```<code>header("Content-type: application/msexcel");
header("Content-Disposition: attachment; filename=action.xls");
</code>```

The problem is when the large table has about more than 55000 rows. When this happens, the file sent is 0 bytes and the user opens a empty file. I am sending the file through this after the headers:

```<code>echo $output;
</code>```

When the table has not too many rows, the file sent work. How to send a file in this way that the size of the string $output don't matter?

答:
```<code>header("Content-type: application/msexcel");
header("Content-Disposition: attachment; filename=action.xls");
</code>```

Move these lines to the top the page or Script before html table it will starts working

Body:
I am creating a very large table in a single string $output with the data from a MySQL database. In end of the php script, I send two headers:

header("Content-type: application/msexcel");
header("Content-Disposition: attachment; filename=action.xls");

The problem is when the large table has about more than 55000 rows. When this happens, the file sent is 0 bytes and the user opens a empty file. I am sending the file through this after the headers:

echo $output;

When the table has not too many rows, the file sent work. How to send a file in this way that the size of the string $output don't matter?

Body:
header("Content-type: application/msexcel");
header("Content-Disposition: attachment; filename=action.xls");

Move these lines to the top the page or Script before html table it will starts working


问:
Angular return value promise function
i have the following function, which i would like to return the value. It doesnt return anything. Im starting with Angular, so this is new for me.. how can i fix it?

```<code>        function GetAuth2Token(device)
        {
           QRC.setTargetIpAddress(device.ip, device.index);
           QRC.getToken(vm.current_password ||'12345678', device.index).then(sucFn);
        function sucFn(data) {
            QRC.setTargetAuthToken(data.data.access_token);
            return data.data.access_token;
        }
    }
</code>```

And then, when i call the function:

```<code>                var access_token = GetAuth2Token(vm.scannedDevices[i]);
</code>```

But it doesn`t work, it does not return anything.
Thanks

答:
Try like this.</p>

```<code>var access_token;
GetAuth2Token(vm.scannedDevices[i]).then(function(data){
    access_token = data;
});
</code>```

Title: Angular return value promise function

Body:
i have the following function, which i would like to return the value. It doesnt return anything. Im starting with Angular, so this is new for me.. how can i fix it?

        function GetAuth2Token(device)
        {
           QRC.setTargetIpAddress(device.ip, device.index);
           QRC.getToken(vm.current_password ||'12345678', device.index).then(sucFn);
        function sucFn(data) {
            QRC.setTargetAuthToken(data.data.access_token);
            return data.data.access_token;
        }
    }

And then, when i call the function:

                var access_token = GetAuth2Token(vm.scannedDevices[i]);

But it doesn`t work, it does not return anything.
Thanks

Body:
Try like this.

var access_token;
GetAuth2Token(vm.scannedDevices[i]).then(function(data){
    access_token = data;
});


问:
MySQL AUTO_INCREMENT does not ROLLBACK
I'm using MySQL's AUTO_INCREMENT field and InnoDB to support transactions. I noticed when I rollback the transaction, the AUTO_INCREMENT field is not rollbacked? I found out that it was designed this way but are there any workarounds to this? </p>

答:
Why do you care if it is rolled back?  AUTO_INCREMENT key fields are not supposed to have any meaning so you really shouldn't care what value is used.

If you have information you're trying to preserve, perhaps another non-key column is needed.

OwnerDisplayName: Gian Paulo

Title: MySQL AUTO_INCREMENT does not ROLLBACK

OwnerDisplayName: Paul Lefebvre


问:
How to use TypeToken + generics with Gson in Kotlin
I'm unable to get a List of generic type from a custom class (Turns):

```<code>val turnsType = TypeToken<List<Turns>>() {}.type
val turns = Gson().fromJson(pref.turns, turnsType)
</code>```

it said:

```<code>cannot access '<init>' it is 'public /*package*/' in 'TypeToken'
</code>```

答:
This works as well, and is simpler</p>

```<code>    inline fun <reified T> Gson.fromJson(json: String) : T =
         this.fromJson<T>(json, T::class.java)
</code>```

Body:
I'm unable to get a List of generic type from a custom class (Turns):

val turnsType = TypeToken<List<Turns>>() {}.type
val turns = Gson().fromJson(pref.turns, turnsType)

it said:

cannot access '<init>' it is 'public /*package*/' in 'TypeToken'

Body:
This works as well, and is simpler

    inline fun <reified T> Gson.fromJson(json: String) : T =
         this.fromJson<T>(json, T::class.java)


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

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

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

I'm talking German addresses...
Thanks!

答:
In the USA, you can use USPS Address Standardization Web Tool. It verifies and normalizes addresses for you. This way, you can normalize the address before checking if it already exists in the database. If all the addresses in the database are already normalized, you'll be able to spot duplicates easily.

Sample URL:

https://production.shippingapis.com/ShippingAPI.dll?API=Verify&XML=insert_request_XML_here

Sample request:

```<code><AddressValidateRequest USERID="XXXXX">
  <IncludeOptionalElements>true</IncludeOptionalElements>
  <ReturnCarrierRoute>true</ReturnCarrierRoute>
  <Address ID="0">
    <FirmName />
    <Address1 />
    <Address2>205 bagwell ave</Address2>
    <City>nutter fort</City>
    <State>wv</State>
    <Zip5></Zip5>
    <Zip4></Zip4>
  </Address>
</AddressValidateRequest>
</code>```

Sample response:

```<code><AddressValidateResponse>
  <Address ID="0">
    <Address2>205 BAGWELL AVE</Address2>
    <City>NUTTER FORT</City>
    <State>WV</State>
    <Zip5>26301</Zip5>
    <Zip4>4322</Zip4>
    <DeliveryPoint>05</DeliveryPoint>
    <CarrierRoute>C025</CarrierRoute>
  </Address>
</AddressValidateResponse>
</code>```

Other countries might have their own APIs. Other people mentioned 3rd party APIs that support multiple countries that might be useful in some cases.

OwnerDisplayName: Johannes

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

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

Quellenstrasse 66/11
Quellenstr. 66a-11

I'm talking German addresses...
Thanks!

LastEditorDisplayName: Remou

Body:
In the USA, you can use USPS Address Standardization Web Tool. It verifies and normalizes addresses for you. This way, you can normalize the address before checking if it already exists in the database. If all the addresses in the database are already normalized, you'll be able to spot duplicates easily.

Sample URL:

https://production.shippingapis.com/ShippingAPI.dll?API=Verify&XML=insert_request_XML_here

Sample request:

<AddressValidateRequest USERID="XXXXX">
  <IncludeOptionalElements>true</IncludeOptionalElements>
  <ReturnCarrierRoute>true</ReturnCarrierRoute>
  <Address ID="0">
    <FirmName />
    <Address1 />
    <Address2>205 bagwell ave</Address2>
    <City>nutter fort</City>
    <State>wv</State>
    <Zip5></Zip5>
    <Zip4></Zip4>
  </Address>
</AddressValidateRequest>

Sample response:

<AddressValidateResponse>
  <Address ID="0">
    <Address2>205 BAGWELL AVE</Address2>
    <City>NUTTER FORT</City>
    <State>WV</State>
    <Zip5>26301</Zip5>
    <Zip4>4322</Zip4>
    <DeliveryPoint>05</DeliveryPoint>
    <CarrierRoute>C025</CarrierRoute>
  </Address>
</AddressValidateResponse>

Other countries might have their own APIs. Other people mentioned 3rd party APIs that support multiple countries that might be useful in some cases.


问:
how to use sinon js with Express js unit testing
Hi i want to do unit testing on my express js code i want to mock data so after searching multiple websites and blogs i found this library but i am not clear how can i use this library for mocking or data.
My testing code is

```<code>var request = require('supertest');
var server = require('./app');
var chai = require('chai');
var chaiHttp = require('chai-http');

var server = require('./app');

var should = chai.should();
chai.use(chaiHttp);

describe('loading express', function () {

  it('responds to /', function testSlash(done) {
    request(server)
      .get('/')
      .expect(200, done);
  });

  it('404 everything else', function testPath(done) {
    request(server)
      .get('/foo/bar')
      .expect(404, done);
  });

  it('responds to /customers/getCustomerData', function testPath(done) {
    request(server)
      .get('/customers/getCustomerData?id=0987654321')
      .end(function(err, res){
        res.should.have.status(200);
        res.body.should.be.a('object');
        res.body.status.should.equal("success");
        res.body.data.customerId.should.equal("0987654321");

        done();
      });
  });

});
</code>```

Currently this code is fetching data from database but i want Unit testing using mock data. How can i achieve this?

__EDIT__

I want to test the code which is written inside Express js routes file. this routes i am calling inside app.js file like this

```<code>var customers = require('./routes/customers');
app.use('/customers', customers);
</code>```

now the code which customers route file contain is

```<code>function getCustomerData(req, res, next) {
    var response = {};
    var cb = function (response) {
        res.send(response);
    }
    var modelObj = req.models.customer_master;
    var data = req.query;
    controllers.customers.get(modelObj, data, cb);
};
router.get('/getCustomerData', function (req, res, next) {
    getCustomerData(req, res, next);
});
</code>```

I want to test the response of "get" method using mock data

答:
If you wish to mock, you can use sinon express mocks here or if you want to test the actual response data, JSON, use this example

The express route, in the example, takes a parameter and returns a JSON

```<code>it('should respond with JSON data', function (done) {
  request(server)
    .get('/about/jv')
    .expect(200)
    .end(function (err, response) {
      assert.equal(response.header['content-type'], 'application/json; charset=utf-8');
      assert.deepEqual(response.body, {
        "data":{
        "username":"hellojv"}
      });
      done();
    });
</code>```

but as mentioned above, if you want to use sinon then use the mock library. The example uses Mocha and supertest.

Body:
Hi i want to do unit testing on my express js code i want to mock data so after searching multiple websites and blogs i found this library but i am not clear how can i use this library for mocking or data.
My testing code is

var request = require('supertest');
var server = require('./app');
var chai = require('chai');
var chaiHttp = require('chai-http');

var server = require('./app');

var should = chai.should();
chai.use(chaiHttp);

describe('loading express', function () {

  it('responds to /', function testSlash(done) {
    request(server)
      .get('/')
      .expect(200, done);
  });

  it('404 everything else', function testPath(done) {
    request(server)
      .get('/foo/bar')
      .expect(404, done);
  });

  it('responds to /customers/getCustomerData', function testPath(done) {
    request(server)
      .get('/customers/getCustomerData?id=0987654321')
      .end(function(err, res){
        res.should.have.status(200);
        res.body.should.be.a('object');
        res.body.status.should.equal("success");
        res.body.data.customerId.should.equal("0987654321");

        done();
      });
  });

});

Currently this code is fetching data from database but i want Unit testing using mock data. How can i achieve this?

__EDIT__

I want to test the code which is written inside Express js routes file. this routes i am calling inside app.js file like this

var customers = require('./routes/customers');
app.use('/customers', customers);

now the code which customers route file contain is

function getCustomerData(req, res, next) {
    var response = {};
    var cb = function (response) {
        res.send(response);
    }
    var modelObj = req.models.customer_master;
    var data = req.query;
    controllers.customers.get(modelObj, data, cb);
};
router.get('/getCustomerData', function (req, res, next) {
    getCustomerData(req, res, next);
});

I want to test the response of "get" method using mock data

Body:
If you wish to mock, you can use sinon express mocks here or if you want to test the actual response data, JSON, use this example

The express route, in the example, takes a parameter and returns a JSON

it('should respond with JSON data', function (done) {
  request(server)
    .get('/about/jv')
    .expect(200)
    .end(function (err, response) {
      assert.equal(response.header['content-type'], 'application/json; charset=utf-8');
      assert.deepEqual(response.body, {
        "data":{
        "username":"hellojv"}
      });
      done();
    });

but as mentioned above, if you want to use sinon then use the mock library. The example uses Mocha and supertest.


问:
Running Selenium Tests through Linux Server
This is a general question, but I want to run my Selenium tests on a cloud Linux Server. I am accessing this server using PuTTY, which is just a terminal.

I was wondering how I could get my Selenium scripts to run on this VM.

Currently I have a Selenium Grid set up with physical machines, I just do not know how to set one up through a server where the only communication I have with it is through PuTTY and a terminal.

答: You can also use PhantomJS to do a headless Automation, that doesn't need any GUI installation on Server.</p>


问:
Modal works, until duplicated
I have a javascript modal that I created, which works fine, unless there are 2 on the page. When 2 of them exist on the page, the first one will work, but the next ones do now.

Here is the JS that controls it:

```<code>// Get the button that opens the modal
let trigger = document.getElementsByClassName("js-modal")[0];
trigger.onclick = function() {
  modal.style.display = "block";
};

// Get the modal linked with with trigger element
let modal = document.getElementById(
  trigger.href.substring(trigger.href.indexOf("#") + 1)
);

// When the user clicks the button, open the modal
let allClose = modal.getElementsByClassName("js-modal-close");

// All elments linked to the modal can close the modal
for (let i = 0; i < allClose.length; i++) {
  allClose[i].onclick = function() {
    modal.style.display = "none";
  };
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(e) {
  if (e.target == modal) {
     modal.style.display = "none";
  }
};
</code>```

and here is a working example. I've tried messing around with using var instead of let, but not 100% sure on how to scope them to their specific html structures programtically.

答:
Here is a solution, dirty but works
jsfiddle</p>

```<code>var trigger = document.getElementsByClassName("js-modal")[1];
trigger.onclick = function() {
modal.style.display = "block";
};
</code>```

Title: Modal works, until duplicated

Body:
I have a javascript modal that I created, which works fine, unless there are 2 on the page. When 2 of them exist on the page, the first one will work, but the next ones do now.

Here is the JS that controls it:

// Get the button that opens the modal
let trigger = document.getElementsByClassName("js-modal")[0];
trigger.onclick = function() {
  modal.style.display = "block";
};

// Get the modal linked with with trigger element
let modal = document.getElementById(
  trigger.href.substring(trigger.href.indexOf("#") + 1)
);

// When the user clicks the button, open the modal
let allClose = modal.getElementsByClassName("js-modal-close");

// All elments linked to the modal can close the modal
for (let i = 0; i < allClose.length; i++) {
  allClose[i].onclick = function() {
    modal.style.display = "none";
  };
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(e) {
  if (e.target == modal) {
     modal.style.display = "none";
  }
};

and here is a working example. I've tried messing around with using var instead of let, but not 100% sure on how to scope them to their specific html structures programtically.

Body:
Here is a solution, dirty but works
jsfiddle

var trigger = document.getElementsByClassName("js-modal")[1];
trigger.onclick = function() {
modal.style.display = "block";
};


答:
```<code>let trigger = document.getElementsByClassName("js-modal")[0];
</code>```

<p>You are only binding to the first button in your js. Nothing is bound to your second </p>

Title: Modal works, until duplicated

Body:
let trigger = document.getElementsByClassName("js-modal")[0];

You are only binding to the first button in your js. Nothing is bound to your second