问:
How to get value from other selected documents and display value into one document
I have a list of document in view. I also have a button inside view where I can create new document with value from existed document. For this new document, I will use different form for new document created. In my view, document is divide by Status. I also has dialogBox too for me to set batchNo for new documents.

So, the process is like this:

First, I will select document based on it status. So let's say I have 5 documents under "Spoilt" status, I can choose how many document I want. So I choose 2 documents only.

After document selected, I will click button to create one new documents using lotusscript. After button clicked, DialogBox will show. I insert batchNo and click OK.

Then, the code will check that status of documents and create new document by getting value from 3 documents and display into new document.

For example, I need to get value from field "PSerialNo" and "PType" from 2 documents. As you can see below. Value from document1 and document2, I want to insert in new document. So if document1, PSerialNo into WSerialNo1 and PType into WType1. And if document2, PSerialNo into WSerialNo2 and PType into WType2 and so on.

Document 1

Document 2

New Document

This is my code to create new document.

```<code>Set doc = dc.GetFirstDocument()

While Not (doc Is Nothing)
    If doc.PStatus(0) = "Active" Then
        Set newdoc = New NotesDocument(db)
        newdoc.Form = "WriteOff"

        newdoc.WABatchNo = wDialogDoc.WBatchNo(0)
        newdoc.WType = doc.PType(0)
        newdoc.WSerialNo = doc.PSerialNo(0)

        newdoc.ComputeWithForm(False,False)
        newdoc.save(True,False)

    End If
    doc = dc.GetNextDocument(doc)
Wend
</code>```

My problem now, if I create new document, and I want to get value from two documents, it not insert into one new document but it insert into two different new document. How can I fix it. Any advice or help I appreciate. Thanks!

答:
It's been more than 10 years since I wrote LotusScript, so I might be wrong.</p>

```<code>Set doc = dc.GetFirstDocument()
Dim docCreated As Boolean 'flag a document was created
Dim i As Integer 'index for each document

docCreated = False
i = 0
While Not (doc Is Nothing)
    If doc.PStatus(0) = "Active" Then
        If Not docCreated Then 'only create a document for first doc
            Set newdoc = New NotesDocument(db)
            newdoc.Form = "WriteOff"
            docCreated = True
        End If
        i = i + 1

        newdoc.WABatchNo = wDialogDoc.WBatchNo(0)
        ' not sure about this part, but the idea is to set WType1 for first doc, WType2 for 2nd doc, and so on
        Call newdoc.ReplaceItemValue("WType" & i, doc.PType(0))
        Call newdoc.ReplaceItemValue("WSerialNo" & i, doc.PSerialNo(0))
    End If
    doc = dc.GetNextDocument(doc)
Wend

If docCreated Then
    Call newdoc.ComputeWithForm(False,False)
    Call newdoc.save(True,False)
End If
</code>```

Body:
I have a list of document in view. I also have a button inside view where I can create new document with value from existed document. For this new document, I will use different form for new document created. In my view, document is divide by Status. I also has dialogBox too for me to set batchNo for new documents.

So, the process is like this:

First, I will select document based on it status. So let's say I have 5 documents under "Spoilt" status, I can choose how many document I want. So I choose 2 documents only.

After document selected, I will click button to create one new documents using lotusscript. After button clicked, DialogBox will show. I insert batchNo and click OK.

Then, the code will check that status of documents and create new document by getting value from 3 documents and display into new document.

For example, I need to get value from field "PSerialNo" and "PType" from 2 documents. As you can see below. Value from document1 and document2, I want to insert in new document. So if document1, PSerialNo into WSerialNo1 and PType into WType1. And if document2, PSerialNo into WSerialNo2 and PType into WType2 and so on.

Document 1

Document 2

New Document

This is my code to create new document.

Set doc = dc.GetFirstDocument()

While Not (doc Is Nothing)
    If doc.PStatus(0) = "Active" Then
        Set newdoc = New NotesDocument(db)
        newdoc.Form = "WriteOff"

        newdoc.WABatchNo = wDialogDoc.WBatchNo(0)
        newdoc.WType = doc.PType(0)
        newdoc.WSerialNo = doc.PSerialNo(0)

        newdoc.ComputeWithForm(False,False)
        newdoc.save(True,False)

    End If
    doc = dc.GetNextDocument(doc)
Wend

My problem now, if I create new document, and I want to get value from two documents, it not insert into one new document but it insert into two different new document. How can I fix it. Any advice or help I appreciate. Thanks!

Body:
It's been more than 10 years since I wrote LotusScript, so I might be wrong.

Set doc = dc.GetFirstDocument()
Dim docCreated As Boolean 'flag a document was created
Dim i As Integer 'index for each document

docCreated = False
i = 0
While Not (doc Is Nothing)
    If doc.PStatus(0) = "Active" Then
        If Not docCreated Then 'only create a document for first doc
            Set newdoc = New NotesDocument(db)
            newdoc.Form = "WriteOff"
            docCreated = True
        End If
        i = i + 1

        newdoc.WABatchNo = wDialogDoc.WBatchNo(0)
        ' not sure about this part, but the idea is to set WType1 for first doc, WType2 for 2nd doc, and so on
        Call newdoc.ReplaceItemValue("WType" & i, doc.PType(0))
        Call newdoc.ReplaceItemValue("WSerialNo" & i, doc.PSerialNo(0))
    End If
    doc = dc.GetNextDocument(doc)
Wend

If docCreated Then
    Call newdoc.ComputeWithForm(False,False)
    Call newdoc.save(True,False)
End If


来源: stackexchange

问:
Android Studio 3.4 for Windows 10 - can't find the Device File Explorer
Good evening,

I looked everywhere but I still can't find Device File Explorer (DFE).

The device is connected and recognized by ADB in the DOS prompt

The device has the "Debug USB" option enabled and it's in "File Transfer" USB mode

In Android Studio there's no DFE icon in the bottom right corner

In the "View > Tool Windows" menu there's nothing useful

In the "Tools" menu there's nothing useful

How can I find it?

Thanks

答:
This is how it should look alike:

In case that button should be missing, the installation might be broken.

ContentLicense: CC BY-SA 4.0


问:
Lasso Regression: The continuous heavy step function
From many documents, I have learned the recipe of Ridge regression that is:

```<code>loss_Ridge = loss_function + lambda x L2 norm of slope
</code>```

and the recipe of Lasso regression that is:

```<code>loss_Lasso = loss_function + lambda x L1 norm of slope
</code>```

When I have read topic "Implementing Lasso and Ridge Regression" in "TensorFlow Machine Learning Cookbook", its author explained that:

"...we will use a continuous approximation to a step function, called
  the continuous heavy step function..."

and its author also provided lines of code here.
I don't understand about which is called 'the continuous heavy step function' in this context. Please help me.

答:
From the link that you provided,

```<code>if regression_type == 'LASSO':
    # Declare Lasso loss function
    # Lasso Loss = L2_Loss + heavyside_step,
    # Where heavyside_step ~ 0 if A < constant, otherwise ~ 99
    lasso_param = tf.constant(0.9)
    heavyside_step = tf.truediv(1., tf.add(1., tf.exp(tf.multiply(-50., tf.subtract(A, lasso_param)))))
    regularization_param = tf.multiply(heavyside_step, 99.)
loss = tf.add(tf.reduce_mean(tf.square(y_target - model_output)), regularization_param)
</code>```

This heavyside_step function is very close to a logistic function which in turn can be a continuous approximation for a step function.

You use continuous approximation because the loss function needs to be differentiable with respect to the parameters of your model.

To get an intuition about read the constrained formulation section 1.6 in https://www.cs.ubc.ca/~schmidtm/Documents/2005_Notes_Lasso.pdf

You can see that in your code if A < 0.9 then regularization_param vanishes, so optimization will constrain A in that range.

Body:
From many documents, I have learned the recipe of Ridge regression that is:

loss_Ridge = loss_function + lambda x L2 norm of slope

and the recipe of Lasso regression that is:

loss_Lasso = loss_function + lambda x L1 norm of slope

When I have read topic "Implementing Lasso and Ridge Regression" in "TensorFlow Machine Learning Cookbook", its author explained that:

"...we will use a continuous approximation to a step function, called
  the continuous heavy step function..."

and its author also provided lines of code here.
I don't understand about which is called 'the continuous heavy step function' in this context. Please help me.

Body:
From the link that you provided,

if regression_type == 'LASSO':
    # Declare Lasso loss function
    # Lasso Loss = L2_Loss + heavyside_step,
    # Where heavyside_step ~ 0 if A < constant, otherwise ~ 99
    lasso_param = tf.constant(0.9)
    heavyside_step = tf.truediv(1., tf.add(1., tf.exp(tf.multiply(-50., tf.subtract(A, lasso_param)))))
    regularization_param = tf.multiply(heavyside_step, 99.)
loss = tf.add(tf.reduce_mean(tf.square(y_target - model_output)), regularization_param)

This heavyside_step function is very close to a logistic function which in turn can be a continuous approximation for a step function.

You use continuous approximation because the loss function needs to be differentiable with respect to the parameters of your model.

To get an intuition about read the constrained formulation section 1.6 in https://www.cs.ubc.ca/~schmidtm/Documents/2005_Notes_Lasso.pdf

You can see that in your code if A < 0.9 then regularization_param vanishes, so optimization will constrain A in that range.


问:
Is there any type of file that is unsafe to allow client to upload on Google Storage (S3)?
The head question pretty much states everything. Is there any type of file that is unsafe to allow client to upload on Google Storage (S3)? For instance, you wouldn't want to allow any executable files on your server (FTP), but since no files (afaik) can be executed on Google Storage (S3) there is no need to implement any file filter?</p>

答:
S3 is Amazon Storage, not Google Storage.

And there is no unsafe type to upload. The S3 container is safe.

If you find a flaw, you can probably claim a lot of money from Google. Or Amazon, I forgot.

ContentLicense: CC BY-SA 3.0


问:
Does JavaScript pass by reference?
Does JavaScript pass by references or pass by values?

Here is an example from JavaScript: The Good Parts. I am very confused about the my parameter for the rectangle function. It is actually undefined, and redefined inside the function. There are no original reference. If I remove it from the function parameter, the inside area function is not able to access it.

Is it a closure? But no function is returned.

```<code>var shape = function (config) {
    var that = {};
    that.name = config.name || "";
    that.area = function () {
        return 0;
    };
    return that;
};

var rectangle = function (config, my) {
    my = my || {};
    my.l = config.length || 1;
    my.w = config.width || 1;
    var that = shape(config);
    that.area = function () {
        return my.l * my.w;
    };
    return that;
};

myShape = shape({
    name: "Unhnown"
});

myRec = rectangle({
    name: "Rectangle",
    length: 4,
    width: 6
});

console.log(myShape.name + " area is " + myShape.area() + " " + myRec.name + " area is " + myRec.area());
</code>```

答:
Objects are always pass by reference and primitives by value. Just keep that parameter at the same address for objects.

Here's some code to illustrate what I mean (try it in a JavaScript sandbox such as https://js.do/).

Unfortunately you can't only retain the address of the parameter; you retain all the original member values as well.

