问:
python apply a function after checking if variable is single list or list of lists
I intend to apply a function to a variable. I do not know beforehand if the incoming variable will be a list of list or a single list. e.g

```<code>var_name = [a, b, c]
or
var_name = [[a,b,c], [d,e,f], [h,i,j]]
</code>```

The list of list could contain as many lists as possible. How do I go about verifying if the variable is a list or list of lists. I intend to apply a function depending on the type. I tried to use len(var_name) but the length for list will be the number of items in single list while for list of lists, it is the number of lists in the list of lists.

what I am trying to achieve is this:

```<code>#function for list
def apply_val(lst):
    do something with single list
#function for list of list
def apply_val2(lst):
    do something with list of lists

var_name = single_list or list_of_lists
if var_name == single list
    apply_val(single_list)
else:
    apply_val(list_of_lists)
</code>```

How do I check if the var_name is a list or list of lists?

答:
list of lists does not mean anything, what is [["foo", "bar"], "baz"] ?

However, if you are sure you could only have "list of something that is not a list" and "list of list", just:

Check the list is not empty

Then, check the type of first item

```<code>if len(my_list) > 0:
  if isinstance(my_list[0], list):
    # List of list
    pass
  else:
    # Simple list
    pass
</code>```

Body:
I intend to apply a function to a variable. I do not know beforehand if the incoming variable will be a list of list or a single list. e.g

var_name = [a, b, c]
or
var_name = [[a,b,c], [d,e,f], [h,i,j]]

The list of list could contain as many lists as possible. How do I go about verifying if the variable is a list or list of lists. I intend to apply a function depending on the type. I tried to use len(var_name) but the length for list will be the number of items in single list while for list of lists, it is the number of lists in the list of lists.

what I am trying to achieve is this:

#function for list
def apply_val(lst):
    do something with single list
#function for list of list
def apply_val2(lst):
    do something with list of lists

var_name = single_list or list_of_lists
if var_name == single list
    apply_val(single_list)
else:
    apply_val(list_of_lists)

How do I check if the var_name is a list or list of lists?

Body:
list of lists does not mean anything, what is [["foo", "bar"], "baz"] ?

However, if you are sure you could only have "list of something that is not a list" and "list of list", just:

Check the list is not empty

Then, check the type of first item

if len(my_list) > 0:
  if isinstance(my_list[0], list):
    # List of list
    pass
  else:
    # Simple list
    pass


来源: stackexchange

问:
How to add @Override, @Deprecate and static modifiers to methods automatically for all project Java classes where necessary?
I need to insert @Override / @Deprecated annotations and static modifiers automatically where necessary to all Java files of concrete project is opened in Eclipse IDE.

Eclipse has a great ability to insert @Override/@Deprecate annotations and add static modifiers on Java files saving (Preferences -> Java -> Editor -> Save actions -> Additional actions). But Eclipse can apply these actions only on edited java file and only when saving it.

Sure, I can insert a tab or space into the each file using Eclipse as editor and save it to activate Eclipse refactoring tools on save action, but I have a very big code amount to process, so this is very nasty.

Maybe there is an Eclipse plugin which supports such type of code refactoring?

If there are no solutions, I`ll try to write my own Eclipse RCP plugin for that.

答:
It can be done by save actions. When you save the file, eclipse will automatically add these annotation for you.

Please follow the following setting:

Window => Preferences => Java => Editor => Save Actions, and check "Add missing @Override annotations'.

ContentLicense: CC BY-SA 4.0


问:
How do I embed a webgl build game that I created in unity into a website
okay, so I have a game that I developed in unity. I exported it as a WebGL build now wanted to know, would it possible to embed this game into a website? At this point in time, I only know how to create web forms using ASP.net in c# with visual studio and I would like to be able to embed my game into a website I created.</p>

答:
well.

first Upload Unity WebGL outputs to your web server,

and in your website, Simply just create iframe and put your webgl index.html in the iframe.


问:
Faster way to fetch a single data from db with codeigniter
hi want to get only one column from one result from my database. So i do it in this way

```<code>$this->db->select('myclolumn')->where('id',$id);
$query = $this->db->get('mytable');
$temp=$query->row_array();
$finalresult=$temp['mycolumn'];
</code>```

Maybe there is a easier or faster way to do the same?

答:
You can do it like this:

```<code>$finalresult = $this->db->select('myclolumn')
                        ->where('id',$id)
                        ->get('mytable')->row()
                        ->mycolumn;
</code>```

All in only one command instead of a lot of variables and extra code.

In case you need to provide a default value if the row is null, break the command to:

```<code>$row = $this->db->select('myclolumn')
                        ->where('id',$id)
                        ->get('mytable')
                        ->row();
$finalresult = ($row)?$row->mycolumn:'your default value';
</code>```

Body:
hi want to get only one column from one result from my database. So i do it in this way

$this->db->select('myclolumn')->where('id',$id);
$query = $this->db->get('mytable');
$temp=$query->row_array();
$finalresult=$temp['mycolumn'];

Maybe there is a easier or faster way to do the same?

Body:
You can do it like this:

$finalresult = $this->db->select('myclolumn')
                        ->where('id',$id)
                        ->get('mytable')->row()
                        ->mycolumn;

All in only one command instead of a lot of variables and extra code.

In case you need to provide a default value if the row is null, break the command to:

$row = $this->db->select('myclolumn')
                        ->where('id',$id)
                        ->get('mytable')
                        ->row();
$finalresult = ($row)?$row->mycolumn:'your default value';


问:
rvest - find html-node with last page number
I'm learning web scraping and created a little exercise for myself to scrape all titles of a recipe site: https://pinchofyum.com/recipes?fwp_paged=1. (I got inspired by this post: https://www.kdnuggets.com/2017/06/web-scraping-r-online-food-blogs.html).

I want to scrape the value of the last page number, which is (at time of writing) number 64. You can find the number of pages at the bottom. I see that this is stored as "a.facetwp-page last", but for some reason cannot access this node. I can see that the page number values are stored as 'data-page', but I'm unable to get this value through 'html_attrs'.

I believe the parent node is "div.facetwp-pager" and I can access that one as follows:

```<code>library(rvest)
pg <- read_html("https://pinchofyum.com/recipes")
html_nodes(pg, "div.facetwp-pager")
</code>```

But this is as far as I get. I guess I'm missing something small, but cannot figure out what it is. I know about Rselenium, but I would like to know if and how to get that last page value (64) with rvest.

答:
Sometimes scraping with rvest doesn't work, especially when the webpage is dynamically generated with java script (I also wasn't able to scrape this info with rvest). In those cases, you can use the RSelenium package. I was able to scrape your desired element like this:

```<code>library(RSelenium)

rD <- rsDriver(browser = c("firefox")) #specify browser type you want Selenium to open
remDr <- rD$client
remDr$navigate("https://pinchofyum.com/recipes?fwp_paged=1") # navigates to webpage

webElem <- remDr$findElement(using = "css selector", ".last") #find desired element

txt <- webElem$getElementText() # gets us the HTML

#> txt
#>[[1]]
#>[1] "64"
</code>```

Body:
I'm learning web scraping and created a little exercise for myself to scrape all titles of a recipe site: https://pinchofyum.com/recipes?fwp_paged=1. (I got inspired by this post: https://www.kdnuggets.com/2017/06/web-scraping-r-online-food-blogs.html).

I want to scrape the value of the last page number, which is (at time of writing) number 64. You can find the number of pages at the bottom. I see that this is stored as "a.facetwp-page last", but for some reason cannot access this node. I can see that the page number values are stored as 'data-page', but I'm unable to get this value through 'html_attrs'.

I believe the parent node is "div.facetwp-pager" and I can access that one as follows:

library(rvest)
pg <- read_html("https://pinchofyum.com/recipes")
html_nodes(pg, "div.facetwp-pager")

But this is as far as I get. I guess I'm missing something small, but cannot figure out what it is. I know about Rselenium, but I would like to know if and how to get that last page value (64) with rvest.

Body:
Sometimes scraping with rvest doesn't work, especially when the webpage is dynamically generated with java script (I also wasn't able to scrape this info with rvest). In those cases, you can use the RSelenium package. I was able to scrape your desired element like this:

library(RSelenium)

rD <- rsDriver(browser = c("firefox")) #specify browser type you want Selenium to open
remDr <- rD$client
remDr$navigate("https://pinchofyum.com/recipes?fwp_paged=1") # navigates to webpage

webElem <- remDr$findElement(using = "css selector", ".last") #find desired element

txt <- webElem$getElementText() # gets us the HTML

#> txt
#>[[1]]
#>[1] "64"


问:
How to check if consecutive digits in a number are even or odd?
I am doing some exercises and learning Python. I need to be able to check for an input number whether its consecutive digits are even or odd. So, if the first number is odd, the next should be even and so on in order for the terms to comply. I have the following code:

```<code>def par_nepar(n):
    cifre = []

    while n != 0:
        cifre.append(n % 10)
        n //= 10

    cifre = cifre[::-1]
    ind = cifre[0]
    for broj in cifre:
        if cifre[0] % 2 == 0:
            # for br in range(len(cifre)):
            if cifre[ind + 1] % 2 != 0:
                ind = cifre[ind+1]

n = int(input("Unesite broj n: "))
print(par_nepar(n))
</code>```

As you can see, I am struggling with index looping. I took the input number and transformed it into a list. Created a variable for index[0] and don't really know how to loop through consecutive indexes. I know I might be able to use zip or enumerate but I think that is not a truly pythonic solution here and probably there is a simpler way to loop over consecutive list numbers and compare them to index[-1].

Input examples:

```<code>>>>print(par_nepar(2749)) # Every consecutive digits shifts odd->even or even->odd
True
>>>print(par_nepar(2744)) # Two last digits are even
False
</code>```

答:
Maybe you would also like this one liner.

In a single loop, we find if the number mod 2 is the same as the (first number + the index) mod 2.

This works for you alternating use case.

```<code>par_nepar = lambda x: all([(int(k) % 2) == ((i + int(str(x)[0])) % 2) for (i, k) in enumerate(str(x))])

print(par_nepar(2749))
print(par_nepar(2744))

# Output
True
False
</code>```

Or if you want with the strings you said, slightly bigger

```<code>par_nepar = lambda x: 'The number complies to the needed terms. ' if all(
    [(int(k) % 2) == ((i + int(str(x)[0])) % 2) for (i, k) in
     enumerate(str(x))]) else "The number doesn't comply to the needed terms."

#Output
The number complies to the needed terms.
The number doesn't comply to the needed terms.
</code>```

Body:
I am doing some exercises and learning Python. I need to be able to check for an input number whether its consecutive digits are even or odd. So, if the first number is odd, the next should be even and so on in order for the terms to comply. I have the following code:

def par_nepar(n):
    cifre = []

    while n != 0:
        cifre.append(n % 10)
        n //= 10

    cifre = cifre[::-1]
    ind = cifre[0]
    for broj in cifre:
        if cifre[0] % 2 == 0:
            # for br in range(len(cifre)):
            if cifre[ind + 1] % 2 != 0:
                ind = cifre[ind+1]

n = int(input("Unesite broj n: "))
print(par_nepar(n))

As you can see, I am struggling with index looping. I took the input number and transformed it into a list. Created a variable for index[0] and don't really know how to loop through consecutive indexes. I know I might be able to use zip or enumerate but I think that is not a truly pythonic solution here and probably there is a simpler way to loop over consecutive list numbers and compare them to index[-1].

Input examples:

>>>print(par_nepar(2749)) # Every consecutive digits shifts odd->even or even->odd
True
>>>print(par_nepar(2744)) # Two last digits are even
False

Body:
Maybe you would also like this one liner.

In a single loop, we find if the number mod 2 is the same as the (first number + the index) mod 2.

This works for you alternating use case.

par_nepar = lambda x: all([(int(k) % 2) == ((i + int(str(x)[0])) % 2) for (i, k) in enumerate(str(x))])

print(par_nepar(2749))
print(par_nepar(2744))

# Output
True
False

Or if you want with the strings you said, slightly bigger

par_nepar = lambda x: 'The number complies to the needed terms. ' if all(
    [(int(k) % 2) == ((i + int(str(x)[0])) % 2) for (i, k) in
     enumerate(str(x))]) else "The number doesn't comply to the needed terms."

#Output
The number complies to the needed terms.
The number doesn't comply to the needed terms.


问:
Show column names of the table in 1st data row of the query output dynamically in Oracle
There is one table , let us say VW_RESULT like below :

ID        Quarter   Risk

00001     Q0        2

00001     Q1        3

00001     Q2        1

00001     Q3        1

00001     Q4        2

Now I have to show the column names in the 1st row.

I want output like this :

Col1      Col2      Col3

ID        Quarter   Risk

00001     Q0        2

00001     Q1        3

00001     Q2        1

00001     Q3        1

00001     Q4        2

I can easily achieve this if the number of columns is fixed, using UNION ALL.

But the number of columns will vary from time to time.

I want to make this dynamic so that I don't have to put column names manually.

I am using Oracle 11g.

答: Take your columns in variable and concatenate all columns you are getting at every run..execute your with execute immediate and concatenate your variable with the statement as well</p>


问:
Unable to find HTML table with Python using BeautifulSoup
I am unable to locate the HTML table with class table-light border rounded. Do you all know why this may be?

Here is my attempt:

```<code>import requests
from bs4 import BeautifulSoup

url = "https://iextrading.com/trading/eligible-symbols/"
r = requests.get(url)
soup = BeautifulSoup(r.text, 'html.parser')
table = soup.find('table', class_ = 'table-light border rounded')
print(table) # returns "None"
</code>```

Note, there is no table tag in the soup object / variable. However, when inspecting the webpage, there is indeed a table tag. I can't seem to locate it.

Any help or guidance is much appreciated. I am trying to create a list of Symbols.

Please see the following screenshots for additional information:

答:
The site is loading data with a xhr request you have to inspect them from networks tab and find out from where they are loading data.

In your case they are loading data from Here

Body:
I am unable to locate the HTML table with class table-light border rounded. Do you all know why this may be?

Here is my attempt:

import requests
from bs4 import BeautifulSoup

url = "https://iextrading.com/trading/eligible-symbols/"
r = requests.get(url)
soup = BeautifulSoup(r.text, 'html.parser')
table = soup.find('table', class_ = 'table-light border rounded')
print(table) # returns "None"

Note, there is no table tag in the soup object / variable. However, when inspecting the webpage, there is indeed a table tag. I can't seem to locate it.

Any help or guidance is much appreciated. I am trying to create a list of Symbols.

Please see the following screenshots for additional information:


问:
Insert key value pairs from array into SQL query string
I have this code with array:

```<code>const dataToset = [
    { key: 'key1', value: "some data" },
    { key: 'key2', value: 37 },
];

await db.query(`
    UPDATE some_table
    SET ${dataToset.map(data => `${data.key} = ${data.value}`)}
    WHERE id ${id}`);
</code>```

result query is next: UPDATE some_table SET key1=some data,key2=37 WHERE id=1
and it fails, because some data should be passed as string.
How to get valid query: UPDATE some_table SET key1="some data",key2=37 WHERE id=1?

p.s. I am getting next error: syntax error near "data"

答:
Aside from syntax error (it has to be WHERE id=1), I would do explicit array to string conversion, using .join(', ') and somewhat change your template string, paying attention that (only) string value should be enclosed into single quotes:

const dataToset = [
          { key: 'key1', value: "some data" },
          { key: 'key2', value: 37 },
      ],
      id = 1
      query = `
        UPDATE some_table
        SET ${
          dataToset
            .map(({key,value}) =>
              typeof value == 'string' ?
              key+"='"+value+"'" :
              key+'='+value)
            .join(', ')
        }
        WHERE id=${id}
      `

console.log(query)```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper{min-height:100%;}</code>```

Body:
I have this code with array:

const dataToset = [
    { key: 'key1', value: "some data" },
    { key: 'key2', value: 37 },
];

await db.query(`
    UPDATE some_table
    SET ${dataToset.map(data => `${data.key} = ${data.value}`)}
    WHERE id ${id}`);

result query is next: UPDATE some_table SET key1=some data,key2=37 WHERE id=1
and it fails, because some data should be passed as string.
How to get valid query: UPDATE some_table SET key1="some data",key2=37 WHERE id=1?

p.s. I am getting next error: syntax error near "data"

Body:
Aside from syntax error (it has to be WHERE id=1), I would do explicit array to string conversion, using .join(', ') and somewhat change your template string, paying attention that (only) string value should be enclosed into single quotes:

const dataToset = [
          { key: 'key1', value: "some data" },
          { key: 'key2', value: 37 },
      ],
      id = 1
      query = `
        UPDATE some_table
        SET ${
          dataToset
            .map(({key,value}) =>
              typeof value == 'string' ?
              key+"='"+value+"'" :
              key+'='+value)
            .join(', ')
        }
        WHERE id=${id}
      `

console.log(query)

.as-console-wrapper{min-height:100%;}


问:
jQuery get img width after src change and before fadeIn
I've got quite the problem with jQuery and a custom photo gallery I am building.  I've searched high and low and tried endlessly different solutions but nothing is working perfectly.  So let me present the information:

This photo gallery has thumbnails on the left side and a big image in the center.  Every thumbnail can be clicked which calls a function passing in its' ID.  What I want it to do is, AJAX POST to server to get image comment and image name.  Fadeout the current big picture div, switch the src in the img tag, get the new image's width, set the width of an overlaying comment div, fadeIn the big picture div.

The problem is that I can't get the width of the new image after it has loaded (even using the a form of .load() to wait for the image to finish loading).  Now I can get it to work when I fadeIn the new image and then get the width but that isn't what I need.  I need to get the width and set the div's width before I fadeIn.

Any ideas or corrections would be great, hopefully I have provided enough information.

Here is the code I am wrestling with:

```<code>function thumbClick(val) {
    $.post('ajax.php', {
        photo_in: val
    }, function (data) {
        $('div#picture').fadeOut('slow', function () {

            //$('img#big-picture').load(function(){
            $('img#big-picture').one('load', function () {

                //alert($('img#big-picture').width());
                //will alert 0
                $('div#picture').fadeIn('slow', function () {
                    $('div#comment-box').width($('img#big-picture').width());
                    //set comment to what I want
                    $('p#comment').html("");
                    //alert($('img#big-picture').width());
                    //will alert new image width after FadeIN
                    $('p#comment').html(data.comment);
                });

            }); //end of one(load)
            $('img#big-picture').attr("src", data.newImage);

        }); //end of fadeout
    }, "json"); //end of post
}
</code>```

答:
I've encountered this before; what seems to be the easiest solution is to quickly show the image, grab it's width, and hide it again. This operation occurs so quickly users will never notice.
In your case, i believe the code would be:</p>

```<code>$("#big-picture").show();
alert($('#big-picture').width()); //this should be the real width, now
$("#big-picture").hide();
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I've got quite the problem with jQuery and a custom photo gallery I am building.  I've searched high and low and tried endlessly different solutions but nothing is working perfectly.  So let me present the information:

This photo gallery has thumbnails on the left side and a big image in the center.  Every thumbnail can be clicked which calls a function passing in its' ID.  What I want it to do is, AJAX POST to server to get image comment and image name.  Fadeout the current big picture div, switch the src in the img tag, get the new image's width, set the width of an overlaying comment div, fadeIn the big picture div.

The problem is that I can't get the width of the new image after it has loaded (even using the a form of .load() to wait for the image to finish loading).  Now I can get it to work when I fadeIn the new image and then get the width but that isn't what I need.  I need to get the width and set the div's width before I fadeIn.

Any ideas or corrections would be great, hopefully I have provided enough information.

Here is the code I am wrestling with:

function thumbClick(val) {
    $.post('ajax.php', {
        photo_in: val
    }, function (data) {
        $('div#picture').fadeOut('slow', function () {

            //$('img#big-picture').load(function(){
            $('img#big-picture').one('load', function () {

                //alert($('img#big-picture').width());
                //will alert 0
                $('div#picture').fadeIn('slow', function () {
                    $('div#comment-box').width($('img#big-picture').width());
                    //set comment to what I want
                    $('p#comment').html("");
                    //alert($('img#big-picture').width());
                    //will alert new image width after FadeIN
                    $('p#comment').html(data.comment);
                });

            }); //end of one(load)
            $('img#big-picture').attr("src", data.newImage);

        }); //end of fadeout
    }, "json"); //end of post
}

Body:
I've encountered this before; what seems to be the easiest solution is to quickly show the image, grab it's width, and hide it again. This operation occurs so quickly users will never notice.
In your case, i believe the code would be:

$("#big-picture").show();
alert($('#big-picture').width()); //this should be the real width, now
$("#big-picture").hide();


问:
Angular CLI - different sets of dev and prod assets
I can't seem to find if and how it would be possible to use a different set of assets whenever I use the --prod switch of ng build.

The use case is that I have multiple projects with a common set of assets in a shared folder, so the configuration of each single project in angular.json is like this:

```<code>"assets": [
  {
    "glob": "**/*",
    "input": "src/assets",
    "output": "/assets/"
  },
  {
    "glob": "**/*",
    "input": "projects/project1/src/assets/",
    "output": "/assets/"
  }
],
...
"assets": [
  {
    "glob": "**/*",
    "input": "src/assets",
    "output": "/assets/"
  },
  {
    "glob": "**/*",
    "input": "projects/project2/src/assets/",
    "output": "/assets/"
  }
],

</code>```

When making production builds, I would like to remove the common src/assets path.

Is it possible?

答:
You need check for setting up configuration. This configuration will help you to create different environment for your project. In your case project 2.

you need to set different environment on the angular.json