```<code>a = { key: 'bevmo' };
testRetain(a);
document.write(' after function ');
document.write(a.key);

function testRetain (b)
{
    document.write(' arg0 is ');
    document.write(arguments[0].key);
    b.key = 'passed by reference';
    var retain = b; // Retaining the original address of the parameter

    // Address of left set to address of right, changes address of parameter
    b = {key: 'vons'}; // Right is a new object with a new address
    document.write(' arg0 is ');
    document.write(arguments[0].key);

    // Now retrieve the original address of the parameter for pass by reference
    b = retain;
    document.write(' arg0 is ');
    document.write(arguments[0].key);
}
</code>```

Result:

arg0 is bevmo arg0 is vons arg0 is passed by reference after function passed by reference

Title: Does JavaScript pass by reference?

Body:
Does JavaScript pass by references or pass by values?

Here is an example from JavaScript: The Good Parts. I am very confused about the my parameter for the rectangle function. It is actually undefined, and redefined inside the function. There are no original reference. If I remove it from the function parameter, the inside area function is not able to access it.

Is it a closure? But no function is returned.

var shape = function (config) {
    var that = {};
    that.name = config.name || "";
    that.area = function () {
        return 0;
    };
    return that;
};

var rectangle = function (config, my) {
    my = my || {};
    my.l = config.length || 1;
    my.w = config.width || 1;
    var that = shape(config);
    that.area = function () {
        return my.l * my.w;
    };
    return that;
};

myShape = shape({
    name: "Unhnown"
});

myRec = rectangle({
    name: "Rectangle",
    length: 4,
    width: 6
});

console.log(myShape.name + " area is " + myShape.area() + " " + myRec.name + " area is " + myRec.area());

Body:
Objects are always pass by reference and primitives by value. Just keep that parameter at the same address for objects.

Here's some code to illustrate what I mean (try it in a JavaScript sandbox such as https://js.do/).

Unfortunately you can't only retain the address of the parameter; you retain all the original member values as well.

a = { key: 'bevmo' };
testRetain(a);
document.write(' after function ');
document.write(a.key);

function testRetain (b)
{
    document.write(' arg0 is ');
    document.write(arguments[0].key);
    b.key = 'passed by reference';
    var retain = b; // Retaining the original address of the parameter

    // Address of left set to address of right, changes address of parameter
    b = {key: 'vons'}; // Right is a new object with a new address
    document.write(' arg0 is ');
    document.write(arguments[0].key);

    // Now retrieve the original address of the parameter for pass by reference
    b = retain;
    document.write(' arg0 is ');
    document.write(arguments[0].key);
}

Result:

arg0 is bevmo arg0 is vons arg0 is passed by reference after function passed by reference


问:
why does select method return 0 immediately when I try to telnet it?
I am not familiar with Java Nio. I tried to write a little demo like this:

```<code>    ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
    serverSocketChannel.bind(new InetSocketAddress(9999)).configureBlocking(false);
    serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

    for (; ; ) {
        int select = selector.select(2_000);
        if (select == 0) {
            System.out.println("no event");
            continue;
        }
        System.out.println("select = " + select);
   }
</code>```

Timeout is set to 2 seconds and the program print "no event" every 2 seconds.

But when I tried to telnet it and it begins to print "no event" very fast.It seems that the select method returns value 0  without being blocked.

Why? That is the first question.

And when I tried to add some logics in for loop like this:

```<code>for (; ; ) {
            int select = selector.select();
            if (select == 0) {
                System.out.println("no event");
                continue;
            }
            System.out.println("select = " + select);
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            System.out.println("iterator = " + iterator.hasNext());
            while (iterator.hasNext()) {
                SelectionKey key = iterator.next();
                iterator.remove();
            }
        }

</code>```

Then I telnet it again ,the select method returns 1.

Why? That is the second question.

First time ask questions here. Please forgive my poor English.

答:
The number you are providing in select(long) is not the same as Thread.sleep(long). According to:

https://docs.oracle.com/javase/7/docs/api/java/nio/channels/Selector.html#select(long)

select is a blocking operation, but it proceeds as soon as it is able to select a channel. So, when you are connected, it will continually loop and output. The long value you are providing is to tell the select(long) method when to give up trying to select a channel, not sleep the thread regardless. In order to guarantee a sleep of a minimum 2 seconds, you need to add Thread.sleep(2000) before the end of the loop.

As for the return value, select() returns the number of keys that were updated, which may be zero. When you connect again with telnet, you are providing a new key that can be updated. If you have only one connection, there is no need to be selecting a new channel to listen on. Thus, nothing gets toggled. If you have two connections, it makes sense that one of them would be modified each time.

Body:
I am not familiar with Java Nio. I tried to write a little demo like this:

    ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
    serverSocketChannel.bind(new InetSocketAddress(9999)).configureBlocking(false);
    serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

    for (; ; ) {
        int select = selector.select(2_000);
        if (select == 0) {
            System.out.println("no event");
            continue;
        }
        System.out.println("select = " + select);
   }

Timeout is set to 2 seconds and the program print "no event" every 2 seconds.

But when I tried to telnet it and it begins to print "no event" very fast.It seems that the select method returns value 0  without being blocked.

Why? That is the first question.

And when I tried to add some logics in for loop like this:

for (; ; ) {
            int select = selector.select();
            if (select == 0) {
                System.out.println("no event");
                continue;
            }
            System.out.println("select = " + select);
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            System.out.println("iterator = " + iterator.hasNext());
            while (iterator.hasNext()) {
                SelectionKey key = iterator.next();
                iterator.remove();
            }
        }

Then I telnet it again ,the select method returns 1.

Why? That is the second question.

First time ask questions here. Please forgive my poor English.


问:
Using information from a previous page on a new page with JS
I'm new to Javascript and I need help figuring out this process, or at least figuring out what methods to use.  I don't really need a full solution, just some advice on what direction to go in.

I have a page with a list of links.  When a user clicks on any of the links, they are directed to the same html page ("park.html").  However, that page will be filled with different information based on which link the user clicks.  I will populate "parks.html" with info using a JSON and Javascript, but I just need some type of identifier to be supplied to "park.html" that will be different depending on which link is clicked.

I'm not sure whether to use event listeners, cookies, or possibly React?  I tried giving each link an event listener which calls a function that uses "event.target.innerHTML" to get the text of the link the user clicked on.  I've also tried running that function onload of "park.html", but I don't know how to pass information from the link clicked to that function call.

This is my code that creates the list of links.  "Entry" is drawn from a JSON file -- the list is being created correctly.

```<code>function appendToList(entry, resultsList) {
    let listElement = document.createElement("li");
    let listLink = document.createElement("a");
    listLink.setAttribute("href", "park.html");
    listLink.setAttribute("id", entry.fullName);
    listLink.appendChild(document.createTextNode(entry.fullName));

    listLink.addEventListener("click", () => {
        qVal = listLink.id;
        console.log(qVal);
        get_park_data(qVal);
    });

    listElement.appendChild(listLink);
    resultsList.appendChild(listElement);
    return resultsList;
}
</code>```

I think the function that the listener calls (get_park_data) is running correctly, but runs on the page that the list is on -- not the page that the list elements link to.

So, how do I get an identifier of which link was clicked to be supplied to the page that is called?

I'd appreciate any insight! Thanks!

答: Why not use query parameters in the URL? It's pretty much easier. You'll just have to append it to the URL and you can change it everytime a user clicks a link.</p>

Body:
I'm new to Javascript and I need help figuring out this process, or at least figuring out what methods to use.  I don't really need a full solution, just some advice on what direction to go in.

I have a page with a list of links.  When a user clicks on any of the links, they are directed to the same html page ("park.html").  However, that page will be filled with different information based on which link the user clicks.  I will populate "parks.html" with info using a JSON and Javascript, but I just need some type of identifier to be supplied to "park.html" that will be different depending on which link is clicked.

I'm not sure whether to use event listeners, cookies, or possibly React?  I tried giving each link an event listener which calls a function that uses "event.target.innerHTML" to get the text of the link the user clicked on.  I've also tried running that function onload of "park.html", but I don't know how to pass information from the link clicked to that function call.

This is my code that creates the list of links.  "Entry" is drawn from a JSON file -- the list is being created correctly.

function appendToList(entry, resultsList) {
    let listElement = document.createElement("li");
    let listLink = document.createElement("a");
    listLink.setAttribute("href", "park.html");
    listLink.setAttribute("id", entry.fullName);
    listLink.appendChild(document.createTextNode(entry.fullName));

    listLink.addEventListener("click", () => {
        qVal = listLink.id;
        console.log(qVal);
        get_park_data(qVal);
    });

    listElement.appendChild(listLink);
    resultsList.appendChild(listElement);
    return resultsList;
}

I think the function that the listener calls (get_park_data) is running correctly, but runs on the page that the list is on -- not the page that the list elements link to.

So, how do I get an identifier of which link was clicked to be supplied to the page that is called?

I'd appreciate any insight! Thanks!


问:
How to capitalize the first character of each word in a string
Is there a function built into Java that capitalizes the first character of each word in a String, and does not affect the others?

Examples:

jon skeet -> Jon Skeet

miles o'Brien -> Miles O'Brien (B remains capital, this rules out Title Case)

old mcdonald -> Old Mcdonald*