```<code>"project2": {
          "fileReplacements": [
            {
              "replace": "", //project 1 folder
              "with": "" // project 2 folder
            },
            {
              "replace": "src/environments/environment.ts",
              "with": "src/environments/environment.prod.ts"
            }
          ]
        }
</code>```

after setup you can hit command

```<code>ng build --configuration project2
</code>```

Note: you need to set necessary parameter in new environment like below

```<code>"optimization": true,
"outputHashing": "all",
"sourceMap": false,
"extractCss": true,
"namedChunks": false,
"aot": true,
"extractLicenses": true,
"vendorChunk": false,
"buildOptimizer": true,
</code>```

Detail official documentation link https://angular.io/guide/build

Body:
I can't seem to find if and how it would be possible to use a different set of assets whenever I use the --prod switch of ng build.

The use case is that I have multiple projects with a common set of assets in a shared folder, so the configuration of each single project in angular.json is like this:

"assets": [
  {
    "glob": "**/*",
    "input": "src/assets",
    "output": "/assets/"
  },
  {
    "glob": "**/*",
    "input": "projects/project1/src/assets/",
    "output": "/assets/"
  }
],
...
"assets": [
  {
    "glob": "**/*",
    "input": "src/assets",
    "output": "/assets/"
  },
  {
    "glob": "**/*",
    "input": "projects/project2/src/assets/",
    "output": "/assets/"
  }
],

When making production builds, I would like to remove the common src/assets path.

Is it possible?

Body:
You need check for setting up configuration. This configuration will help you to create different environment for your project. In your case project 2.

you need to set different environment on the angular.json

"project2": {
          "fileReplacements": [
            {
              "replace": "", //project 1 folder
              "with": "" // project 2 folder
            },
            {
              "replace": "src/environments/environment.ts",
              "with": "src/environments/environment.prod.ts"
            }
          ]
        }

after setup you can hit command

ng build --configuration project2

Note: you need to set necessary parameter in new environment like below

"optimization": true,
"outputHashing": "all",
"sourceMap": false,
"extractCss": true,
"namedChunks": false,
"aot": true,
"extractLicenses": true,
"vendorChunk": false,
"buildOptimizer": true,

Detail official documentation link https://angular.io/guide/build


问:
Is there a way to pretty print SELECT query result in ClickHouse?
Alternative in ClickHouse Select query to pretty print like in MySQL vertically.

For example -

SELECT * from table \g;
```

<p>I found this resource but its just text
https://clickhouse-docs.readthedocs.io/en/latest/formats/vertical.html</p>

<p>With --multiline as a parameter for clickhouse-client I am getting following error . Though i can use \G format as per one of the answer without this param :</p>

``` :) select * from hits_v1 limit 2; \G
:-] ;

Syntax error (Multi-statements are not allowed): failed at position 30 (end of query):

select * from hits_v1 limit 2; \G ;
```

答:
Well, it was quick. I have to use FORMAT Parameter :

select * from hits_v1  limit 100  FORMAT Vertical;
```

More to study here :
https://clickhouse.tech/docs/en/interfaces/formats/

Body:
Alternative in ClickHouse Select query to pretty print like in MySQL vertically.

For example -

SELECT * from table \g;

I found this resource but its just text
https://clickhouse-docs.readthedocs.io/en/latest/formats/vertical.html

With --multiline as a parameter for clickhouse-client I am getting following error . Though i can use \G format as per one of the answer without this param :

 :) select * from hits_v1 limit 2; \G
:-] ;

Syntax error (Multi-statements are not allowed): failed at position 30 (end of query):

select * from hits_v1 limit 2; \G ;

Body:
Well, it was quick. I have to use FORMAT Parameter :

select * from hits_v1  limit 100  FORMAT Vertical;

More to study here :
https://clickhouse.tech/docs/en/interfaces/formats/


问:
Linkedlist keep track of min in constant time?

EDIT:

This isn't as trivial as
  you think. Consider the fact that each
  addition of a new number pushes out an
  old number from the linkedlist.

The solution doesn't seem to be as
  simple as keeping track of a min
  number with a variable. What if the
  minimum gets pushed out of the
  linkedlist? Then what? How do you know
  what the new min is?

I heard this interview question:

You have a fixed length linked list.

At time t=0, the linkedlist is filled
with random numbers.

At each increment in time, one new
number is fed into the head of the
linkedlist, and one number is pushed
out from the tail.

You are allowed only ONE traversal before the first time interval.

This means one traversal ever. Not once at every time t.

.

O(1) storage.

Your task is to be able to return the min of the linkedlist at every time interation.

What is an algorithm that would be able to do this?

Interesting note:

Since there's no information regarding time complexity, you are allowed to use sort operations. The only problem then is: sorting takes more than one iteration.

答:
So, basically, this is a queue, implemented as a linked list (correct me if I am wrong).
To solve this, I would just change the idea of the node. A typical node will have next pointer and a value. Change this to have three elements, nextPointer, value and minSoFar. If you don't like the idea of changing the queue design, still, read this algo and I have provided another idea at the end.

I think this can be done in O(1) The trick is while traversing the list, keep track of the smallest element encountered until that point in the list and store it in the current node. So, for example you have the following queue

Head at 5 and tail at 13

5 |7 |6 |9 |5 |13 |

My modified queue will contain the nodes like

{5,5}|{7,6}|{6,6}|{9,9}|{13,13}| ({nodeVal, minSoFar})

Now, consider an operation, adding 3 to the queue and removing 13, the queue becomes

{3,3}|{5,5}|{7,6}|{6,6}|{9,9}|

Since 3 is less than the current head element, the min so far for the head element is its value

Consider another case where you need to add 15 to the queue

{15,5}|{5,5}|{7,6}|{6,6}|{9,9}|

Since 15 is greater than the current head element, the current minimum value becomes 5.

So to find the minimum element in the queue/list, all you need to do is check the head element and your time complexity will be O(1)

If you don't want to modify the queue, maintain a parallel queue and keep the minValueSoFar in that queue and mirror the operations in that queue.


答:
if the single list is always just values AND the list of lists always contains ONLY lists, you can check if it is a single list or list of lists like so:

```<code>list1 = [1,2,3]
list2 = [[1,2,3],[1,2,3]]

if type(list2[0]) == list:
    print('list of lists')
else:
    print('single list')
</code>```

returns 'list of lists' for list2 and 'single list' for list1

if there is a mix you could do something like:

```<code>list3 = [1,[1,2,3], 4.343, 'string']
types = set([type(element) for element in list3])
if list in types and len(types) > 1:
    print('mixed')
</code>```

Title: python apply a function after checking if variable is single list or list of lists

Body:
I intend to apply a function to a variable. I do not know beforehand if the incoming variable will be a list of list or a single list. e.g

var_name = [a, b, c]
or
var_name = [[a,b,c], [d,e,f], [h,i,j]]

The list of list could contain as many lists as possible. How do I go about verifying if the variable is a list or list of lists. I intend to apply a function depending on the type. I tried to use len(var_name) but the length for list will be the number of items in single list while for list of lists, it is the number of lists in the list of lists.

what I am trying to achieve is this:

#function for list
def apply_val(lst):
    do something with single list
#function for list of list
def apply_val2(lst):
    do something with list of lists

var_name = single_list or list_of_lists
if var_name == single list
    apply_val(single_list)
else:
    apply_val(list_of_lists)

How do I check if the var_name is a list or list of lists?

Body:
if the single list is always just values AND the list of lists always contains ONLY lists, you can check if it is a single list or list of lists like so:

list1 = [1,2,3]
list2 = [[1,2,3],[1,2,3]]

if type(list2[0]) == list:
    print('list of lists')
else:
    print('single list')

returns 'list of lists' for list2 and 'single list' for list1

if there is a mix you could do something like:

list3 = [1,[1,2,3], 4.343, 'string']
types = set([type(element) for element in list3])
if list in types and len(types) > 1:
    print('mixed')


问:
Airflow Slack failed to send Message
I am trying to achieve Airflow integration with Slack,
have received the webhook URL, and created the connection as below. Why is it showing google.com ??

Why is it using the default http_conn_id and connecting to google ??

But got an error as below

ERROR - Error in sending a message to Slack channel #airflow-alerts
            by Airflow: 404:Not Found

```<code>{base_hook.py:83} INFO - Using connection to: id: http_default. Host: https://www.google.com/, Port: None, Schema: None, Login: None, Password: None, extra: {}
{logging_mixin.py:95} INFO - [2020-05-29 12:43:21,374] {http_hook.py:128} INFO - Sending 'POST' to url: https://www.google.com//T00A6ASFHD8S/G1FDF4K/a3zfKsadfsrScxgadfsdafOIgIvgW

requests.exceptions.HTTPError: 404 Client Error: Not Found for url: https://www.google.com//T00A6ASFHD8S/G1FDF4K/a3zfKsadfsrScxgadfsdafOIgIvgW
</code>```

But I got the below error, unable to figure out

答: Your connection is not setup correctly, you need to select HTTP as the Conn Type, leave the Extra field blank and put the webhook token (format is /STRING/STRING/STRING) in the Password field. Then you can use the SlackWebhookOperator operator which allows you to set the channel and username.

Title: Airflow Slack failed to send Message

Body:
I am trying to achieve Airflow integration with Slack,
have received the webhook URL, and created the connection as below. Why is it showing google.com ??

Why is it using the default http_conn_id and connecting to google ??

But got an error as below

ERROR - Error in sending a message to Slack channel #airflow-alerts
            by Airflow: 404:Not Found

{base_hook.py:83} INFO - Using connection to: id: http_default. Host: https://www.google.com/, Port: None, Schema: None, Login: None, Password: None, extra: {}
{logging_mixin.py:95} INFO - [2020-05-29 12:43:21,374] {http_hook.py:128} INFO - Sending 'POST' to url: https://www.google.com//T00A6ASFHD8S/G1FDF4K/a3zfKsadfsrScxgadfsdafOIgIvgW

requests.exceptions.HTTPError: 404 Client Error: Not Found for url: https://www.google.com//T00A6ASFHD8S/G1FDF4K/a3zfKsadfsrScxgadfsdafOIgIvgW

But I got the below error, unable to figure out


问:
Convert a Pandas 'DOB' column to 'Age' but it has NaT/empty values due to which it throws an error "NaTType does not support strftime"
I have a client's data which contains a DOB column and I want to calculate the age, but there are missing cells so it throws an error "NaTType does not support strftime". I want to populate the missing value with mean age later. Here's what I tried</p>

```<code>for row in new_data['DOB']:
    if row is pd.NaT:
        continue
    else:
        new_data['DOB'] = new_data['DOB'].apply('{:06}'.format)
        now = pd.Timestamp('now')
        new_data['DOB'] = pd.to_datetime(new_data['DOB'], format='%m%d%y')
        new_data['DOB'] = new_data['DOB'].where(df['DOB'] < now, new_data['DOB'] -  np.timedelta64(100, 'Y'))
        new_data['age'] = (now - new_data['DOB']).astype('<m8[Y]')

new_data

</code>```