*(Old McDonald would be find too, but I don't expect it to be THAT smart.)

A quick look at the Java String Documentation reveals only toUpperCase() and toLowerCase(), which of course do not provide the desired behavior. Naturally, Google results are dominated by those two functions. It seems like a wheel that must have been invented already, so it couldn't hurt to ask so I can use it in the future.

答:
Heres a lil program I was using to capitalize each first letter word in every subfolder of a parent directory.</p>

```<code>private void capitalize(String string)
{
    List<String> delimiters = new ArrayList<>();
    delimiters.add(" ");
    delimiters.add("_");

    File folder = new File(string);
    String name = folder.getName();
    String[] characters = name.split("");

    String newName = "";
    boolean capitalizeNext = false;

    for (int i = 0; i < characters.length; i++)
    {
        String character = characters[i];

        if (capitalizeNext || i == 0)
        {
            newName += character.toUpperCase();
            capitalizeNext = false;
        }
        else
        {
            if (delimiters.contains(character)) capitalizeNext = true;
            newName += character;
        }
    }

    folder.renameTo(new File(folder.getParent() + File.separator + newName));
}
</code>```

Body:
Heres a lil program I was using to capitalize each first letter word in every subfolder of a parent directory.

private void capitalize(String string)
{
    List<String> delimiters = new ArrayList<>();
    delimiters.add(" ");
    delimiters.add("_");

    File folder = new File(string);
    String name = folder.getName();
    String[] characters = name.split("");

    String newName = "";
    boolean capitalizeNext = false;

    for (int i = 0; i < characters.length; i++)
    {
        String character = characters[i];

        if (capitalizeNext || i == 0)
        {
            newName += character.toUpperCase();
            capitalizeNext = false;
        }
        else
        {
            if (delimiters.contains(character)) capitalizeNext = true;
            newName += character;
        }
    }

    folder.renameTo(new File(folder.getParent() + File.separator + newName));
}


问:
Scraping JSON link is not working using fromJSON(url)
For web scraping I normally use the jsonlite::fromJSON(url) command which usually does the job for me. However this time it is inside another text.
Basically like this:

```<code>jQuery([
JSON stuff that I am more used to
]);
</code>```

How do I get around this easily?
The actual data looks like this when I call the address (I have tapped it more pretty):

```<code>jQuery(
[
{"Date":"2019-05-31T00:00:00+02:00","FromTime":"2019-05-31T00:00:00+02:00","ToTime":"2019-05-31T00:15:00+02:00","Value":3315.9120000000003,"Value2":2584.244,"Value3":731.668},
{"Date":"2019-05-31T00:00:00+02:00","FromTime":"2019-05-31T00:15:00+02:00","ToTime":"2019-05-31T00:30:00+02:00","Value":3386.238,"Value2":2655.814,"Value3":730.424}
]
);
</code>```

The errormessage I get when I try to make the function parse it is

```<code>Error in parse_con(txt, bigint_as_char) :
  lexical error: invalid char in json text.
                                       jQuery([{"Date":"2019-05-29T00:
                     (right here) ------^
</code>```

End goal is just to have a dataframe to continue work on.

答:
You can substr what you want from rvest return. It looks like jquery return will have start and end syntax</p>

```<code>library(rvest)
library(jsonlite)

url <- 'https://ws.50hertz.com/web02/api/PhotovoltaicActual/ListRecords?filterDateTime=2019-05-30T22:23:14.716Z&callback=jQuery&_=1559254994256'
r <- read_html(url) %>%
  html_node("p") %>%
  html_text()

x <- jsonlite::fromJSON(substr(r[1], 8, nchar(r) - 2))
</code>```

Body:
For web scraping I normally use the jsonlite::fromJSON(url) command which usually does the job for me. However this time it is inside another text.
Basically like this:

jQuery([
JSON stuff that I am more used to
]);

How do I get around this easily?
The actual data looks like this when I call the address (I have tapped it more pretty):

jQuery(
[
{"Date":"2019-05-31T00:00:00+02:00","FromTime":"2019-05-31T00:00:00+02:00","ToTime":"2019-05-31T00:15:00+02:00","Value":3315.9120000000003,"Value2":2584.244,"Value3":731.668},
{"Date":"2019-05-31T00:00:00+02:00","FromTime":"2019-05-31T00:15:00+02:00","ToTime":"2019-05-31T00:30:00+02:00","Value":3386.238,"Value2":2655.814,"Value3":730.424}
]
);

The errormessage I get when I try to make the function parse it is

Error in parse_con(txt, bigint_as_char) :
  lexical error: invalid char in json text.
                                       jQuery([{"Date":"2019-05-29T00:
                     (right here) ------^

End goal is just to have a dataframe to continue work on.

Body:
You can substr what you want from rvest return. It looks like jquery return will have start and end syntax

library(rvest)
library(jsonlite)

url <- 'https://ws.50hertz.com/web02/api/PhotovoltaicActual/ListRecords?filterDateTime=2019-05-30T22:23:14.716Z&callback=jQuery&_=1559254994256'
r <- read_html(url) %>%
  html_node("p") %>%
  html_text()

x <- jsonlite::fromJSON(substr(r[1], 8, nchar(r) - 2))


问:
How to check the response from global fetch in JEST test case
So, i am using jest for testing my node function which is calling  fetch() APi to get the data, now when I am writing the test cases for the same i am getting an error like :

```<code>expect(received).resolves.toEqual()

    Matcher error: received value must be a promise

    Received has type:  function
    Received has value: [Function mockConstructor]
</code>```

my function :

```<code> export function dataHandler (req, res, next) {
    const url= "someURL"
    if (url ) {
        return fetch(url )
            .then((response) => response.json())
            .then((response) => {
                if (response.data) {
                    console.log(response);
                    res.redirect(somewhere`);
                } else {
                    throw Error(response.statusText);
                }
            })
            .catch((error) => {
                next(error);
            });
    }
}
</code>```

testcase :

```<code> it('check if fetch returning the response', async () => {
        // Setup
        const req = jest.fn(),
            res = { redirect: jest.fn() },
            next = jest.fn();
        global.fetch = jest.fn().mockImplementation(() => {
            return new Promise((resolve) =>
                resolve({
                    json: () => {
                        return { data: "hello"};
                    }
                })
            );
        });
        await middlewares.dataHandler(req, res, next);
        //  Assert
        expect(global.fetch).resolves.toEqual({ data: "hello" });
    });
</code>```

Please be advised I am not using any mocking API, and would prefer not to.

Can anyone help me with what's going wrong?

答:
.resolves can only be used with a Promise.

global.fetch is a function so Jest throws an error.

If you are trying to assert that the Promise returned by calling global.fetch resolves to an object with a json function that returns { data: 'hello' } then you can do this:

```<code>expect((await global.fetch()).json()).toEqual({ data: 'hello' });  // Success!
</code>```

...but I suspect that you are really trying to verify that response.data existed and that res.redirect was called with 'somewhere' in which case your assertion should just be this:

```<code>expect(res.redirect).toHaveBeenCalledWith('somewhere');  // Success!
</code>```

Body:
So, i am using jest for testing my node function which is calling  fetch() APi to get the data, now when I am writing the test cases for the same i am getting an error like :

expect(received).resolves.toEqual()

    Matcher error: received value must be a promise

    Received has type:  function
    Received has value: [Function mockConstructor]

my function :

 export function dataHandler (req, res, next) {
    const url= "someURL"
    if (url ) {
        return fetch(url )
            .then((response) => response.json())
            .then((response) => {
                if (response.data) {
                    console.log(response);
                    res.redirect(somewhere`);
                } else {
                    throw Error(response.statusText);
                }
            })
            .catch((error) => {
                next(error);
            });
    }
}

testcase :

 it('check if fetch returning the response', async () => {
        // Setup
        const req = jest.fn(),
            res = { redirect: jest.fn() },
            next = jest.fn();
        global.fetch = jest.fn().mockImplementation(() => {
            return new Promise((resolve) =>
                resolve({
                    json: () => {
                        return { data: "hello"};
                    }
                })
            );
        });
        await middlewares.dataHandler(req, res, next);
        //  Assert
        expect(global.fetch).resolves.toEqual({ data: "hello" });
    });

Please be advised I am not using any mocking API, and would prefer not to.

Can anyone help me with what's going wrong?

Body:
.resolves can only be used with a Promise.

global.fetch is a function so Jest throws an error.

If you are trying to assert that the Promise returned by calling global.fetch resolves to an object with a json function that returns { data: 'hello' } then you can do this:

expect((await global.fetch()).json()).toEqual({ data: 'hello' });  // Success!

...but I suspect that you are really trying to verify that response.data existed and that res.redirect was called with 'somewhere' in which case your assertion should just be this:

expect(res.redirect).toHaveBeenCalledWith('somewhere');  // Success!


问:
what is the right way to use `material-icons`?
I am using material-ui in my react project. I found there are two different ways to use their icons.

One is from this web site: https://material.io/tools/icons/?icon=3d_rotation&style=baseline. You can download the icon on the left panel by click it. Or you can install material-design-icons on your project.

Another way is to import them like:

```<code>import SearchIcon from '@material-ui/icons/Search';
import ArrowDownwardIcon from '@material-ui/icons/ArrowDownward';
import Close from '@material-ui/icons/Close'
</code>```

I wonder are they same? Or what is the different?

答:
If you're using Material-UI, the way I (and they) suggest to use them is with SVGIcons, the @material-ui/icons package. What I typically do is look up icons on that website you posted and pull them in from @material-ui/icons.

For example, on that website you'll see one called alarm_on well you import it from that package like import YourIcon from '@material-ui/icons/AlarmOn'.

And the reason I like to do this and not use Icon Fonts is because when people with bad connections try to load your app, the icon might not even load and they'll see an ugly "alarm_on" in plain text where the icon would be.

Take a look at the usage section here.

Body:
I am using material-ui in my react project. I found there are two different ways to use their icons.

One is from this web site: https://material.io/tools/icons/?icon=3d_rotation&style=baseline. You can download the icon on the left panel by click it. Or you can install material-design-icons on your project.

Another way is to import them like:

import SearchIcon from '@material-ui/icons/Search';
import ArrowDownwardIcon from '@material-ui/icons/ArrowDownward';
import Close from '@material-ui/icons/Close'

I wonder are they same? Or what is the different?


问:
docker exec -it bash gives error "executable file not found in $PATH" - but launching bash through Kitematic works
When I attempt to run docker exec -it bash
I get the error executable file not found in $PATH"

I haven't been able to find much online pertaining to this issue. I was able to launch bash through Kitematic so it wasn't a big problem but I would love to know why it wouldn't let me launch bash with exec. This is my second day with Docker so i'm sure it's something simple but I really appreciate any help. I can get.

答:
From your comment:

It doesn't say what executable specifically, here is the entire error: starting container process caused "exec: \"-it\": executable file not found in $PATH"

Actually, it does list the command, -it that it is looking to run. Everything after the container id is part of the command to run, and it looks like you've put the flags after the container id. You want:

```<code>docker exec -it $other_exec_flags $container_id $cmd_string
</code>```

Or as Abhineet said:

```<code>docker exec -it <container_name> bash
</code>```

Which is not the same as the failing command:

```<code>docker exec <container_name> -it bash
</code>```

Body:
From your comment:

It doesn't say what executable specifically, here is the entire error: starting container process caused "exec: \"-it\": executable file not found in $PATH"

Actually, it does list the command, -it that it is looking to run. Everything after the container id is part of the command to run, and it looks like you've put the flags after the container id. You want:

docker exec -it $other_exec_flags $container_id $cmd_string

Or as Abhineet said:

docker exec -it <container_name> bash

Which is not the same as the failing command:

docker exec <container_name> -it bash


问:
How to search for a particular row, column value and then return the row number?
I'm having an trouble making an excel formula at the moment which would get first search for the row, column value and then return the row number from which I can get the another column value in the same row.

Right now, I've made this function. =INDEX('Rent'!$D$2:$D$73, MATCH(0, ($B$6='Rent'!$B$2:$B$73)*($C$7='Rent'!$A$2:$A$73),0))

Here rent is another sheet, and first i'm searching for the particular value like $B$6 here in first MATCH function by searching for the value in 'Rent' sheet's column and then same for next check. The resulting match would contain bow $B$6 and similarly $C$7 in the same row and then I want to return the value of another column value in the same row.

Please, let me know how can I do this. I've been stuck at this a long time.

The rent sheet looks like this:

答:
Based on your data, I think you can just use SUMIFS for this:

```<code>=SUMIFS('Rent'!$D$2:$D$73,'Rent'!$B$2:$B$73,$B$6,'Rent'!$A$2:$A$73,$C$7)
</code>```

Body:
Based on your data, I think you can just use SUMIFS for this:

=SUMIFS('Rent'!$D$2:$D$73,'Rent'!$B$2:$B$73,$B$6,'Rent'!$A$2:$A$73,$C$7)


问:
IE doesn't evaluate meta-refresh anymore after pressing F5
Ridiculous simple HTML-file:

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                      "http://www.w3.org/TR/html4/loose.dtd">
<html>
  <head>
    <meta http-equiv="refresh" content="5; URL=./test.html">
  </head>
  <body>
    <h1>Hello World</h1>
  </body>