答:
Assuming that your DOB column is of datetime time you could do (pd.Timestamp('now')-df.DOB)/pd.Timedelta('1Y').

Example:

```<code>df = pd.DataFrame({'DOB': pd.to_datetime('2020')-pd.to_timedelta(pd.np.random.randint(7000,20000,5), 'D')})
df.iloc[[1,3]] = None

df['age'] = (pd.Timestamp('now') - df.DOB)/pd.Timedelta('1Y')
df.age = df.age.fillna(df.age.mean()).astype(int)
</code>```

Result:

```<code>         DOB  age
0 1997-02-05   23
1        NaT   25
2 1991-12-08   28
3        NaT   25
4 1995-12-30   24
</code>```

Body:
I have a client's data which contains a DOB column and I want to calculate the age, but there are missing cells so it throws an error "NaTType does not support strftime". I want to populate the missing value with mean age later. Here's what I tried

for row in new_data['DOB']:
    if row is pd.NaT:
        continue
    else:
        new_data['DOB'] = new_data['DOB'].apply('{:06}'.format)
        now = pd.Timestamp('now')
        new_data['DOB'] = pd.to_datetime(new_data['DOB'], format='%m%d%y')
        new_data['DOB'] = new_data['DOB'].where(df['DOB'] < now, new_data['DOB'] -  np.timedelta64(100, 'Y'))
        new_data['age'] = (now - new_data['DOB']).astype('<m8[Y]')

new_data

Body:
Assuming that your DOB column is of datetime time you could do (pd.Timestamp('now')-df.DOB)/pd.Timedelta('1Y').

Example:

df = pd.DataFrame({'DOB': pd.to_datetime('2020')-pd.to_timedelta(pd.np.random.randint(7000,20000,5), 'D')})
df.iloc[[1,3]] = None

df['age'] = (pd.Timestamp('now') - df.DOB)/pd.Timedelta('1Y')
df.age = df.age.fillna(df.age.mean()).astype(int)

Result:

         DOB  age
0 1997-02-05   23
1        NaT   25
2 1991-12-08   28
3        NaT   25
4 1995-12-30   24


问:
Which function should I define as live and how would I do it without click event?
I have a refresh function that is set to refresh on a time interval. There is a function within that function called scrollTo which scrolls to the last element of the box. The problem is that elements are constantly being added to the box so without the use of 'live' the scrollTo will find a div and stick to it instead of finding the new last-child and scrolling to it on refresh. Which function should I apply live to, the refresh() or the ScrollTo and I always see live with a click event, can you attach it in a different way?</p>

```<code>  function refresh() {

$.scrollTo('div[chunk_id="'+autoscroll+'"] > :last-child', 800, {easing:'elasout',offset:-250} );

}
</code>```

答:
would this do the same?:

```<code>function refresh() {
  var div = $('div[chunk_id="'+autoscroll+'"] > :last-child');

  $.scrollTo(div, 800, {easing:'elasout',offset:-250} );
}
</code>```

I don't think it will since you are explicitly creating a scoped variable.  It should recalculate that value on each run of the function.

Body:
I have a refresh function that is set to refresh on a time interval. There is a function within that function called scrollTo which scrolls to the last element of the box. The problem is that elements are constantly being added to the box so without the use of 'live' the scrollTo will find a div and stick to it instead of finding the new last-child and scrolling to it on refresh. Which function should I apply live to, the refresh() or the ScrollTo and I always see live with a click event, can you attach it in a different way?

  function refresh() {

$.scrollTo('div[chunk_id="'+autoscroll+'"] > :last-child', 800, {easing:'elasout',offset:-250} );

}

Body:
would this do the same?:

function refresh() {
  var div = $('div[chunk_id="'+autoscroll+'"] > :last-child');

  $.scrollTo(div, 800, {easing:'elasout',offset:-250} );
}

I don't think it will since you are explicitly creating a scoped variable.  It should recalculate that value on each run of the function.


问:
Uncaught TypeError: submitBtn.addEventListner is not a function
```<code><form class="modal-content" id="bookingForm">
    <div class="formContainer">
      <h1>Booking Form</h1>
      <p>Please fill in this form to Book The Trip.</p>
      <hr>
      <label for="email"><b>Email</b></label>
      <input type="text" placeholder="Enter Email" name="email" required id="email">

      <label><b>Package</b></label>

      <input type="text" id="packageFields" name="teste2">

      <label for="psw"><b>Name</b></label>
      <input type="text" placeholder="Enter Name" name="name" required id="name">

      <label for="psw-repeat"><b>Phone No.</b></label>
      <input type="tel" placeholder="Enter Phone No." name="psw-repeat" required id="phone">

      <label for="psw-repeat"><b>Date Of Journey</b></label>
      <input type="date" placeholder="Enter Phone No." name="psw-repeat" required id="date">

      <p>By creating an account you agree to our <a href="#" style="color:dodgerblue">Terms & Privacy</a>.</p>

      <div class="clearfix">
        <button type="submit" class="signupbtn">Confirm Booking</button>
        <button type="button" onclick="document.getElementById('bookingForm').style.display='none'" class="cancelbtn">Cancel</button>
      </div>
    </div>
  </form>
    </script>
    <script src="https://www.gstatic.com/firebasejs/7.14.5/firebase-app.js"></script>

    <!-- Insert these scripts at the bottom of the HTML, but before you use any Firebase services -->

 <!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->
 <script src="/__/firebase/7.14.5/firebase-app.js"></script>

 <!-- If you enabled Analytics in your project, add the Firebase SDK for Analytics -->
 <script src="/__/firebase/7.14.5/firebase-analytics.js"></script>

 <!-- Add Firebase products that you want to use -->
 <script src="/__/firebase/7.14.5/firebase-auth.js"></script>
 <script src="/__/firebase/7.14.5/firebase-firestore.js"></script>
 <script src="/__/firebase/init.js"></script>
 <script src="bookingSubmit.js">    </script>
</code>```

This Is The Html And The JavaSript Is Given Below:

```<code>var firebaseConfig = {
   apiKey: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
   authDomain: "hxxxxxxxxxxxx.firebaseapp.com",
   databaseURL: "https://xxxxxxxxx.firebaseio.com",
   projectId: "xxxxxxxxx",
   storageBucket: "xxxxxxxxx.appspot.com",
   messagingSenderId: "xxxxxxxxxxx",
   appId: "x:xxxxxxxxxxxx:web:xxxxxxxxxxxxxxxxxxxxxx",
   measurementId: "G-xxxxxxxxxx"
 };

//reference messages collection

var firestore =  firebase.firestore();

const submitBtn = document.querySelector(".signupbtn");

let email = document.querySelector('#email');
let packageFields = document.querySelector('#packageFields');
let name = document.querySelector('#name');
let phone = document.querySelector('#phone');
let date = document.querySelector('#date');

const db = firestore.collection("BookingData");

submitBtn.addEventListner('click', function(){
  let userEmailInput = email.value;
  let userPackageInput = packageFields.value;
  let userNameInput = name.value;
  let userPhoneInput = phone.value;
  let userDateInput = date.value;

  db.doc()
  .set({
    email:userEmailInput,
    package:userPackageInput,
    name:userNameInput,
    phone:userPhoneInput,
    date:userDateInput
  })
  .then(function(){
    console.log("Data Saved");
  })
  .catch(function(error){
    console.log(error);
  });
});
</code>```

I am trying to Store The Data Of My Contact Form in firebase. But Its Giving The Error

Uncaught TypeError: submitBtnis null
      at bookingSubmit.js:27

I Am putting the script at the end then why is it giving this error?

What is its cause and how to solve it...??

答:
You are using:

```<code>const submitBtn = document.querySelector("#signupbtn");
</code>```

to select

```<code><button type="submit" class="signupbtn">Confirm Booking</button>
</code>```

You either need to select based on class name: ".signupbtn" or set an ID and not a class on the element.

Body:
<form class="modal-content" id="bookingForm">

Booking Form

Please fill in this form to Book The Trip.

      Email
      <input type="text" placeholder="Enter Email" name="email" required id="email">

      Package

      <input type="text" id="packageFields" name="teste2">

      Name
      <input type="text" placeholder="Enter Name" name="name" required id="name">

      Phone No.
      <input type="tel" placeholder="Enter Phone No." name="psw-repeat" required id="phone">

      Date Of Journey
      <input type="date" placeholder="Enter Phone No." name="psw-repeat" required id="date">

By creating an account you agree to our Terms & Privacy.

        <button type="submit" class="signupbtn">Confirm Booking</button>
        <button type="button" onclick="document.getElementById('bookingForm').style.display='none'" class="cancelbtn">Cancel</button>

  </form>
    </script>

This Is The Html And The JavaSript Is Given Below:

var firebaseConfig = {
   apiKey: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
   authDomain: "hxxxxxxxxxxxx.firebaseapp.com",
   databaseURL: "https://xxxxxxxxx.firebaseio.com",
   projectId: "xxxxxxxxx",
   storageBucket: "xxxxxxxxx.appspot.com",
   messagingSenderId: "xxxxxxxxxxx",
   appId: "x:xxxxxxxxxxxx:web:xxxxxxxxxxxxxxxxxxxxxx",
   measurementId: "G-xxxxxxxxxx"
 };

//reference messages collection

var firestore =  firebase.firestore();

const submitBtn = document.querySelector(".signupbtn");

let email = document.querySelector('#email');
let packageFields = document.querySelector('#packageFields');
let name = document.querySelector('#name');
let phone = document.querySelector('#phone');
let date = document.querySelector('#date');

const db = firestore.collection("BookingData");

submitBtn.addEventListner('click', function(){
  let userEmailInput = email.value;
  let userPackageInput = packageFields.value;
  let userNameInput = name.value;
  let userPhoneInput = phone.value;
  let userDateInput = date.value;

  db.doc()
  .set({
    email:userEmailInput,
    package:userPackageInput,
    name:userNameInput,
    phone:userPhoneInput,
    date:userDateInput
  })
  .then(function(){
    console.log("Data Saved");
  })
  .catch(function(error){
    console.log(error);
  });
});

I am trying to Store The Data Of My Contact Form in firebase. But Its Giving The Error

Uncaught TypeError: submitBtnis null
      at bookingSubmit.js:27

I Am putting the script at the end then why is it giving this error?

What is its cause and how to solve it...??

Body:
You are using:

const submitBtn = document.querySelector("#signupbtn");

to select

<button type="submit" class="signupbtn">Confirm Booking</button>

You either need to select based on class name: ".signupbtn" or set an ID and not a class on the element.


问:
Making a graph with different colours
I have a dataset of corona virus which looks something like this

```<code>day month cases deaths country
3     5     10    1     USA
4     5     12    2     USA
</code>```

it has multiple entries for each country for different days, I made it filter out so it only gets the data from 28th of May now I want to make a graph for every country with how many cases they have use pandas and matploitlib

However it's not working properly

when I use

```<code>import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_excel("covid.xlsx")
print(df.columns.tolist())
df.loc[(df.day == 28) & (df.month==5), :].plot.line(x='countriesAndTerritories', y='deaths')
plt.show()
</code>```

The code executes but only shows 5 countries and the countriesAndTerritories is on the x axis, when I switch around x='countriesAndTerritories', y='deaths' I get TypeError: no numeric data to plot

This is  a reference of what I want: https://qap.ecdc.europa.eu/public/single/?appid=f818d019-18c5-41e0-99e6-bd2b7f6f17b5&obj=3d471628-9a6e-4938-95da-0cba933925ca&opt=nointeraction&select=clearall (europe's data visualization)

答:
I believe you would like to plot day vs deaths and the country as a legend. Is my understanding correct? If that is the case, you can do something like this:</p>

```<code>plt.scatter(df['day'], df['deaths'],label= df['country'])
</code>```

Title: Making a graph with different colours

Body:
I have a dataset of corona virus which looks something like this

day month cases deaths country
3     5     10    1     USA
4     5     12    2     USA

it has multiple entries for each country for different days, I made it filter out so it only gets the data from 28th of May now I want to make a graph for every country with how many cases they have use pandas and matploitlib

However it's not working properly

when I use

import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_excel("covid.xlsx")
print(df.columns.tolist())
df.loc[(df.day == 28) & (df.month==5), :].plot.line(x='countriesAndTerritories', y='deaths')
plt.show()

The code executes but only shows 5 countries and the countriesAndTerritories is on the x axis, when I switch around x='countriesAndTerritories', y='deaths' I get TypeError: no numeric data to plot

This is  a reference of what I want: https://qap.ecdc.europa.eu/public/single/?appid=f818d019-18c5-41e0-99e6-bd2b7f6f17b5&obj=3d471628-9a6e-4938-95da-0cba933925ca&opt=nointeraction&select=clearall (europe's data visualization)

Body:
I believe you would like to plot day vs deaths and the country as a legend. Is my understanding correct? If that is the case, you can do something like this:

plt.scatter(df['day'], df['deaths'],label= df['country'])


答:
You should add an id on your element rather than a class.

```<code> <button type="submit" id="signupbtn" class="signupbtn">Confirm Booking</button>
 const submitBtn = document.querySelector("#signupbtn");
</code>```

Also there is a typo in the addEventListener
https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener

It should be

```<code>submitBtn.addEventListener('click', function(e){

   //Remove default form submit behaviour.
   e.preventDefault();
   //...
</code>```

and not

```<code>submitBtn.addEventListner('click', function(){ //Typo in addEventListner
</code>```

Title: Uncaught TypeError: submitBtn.addEventListner is not a function

Body:
You should add an id on your element rather than a class.

 <button type="submit" id="signupbtn" class="signupbtn">Confirm Booking</button>
 const submitBtn = document.querySelector("#signupbtn");

Also there is a typo in the addEventListener
https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener

It should be