</html>
</code>```

When I open the file with any browser, the browsers behave well and reload the page every 5 seconds.

But when I refresh the page manually between two refreshes (F5), the IE (V 8.0.6001.18702) doesn't evaluate the meta tag anymore and the page gets no longer refreshed. Opera, FF and Safari still work as expected and refresh every 5 seconds.

Has anybody else experienced such a problem? How (apart of using Javascript, of course) could this issue be solved?

Edit 1:

Verified this behavior also on IE6, so I guess it's a general IE problem. Any hints how to overcome this?

Edit 2:

To keep that topic going:

is that a known problem or would it
be worth to file a bug ticket
somewhere (where?)?

Could someone
verify that behavior with IE7 and/or
IE9?

答:
As far as i know theres only the mta or javascript way.

Another option might be to use

```<code>header("Location: url");
</code>```

if you can use php, its not really a refresh in it common way, but you could use to redirect to the same page again

As with the meta way, did you tried to put a full url? ( IE, arrg )

Body:
Ridiculous simple HTML-file:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                      "http://www.w3.org/TR/html4/loose.dtd">

    <meta http-equiv="refresh" content="5; URL=./test.html">

Hello World

When I open the file with any browser, the browsers behave well and reload the page every 5 seconds.

But when I refresh the page manually between two refreshes (F5), the IE (V 8.0.6001.18702) doesn't evaluate the meta tag anymore and the page gets no longer refreshed. Opera, FF and Safari still work as expected and refresh every 5 seconds.

Has anybody else experienced such a problem? How (apart of using Javascript, of course) could this issue be solved?

Edit 1:

Verified this behavior also on IE6, so I guess it's a general IE problem. Any hints how to overcome this?

Edit 2:

To keep that topic going:

is that a known problem or would it
be worth to file a bug ticket
somewhere (where?)?

Could someone
verify that behavior with IE7 and/or
IE9?

Body:
As far as i know theres only the mta or javascript way.

Another option might be to use

header("Location: url");

if you can use php, its not really a refresh in it common way, but you could use to redirect to the same page again

As with the meta way, did you tried to put a full url? ( IE, arrg )


问:
how to Entry.insert() work with frames in tkinter?
i am trying to make a program that help me in my work at the school and i made lots of progress with it but i am messing now i need to fined how to make the path of the file to show on the Entry widget i tried lots of the stuffs in here and i may didn't git the idea behind it please help me with it

```<code>import tkinter as tk
from tkinter.filedialog import askopenfilename
from tkinter.messagebox import showerror
from tkinter import ttk
import xlrd