submitBtn.addEventListener('click', function(e){

   //Remove default form submit behaviour.
   e.preventDefault();
   //...

and not

submitBtn.addEventListner('click', function(){ //Typo in addEventListner


问:
How to take input while an output is constantly running
So I am actually trying to make a stopwatch application that acts like an exact stopwatch so it needs to take input so what I want to do is whenever the user enters something the loop will break.....

This is my code..........

```<code>public class Stop {
    public static void stopwatch() {
        Scanner sc = new Scanner(System.in);

        System.out.println("Enter anything when you want to stop");
        for(double i = 0; true; i+=0.5) {
            System.out.println(i);

            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    }
}
</code>```

So, I want to take an input but it should be optional whether the user enters or not if he enters the loop will break else it will continue...

My output should be like

```<code>Enter anything when you want to stop
0.0
0.5
1.0
1.5
stop
You stopped
</code>```

How do I do that?

答:
You can do it this way:

```<code>    public static void stopwatch() {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter anything when you want to stop");

        for (double i = 0; true; i += 0.5) {
            try {
                if (!br.ready()) {
                    System.out.println(i);
                    Thread.sleep(500);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
</code>```

You have to type something and press Enter if you're running it in IDE console.
Do not use Scanner as it blocks and waits for the input.

Body:
So I am actually trying to make a stopwatch application that acts like an exact stopwatch so it needs to take input so what I want to do is whenever the user enters something the loop will break.....

This is my code..........

public class Stop {
    public static void stopwatch() {
        Scanner sc = new Scanner(System.in);

        System.out.println("Enter anything when you want to stop");
        for(double i = 0; true; i+=0.5) {
            System.out.println(i);

            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    }
}

So, I want to take an input but it should be optional whether the user enters or not if he enters the loop will break else it will continue...

My output should be like

Enter anything when you want to stop
0.0
0.5
1.0
1.5
stop
You stopped

How do I do that?

Body:
You can do it this way:

    public static void stopwatch() {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter anything when you want to stop");

        for (double i = 0; true; i += 0.5) {
            try {
                if (!br.ready()) {
                    System.out.println(i);
                    Thread.sleep(500);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

You have to type something and press Enter if you're running it in IDE console.
Do not use Scanner as it blocks and waits for the input.


问:
Validating forms Ajax PHP
The jQuery/JavaScript/Ajax code is not mine. I'm learning and trying to understand it. The issue that I am having is after the data gets sent to the database the form is suppose to add class="show" to #sendmessage but its adding class="show" to #errormessage even though it was successful and the data was entered into the database. I don't understand why or how to fix it.

contact form index.html

```<code> <div class="form">
                    <div id="sendmessage">Your message has been sent. Thank you!</div>
                    <div id="errormessage"></div>
                    <form action="contactform/contactform.php" method="POST" role="form" class="contactForm">
                        <div class="form-row">
                            <div class="form-group col-md-6">
                                <input type="text" name="name" class="form-control" id="name" placeholder="Your Name" data-rule="minlen:4" data-msg="Please enter at least 4 chars" />
                                <div class="validation"></div>
                            </div>
                            <div class="form-group col-md-6">
                                <input type="email" class="form-control" name="email" id="email" placeholder="Your Email" data-rule="email" data-msg="Please enter a valid email" />
                                <div class="validation"></div>
                            </div>
                        </div>
                        <div class="form-group">
                            <input type="text" class="form-control" name="subject" id="subject" placeholder="Subject" data-rule="minlen:8" data-msg="Please enter at least 8 chars of subject" />
                            <div class="validation"></div>
                        </div>
                        <div class="form-group">
                            <textarea class="form-control" name="message" rows="5" data-rule="required" data-msg="Please write something for us" placeholder="Message"></textarea>
                            <div class="validation"></div>
                        </div>
                        <div class="text-center"><button type="submit">Send Message</button></div>
                    </form>
                </div>
</code>```

contactform.js

```<code>jQuery(document).ready(function($) {
  "use strict";

  //Contact
  $('form.contactForm').submit(function() {
    var f = $(this).find('.form-group'),
      ferror = false,
      emailExp = /^[^\s()<>@,;:\/]+@\w[\w\.-]+\.[a-z]{2,}$/i;

    f.children('input').each(function() { // run all inputs

      var i = $(this); // current input
      var rule = i.attr('data-rule');

      if (rule !== undefined) {
        var ierror = false; // error flag for current input
        var pos = rule.indexOf(':', 0);
        if (pos >= 0) {
          var exp = rule.substr(pos + 1, rule.length);
          rule = rule.substr(0, pos);
        } else {
          rule = rule.substr(pos + 1, rule.length);
        }

        switch (rule) {
          case 'required':
            if (i.val() === '') {
              ferror = ierror = true;
            }
            break;

          case 'minlen':
            if (i.val().length < parseInt(exp)) {
              ferror = ierror = true;
            }
            break;

          case 'email':
            if (!emailExp.test(i.val())) {
              ferror = ierror = true;
            }
            break;

          case 'checked':
            if (! i.is(':checked')) {
              ferror = ierror = true;
            }
            break;

          case 'regexp':
            exp = new RegExp(exp);
            if (!exp.test(i.val())) {
              ferror = ierror = true;
            }
            break;
        }
        i.next('.validation').html((ierror ? (i.attr('data-msg') !== undefined ? i.attr('data-msg') : 'wrong Input') : '')).show('blind');
      }
    });
    f.children('textarea').each(function() { // run all inputs

      var i = $(this); // current input
      var rule = i.attr('data-rule');

      if (rule !== undefined) {
        var ierror = false; // error flag for current input
        var pos = rule.indexOf(':', 0);
        if (pos >= 0) {
          var exp = rule.substr(pos + 1, rule.length);
          rule = rule.substr(0, pos);
        } else {
          rule = rule.substr(pos + 1, rule.length);
        }

        switch (rule) {
          case 'required':
            if (i.val() === '') {
              ferror = ierror = true;
            }
            break;

          case 'minlen':
            if (i.val().length < parseInt(exp)) {
              ferror = ierror = true;
            }
            break;
        }
        i.next('.validation').html((ierror ? (i.attr('data-msg') != undefined ? i.attr('data-msg') : 'wrong Input') : '')).show('blind');
      }
    });
    if (ferror) return false;
    else var str = $(this).serialize();
    var action = $(this).attr('action');
    if( ! action ) {
      action = 'contactform/contactform.php';
    }
    $.ajax({
      type: "POST",
      url: action,
      data: str,
      success: function(msg) {
         //alert(msg);
        if (msg == 'OK') {
          $("#sendmessage").addClass("show");
          $("#errormessage").removeClass("show");
          $('.contactForm').find("input, textarea").val("");
        } else {
          $("#sendmessage").removeClass("show");
          $("#errormessage").addClass("show");
          $('#errormessage').html(msg);
        }

      }
    });
    return false;
  });

});

</code>```

contactform.php

```<code><?php
//Define access
define('_VALID', 'Yes');
//required files
require_once('../include/config/config.php');

//variables
$contactFormName = '';
$contactFormEmail = '';
$contactFormSubject = '';
$contactFormMessage = '';
$checkStep = 1;

//Add new message
if (isset($_POST['name'])){

        //Get values
        $contactFormName = $_POST['name'];
        $contactFormEmail = $_POST['email'];
        $contactFormSubject = $_POST['subject'];
        $contactFormMessage = $_POST['message'];

        // 1. check name form field
        if($checkStep == 1){
            if($contactFormName === $_POST['name']){
                $contactFormName = filterName($contactFormName);
                $checkStep++;

            }else{
                echo "No its not working";
            }
        }
            // 2. check email field
            if($checkStep == 2){
                if($contactFormEmail === $_POST['email']){
                    $contactFormEmail = filterEmail($contactFormEmail);
                    $checkStep++;
                }else{
                        echo "Uh Oh! Something went wrong with your email please try again!";
                    }
                }

            // 3. check subject
            if($checkStep == 3){
                if($contactFormSubject === $_POST['subject']){
                    $contactFormSubject = filterSubject($contactFormSubject);
                    $checkStep++;
                }else{
                    echo "Uh Oh! Whats up with your subject";
                }
            }
            // 4. check message
            if($checkStep == 4){
                 if($contactFormMessage === $_POST['message']){
                    $contactFormMessage = filterMessage($contactFormMessage);
                     $checkStep++;
                }else{
                    echo "Uh ho!  Please write us a message";
                }
            }
            // 5. insert message
            if($checkStep == 5){
                $sqlAddMessage = "
                    INSERT INTO contact_form(
                        name,
                        email,
                        subject,
                        message
                    ) VALUES(
                        '$contactFormName',
                        '$contactFormEmail',
                        '$contactFormSubject',
                        '$contactFormMessage'
                    )
                ";
                $queryAddMessage = $GLOBALS['mysqli']->query($sqlAddMessage);

                if($queryAddMessage){

                //code goes here
                }

            }else{
                echo "Uh Oh! NO No No. Check step 5";
            }
        }

?>

</code>```

答: Just use a jQuery form validation plugin to validate form and its easier than using AJAX for the same.</p>

Title: Validating forms Ajax PHP

Body:
The jQuery/JavaScript/Ajax code is not mine. I'm learning and trying to understand it. The issue that I am having is after the data gets sent to the database the form is suppose to add class="show" to #sendmessage but its adding class="show" to #errormessage even though it was successful and the data was entered into the database. I don't understand why or how to fix it.

contact form index.html

Your message has been sent. Thank you!

                    <form action="contactform/contactform.php" method="POST" role="form" class="contactForm">

                                <input type="text" name="name" class="form-control" id="name" placeholder="Your Name" data-rule="minlen:4" data-msg="Please enter at least 4 chars" />

                                <input type="email" class="form-control" name="email" id="email" placeholder="Your Email" data-rule="email" data-msg="Please enter a valid email" />

                            <input type="text" class="form-control" name="subject" id="subject" placeholder="Subject" data-rule="minlen:8" data-msg="Please enter at least 8 chars of subject" />

                            <textarea class="form-control" name="message" rows="5" data-rule="required" data-msg="Please write something for us" placeholder="Message"></textarea>

<button type="submit">Send Message</button>

                    </form>

contactform.js

jQuery(document).ready(function($) {
  "use strict";

  //Contact
  $('form.contactForm').submit(function() {
    var f = $(this).find('.form-group'),
      ferror = false,
      emailExp = /^[^\s()<>@,;:\/]+@\w[\w\.-]+\.[a-z]{2,}$/i;

    f.children('input').each(function() { // run all inputs

      var i = $(this); // current input
      var rule = i.attr('data-rule');

      if (rule !== undefined) {
        var ierror = false; // error flag for current input
        var pos = rule.indexOf(':', 0);
        if (pos >= 0) {
          var exp = rule.substr(pos + 1, rule.length);
          rule = rule.substr(0, pos);
        } else {
          rule = rule.substr(pos + 1, rule.length);
        }

        switch (rule) {
          case 'required':
            if (i.val() === '') {
              ferror = ierror = true;
            }
            break;

          case 'minlen':
            if (i.val().length < parseInt(exp)) {
              ferror = ierror = true;
            }
            break;

          case 'email':
            if (!emailExp.test(i.val())) {
              ferror = ierror = true;
            }
            break;

          case 'checked':
            if (! i.is(':checked')) {
              ferror = ierror = true;
            }
            break;

          case 'regexp':
            exp = new RegExp(exp);
            if (!exp.test(i.val())) {
              ferror = ierror = true;
            }
            break;
        }
        i.next('.validation').html((ierror ? (i.attr('data-msg') !== undefined ? i.attr('data-msg') : 'wrong Input') : '')).show('blind');
      }
    });
    f.children('textarea').each(function() { // run all inputs

      var i = $(this); // current input
      var rule = i.attr('data-rule');

      if (rule !== undefined) {
        var ierror = false; // error flag for current input
        var pos = rule.indexOf(':', 0);
        if (pos >= 0) {
          var exp = rule.substr(pos + 1, rule.length);
          rule = rule.substr(0, pos);
        } else {
          rule = rule.substr(pos + 1, rule.length);
        }

        switch (rule) {
          case 'required':
            if (i.val() === '') {
              ferror = ierror = true;
            }
            break;

          case 'minlen':
            if (i.val().length < parseInt(exp)) {
              ferror = ierror = true;
            }
            break;
        }
        i.next('.validation').html((ierror ? (i.attr('data-msg') != undefined ? i.attr('data-msg') : 'wrong Input') : '')).show('blind');
      }
    });
    if (ferror) return false;
    else var str = $(this).serialize();
    var action = $(this).attr('action');
    if( ! action ) {
      action = 'contactform/contactform.php';
    }
    $.ajax({
      type: "POST",
      url: action,
      data: str,
      success: function(msg) {
         //alert(msg);
        if (msg == 'OK') {
          $("#sendmessage").addClass("show");
          $("#errormessage").removeClass("show");
          $('.contactForm').find("input, textarea").val("");
        } else {
          $("#sendmessage").removeClass("show");
          $("#errormessage").addClass("show");
          $('#errormessage').html(msg);
        }

      }
    });
    return false;
  });

});

contactform.php

<?php
//Define access
define('_VALID', 'Yes');
//required files
require_once('../include/config/config.php');

//variables
$contactFormName = '';
$contactFormEmail = '';
$contactFormSubject = '';
$contactFormMessage = '';
$checkStep = 1;

//Add new message
if (isset($_POST['name'])){

        //Get values
        $contactFormName = $_POST['name'];
        $contactFormEmail = $_POST['email'];
        $contactFormSubject = $_POST['subject'];
        $contactFormMessage = $_POST['message'];

        // 1. check name form field
        if($checkStep == 1){
            if($contactFormName === $_POST['name']){
                $contactFormName = filterName($contactFormName);
                $checkStep++;

            }else{
                echo "No its not working";
            }
        }
            // 2. check email field
            if($checkStep == 2){
                if($contactFormEmail === $_POST['email']){
                    $contactFormEmail = filterEmail($contactFormEmail);
                    $checkStep++;
                }else{
                        echo "Uh Oh! Something went wrong with your email please try again!";
                    }
                }

            // 3. check subject
            if($checkStep == 3){
                if($contactFormSubject === $_POST['subject']){
                    $contactFormSubject = filterSubject($contactFormSubject);
                    $checkStep++;
                }else{
                    echo "Uh Oh! Whats up with your subject";
                }
            }
            // 4. check message
            if($checkStep == 4){
                 if($contactFormMessage === $_POST['message']){
                    $contactFormMessage = filterMessage($contactFormMessage);
                     $checkStep++;
                }else{
                    echo "Uh ho!  Please write us a message";
                }
            }
            // 5. insert message
            if($checkStep == 5){
                $sqlAddMessage = "
                    INSERT INTO contact_form(
                        name,
                        email,
                        subject,
                        message
                    ) VALUES(
                        '$contactFormName',
                        '$contactFormEmail',
                        '$contactFormSubject',
                        '$contactFormMessage'
                    )
                ";
                $queryAddMessage = $GLOBALS['mysqli']->query($sqlAddMessage);

                if($queryAddMessage){

                //code goes here
                }

            }else{
                echo "Uh Oh! NO No No. Check step 5";
            }
        }

?>


问:
PyQt5, Qlabel text in multiple colors
how can i set multiple colors inside a Qlabel text?
for example:

```<code>Qlabel.setText("Hello World!")
</code>```

I want the "Hello" to be in blue, the "World" in red & the "!" in green
is it possible?

I found that answer online for QT but this is not Python language:

```<code>ql->setText("<font color=\"blue\">Hello</font> <font color=\"red\">World</font><font color=\"green">!</font>");
</code>```

答:
It's easy, if you're familiar with HTML:
Do something like this:

```<code>QLabel.setText('<font color="blue">Hello</font><font color="red"> World</font><font color="green">!</font>')
</code>```

Hope this helps :)

Title: PyQt5, Qlabel text in multiple colors

Body:
how can i set multiple colors inside a Qlabel text?
for example:

Qlabel.setText("Hello World!")

I want the "Hello" to be in blue, the "World" in red & the "!" in green
is it possible?

I found that answer online for QT but this is not Python language:

ql->setText("Hello World!");

Body:
It's easy, if you're familiar with HTML:
Do something like this:

QLabel.setText('<font color="blue">Hello</font><font color="red"> World</font><font color="green">!</font>')

Hope this helps :)


问:
Faster way to fetch a single data from db with codeigniter
hi want to get only one column from one result from my database. So i do it in this way

```<code>$this->db->select('myclolumn')->where('id',$id);
$query = $this->db->get('mytable');
$temp=$query->row_array();
$finalresult=$temp['mycolumn'];
</code>```

Maybe there is a easier or faster way to do the same?

答:
so based on DanishAli's comment</p>

```<code>$this->db->select('myclolumn')->where('id',$id);
$query = $this->db->get('mytable');
$finalresult=$query->row()->mycloumn;
</code>```

Body:
hi want to get only one column from one result from my database. So i do it in this way

$this->db->select('myclolumn')->where('id',$id);
$query = $this->db->get('mytable');
$temp=$query->row_array();
$finalresult=$temp['mycolumn'];

Maybe there is a easier or faster way to do the same?

Body:
so based on DanishAli's comment

$this->db->select('myclolumn')->where('id',$id);
$query = $this->db->get('mytable');
$finalresult=$query->row()->mycloumn;


问:
How to prevent duplicate form submission in ASP.NET MVC 3?
I have a razor view that renders a html form and it posts to the server.
If the form values are right then it gets saved to database.
After insertion, I redirect to another view where user can make further changes.

Right now the user can hit browser back button and resubmit the form to create another record in db.

How do I prevent duplicate submission in my MVC app?

答: One solution is to put a hidden "token" field on the form that's generated randomly when the form loads. When you see that token come back on creation store it somewhere temporarily (in session if you're using sessions for example). If you see the same one again, you can assume the same form was submitted twice quickly together.</p>


问:
React - add one more property to state
So I populate the state for 'Sources' by fetching a list of sources from an api with axios. The resulting state of sources is an array of objects with some properties (see the screenshotp below;

```<code>const [articles, setArticles] = useState([]);
const [sources, setSources] = useState([]);
const [EndPoint, setEndPoint] = useState({
    headlines_url: 'top-headlines?',
    sources_url: 'sources?language=en&'
});

useEffect(() => {
        axios.all([
            axios.get(`http://newsapi.org/v2/${EndPoint.headlines_url}country=gb&apiKey=xxx`),
            axios.get(`http://newsapi.org/v2/${EndPoint.sources_url}country=gb&apiKey=xxx`)
        ])
        .then(res => {
            const newArticles = res[0].data.articles;
            const newSources = res[1].data.sources;
            setArticles(newArticles);
            setSources(newSources);
        })
    }, [EndPoint]);
</code>```

What I'll be trying to do is to add checkboxes next to sources to indicate which sources to take articles from. First, however, I'd need one more property on the sources (Eg. active: true/false) to keep track of which source has been selected.
Would it be better to add one more property to the existing 'sources' object or create a completely new object referencing the sources id property? and how would I do it?

Thanks

答:
I suggest you add another useEffect() and edit the source object in there. Use sources as a dependency in the useEffect().

Tip: Enclose all the code in your useEffect where you call the API into a async function.
Ex:

```<code>useEffect(() => {
            const fetchData = async () => {
                axios.all([
                async axios.get(`http://newsapi.org/v2/${EndPoint.headlines_url}country=gb&apiKey=xxx`),
                async axios.get(`http://newsapi.org/v2/${EndPoint.sources_url}country=gb&apiKey=xxx`)
            ])
            .then(res => {
                const newArticles = res[0].data.articles;
                const newSources = res[1].data.sources;
                setArticles(newArticles);
                setSources(newSources);
            })
          }
            fetchData()
        }, [EndPoint]);
</code>```

Title: React - add one more property to state

Body:
So I populate the state for 'Sources' by fetching a list of sources from an api with axios. The resulting state of sources is an array of objects with some properties (see the screenshotp below;

const [articles, setArticles] = useState([]);
const [sources, setSources] = useState([]);
const [EndPoint, setEndPoint] = useState({
    headlines_url: 'top-headlines?',
    sources_url: 'sources?language=en&'
});

useEffect(() => {
        axios.all([
            axios.get(`http://newsapi.org/v2/${EndPoint.headlines_url}country=gb&apiKey=xxx`),
            axios.get(`http://newsapi.org/v2/${EndPoint.sources_url}country=gb&apiKey=xxx`)
        ])
        .then(res => {
            const newArticles = res[0].data.articles;
            const newSources = res[1].data.sources;
            setArticles(newArticles);
            setSources(newSources);
        })
    }, [EndPoint]);

What I'll be trying to do is to add checkboxes next to sources to indicate which sources to take articles from. First, however, I'd need one more property on the sources (Eg. active: true/false) to keep track of which source has been selected.
Would it be better to add one more property to the existing 'sources' object or create a completely new object referencing the sources id property? and how would I do it?

Thanks

Body:
I suggest you add another useEffect() and edit the source object in there. Use sources as a dependency in the useEffect().

Tip: Enclose all the code in your useEffect where you call the API into a async function.
Ex:

useEffect(() => {
            const fetchData = async () => {
                axios.all([
                async axios.get(`http://newsapi.org/v2/${EndPoint.headlines_url}country=gb&apiKey=xxx`),
                async axios.get(`http://newsapi.org/v2/${EndPoint.sources_url}country=gb&apiKey=xxx`)
            ])
            .then(res => {
                const newArticles = res[0].data.articles;
                const newSources = res[1].data.sources;
                setArticles(newArticles);
                setSources(newSources);
            })
          }
            fetchData()
        }, [EndPoint]);


问:
Compiling Spring Applications to GraalVM Native Images
The GraalVM system apparently cannot compile a Spring application into a native image.

Can we compile a subset of the Spring application -- say, as a separate library -- and then use that with the remainder compiled using the usual javac compiler?

Or maybe if we leave out some Spring features from our application?

Any other possibilities?

答:
As May 2020, Spring has release Spring Graalvm Native.
Spring Graalvm Native</p>


问:
lowercase locale name (ja-jp) with i18next is not working, while ja-JP works
I am using i18next with aurelia using the i18next aurelia plugin.

The problem I am facing is in locale case sensitivity.

When I set my url to http://localhost/ja-JP
 everything works fine, but changing the url to http://localhost/ja-jp throws this error

```<code>Possible Unhandled Promise Rejection: ["failed loading locales/ja-JP/translation.json"]
</code>```

I thought that i18next is by default looking into case sensitive directory, so I tried keeping two directories ja-JP and ja-jp too, but still same problem.

Any idea why would it be a problem?

http://localhost/ja/ and http://localhost/en both work perfectly fine though

if it is relevant, here is the webpack conf section

```<code> "aurelia-i18n": [
        { name: "locales/ja-jp/translation.json" },
        { name: "locales/en-us/translation.json" }
      ]
</code>```

and the aurelia configuration for i18next

```<code>export function configure(aurelia: Aurelia) {
  aurelia.use
    .standardConfiguration()
    .plugin(PLATFORM.moduleName('aurelia-validation'))
    .plugin(PLATFORM.moduleName('au-table'))
    .plugin(PLATFORM.moduleName("aurelia-i18n"), (instance) => {
      let aliases = ["t", "i18n"];
      TCustomAttribute.configureAliases(aliases);

      instance.i18next.use(Backend.with(aurelia.loader));

      return instance.setup({
        backend: {
          loadPath: "./locales/{{lng}}/{{ns}}.json"
        },
        attributes: aliases,
        lng: "en-us",
        fallbackLng: "en-us",
        load: "currentOnly",
        debug: false
      });
    })
  .feature(PLATFORM.moduleName('resources/index'))
  .developmentLogging(environment.debug ? 'debug' : 'warn');

  if (environment.testing) {
    aurelia.use.plugin(PLATFORM.moduleName('aurelia-testing'))
  }

  aurelia.start().then(() => aurelia.setRoot(PLATFORM.moduleName('app')));
}
</code>```

答:
There is lowerCaseLng Option that will help you.
https://www.i18next.com/overview/configuration-options

```<code>i18next
  .init({
    ...
    lowerCaseLng: true
  });
</code>```

Body:
I am using i18next with aurelia using the i18next aurelia plugin.

The problem I am facing is in locale case sensitivity.

When I set my url to http://localhost/ja-JP
 everything works fine, but changing the url to http://localhost/ja-jp throws this error

Possible Unhandled Promise Rejection: ["failed loading locales/ja-JP/translation.json"]

I thought that i18next is by default looking into case sensitive directory, so I tried keeping two directories ja-JP and ja-jp too, but still same problem.

Any idea why would it be a problem?

http://localhost/ja/ and http://localhost/en both work perfectly fine though

if it is relevant, here is the webpack conf section

 "aurelia-i18n": [
        { name: "locales/ja-jp/translation.json" },
        { name: "locales/en-us/translation.json" }
      ]

and the aurelia configuration for i18next

export function configure(aurelia: Aurelia) {
  aurelia.use
    .standardConfiguration()
    .plugin(PLATFORM.moduleName('aurelia-validation'))
    .plugin(PLATFORM.moduleName('au-table'))
    .plugin(PLATFORM.moduleName("aurelia-i18n"), (instance) => {
      let aliases = ["t", "i18n"];
      TCustomAttribute.configureAliases(aliases);

      instance.i18next.use(Backend.with(aurelia.loader));

      return instance.setup({
        backend: {
          loadPath: "./locales/{{lng}}/{{ns}}.json"
        },
        attributes: aliases,
        lng: "en-us",
        fallbackLng: "en-us",
        load: "currentOnly",
        debug: false
      });
    })
  .feature(PLATFORM.moduleName('resources/index'))
  .developmentLogging(environment.debug ? 'debug' : 'warn');

  if (environment.testing) {
    aurelia.use.plugin(PLATFORM.moduleName('aurelia-testing'))
  }

  aurelia.start().then(() => aurelia.setRoot(PLATFORM.moduleName('app')));
}

Body:
There is lowerCaseLng Option that will help you.
https://www.i18next.com/overview/configuration-options

i18next
  .init({
    ...
    lowerCaseLng: true
  });


问:
How does this JavaScript Asynchronous code work?
I want to know what is passed to the parameter inside the .then callback function? Is it the resolved value of the getUsers() function.

function getFirstUser() {
  return getUsers().then(function(users) {
    return users[0].name;
  }).catch(function(err) {
    return {
      name: 'default user'
    };
  });
}
```

答:
Is it the resolved value of the getUsers() function?

Yes, it is. and err is the rejected value of the getUsers() function.

Example:

const promise = Promise.resolve(":)"); // Same as new Promise( res => res(":)") )

promise.then( value => {
  console.log(value); // Logs :)
});```


问:
Scatterplot function that can change based on variables for axes
I am trying to write a function that seems like it should be very simple but I am having problems with it. I want to write a function that takes in three arguements: a dataframe, x-axis variable and y-axis variable. Based on these, I want it to return a scatterplot in which the x-axis variable and y-axis variable can be changed. This is the very basic function I wrote:

```<code>scatter_plot <- function(dataframe, x_input, y_input) {
  plot <- ggplot(data = dataframe) +
    geom_point(mapping = aes(x = x_input, y = y_input),
    )
}
</code>```

For reproducibility, consider the dataset midwest that is in the ggplot2 package. The code I wrote does not produce errors when I run it, but when I try to pass arguments into it, such as

```<code>scatter_plot(midwest, percollege, percpovertyknown)
</code>```

the function returns

"Error in FUN(X[[i]], ...) : object 'percollege' not found"

It seems like it does not recognize the variables in the argument, but I have been playing around with the function for quite some time and I can't seem to figure it out. Can someone help me with how to fix this so my function works correctly?

答:
Using !!rlang::ensym() in your function should work.

```<code>scatter_plot <- function(dataframe, x_input, y_input) {
  plot <- ggplot(data = dataframe) +
    geom_point(mapping = aes(x = !!rlang::ensym(x_input), y = !!rlang::ensym(y_input)))
  plot
}
</code>```

Example

```<code>scatter_plot(midwest, percollege, percpovertyknown)
</code>```

Body:
I am trying to write a function that seems like it should be very simple but I am having problems with it. I want to write a function that takes in three arguements: a dataframe, x-axis variable and y-axis variable. Based on these, I want it to return a scatterplot in which the x-axis variable and y-axis variable can be changed. This is the very basic function I wrote:

scatter_plot <- function(dataframe, x_input, y_input) {
  plot <- ggplot(data = dataframe) +
    geom_point(mapping = aes(x = x_input, y = y_input),
    )
}

For reproducibility, consider the dataset midwest that is in the ggplot2 package. The code I wrote does not produce errors when I run it, but when I try to pass arguments into it, such as

scatter_plot(midwest, percollege, percpovertyknown)

the function returns

"Error in FUN(X[[i]], ...) : object 'percollege' not found"

It seems like it does not recognize the variables in the argument, but I have been playing around with the function for quite some time and I can't seem to figure it out. Can someone help me with how to fix this so my function works correctly?

Body:
Using !!rlang::ensym() in your function should work.

scatter_plot <- function(dataframe, x_input, y_input) {
  plot <- ggplot(data = dataframe) +
    geom_point(mapping = aes(x = !!rlang::ensym(x_input), y = !!rlang::ensym(y_input)))
  plot
}

Example

scatter_plot(midwest, percollege, percpovertyknown)