class SchoolProjict(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        self.app_data = {"name": tk.StringVar(),
                         }
        container = tk.Frame(self)
        container.pack(side = "top", fill = "both", expand = True)
        container.grid_rowconfigure(0, weight = 1)
        container.grid_columnconfigure(0, weight = 1)
        self.frames = {}
        for F in (StartPage,  SetingPage):
            frame = F(container, self)
            self.frames[F] = frame
            frame.grid(row = 0, column = 0, sticky = "nsew")
        self.show_frame(StartPage)

    def show_frame(self, cont):
        frame = self.frames[cont]
        frame.tkraise()

    def get_page(self, classname):
        for page in self.frames.values():
            if str(page.__class__.__name__) == classname:
                return page
        return None

def printingstuff(var1):
    print (var1)

def printontherthing(page_class):
    print(page_class)

class StartPage(tk.Frame):
    def __init__(self, parent, controller):
        self.controller = controller
        tk.Frame.__init__(self, parent)
        lablel = ttk.Label(self, text = "Main Page")
        lablel.pack(pady = 10, padx = 10)
        button2 = ttk.Button(self, text = "Siting", command = lambda: controller.show_frame(SetingPage))
        button2.pack()

class SetingPage(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        lablel = tk.Label(self, text = "Siting Page")
        lablel.grid(row = 0, column = 0)
        text1 = tk.Entry(self)  #<== i want to show the path of the file i am going to open Here after i select it from openfile
        text1.grid(row = 2, column = 0)
        text1.focus()
        button1 = tk.Button(self, text = "print text1", command = lambda: printingstuff(text1.get()))
        button1.grid(row = 3, column = 0)
        button2 = tk.Button(self, text="open file", command= self.load_file, width=10)
        button2.grid(row = 3, column = 1)
        button4 = tk.Button(self, text = "Main Page", command = lambda: controller.show_frame(StartPage))
        button4.grid(row = 4, column = 1)

    def load_file(self):
        fname = askopenfilename(filetypes=(("Excel file", "*.xls"),
                                           ("HTML files", "*.html;*.htm"),
                                           ("All files", "*.*") ))
        if fname:
            try:
                # print(fname)
                value = str(fname)
                page_var = self.controller.get_page("SetingPage")
                page_var.text1.insert(0, value)
                return

            except:
                showerror("Open Source File", "Failed to read file\n'%s'" % fname)
            return

app = SchoolProjict()
app.mainloop()
</code>```

it gave me an error whine i run it and select the file
this is what i have as an error

答:
You need to make your text an attribute of the class SetingPage by adding self.

```<code>class SetingPage(tk.Frame):
    def __init__(self, parent, controller):
        ...
        self.text1 = tk.Entry(self)  #<== i want to show the path of the file i am going to open Here after i select it from openfile
        self.text1.grid(row = 2, column = 0)
        self.text1.focus()
        button1 = tk.Button(self, text = "print text1", command = lambda: printingstuff(self.text1.get()))
        ...
</code>```

Body:
i am trying to make a program that help me in my work at the school and i made lots of progress with it but i am messing now i need to fined how to make the path of the file to show on the Entry widget i tried lots of the stuffs in here and i may didn't git the idea behind it please help me with it

import tkinter as tk
from tkinter.filedialog import askopenfilename
from tkinter.messagebox import showerror
from tkinter import ttk
import xlrd

class SchoolProjict(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        self.app_data = {"name": tk.StringVar(),
                         }
        container = tk.Frame(self)
        container.pack(side = "top", fill = "both", expand = True)
        container.grid_rowconfigure(0, weight = 1)
        container.grid_columnconfigure(0, weight = 1)
        self.frames = {}
        for F in (StartPage,  SetingPage):
            frame = F(container, self)
            self.frames[F] = frame
            frame.grid(row = 0, column = 0, sticky = "nsew")
        self.show_frame(StartPage)

    def show_frame(self, cont):
        frame = self.frames[cont]
        frame.tkraise()

    def get_page(self, classname):
        for page in self.frames.values():
            if str(page.__class__.__name__) == classname:
                return page
        return None

def printingstuff(var1):
    print (var1)

def printontherthing(page_class):
    print(page_class)

class StartPage(tk.Frame):
    def __init__(self, parent, controller):
        self.controller = controller
        tk.Frame.__init__(self, parent)
        lablel = ttk.Label(self, text = "Main Page")
        lablel.pack(pady = 10, padx = 10)
        button2 = ttk.Button(self, text = "Siting", command = lambda: controller.show_frame(SetingPage))
        button2.pack()

class SetingPage(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        lablel = tk.Label(self, text = "Siting Page")
        lablel.grid(row = 0, column = 0)
        text1 = tk.Entry(self)  #<== i want to show the path of the file i am going to open Here after i select it from openfile
        text1.grid(row = 2, column = 0)
        text1.focus()
        button1 = tk.Button(self, text = "print text1", command = lambda: printingstuff(text1.get()))
        button1.grid(row = 3, column = 0)
        button2 = tk.Button(self, text="open file", command= self.load_file, width=10)
        button2.grid(row = 3, column = 1)
        button4 = tk.Button(self, text = "Main Page", command = lambda: controller.show_frame(StartPage))
        button4.grid(row = 4, column = 1)

    def load_file(self):
        fname = askopenfilename(filetypes=(("Excel file", "*.xls"),
                                           ("HTML files", "*.html;*.htm"),
                                           ("All files", "*.*") ))
        if fname:
            try:
                # print(fname)
                value = str(fname)
                page_var = self.controller.get_page("SetingPage")
                page_var.text1.insert(0, value)
                return

            except:
                showerror("Open Source File", "Failed to read file\n'%s'" % fname)
            return

app = SchoolProjict()
app.mainloop()

it gave me an error whine i run it and select the file
this is what i have as an error

Body:
You need to make your text an attribute of the class SetingPage by adding self.

class SetingPage(tk.Frame):
    def __init__(self, parent, controller):
        ...
        self.text1 = tk.Entry(self)  #<== i want to show the path of the file i am going to open Here after i select it from openfile
        self.text1.grid(row = 2, column = 0)
        self.text1.focus()
        button1 = tk.Button(self, text = "print text1", command = lambda: printingstuff(self.text1.get()))
        ...


问:
Fail to start Portainer agent with error "Unable to retrieve advertise address"
I ran followimng command to deploy Portainer on a Win Server 2019 (V1809).

Deploy Portainer Agent on a standalone Windows Server 2016 Docker Host

$ docker run -d -p 9001:9001 --name portainer_agent --restart=always -v .\pipe\docker_engine:.\pipe\docker_engine portainer/agent

How should I resolve the "Unable to retrieve advertise address" error?

Here is the agent container log:

2019/05/29 12:21:14 [ERROR] - Unable to retrieve advertise address: Unable to retrieve the address on which the agent can advertise. Check your network settings

2019/05/29 12:22:16 [ERROR] - Unable to retrieve advertise address: Unable to retrieve the address on which the agent can advertise. Check your network settings

2019/05/29 12:23:18 [ERROR] - Unable to retrieve advertise address: Unable to retrieve the address on which the agent can advertise. Check your network settings

2019/05/29 12:24:20 [ERROR] - Unable to retrieve advertise address: Unable to retrieve the address on which the agent can advertise. Check your network settings

2019/05/29 12:25:21 [ERROR] - Unable to retrieve advertise address: Unable to retrieve the address on which the agent can advertise. Check your network settings

答:
Following command works.

docker run -d -p 9001:9001 --name portainer_agent --restart=always -v .\pipe\docker_engine:.\pipe\docker_engine portainerci/agent:develop


问:
Reformatting a phone number in Laravel using Javascript
I have a function that formats telephone numbers as a user types their phone number in. I also have a blade.php template that has the phone number field as part of the form. How do I get the blade template to invoke my telephone() function from my main.js file?

Contact.blade.php

```<code>               <div class="field">
                    <label for="name" class="label">Phone Number</label>
                    <div class="control">
                        <input type="text" id="phonenumber" class="input {{$errors->has('phonenumber') ? 'is-danger' : 'is-success'}}"
                               name="phonenumber" placeholder="Enter phone number" value="{{old('phonenumber')}}">
                    </div>
                </div>
</code>```

main.js

```<code>function telephone(){
    document.getElementById('phonenumber').addEventListener('input', function (e) {
        var x = e.target.value.replace(/\D/g, '').match(/(\d{0,3})(\d{0,3})(\d{0,4})/);
        e.target.value = !x[2] ? x[1] : '(' + x[1] + ') ' + x[2] + (x[3] ? '-' + x[3] : '');
    });
}
</code>```

app.blade.php

```<code><!DOCTYPE html>
<html lang="en">
<head>

 <script type="text/javascript" src="{{URL::asset('js/main.js')}}"></script>
    <link href="{{url('/css/style.css')}}" type="text/css" rel="stylesheet">
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>

@include('inc.contact')
</body>
</code>```

答: You can use onKeyDown or onKeyUp on the phonenumber input tag and point it to your telephone() function

Body:
I have a function that formats telephone numbers as a user types their phone number in. I also have a blade.php template that has the phone number field as part of the form. How do I get the blade template to invoke my telephone() function from my main.js file?

Contact.blade.php

                    Phone Number

                        <input type="text" id="phonenumber" class="input {{$errors->has('phonenumber') ? 'is-danger' : 'is-success'}}"
                               name="phonenumber" placeholder="Enter phone number" value="{{old('phonenumber')}}">

main.js

function telephone(){
    document.getElementById('phonenumber').addEventListener('input', function (e) {
        var x = e.target.value.replace(/\D/g, '').match(/(\d{0,3})(\d{0,3})(\d{0,4})/);
        e.target.value = !x[2] ? x[1] : '(' + x[1] + ') ' + x[2] + (x[3] ? '-' + x[3] : '');
    });
}

app.blade.php

<!DOCTYPE html>

    <link href="{{url('/css/style.css')}}" type="text/css" rel="stylesheet">
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet">

@include('inc.contact')


问:
str object has no attribute batch annotate images
I want to extract text from the image and using google vision API but getting an error "str object has no attribute batch annotate images".

```<code>import io
import os

# Imports the Google Cloud client library
from google.cloud import vision
from google.cloud.vision import types

# Instantiates a client
client = vision.ImageAnnotatorClient('OCR and voice-bd78adad8bd9.json')

# The name of the image file to annotate
file_name = 'b1.jpg'

# Loads the image into memory
with io.open(file_name, 'rb') as image_file:
    content = image_file.read()

image = types.Image(content=content)

# Performs label detection on the image file
response = client.label_detection(image=image)
labels = response.label_annotations

print('Labels:')
for label in labels:
    print(label.description)
</code>```

The error showing to me is the following

```<code>---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-1-c65657163dd3> in <module>
     19
     20 # Performs label detection on the image file
---> 21 response = client.label_detection(image=image)
     22 labels = response.label_annotations
     23

~\Anaconda3\lib\site-packages\google\cloud\vision_helpers\decorators.py in inner(self, image, max_results, retry, timeout, **kwargs)
     99             copied_features["max_results"] = max_results
    100         request = dict(image=image, features=[copied_features], **kwargs)
--> 101         response = self.annotate_image(request, retry=retry, timeout=timeout)
    102         return response
    103

~\Anaconda3\lib\site-packages\google\cloud\vision_helpers\__init__.py in annotate_image(self, request, retry, timeout)
     70         # of them.
     71         protobuf.setdefault(request, "features", self._get_all_features())
---> 72         r = self.batch_annotate_images([request], retry=retry, timeout=timeout)
     73         return r.responses[0]
     74

~\Anaconda3\lib\site-packages\google\cloud\vision_v1\gapic\image_annotator_client.py in batch_annotate_images(self, requests, retry, timeout, metadata)
    224                 "batch_annotate_images"
    225             ] = google.api_core.gapic_v1.method.wrap_method(
--> 226                 self.transport.batch_annotate_images,
    227                 default_retry=self._method_configs["BatchAnnotateImages"].retry,
    228                 default_timeout=self._method_configs["BatchAnnotateImages"].timeout,

AttributeError: 'str' object has no attribute 'batch_annotate_images'
</code>```

I will be good if you could provide me with some source link where I could learn more about the GOOGLE API

答:
Change

```<code>client = vision.ImageAnnotatorClient('OCR and voice-bd78adad8bd9.json')
</code>```

to

```<code>client = vision.ImageAnnotatorClient()
</code>```

In your terminal, set the environment variable GOOGLE_APPLICATION_CREDENTIALS.

```<code>export GOOGLE_APPLICATION_CREDENTIALS='path/to/your/service_account.json'
</code>```

Here is the quickstart guide.

Body:
I want to extract text from the image and using google vision API but getting an error "str object has no attribute batch annotate images".

import io
import os

# Imports the Google Cloud client library
from google.cloud import vision
from google.cloud.vision import types

# Instantiates a client
client = vision.ImageAnnotatorClient('OCR and voice-bd78adad8bd9.json')

# The name of the image file to annotate
file_name = 'b1.jpg'

# Loads the image into memory
with io.open(file_name, 'rb') as image_file:
    content = image_file.read()

image = types.Image(content=content)

# Performs label detection on the image file
response = client.label_detection(image=image)
labels = response.label_annotations

print('Labels:')
for label in labels:
    print(label.description)

The error showing to me is the following

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-1-c65657163dd3> in <module>
     19
     20 # Performs label detection on the image file
---> 21 response = client.label_detection(image=image)
     22 labels = response.label_annotations
     23

~\Anaconda3\lib\site-packages\google\cloud\vision_helpers\decorators.py in inner(self, image, max_results, retry, timeout, **kwargs)
     99             copied_features["max_results"] = max_results
    100         request = dict(image=image, features=[copied_features], **kwargs)
--> 101         response = self.annotate_image(request, retry=retry, timeout=timeout)
    102         return response
    103

~\Anaconda3\lib\site-packages\google\cloud\vision_helpers\__init__.py in annotate_image(self, request, retry, timeout)
     70         # of them.
     71         protobuf.setdefault(request, "features", self._get_all_features())
---> 72         r = self.batch_annotate_images([request], retry=retry, timeout=timeout)
     73         return r.responses[0]
     74

~\Anaconda3\lib\site-packages\google\cloud\vision_v1\gapic\image_annotator_client.py in batch_annotate_images(self, requests, retry, timeout, metadata)
    224                 "batch_annotate_images"
    225             ] = google.api_core.gapic_v1.method.wrap_method(
--> 226                 self.transport.batch_annotate_images,
    227                 default_retry=self._method_configs["BatchAnnotateImages"].retry,
    228                 default_timeout=self._method_configs["BatchAnnotateImages"].timeout,

AttributeError: 'str' object has no attribute 'batch_annotate_images'

I will be good if you could provide me with some source link where I could learn more about the GOOGLE API

Body:
Change

client = vision.ImageAnnotatorClient('OCR and voice-bd78adad8bd9.json')

to

client = vision.ImageAnnotatorClient()

In your terminal, set the environment variable GOOGLE_APPLICATION_CREDENTIALS.

export GOOGLE_APPLICATION_CREDENTIALS='path/to/your/service_account.json'

Here is the quickstart guide.


问:
Temperature Converter is giving me NaN
I need to make a temperature converter using forms and it has to have the ok button display the information and a clear button to clear all information.

This is what I have tried to do but it gives me NaN

function temperatureConverter(valNum) {

  valNum = parseFloat(valNum);

  document.getElementById("outputCelcius").innerHTML=(valNum-32)/1.8;

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h2>Temperature Converter</h2>

Ok now my issue is that I need everything cleared even the Celsius data but I can't find a way for it to work
<p>Type a value in the Fahrenheit field to convert te value to Celsius:</p>

<p>

  <label>Fahrenheit</label>

  <input id="inputFahrenheit" type="text" placeholder="Fahrenheit">

  <input id= "button1" type= "button" value= "OK"  onclick="temperatureConverter(this.value)">

  <input id= "reset1" type= "reset" value= "Clear" onclick="temperatureConverter">

</p>

<p>Celcius: <span id="outputCelcius"></span></p></code>```

答:
Here is the basics needed to get your code working. Basically it is simply just changing what value is passed to the temperatureConverter function. Before you were passing it the value of the button that was being clicked, not the value of the input element you were trying to read. Also, I'm unsure on this one as I didn't look it up, but the reset element wasn't working for me until I put your items inside of a <form> element.

function temperatureConverter(valNum) {

  valNum = parseFloat(valNum);

  document.getElementById("outputCelcius").innerHTML=(valNum-32)/1.8;

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h2>Temperature Converter</h2>

<p>Type a value in the Fahrenheit field to convert te value to Celsius:</p>
<form>
<p>

  <label>Fahrenheit</label>

  <input id="inputFahrenheit" type="text" placeholder="Fahrenheit">

  <input id= "button1" type= "button" value= "OK"  onclick="temperatureConverter(document.querySelector('#inputFahrenheit').value)">

  <input id= "reset1" type= "reset" value= "Clear">

</p>
</form>

<p>Celcius: <span id="outputCelcius"></span></p></code>```

Please note that most of the time, people don't like putting the event listener in the on[event] attributes, and many developers will prefer that you do something more like this:

// () => {} is something called Arrow function notation, if you didn't know it already.
document.addEventListener('DOMContentLoaded', () => {
  function updateOutput(value) {
    // make sure you do some checking to avoid XSS attacks.
    document.querySelector('#output').innerHTML = value;
  }
  // keeps the form from submitting since we don't have an actual form handler and this is all front-end
  document.querySelector('#converterForm').addEventListener('submit',(e)=>{
    e.preventDefault();
  });
  document.querySelector('#convert').addEventListener('click', () => {
    updateOutput(convertToCelsius(document.querySelector('#fahrenheit').value));
  });
});

function convertToCelsius(f) {
  if(typeof f == 'string') f = parseFloat(f, 10);
  if(isNaN(f)) {
    throw new Error('Invalid parameter passed to function convertToCelsius');
  }
  return (f-32) * 5 / 9;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form id="converterForm" action="/">
  <input type="number" id="fahrenheit" placeholder="Fahrenheit value">
  <input type="button" id="convert" value="Convert to Celsius">
  <input type="reset" value="Clear">
  <div id="output">
  </div>
</form></code>```

Other than that, a good way to check why a function isn't working is to use console.log in your code and then check the Javascript browser (in Chrome you can get to it by hitting ctrl+shift+j, in Firefox I believe it's ctrl+shift+i).

Title: Temperature Converter is giving me NaN

Body:
I need to make a temperature converter using forms and it has to have the ok button display the information and a clear button to clear all information.

This is what I have tried to do but it gives me NaN

function temperatureConverter(valNum) {

  valNum = parseFloat(valNum);

  document.getElementById("outputCelcius").innerHTML=(valNum-32)/1.8;

}

Temperature Converter

Ok now my issue is that I need everything cleared even the Celsius data but I can't find a way for it to work

Type a value in the Fahrenheit field to convert te value to Celsius:

  Fahrenheit

  <input id="inputFahrenheit" type="text" placeholder="Fahrenheit">

  <input id= "button1" type= "button" value= "OK"  onclick="temperatureConverter(this.value)">

  <input id= "reset1" type= "reset" value= "Clear" onclick="temperatureConverter">

Celcius:

Body:
Here is the basics needed to get your code working. Basically it is simply just changing what value is passed to the temperatureConverter function. Before you were passing it the value of the button that was being clicked, not the value of the input element you were trying to read. Also, I'm unsure on this one as I didn't look it up, but the reset element wasn't working for me until I put your items inside of a <form> element.

function temperatureConverter(valNum) {

  valNum = parseFloat(valNum);

  document.getElementById("outputCelcius").innerHTML=(valNum-32)/1.8;

}

<h2>Temperature Converter</h2>

<p>Type a value in the Fahrenheit field to convert te value to Celsius:</p>
<form>
<p>

  <label>Fahrenheit</label>

  <input id="inputFahrenheit" type="text" placeholder="Fahrenheit">

  <input id= "button1" type= "button" value= "OK"  onclick="temperatureConverter(document.querySelector('#inputFahrenheit').value)">

  <input id= "reset1" type= "reset" value= "Clear">

</p>
</form>

<p>Celcius: <span id="outputCelcius"></span></p>

Please note that most of the time, people don't like putting the event listener in the on[event] attributes, and many developers will prefer that you do something more like this:

// () => {} is something called Arrow function notation, if you didn't know it already.
document.addEventListener('DOMContentLoaded', () => {
  function updateOutput(value) {
    // make sure you do some checking to avoid XSS attacks.
    document.querySelector('#output').innerHTML = value;
  }
  // keeps the form from submitting since we don't have an actual form handler and this is all front-end
  document.querySelector('#converterForm').addEventListener('submit',(e)=>{
    e.preventDefault();
  });
  document.querySelector('#convert').addEventListener('click', () => {
    updateOutput(convertToCelsius(document.querySelector('#fahrenheit').value));
  });
});

function convertToCelsius(f) {
  if(typeof f == 'string') f = parseFloat(f, 10);
  if(isNaN(f)) {
    throw new Error('Invalid parameter passed to function convertToCelsius');
  }
  return (f-32) * 5 / 9;
}

<form id="converterForm" action="/">
  <input type="number" id="fahrenheit" placeholder="Fahrenheit value">
  <input type="button" id="convert" value="Convert to Celsius">
  <input type="reset" value="Clear">
  <div id="output">
  </div>
</form>

Other than that, a good way to check why a function isn't working is to use console.log in your code and then check the Javascript browser (in Chrome you can get to it by hitting ctrl+shift+j, in Firefox I believe it's ctrl+shift+i).


问:
Complete list of React JSX component properties
Is there any particular website that contains a complete list of properties for all JSX components?

For example: <button> has onClick and much more.

答: If I'm not mistaken, onClick is an event handler native to JavaScript. As for a ' list of properties ' , I would read the React Docs, here. Typically you make your own props for JSX components.</p>


问:
Generate array of times (as strings) for every X minutes in JavaScript
I'm trying to create an array of times (strings, not Date objects) for every X minutes throughout a full 24 hours. For example, for a 5 minute interval the array would be:

```<code>['12:00 AM', '12:05 AM', '12:10 AM', '12:15 AM', ..., '11:55 PM']
</code>```

My quick and dirty solution was to use 3 nested for loops:

```<code>var times = []
  , periods = ['AM', 'PM']
  , hours = [12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
  , prop = null
  , hour = null
  , min = null;

for (prop in periods) {
  for (hour in hours) {
    for (min = 0; min < 60; min += 5) {
      times.push(('0' + hours[hour]).slice(-2) + ':' + ('0' + min).slice(-2) + " " + periods[prop]);
    }
  }
}
</code>```

This outputs the desired result but I'm wondering if there's a more elegant solution. Is there a way to do this that's:

more readable

less time complex

Body:
I'm trying to create an array of times (strings, not Date objects) for every X minutes throughout a full 24 hours. For example, for a 5 minute interval the array would be:

['12:00 AM', '12:05 AM', '12:10 AM', '12:15 AM', ..., '11:55 PM']

My quick and dirty solution was to use 3 nested for loops:

var times = []
  , periods = ['AM', 'PM']
  , hours = [12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
  , prop = null
  , hour = null
  , min = null;

for (prop in periods) {
  for (hour in hours) {
    for (min = 0; min < 60; min += 5) {
      times.push(('0' + hours[hour]).slice(-2) + ':' + ('0' + min).slice(-2) + " " + periods[prop]);
    }
  }
}

This outputs the desired result but I'm wondering if there's a more elegant solution. Is there a way to do this that's:

more readable

less time complex

Body:
const getTimes = (increment = 2) => {
  const times = [];
  for (let i = 0; i < 24; i++) {
    times.push({
      value: `${i === 0 || i - 12 === 0 ? 12 : i < 12 ? i : i - 12}:00 ${i < 12 ? 'AM' : 'PM'}`,
      label: `${i === 0 || i - 12 === 0 ? 12 : i < 12 ? i : i - 12}:00 ${i < 12 ? 'AM' : 'PM'}`,
    });
    for (let j = 60 / increment; j < 60; j += 60 / increment) {
      times.push({
        value: `${i === 0 || i - 12 === 0 ? 12 : i < 12 ? i : i - 12}:${Math.ceil(j)} ${i < 12 ? 'AM' : 'PM'}`,
        label: `${i === 0 || i - 12 === 0 ? 12 : i < 12 ? i : i - 12}:${Math.ceil(j)} ${i < 12 ? 'AM' : 'PM'}`,
      });
    }
  }
  return times;
};


问:
Lasso Regression: The continuous heavy step function
From many documents, I have learned the recipe of Ridge regression that is:

```<code>loss_Ridge = loss_function + lambda x L2 norm of slope
</code>```

and the recipe of Lasso regression that is:

```<code>loss_Lasso = loss_function + lambda x L1 norm of slope
</code>```

When I have read topic "Implementing Lasso and Ridge Regression" in "TensorFlow Machine Learning Cookbook", its author explained that:

"...we will use a continuous approximation to a step function, called
  the continuous heavy step function..."

and its author also provided lines of code here.
I don't understand about which is called 'the continuous heavy step function' in this context. Please help me.

答:
If you want to normalize features using Lasso Regression here you have one example:</p>

```<code>from sklearn.feature_selection import SelectFromModel
from sklearn.linear_model import Lasso
estimator = Lasso()
featureSelection = SelectFromModel(estimator)
featureSelection.fit(features_vector, target)
selectedFeatures = featureSelection.transform(features_vector)
print(selectedFeatures)
</code>```

Body:
From many documents, I have learned the recipe of Ridge regression that is:

loss_Ridge = loss_function + lambda x L2 norm of slope

and the recipe of Lasso regression that is:

loss_Lasso = loss_function + lambda x L1 norm of slope

When I have read topic "Implementing Lasso and Ridge Regression" in "TensorFlow Machine Learning Cookbook", its author explained that:

"...we will use a continuous approximation to a step function, called
  the continuous heavy step function..."

and its author also provided lines of code here.
I don't understand about which is called 'the continuous heavy step function' in this context. Please help me.

Body:
If you want to normalize features using Lasso Regression here you have one example:

from sklearn.feature_selection import SelectFromModel
from sklearn.linear_model import Lasso
estimator = Lasso()
featureSelection = SelectFromModel(estimator)
featureSelection.fit(features_vector, target)
selectedFeatures = featureSelection.transform(features_vector)
print(selectedFeatures)


问:
how to check the dtype of a column in python pandas
I need to use different functions to treat numeric columns and string columns. What I am doing now is really dumb:

```<code>allc = list((agg.loc[:, (agg.dtypes==np.float64)|(agg.dtypes==np.int)]).columns)
for y in allc:
    treat_numeric(agg[y])

allc = list((agg.loc[:, (agg.dtypes!=np.float64)&(agg.dtypes!=np.int)]).columns)
for y in allc:
    treat_str(agg[y])
</code>```

Is there a more elegant way to do this? E.g.

```<code>for y in agg.columns:
    if(dtype(agg[y]) == 'string'):
          treat_str(agg[y])
    elif(dtype(agg[y]) != 'string'):
          treat_numeric(agg[y])
</code>```

答:
Asked question title is general, but authors use case stated in the body of the question is specific. So any other answers may be used.

But in order to fully answer the title question it should be clarified that it seems like all of the approaches may fail in some cases and require some rework. I reviewed all of them (and some additional) in decreasing of reliability order (in my opinion):

1. Comparing types directly via == (accepted answer).

Despite the fact that this is accepted answer and has most upvotes count, I think this method should not be used at all. Because in fact this approach is discouraged in python as mentioned several times here.

But if one still want to use it - should be aware of some pandas-specific dtypes like pd.CategoricalDType, pd.PeriodDtype, or pd.IntervalDtype. Here one have to use extra type( ) in order to recognize dtype correctly:

s = pd.Series([pd.Period('2002-03','D'), pd.Period('2012-02-01', 'D')])
s
s.dtype == pd.PeriodDtype   # Not working
type(s.dtype) == pd.PeriodDtype # working

>>> 0    2002-03-01
>>> 1    2012-02-01
>>> dtype: period[D]
>>> False
>>> True
```

<p>Another caveat here is that type should be pointed out precisely:</p>

<pre class="lang-py prettyprint-override"><code>s = pd.Series([1,2])
s
s.dtype == np.int64 # Working
s.dtype == np.int32 # Not working

>>> 0    1
>>> 1    2
>>> dtype: int64
>>> True
>>> False
</code>```

2. isinstance() approach.

This method has not been mentioned in answers so far.

So if direct comparing of types is not a good idea - lets try built-in python function for this purpose, namely - isinstance().

It fails just in the beginning, because assumes that we have some objects, but pd.Series or pd.DataFrame may be used as just empty containers with predefined dtype but no objects in it:

s = pd.Series([], dtype=bool)
s

>>> Series([], dtype: bool)
```

<p>But if one somehow overcome this issue, and wants to access each object, for example, in the first row and checks its dtype like something like that:</p>

<pre class="lang-py prettyprint-override"><code>df = pd.DataFrame({'int': [12, 2], 'dt': [pd.Timestamp('2013-01-02'), pd.Timestamp('2016-10-20')]},
                  index = ['A', 'B'])
for col in df.columns:
    df[col].dtype, 'is_int64 = %s' % isinstance(df.loc['A', col], np.int64)

>>> (dtype('int64'), 'is_int64 = True')
>>> (dtype('<M8[ns]'), 'is_int64 = False')
</code>```

It will be misleading in the case of mixed type of data in single column:

df2 = pd.DataFrame({'data': [12, pd.Timestamp('2013-01-02')]},
                  index = ['A', 'B'])
for col in df2.columns:
    df2[col].dtype, 'is_int64 = %s' % isinstance(df2.loc['A', col], np.int64)

>>> (dtype('O'), 'is_int64 = False')
```

<p>And last but not least - this method cannot directly recognize <code>Category</code> dtype. As stated in docs: </p>

<blockquote>
  <p>Returning a single item from categorical data will also return the value, not a categorical of length “1”.</p>
</blockquote>

<pre class="lang-py prettyprint-override"><code>df['int'] = df['int'].astype('category')
for col in df.columns:
    df[col].dtype, 'is_int64 = %s' % isinstance(df.loc['A', col], np.int64)

>>> (CategoricalDtype(categories=[2, 12], ordered=False), 'is_int64 = True')
>>> (dtype('<M8[ns]'), 'is_int64 = False')
</code>```

So this method is also almost inapplicable.

3. df.dtype.kind approach.

This method yet may work with empty pd.Series or pd.DataFrames but has another problems.

First - it is unable to differ some dtypes:

df = pd.DataFrame({'prd'  :[pd.Period('2002-03','D'), pd.Period('2012-02-01', 'D')],
                   'str'  :['s1', 's2'],
                   'cat'  :[1, -1]})
df['cat'] = df['cat'].astype('category')
for col in df:
    # kind will define all columns as 'Object'
    print (df[col].dtype, df[col].dtype.kind)

>>> period[D] O
>>> object O
>>> category O
```

<p>Second, what is actually still unclear for me, it even returns on some dtypes None.</p>

<h2>4. <code>df.select_dtypes</code> approach.</h2>

<p>This is almost what we want. This method designed inside pandas so it handles most corner cases mentioned earlier - empty DataFrames, differs numpy or pandas-specific dtypes well. It works well with single dtype like <code>.select_dtypes('bool')</code>. It may be used even for selecting groups of columns based on dtype:</p>

<pre class="lang-py prettyprint-override"><code>test = pd.DataFrame({'bool' :[False, True], 'int64':[-1,2], 'int32':[-1,2],'float': [-2.5, 3.4],
                     'compl':np.array([1-1j, 5]),
                     'dt'   :[pd.Timestamp('2013-01-02'), pd.Timestamp('2016-10-20')],
                     'td'   :[pd.Timestamp('2012-03-02')- pd.Timestamp('2016-10-20'),
                              pd.Timestamp('2010-07-12')- pd.Timestamp('2000-11-10')],
                     'prd'  :[pd.Period('2002-03','D'), pd.Period('2012-02-01', 'D')],
                     'intrv':pd.arrays.IntervalArray([pd.Interval(0, 0.1), pd.Interval(1, 5)]),
                     'str'  :['s1', 's2'],
                     'cat'  :[1, -1],
                     'obj'  :[[1,2,3], [5435,35,-52,14]]
                    })
test['int32'] = test['int32'].astype(np.int32)
test['cat'] = test['cat'].astype('category')
</code>```

Like so, as stated in the docs:

test.select_dtypes('number')

>>>     int64   int32   float   compl   td
>>> 0      -1      -1   -2.5    (1-1j)  -1693 days
>>> 1       2       2    3.4    (5+0j)   3531 days
```

<p>On may think that here we see first unexpected (at used to be for me: question) results - <code>TimeDelta</code> is included into output <code>DataFrame</code>. But as answered in contrary it should be so, but one have to be aware of it. Note that <code>bool</code> dtype is skipped, that may be also undesired for someone, but it's due to <code>bool</code> and <code>number</code> are in different "subtrees" of numpy dtypes. In case with bool, we may use <code>test.select_dtypes(['bool'])</code> here. </p>

<p>Next restriction of this method is that for current version of pandas (0.24.2), this code: <code>test.select_dtypes('period')</code> will raise <code>NotImplementedError</code>.</p>

<p>And another thing is that it's unable to differ strings from other objects:</p>

<pre class="lang-py prettyprint-override"><code>test.select_dtypes('object')

>>>     str     obj
>>> 0    s1     [1, 2, 3]
>>> 1    s2     [5435, 35, -52, 14]
</code>```

But this is, first - already mentioned in the docs. And second - is not the problem of this method, rather the way strings are stored in DataFrame. But anyway this case have to have some post processing.

5. df.api.types.is_XXX_dtype approach.

This one is intended to be most robust and native way to achieve dtype recognition (path of the module where functions resides says by itself) as i suppose. And it works almost perfectly, but still have at least one caveat and still have to somehow distinguish string columns.

Besides, this may be subjective, but this approach also has more 'human-understandable' number dtypes group processing comparing with .select_dtypes('number'):

for col in test.columns:
    if pd.api.types.is_numeric_dtype(test[col]):
        print (test[col].dtype)

>>> bool
>>> int64
>>> int32
>>> float64
>>> complex128
```

No timedelta and bool is included. Perfect.

My pipeline exploits exactly this functionality at this moment of time, plus a bit of post hand processing.

Output.

Hope I was able to argument the main point - that all discussed approaches may be used, but only pd.DataFrame.select_dtypes() and pd.api.types.is_XXX_dtype should be really considered as the applicable ones.

Body:
I need to use different functions to treat numeric columns and string columns. What I am doing now is really dumb:

allc = list((agg.loc[:, (agg.dtypes==np.float64)|(agg.dtypes==np.int)]).columns)
for y in allc:
    treat_numeric(agg[y])

allc = list((agg.loc[:, (agg.dtypes!=np.float64)&(agg.dtypes!=np.int)]).columns)
for y in allc:
    treat_str(agg[y])

Is there a more elegant way to do this? E.g.

for y in agg.columns:
    if(dtype(agg[y]) == 'string'):
          treat_str(agg[y])
    elif(dtype(agg[y]) != 'string'):
          treat_numeric(agg[y])

Body:
Asked question title is general, but authors use case stated in the body of the question is specific. So any other answers may be used.

But in order to fully answer the title question it should be clarified that it seems like all of the approaches may fail in some cases and require some rework. I reviewed all of them (and some additional) in decreasing of reliability order (in my opinion):

1. Comparing types directly via == (accepted answer).

Despite the fact that this is accepted answer and has most upvotes count, I think this method should not be used at all. Because in fact this approach is discouraged in python as mentioned several times here.

But if one still want to use it - should be aware of some pandas-specific dtypes like pd.CategoricalDType, pd.PeriodDtype, or pd.IntervalDtype. Here one have to use extra type( ) in order to recognize dtype correctly:

s = pd.Series([pd.Period('2002-03','D'), pd.Period('2012-02-01', 'D')])
s
s.dtype == pd.PeriodDtype   # Not working
type(s.dtype) == pd.PeriodDtype # working

>>> 0    2002-03-01
>>> 1    2012-02-01
>>> dtype: period[D]
>>> False
>>> True

Another caveat here is that type should be pointed out precisely:

s = pd.Series([1,2])
s
s.dtype == np.int64 # Working
s.dtype == np.int32 # Not working

>>> 0    1
>>> 1    2
>>> dtype: int64
>>> True
>>> False

2. isinstance() approach.

This method has not been mentioned in answers so far.

So if direct comparing of types is not a good idea - lets try built-in python function for this purpose, namely - isinstance().

It fails just in the beginning, because assumes that we have some objects, but pd.Series or pd.DataFrame may be used as just empty containers with predefined dtype but no objects in it:

s = pd.Series([], dtype=bool)
s

>>> Series([], dtype: bool)

But if one somehow overcome this issue, and wants to access each object, for example, in the first row and checks its dtype like something like that:

df = pd.DataFrame({'int': [12, 2], 'dt': [pd.Timestamp('2013-01-02'), pd.Timestamp('2016-10-20')]},
                  index = ['A', 'B'])
for col in df.columns:
    df[col].dtype, 'is_int64 = %s' % isinstance(df.loc['A', col], np.int64)

>>> (dtype('int64'), 'is_int64 = True')
>>> (dtype('<M8[ns]'), 'is_int64 = False')

It will be misleading in the case of mixed type of data in single column:

df2 = pd.DataFrame({'data': [12, pd.Timestamp('2013-01-02')]},
                  index = ['A', 'B'])
for col in df2.columns:
    df2[col].dtype, 'is_int64 = %s' % isinstance(df2.loc['A', col], np.int64)

>>> (dtype('O'), 'is_int64 = False')

And last but not least - this method cannot directly recognize Category dtype. As stated in docs:

Returning a single item from categorical data will also return the value, not a categorical of length “1”.

df['int'] = df['int'].astype('category')
for col in df.columns:
    df[col].dtype, 'is_int64 = %s' % isinstance(df.loc['A', col], np.int64)

>>> (CategoricalDtype(categories=[2, 12], ordered=False), 'is_int64 = True')
>>> (dtype('<M8[ns]'), 'is_int64 = False')

So this method is also almost inapplicable.

3. df.dtype.kind approach.

This method yet may work with empty pd.Series or pd.DataFrames but has another problems.

First - it is unable to differ some dtypes:

df = pd.DataFrame({'prd'  :[pd.Period('2002-03','D'), pd.Period('2012-02-01', 'D')],
                   'str'  :['s1', 's2'],
                   'cat'  :[1, -1]})
df['cat'] = df['cat'].astype('category')
for col in df:
    # kind will define all columns as 'Object'
    print (df[col].dtype, df[col].dtype.kind)

>>> period[D] O
>>> object O
>>> category O

Second, what is actually still unclear for me, it even returns on some dtypes None.

4. df.select_dtypes approach.

This is almost what we want. This method designed inside pandas so it handles most corner cases mentioned earlier - empty DataFrames, differs numpy or pandas-specific dtypes well. It works well with single dtype like .select_dtypes('bool'). It may be used even for selecting groups of columns based on dtype:

test = pd.DataFrame({'bool' :[False, True], 'int64':[-1,2], 'int32':[-1,2],'float': [-2.5, 3.4],
                     'compl':np.array([1-1j, 5]),
                     'dt'   :[pd.Timestamp('2013-01-02'), pd.Timestamp('2016-10-20')],
                     'td'   :[pd.Timestamp('2012-03-02')- pd.Timestamp('2016-10-20'),
                              pd.Timestamp('2010-07-12')- pd.Timestamp('2000-11-10')],
                     'prd'  :[pd.Period('2002-03','D'), pd.Period('2012-02-01', 'D')],
                     'intrv':pd.arrays.IntervalArray([pd.Interval(0, 0.1), pd.Interval(1, 5)]),
                     'str'  :['s1', 's2'],
                     'cat'  :[1, -1],
                     'obj'  :[[1,2,3], [5435,35,-52,14]]
                    })
test['int32'] = test['int32'].astype(np.int32)
test['cat'] = test['cat'].astype('category')

Like so, as stated in the docs:

test.select_dtypes('number')

>>>     int64   int32   float   compl   td
>>> 0      -1      -1   -2.5    (1-1j)  -1693 days
>>> 1       2       2    3.4    (5+0j)   3531 days

On may think that here we see first unexpected (at used to be for me: question) results - TimeDelta is included into output DataFrame. But as answered in contrary it should be so, but one have to be aware of it. Note that bool dtype is skipped, that may be also undesired for someone, but it's due to bool and number are in different "subtrees" of numpy dtypes. In case with bool, we may use test.select_dtypes(['bool']) here.

Next restriction of this method is that for current version of pandas (0.24.2), this code: test.select_dtypes('period') will raise NotImplementedError.

And another thing is that it's unable to differ strings from other objects:

test.select_dtypes('object')

>>>     str     obj
>>> 0    s1     [1, 2, 3]
>>> 1    s2     [5435, 35, -52, 14]

But this is, first - already mentioned in the docs. And second - is not the problem of this method, rather the way strings are stored in DataFrame. But anyway this case have to have some post processing.

5. df.api.types.is_XXX_dtype approach.

This one is intended to be most robust and native way to achieve dtype recognition (path of the module where functions resides says by itself) as i suppose. And it works almost perfectly, but still have at least one caveat and still have to somehow distinguish string columns.

Besides, this may be subjective, but this approach also has more 'human-understandable' number dtypes group processing comparing with .select_dtypes('number'):

for col in test.columns:
    if pd.api.types.is_numeric_dtype(test[col]):
        print (test[col].dtype)

>>> bool
>>> int64
>>> int32
>>> float64
>>> complex128

No timedelta and bool is included. Perfect.

My pipeline exploits exactly this functionality at this moment of time, plus a bit of post hand processing.

Output.

Hope I was able to argument the main point - that all discussed approaches may be used, but only pd.DataFrame.select_dtypes() and pd.api.types.is_XXX_dtype should be really considered as the applicable ones.


问:
How to retrieve the click event's value of a range input with an Ipad?
Currently working on a custom slider (i.e. input of type "range") inside a react typescript website, it works well on desktop (MacOs and Windows + targeted browsers) and android but something is missing on Ipad (we only focus tablets).
The issue is that we can't set the value by tapping on the slider itself : we can drag it and tap on the labels in top of it but not inside.

I've seen many topics telling that Apple touchable device works differently for many events so I have debug mine to see what was wrong.
My "onClick" method set the current value of the slider based on the value coming from the event but the result shows that, only when executing on Ipad (on Safari and Chrome), those two variables are equals (and so my slider update its value correctly but with the current one) !
In any other environnement, all is working fine and the value of the event is correctly what should be the "future value".

I've also test the different touch events as described below but none was trigger, even with some default preventing.

This is the slider itself (only onClick is triggered) :

```<code><input
    type="range"
    min={-half}
    max={half}
    step="1"
    value={this.state.selectedRange}
    onTouchStart={(e: any) => { console.log("on touch : " + e.target.value);}}
    onTouchMove={(e: any) => { console.log("on touch : " + e.target.value);}}
    onTouchCancel={(e: any) => { console.log("on touch : " + e.target.value);}}
    onTouchEnd={(e: any) => { console.log("on touch : " + e.target.value);}}
    onTouch={(e: any) => { console.log("on touch : " + e.target.value);}}
    onClick={(e: any) => this.onClickSlider(e, "Inputslider + changer")}
    defaultValue={this.state.selectedRange}
    onChange={(e: any) => { this.onChange(e); }}
/>
</code>```

And the onClickSlider :

```<code>onClickSlider(e: any, m: string) {
    let value: any = e.target.value;

    console.log("New Value : " + e.target.value);
    // target value is equal to the current value... (only on Ipad)

    if (this.props.onChange) {
        if (!this.props.slider) {
            value = value - 1;
        }
        this.props.onChange(value);
    }
}
</code>```

I didn't expect an event's value behavior to change so drastically...

Does anyone has a suggestion on how can I retrieve the value of the position where the user touch the slider (it can involved specific platform condition) ?

Thank you !

答:
Try this range input setup to see if it suits your needs. It's based on jQuery, but you should grasp the idea. I tried many failing solutions, and couldn't use preventDefault for my case, so I drummed up this gem that allows instant range input thumb positioning/sliding wherever you touchstart and touchmove on the element:

```<code>document.on('touchstart touchmove', 'input[type="range"]', function(e){

var len = $(this).attr('max');
var offset = $(this).offset();
var xxx = (e.pageX - offset.left);
var xPercent = xxx/$(this).width();
var xPos = Math.round(len)*xPercent;

$(this).attr('value',xPos);
$(this).val(xPos).trigger('input');

});
</code>```

Body:
Currently working on a custom slider (i.e. input of type "range") inside a react typescript website, it works well on desktop (MacOs and Windows + targeted browsers) and android but something is missing on Ipad (we only focus tablets).
The issue is that we can't set the value by tapping on the slider itself : we can drag it and tap on the labels in top of it but not inside.

I've seen many topics telling that Apple touchable device works differently for many events so I have debug mine to see what was wrong.
My "onClick" method set the current value of the slider based on the value coming from the event but the result shows that, only when executing on Ipad (on Safari and Chrome), those two variables are equals (and so my slider update its value correctly but with the current one) !
In any other environnement, all is working fine and the value of the event is correctly what should be the "future value".

I've also test the different touch events as described below but none was trigger, even with some default preventing.

This is the slider itself (only onClick is triggered) :

<input
    type="range"
    min={-half}
    max={half}
    step="1"
    value={this.state.selectedRange}
    onTouchStart={(e: any) => { console.log("on touch : " + e.target.value);}}
    onTouchMove={(e: any) => { console.log("on touch : " + e.target.value);}}
    onTouchCancel={(e: any) => { console.log("on touch : " + e.target.value);}}
    onTouchEnd={(e: any) => { console.log("on touch : " + e.target.value);}}
    onTouch={(e: any) => { console.log("on touch : " + e.target.value);}}
    onClick={(e: any) => this.onClickSlider(e, "Inputslider + changer")}
    defaultValue={this.state.selectedRange}
    onChange={(e: any) => { this.onChange(e); }}
/>

And the onClickSlider :

onClickSlider(e: any, m: string) {
    let value: any = e.target.value;

    console.log("New Value : " + e.target.value);
    // target value is equal to the current value... (only on Ipad)

    if (this.props.onChange) {
        if (!this.props.slider) {
            value = value - 1;
        }
        this.props.onChange(value);
    }
}

I didn't expect an event's value behavior to change so drastically...

Does anyone has a suggestion on how can I retrieve the value of the position where the user touch the slider (it can involved specific platform condition) ?

Thank you !

Body:
Try this range input setup to see if it suits your needs. It's based on jQuery, but you should grasp the idea. I tried many failing solutions, and couldn't use preventDefault for my case, so I drummed up this gem that allows instant range input thumb positioning/sliding wherever you touchstart and touchmove on the element:

document.on('touchstart touchmove', 'input[type="range"]', function(e){

var len = $(this).attr('max');
var offset = $(this).offset();
var xxx = (e.pageX - offset.left);
var xPercent = xxx/$(this).width();
var xPos = Math.round(len)*xPercent;

$(this).attr('value',xPos);
$(this).val(xPos).trigger('input');

});


问:
Cannot inject request paraemter into blade view file
I have the following URL:

https://example.com/?email=test@test.com

then I have the following blade template

<input value="{{Request::query('email') or old('email')}}">

But it's not displaying the email I passed in the get parameter into the input. Instead, it's displaying the value 1

Tried searching haven't found a solution that works.

答:
You can try this:</p>

```<code><input value="{{ request()->email }}">
</code>```

Body:
You can try this:

<input value="{{ request()->email }}">


问:
Selecting an option element from a dropdown by its text value
Given an HTML form element like:

```<code><select id='mydropdown'>
  <option value='foo'>Spam</option>
  <option value='bar'>Eggs</option>
</select>
</code>```

I know I can select the first option with

```<code>document.getElementById("mydropdown").value='foo'
</code>```

However, say I have a variable with the value "Spam"; can I select a dropdown item by its text rather than by its value?

答:
Older IE does not handle options of a select as child nodes, but all browsers implement the text property of a select's option collection.

```<code>function selectbytext(sel, txt){
    if(typeof sel== 'string'){
        sel= document.getELementById(sel) || document.getELementsByName(sel)[0];
    }
    var opts= sel.options;
    for(var i= 0, L= opts.length; i<L; i++){
        if(opts[i].text== txt){
            sel.selectedIndex= i;
            break;
        }
    }
    return i;
}
</code>```

Body:
Given an HTML form element like:

<select id='mydropdown'>
  <option value='foo'>Spam</option>
  <option value='bar'>Eggs</option>
</select>

I know I can select the first option with

document.getElementById("mydropdown").value='foo'

However, say I have a variable with the value "Spam"; can I select a dropdown item by its text rather than by its value?

Body:
Older IE does not handle options of a select as child nodes, but all browsers implement the text property of a select's option collection.

function selectbytext(sel, txt){
    if(typeof sel== 'string'){
        sel= document.getELementById(sel) || document.getELementsByName(sel)[0];
    }
    var opts= sel.options;
    for(var i= 0, L= opts.length; i<L; i++){
        if(opts[i].text== txt){
            sel.selectedIndex= i;
            break;
        }
    }
    return i;
}


问:
How to tokenize on regex pattern and sort the resulting list?
I have a file that looks something like this:

```<code>select a,b,c FROM Xtable
select a,b,c FROM Vtable
select a,b,c FROM Atable
select a,b,c FROM Atable
select d,e,f FROM Atable
</code>```

I want to get a sortedMap:

```<code>{
"Atable":["select a,b,c FROM Atable", "select d,e,f FROM Atable"],
"Vtable":["select a,b,c FROM Vtable"],
"Xtable":["select a,b,c FROM Xtable"]
}
</code>```

The keys of sortedMap will be tableName and values being the textline in list.

I started off with this, but stuck in tokenizing the line for regex matching:

```<code>import re

f = open('mytext.txt', 'r')
x = f.readlines()
print x
f.close()
for i in x:
    p = re.search(".* FROM ", i)
 //now how to tokenize and get the value that follows FROM
</code>```

答:
You can use a combination of defaultdict and regular expressions. Let lines be a list of your lines:

```<code>from collections import defaultdict
pattern = "(select .+ from (\S+).*)"
results = defaultdict(list)

for line in lines:
     query, table = re.findall(pattern, line.strip(), flags=re.I)[0]
     results[table].append(query)
</code>```

Actually, the right way to read the file would be:

```<code>with open('mytext.txt') as infile:
    for line in infile:
         query, table = re.findall(pattern, line.strip(), flags=re.I)[0]
         results[table].append(query)
</code>```

The result is, naturally, a defaultdict. If you want to convert it into an ordered dictionary, call the dictionary constructor:

```<code>from collections import OrderedDict
OrderedDict(sorted(results.items()))
#OrderedDict([('Atable', ['select a,b,c FROM Atable', ...
</code>```

You can make the pattern more robust to keep track of commas, valid identifiers, etc.

Body:
I have a file that looks something like this:

select a,b,c FROM Xtable
select a,b,c FROM Vtable
select a,b,c FROM Atable
select a,b,c FROM Atable
select d,e,f FROM Atable

I want to get a sortedMap:

{
"Atable":["select a,b,c FROM Atable", "select d,e,f FROM Atable"],
"Vtable":["select a,b,c FROM Vtable"],
"Xtable":["select a,b,c FROM Xtable"]
}

The keys of sortedMap will be tableName and values being the textline in list.

I started off with this, but stuck in tokenizing the line for regex matching:

import re

f = open('mytext.txt', 'r')
x = f.readlines()
print x
f.close()
for i in x:
    p = re.search(".* FROM ", i)
 //now how to tokenize and get the value that follows FROM

Body:
You can use a combination of defaultdict and regular expressions. Let lines be a list of your lines:

from collections import defaultdict
pattern = "(select .+ from (\S+).*)"
results = defaultdict(list)

for line in lines:
     query, table = re.findall(pattern, line.strip(), flags=re.I)[0]
     results[table].append(query)

Actually, the right way to read the file would be:

with open('mytext.txt') as infile:
    for line in infile:
         query, table = re.findall(pattern, line.strip(), flags=re.I)[0]
         results[table].append(query)

The result is, naturally, a defaultdict. If you want to convert it into an ordered dictionary, call the dictionary constructor:

from collections import OrderedDict
OrderedDict(sorted(results.items()))
#OrderedDict([('Atable', ['select a,b,c FROM Atable', ...

You can make the pattern more robust to keep track of commas, valid identifiers, etc.