问:
java nio and ByteBuffer problem
I met a problem. I use nio socket to receive message. Upon a complete message is received, I send the dataBuffer which holds the received message to another user. But there is exception below. Where is the problem? I try to call dataBuffer.duplicate() and write it out. But at the receiver side, the read operation throws such exception. I have to assign a new ByteBuffer and make a new copy of message and write it out. In this case, there is no error. But I do not want the copy step. Is there any other way to solve it?

Exception thrown

```<code>java.nio.BufferOverflowException
    at java.nio.HeapByteBuffer.put(Unknown Source)
    at java.nio.ByteBuffer.put(Unknown Source)
    at serviceHandlerPackage.ServiceHandler.readComplete(ServiceHandler.java:218)
</code>```

Code

```<code>readEventHAndler(SocketChannel socket) {
   readCompleteData(socket);
}

readCompleteData(Socket) {
    ByteBuffer dataBuffer; //hold complete message
    if(!dataComplete)  return;
    else   process(dataBuffer);
}

process(dataBuffer) {
   ...

   processHandler();

   sendNext(dataBuffer);

}

sendNext(dataBuffer) {
    write(dataBuffer);

}
</code>```

答:
Your program throws an exception while putting data so I would say that something is wrong with position/limit.

It looks like you are trying to put data into read buffer or trying to put more data than it's size. Buffer will not grow itself (ByteArrayOutputStream is better for this).

Read about clearing, rewinding and flipping in java documentation. This will reset position, limit or size of buffer.

Title: java nio and ByteBuffer problem

Body:
I met a problem. I use nio socket to receive message. Upon a complete message is received, I send the dataBuffer which holds the received message to another user. But there is exception below. Where is the problem? I try to call dataBuffer.duplicate() and write it out. But at the receiver side, the read operation throws such exception. I have to assign a new ByteBuffer and make a new copy of message and write it out. In this case, there is no error. But I do not want the copy step. Is there any other way to solve it?

Exception thrown

java.nio.BufferOverflowException
    at java.nio.HeapByteBuffer.put(Unknown Source)
    at java.nio.ByteBuffer.put(Unknown Source)
    at serviceHandlerPackage.ServiceHandler.readComplete(ServiceHandler.java:218)

Code

readEventHAndler(SocketChannel socket) {
   readCompleteData(socket);
}

readCompleteData(Socket) {
    ByteBuffer dataBuffer; //hold complete message
    if(!dataComplete)  return;
    else   process(dataBuffer);
}

process(dataBuffer) {
   ...

   processHandler();

   sendNext(dataBuffer);

}

sendNext(dataBuffer) {
    write(dataBuffer);

}


问:
How to disable past dates in Android date picker?
How can I disable past dates in my Android date picker?

Here's the code that produces my DatePicker:

```<code>@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
    case DATE_DIALOG_ID:
        // set date picker as current date
        return new DatePickerDialog(this, datePickerListener, year, month,
                day);
    }
    return null;
}

private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {
    public void onDateSet(DatePicker view, int selectedYear,
            int selectedMonth, int selectedDay) {
        year = selectedYear;
        month = selectedMonth+1;
        day = selectedDay;

        startdate.setText(new StringBuilder().append(day).append("-")
                .append(getMonth(month + 1)).append("-").append(year)
                .append(" "));
    }
};
</code>```

答:
With the Material Components Library just use the MaterialDatePicker and build your own DateValidator or you can just use the DateValidatorPointForward provided by the library.

Something like:

```<code>MaterialDatePicker.Builder<Long> builder = MaterialDatePicker.Builder.datePicker();

CalendarConstraints.DateValidator dateValidator = DateValidatorPointForward.now();
//if you need a custom date just use
//CalendarConstraints.DateValidator dateValidator = DateValidatorPointForward.from(yourDate);
constraintsBuilder.setValidator(dateValidator);
builder.setCalendarConstraints(constraintsBuilder.build());

MaterialDatePicker<Long> picker = builder.build();
picker.show(getSupportFragmentManager(), picker.toString());
</code>```

Body:
How can I disable past dates in my Android date picker?

Here's the code that produces my DatePicker:

@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
    case DATE_DIALOG_ID:
        // set date picker as current date
        return new DatePickerDialog(this, datePickerListener, year, month,
                day);
    }
    return null;
}

private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {
    public void onDateSet(DatePicker view, int selectedYear,
            int selectedMonth, int selectedDay) {
        year = selectedYear;
        month = selectedMonth+1;
        day = selectedDay;

        startdate.setText(new StringBuilder().append(day).append("-")
                .append(getMonth(month + 1)).append("-").append(year)
                .append(" "));
    }
};

Body:
With the Material Components Library just use the MaterialDatePicker and build your own DateValidator or you can just use the DateValidatorPointForward provided by the library.

Something like:

MaterialDatePicker.Builder<Long> builder = MaterialDatePicker.Builder.datePicker();

CalendarConstraints.DateValidator dateValidator = DateValidatorPointForward.now();
//if you need a custom date just use
//CalendarConstraints.DateValidator dateValidator = DateValidatorPointForward.from(yourDate);
constraintsBuilder.setValidator(dateValidator);
builder.setCalendarConstraints(constraintsBuilder.build());

MaterialDatePicker<Long> picker = builder.build();
picker.show(getSupportFragmentManager(), picker.toString());


问:
PDF Function doesn't work, even though it did before
Since today, I have this error. I don't know what it means. Can anyone help me?

I tried to see where the problem is, by searching through the browser console, but all I found is this error message. The PDF Function is still there, it's just that every time I click on the button that should trigger the function, it suddenly doesn't work. Even though it worked just fine before.

Here is the error message:

```<code>Uncaught TypeError: Cannot read property 'name' of undefined
    at j (jspdf.min.js:202)
    at k (jspdf.min.js:202)
    at jspdf.min.js:202
    at l (jspdf.min.js:202)
    at d (jspdf.min.js:202)
    at m (jspdf.min.js:202)
    at Object.t.fromHTML (jspdf.min.js:202)
    at printTablePDF (List:174)
    at HTMLButtonElement.onclick (List:148)
</code>```

Here's the code:

```<code><button class="btn btn-secondary btn-block printhide" onclick="printTablePDF()">PDF</button>

<script>
    function generatePDF() {
        let doc = new jsPDF();
        doc.text('test', 10, 10);
        doc.save('test.pdf');
    }

    function printTablePDF() {
        /*
            source: http://jsfiddle.net/xzZ7n/7806/
        */
        var pdf = new jsPDF('p', 'pt', 'letter');

        let source = "<h2 style='font-family: arial, sans-serif;'>Standortliste</h2>";
            source += document.getElementById('printablearea').innerHTML;

        margins = {
            top: 80,
            bottom: 60,
            left: 40,
            width: 522
        };

        pdf.fromHTML(
            source,
            margins.left,
            margins.top, {
            'width': margins.width,

        }, function (dispose) {

            pdf.save('standortliste.pdf');
        }, margins);

    }
</script>
</code>```

答:
Because of this part of code not working you can delete this part and is safely downloading pdf
<code>source += document.getElementById('printablearea').innerHTML;
</code>    </p>

Body:
Since today, I have this error. I don't know what it means. Can anyone help me?

I tried to see where the problem is, by searching through the browser console, but all I found is this error message. The PDF Function is still there, it's just that every time I click on the button that should trigger the function, it suddenly doesn't work. Even though it worked just fine before.

Here is the error message:

Uncaught TypeError: Cannot read property 'name' of undefined
    at j (jspdf.min.js:202)
    at k (jspdf.min.js:202)
    at jspdf.min.js:202
    at l (jspdf.min.js:202)
    at d (jspdf.min.js:202)
    at m (jspdf.min.js:202)
    at Object.t.fromHTML (jspdf.min.js:202)
    at printTablePDF (List:174)
    at HTMLButtonElement.onclick (List:148)

Here's the code:

<button class="btn btn-secondary btn-block printhide" onclick="printTablePDF()">PDF</button>

Body:
Because of this part of code not working you can delete this part and is safely downloading pdf
source += document.getElementById('printablearea').innerHTML;


问:
Session Id's, UUID's and GUID's and just ID's in general
I have an idea. It might be bad, for reasons not known by me, but I would really appreciate your feedback on this!

We've been using Session ID's in a PHP project. And for the first time in 4 years, a duplicate sessionid was generated. Luckily enough I randomly decided to go looking through the Customers Table because I was bored and noticed there was a duplicate entry in the sessionid column and changed it, and references to it, before any real problems occured.

Which led (or lead?) me to ask myself this question:

Basically, any type of ID, be it a session id, uuid or guid can eventually be duplicated because the length of them is not infinite. So then I got thinking, because we never want this to happen again.

I thought, What if we use a combination of date and time, as an identifier? This wouldn't be "random", but it would solve the duplication issue. For example:

```<code>14th of May 2011 04:36:05PM
</code>```

If used as an identifier, could be changed to:

```<code>14052011163605
</code>```

The reason this form of ID will never become duplicated is because no date, combined with time in the future will ever be the same as one in the past, or present.

And since, in our case, these ID's are not meant to be seen by anybody, there's no reason for it to be random, is there?

I'd love to hear your thoughts on this, and, how you approach situations like this. What's your best method of generating [practically] unique ID'S?

答:
UUID / GUIDs are very large (larger than the count of particles in visible universe)

your date/time solution will fail on high loads.  what happens when i need 100+ new ids per second ?

Body:
I have an idea. It might be bad, for reasons not known by me, but I would really appreciate your feedback on this!

We've been using Session ID's in a PHP project. And for the first time in 4 years, a duplicate sessionid was generated. Luckily enough I randomly decided to go looking through the Customers Table because I was bored and noticed there was a duplicate entry in the sessionid column and changed it, and references to it, before any real problems occured.

Which led (or lead?) me to ask myself this question:

Basically, any type of ID, be it a session id, uuid or guid can eventually be duplicated because the length of them is not infinite. So then I got thinking, because we never want this to happen again.

I thought, What if we use a combination of date and time, as an identifier? This wouldn't be "random", but it would solve the duplication issue. For example:

14th of May 2011 04:36:05PM

If used as an identifier, could be changed to:

14052011163605

The reason this form of ID will never become duplicated is because no date, combined with time in the future will ever be the same as one in the past, or present.

And since, in our case, these ID's are not meant to be seen by anybody, there's no reason for it to be random, is there?

I'd love to hear your thoughts on this, and, how you approach situations like this. What's your best method of generating [practically] unique ID'S?


问:
How to change DatePicker's texts color in SwiftUI?
I saw this question but it doesn't work in SwiftUI.

Changing text color of datepicker

I tried .forgroundColor and .accentColor but they don't change the texts' color.

答:
```<code>DatePicker("DatePicker", selection: self.$date, displayedComponents: .hourAndMinute)
              .labelsHidden()
              .colorMultiply(Color.white)
              .colorInvert()
</code>```