问:
MySql Query for running totals return same value for each years
I am not expert in MySql, what I am trying to do is, to create a query will returns the running totals by month and years:

```<code>SELECT DISTINCT
    date_format(t.created_at, "%M") AS month,
    date_format(t.created_at, "%Y") AS year,
    SUM(COUNT(*)) over (order by MONTH(created_at) ) as cumulative
FROM team t
GROUP BY YEAR(created_at), MONTH(created_at)
ORDER BY  MONTH(created_at) ASC
</code>```

Query results:
enter image description here

Anyone know how to solve this? :(

答:
you can't use aggregate function container aggregate function, so you might try to use a subquery get count for each year, month, then use window function in the main query

```<code>SELECT  month,
        year,
        SUM(cnt) over (order by year,month) cumulative
FROM (
    SELECT MONTH(created_at) AS month,
        YEAR(created_at) AS year,
        COUNT(*) as cnt
    FROM team t
    GROUP BY YEAR(created_at), MONTH(created_at)
) t1
</code>```

Body:
I am not expert in MySql, what I am trying to do is, to create a query will returns the running totals by month and years:

SELECT DISTINCT
    date_format(t.created_at, "%M") AS month,
    date_format(t.created_at, "%Y") AS year,
    SUM(COUNT(*)) over (order by MONTH(created_at) ) as cumulative
FROM team t
GROUP BY YEAR(created_at), MONTH(created_at)
ORDER BY  MONTH(created_at) ASC

Query results:
enter image description here

Anyone know how to solve this? :(

Body:
you can't use aggregate function container aggregate function, so you might try to use a subquery get count for each year, month, then use window function in the main query

SELECT  month,
        year,
        SUM(cnt) over (order by year,month) cumulative
FROM (
    SELECT MONTH(created_at) AS month,
        YEAR(created_at) AS year,
        COUNT(*) as cnt
    FROM team t
    GROUP BY YEAR(created_at), MONTH(created_at)
) t1


来源: stackexchange

问:
Problem with PHP regular expressions
I just can't seem to work out how to pull the entire table from a page using regex.

This is my PHP:

```<code>$printable = file_get_contents('http://entertainment.soundboxaudio.com/testplaylist.htm');
$array = array();
preg_match( '/<TABLE>(.*?)<\/TABLE>/si', $printable, $array ) ;
$findit = "$array[1]";
echo("$findit");
</code>```

Any help would be appreciated,

Thanks!

答:
Here we go again... do NOT use regex to extract HTML. HTML is not a regular language and cannot be reliably analyzed with a regex. Use DOM instead.

```<code>$printable = file_get_conttents('...');
$dom = new DOMDocument;
$dom->loadHTML($printable);
$xpath = new DOMXpath($dom);

$tables = $xpath->query("//table");

$table_html = array();

foreach($tables as $table) { // workaround for PHP DOM not support innerHTML
   $temp = new DOMDocument;
   $temp->appendChild($temp->importNode($table, true));
   $table_html[] = trim($temp->saveHTML());
}
</code>```

As well, surrounding variables you're echoing is just a waste of a string operation

```<code>echo $x
echo "$x";
</code>```

work identically, except the quoted version wastes some cpu produce a temporary string that only gets thrown away again.

ContentLicense: CC BY-SA 3.0

Title: Problem with PHP regular expressions

Body:
I just can't seem to work out how to pull the entire table from a page using regex.

This is my PHP:

$printable = file_get_contents('http://entertainment.soundboxaudio.com/testplaylist.htm');
$array = array();
preg_match( '/
(.*?)<\/TABLE>/si', $printable, $array ) ;
$findit = "$array[1]";
echo("$findit");

Any help would be appreciated,

Thanks!

Body:
Here we go again... do NOT use regex to extract HTML. HTML is not a regular language and cannot be reliably analyzed with a regex. Use DOM instead.

$printable = file_get_conttents('...');
$dom = new DOMDocument;
$dom->loadHTML($printable);
$xpath = new DOMXpath($dom);

$tables = $xpath->query("//table");

$table_html = array();

foreach($tables as $table) { // workaround for PHP DOM not support innerHTML
   $temp = new DOMDocument;
   $temp->appendChild($temp->importNode($table, true));
   $table_html[] = trim($temp->saveHTML());
}

As well, surrounding variables you're echoing is just a waste of a string operation

echo $x
echo "$x";

work identically, except the quoted version wastes some cpu produce a temporary string that only gets thrown away again.


问:
How can I position the tooltip to make it responsive?
I'm trying to make a tooltip that should appear on the top of every navigation bar link and should also be responsive i.e when screen size is smaller than certain px say 350px my navbar should appear vertically align and tooltip should appear on the left or right side of every link on hover.

My navigation bar works perfectly on my Page. It's also responsive as it should be.

PROBLEM:
But tooltip is not working in smaller screen size as it should be. It shows on the top of nav div for all link but I want it to left or right side of the links on hover. Please help

.navbar ul{
    margin: 0;padding: 0;
    list-style-type: none;
    background-color: #333;
    overflow: hidden;
}
.navbar li {
    float: left;
    text-align: center;
}
.navbar li a, .dropbtn{
    display: inline-block;
    text-align: center;
    color: white;
    font-size:larger;
    padding: 12px 17px;
    text-decoration: none;
}
.navbar li a:hover {
    background-color: rgb(90, 81, 81);
    text-decoration: underline;
}

/*
.navbar .dropdown{
    display: inline-block;
}*/

/*tooltip CSS*/
.tooltip-text{
    position: absolute;
    display: inline-block;
    padding: 1px 3px;
    margin-left: -7px;
    top: -20px;
    text-align: center;
    background-color: #333;
    color: white;
    border: 0.5px solid black;
    border-radius: 2px;
    opacity: 0;
    transition: opacity 1s;
    z-index: 1;
}

.tooltip-text::after{
    content: "";
    position: absolute;
    top: 100%;margin-left: -5px;
    left: 50%;
    border-width: 6px;
    border-style: solid;
    border-color: #222 transparent transparent transparent;
}

.navbar li:hover .tooltip-text{
    visibility: visible;
    opacity: 1;
}

@media screen and (max-width:540px) {
    .navbar li {
        float: none;
    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>whatever</title>
</head>
<body>
    <div class="navbar">
        <ul>
            <li><span class="tooltip-text">Go to Home</span>Home</li>
            <li><span class="tooltip-text">Technology Page</span>Technology</li>
            <li><span class="tooltip-text">Entertainment Page</span>Entertainment</li>
            <li><span class="tooltip-text">Science Page</span>Science</li>
            <li><span class="tooltip-text">Sports Page</span>Sports</li>
            <li><span class="tooltip-text">About Page</span>About</li>
            <li><span class="tooltip-text">Contact Page</span>Contact Us</li>
        </ul>
    </div>

</body>
</html></code>```

答:
You can use this, the problem was that every tooltip-text was set to be on the top of the page and not of the parent element. I recomend you to use display: flex; to make things responsive.

.navbar ul{
    margin: 0;padding: 0;
    list-style-type: none;
    background-color: #333;
    overflow: hidden;
}
.navbar li {
    float: left;
    text-align: center;
}
.navbar li a, .dropbtn{
    display: inline-block;
    text-align: center;
    color: white;
    font-size:larger;
    padding: 12px 17px;
    text-decoration: none;
}
.navbar li a:hover {
    background-color: rgb(90, 81, 81);
    text-decoration: underline;
}

/*
.navbar .dropdown{
    display: inline-block;
}*/

/*tooltip CSS*/
.tooltip-text{
    position: absolute;
    display: inline-block;
    padding: 1px 3px;
    margin-left: -7px;
    margin: -20px 0 0 0;
    text-align: center;
    background-color: #333;
    color: white;
    border: 0.5px solid black;
    border-radius: 2px;
    opacity: 0;
    transition: opacity 1s;
    z-index: 1;
}

.tooltip-text::after{
    content: "";
    position: absolute;
    margin-left: -5px;
    left: 50%;
    border-width: 6px;
    border-style: solid;
    border-color: #222 transparent transparent transparent;
}

.navbar li:hover .tooltip-text{
    visibility: visible;
    opacity: 1;
}

   /* Edited code */

@media screen and (max-width:540px) {
    .navbar li {
        float: none;
    }

    .tooltip-text {
        position: absolute;
        display: flex;
        padding: 1px 3px;
        margin-left: 10%;
        text-align: center;
        background-color: #333;
        margin-top: 2vh;
        color: white;
        border: 0.5px solid black;
        border-radius: 2px;
        opacity: 0;
        transition: opacity 1s;
        z-index: 1;
    }

    .tooltip-text::after {
        content: "";
        position: absolute;
        transform: rotate(270deg);
        top: 20%;
        margin: 0 0 0 53%;
        border-width: 6px;
        border-style: solid;
        border-color: #222 transparent transparent transparent;
    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>whatever</title>
</head>
<body>
    <div class="navbar">
        <ul>
            <li><span class="tooltip-text">Go to Home</span>Home</li>
            <li><span class="tooltip-text">Technology Page</span>Technology</li>
            <li><span class="tooltip-text">Entertainment Page</span>Entertainment</li>
            <li><span class="tooltip-text">Science Page</span>Science</li>
            <li><span class="tooltip-text">Sports Page</span>Sports</li>
            <li><span class="tooltip-text">About Page</span>About</li>
            <li><span class="tooltip-text">Contact Page</span>Contact Us</li>
        </ul>
    </div>

</body>
</html></code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to make a tooltip that should appear on the top of every navigation bar link and should also be responsive i.e when screen size is smaller than certain px say 350px my navbar should appear vertically align and tooltip should appear on the left or right side of every link on hover.

My navigation bar works perfectly on my Page. It's also responsive as it should be.

PROBLEM:
But tooltip is not working in smaller screen size as it should be. It shows on the top of nav div for all link but I want it to left or right side of the links on hover. Please help

.navbar ul{
    margin: 0;padding: 0;
    list-style-type: none;
    background-color: #333;
    overflow: hidden;
}
.navbar li {
    float: left;
    text-align: center;
}
.navbar li a, .dropbtn{
    display: inline-block;
    text-align: center;
    color: white;
    font-size:larger;
    padding: 12px 17px;
    text-decoration: none;
}
.navbar li a:hover {
    background-color: rgb(90, 81, 81);
    text-decoration: underline;
}

/*
.navbar .dropdown{
    display: inline-block;
}*/

/*tooltip CSS*/
.tooltip-text{
    position: absolute;
    display: inline-block;
    padding: 1px 3px;
    margin-left: -7px;
    top: -20px;
    text-align: center;
    background-color: #333;
    color: white;
    border: 0.5px solid black;
    border-radius: 2px;
    opacity: 0;
    transition: opacity 1s;
    z-index: 1;
}

.tooltip-text::after{
    content: "";
    position: absolute;
    top: 100%;margin-left: -5px;
    left: 50%;
    border-width: 6px;
    border-style: solid;
    border-color: #222 transparent transparent transparent;
}

.navbar li:hover .tooltip-text{
    visibility: visible;
    opacity: 1;
}

@media screen and (max-width:540px) {
    .navbar li {
        float: none;
    }
}

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>whatever</title>

Go to HomeHome

Technology PageTechnology

Entertainment PageEntertainment

Science PageScience

Sports PageSports

About PageAbout

Contact PageContact Us

Body:
You can use this, the problem was that every tooltip-text was set to be on the top of the page and not of the parent element. I recomend you to use display: flex; to make things responsive.

.navbar ul{
    margin: 0;padding: 0;
    list-style-type: none;
    background-color: #333;
    overflow: hidden;
}
.navbar li {
    float: left;
    text-align: center;
}
.navbar li a, .dropbtn{
    display: inline-block;
    text-align: center;
    color: white;
    font-size:larger;
    padding: 12px 17px;
    text-decoration: none;
}
.navbar li a:hover {
    background-color: rgb(90, 81, 81);
    text-decoration: underline;
}

/*
.navbar .dropdown{
    display: inline-block;
}*/

/*tooltip CSS*/
.tooltip-text{
    position: absolute;
    display: inline-block;
    padding: 1px 3px;
    margin-left: -7px;
    margin: -20px 0 0 0;
    text-align: center;
    background-color: #333;
    color: white;
    border: 0.5px solid black;
    border-radius: 2px;
    opacity: 0;
    transition: opacity 1s;
    z-index: 1;
}

.tooltip-text::after{
    content: "";
    position: absolute;
    margin-left: -5px;
    left: 50%;
    border-width: 6px;
    border-style: solid;
    border-color: #222 transparent transparent transparent;
}

.navbar li:hover .tooltip-text{
    visibility: visible;
    opacity: 1;
}

   /* Edited code */

@media screen and (max-width:540px) {
    .navbar li {
        float: none;
    }

    .tooltip-text {
        position: absolute;
        display: flex;
        padding: 1px 3px;
        margin-left: 10%;
        text-align: center;
        background-color: #333;
        margin-top: 2vh;
        color: white;
        border: 0.5px solid black;
        border-radius: 2px;
        opacity: 0;
        transition: opacity 1s;
        z-index: 1;
    }

    .tooltip-text::after {
        content: "";
        position: absolute;
        transform: rotate(270deg);
        top: 20%;
        margin: 0 0 0 53%;
        border-width: 6px;
        border-style: solid;
        border-color: #222 transparent transparent transparent;
    }
}

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>whatever</title>
</head>
<body>
    <div class="navbar">
        <ul>
            <li><span class="tooltip-text">Go to Home</span><a href="#">Home</a></li>
            <li><span class="tooltip-text">Technology Page</span><a href="#">Technology</a></li>
            <li><span class="tooltip-text">Entertainment Page</span><a href="#">Entertainment</a></li>
            <li><span class="tooltip-text">Science Page</span><a href="#">Science</a></li>
            <li><span class="tooltip-text">Sports Page</span><a href="#">Sports</a></li>
            <li><span class="tooltip-text">About Page</span><a href="#">About</a></li>
            <li><span class="tooltip-text">Contact Page</span><a href="#">Contact Us</a></li>
        </ul>
    </div>

</body>
</html>


问:
Sorting a structure by multiple columns in C
Consider a simple struct

```<code>typedef struct test {
int num;
double val;
} test;

int main()
{

test test[5]={ {5,4.3}, {1,0.9}, {1,0.3}, {1,3.2}, {5,1.1}};

for(int i=0; i<5; i++){
    printf("%d: %f\n", test[i].num, test[i].val);
}
    return 0;
}
</code>```

How do we sort it by the first column and then the next one?

Intended Output:

```<code>1: 0.300000
1: 0.900000
1: 3.200000
5: 1.100000
5: 4.300000
</code>```

答:
The key to using qsort() is writing the compare function. The prototype is:

int compare (const void *a, const void *b)
```
<p>Don't let your eyes roll back in your head. <code>a</code> and <code>b</code> are just pointers to elements of the array that will be compared in the <code>compare()</code> function. The function returns <code>-1</code> if <code>a</code> sorts before <code>b</code>, <code>0</code> if they are equal, and <code>1</code> if <code>b</code> sorts before <code>a</code>. All you need to do with <code>a</code> and <code>b</code> is cast to the proper type and then make the desired comparison (ascending, descending, etc..).</p>
<p>In the case you have two values you wish to compare, you simply compare the first, and if they are NOT equal, you provide a return indicating how they should sort on the first value. (your <code>.num</code> member) If the first values with <code>a</code> and <code>b</code> ARE equal, then you provide a return based on the comparison of the second value (your <code>.val</code> member).</p>
<p>You can write the <code>compare()</code> function as:</p>
<pre class="lang-c prettyprint-override"><code>int compare (const void *a, const void *b)
{
    test *x = (test *)a,
         *y = (test *)b;

    /* if ->num not equal, sort by ->num */
    if (x->num != y->num)
      return (x->num > y->num) - (x->num < y->num);

    /* otherwise, sort by val */
    return (x->val > y->val) - (x->val < y->val);
}
</code>```

A short example that sorts the test array (renamed arr):

#include <stdio.h>
#include <stdlib.h>

typedef struct test {
  int num;
  double val;
} test;

int compare (const void *a, const void *b)
{
    test *x = (test *)a,
         *y = (test *)b;

    /* if ->num not equal, sort by ->num */
    if (x->num != y->num)
      return (x->num > y->num) - (x->num < y->num);

    /* otherwise, sort by val */
    return (x->val > y->val) - (x->val < y->val);
}

int main()
{

  test arr[]={ {5,4.3}, {1,0.9}, {1,0.3}, {1,3.2}, {5,1.1}};
  size_t nmemb = sizeof arr/sizeof *arr;

  qsort (arr, nmemb, sizeof *arr, compare);

  for (size_t i = 0; i < nmemb; i++){
      printf ("%d: %f\n", arr[i].num, arr[i].val);
  }
}
```
<p><strong>Example Use/Output</strong></p>
<pre class="lang-none prettyprint-override"><code>$ ./bin/qsortstruct_test
1: 0.300000
1: 0.900000
1: 3.200000
5: 1.100000
5: 4.300000
</code>```

Read the link I posted in the comment and the answer here and let me know if you have further questions.

Body:
Consider a simple struct

typedef struct test {
int num;
double val;
} test;

int main()
{

test test[5]={ {5,4.3}, {1,0.9}, {1,0.3}, {1,3.2}, {5,1.1}};

for(int i=0; i<5; i++){
    printf("%d: %f\n", test[i].num, test[i].val);
}
    return 0;
}

How do we sort it by the first column and then the next one?

Intended Output:

1: 0.300000
1: 0.900000
1: 3.200000
5: 1.100000
5: 4.300000

Body:
The key to using qsort() is writing the compare function. The prototype is:

int compare (const void *a, const void *b)

Don't let your eyes roll back in your head. a and b are just pointers to elements of the array that will be compared in the compare() function. The function returns -1 if a sorts before b, 0 if they are equal, and 1 if b sorts before a. All you need to do with a and b is cast to the proper type and then make the desired comparison (ascending, descending, etc..).

In the case you have two values you wish to compare, you simply compare the first, and if they are NOT equal, you provide a return indicating how they should sort on the first value. (your .num member) If the first values with a and b ARE equal, then you provide a return based on the comparison of the second value (your .val member).

You can write the compare() function as:

int compare (const void *a, const void *b)
{
    test *x = (test *)a,
         *y = (test *)b;

    /* if ->num not equal, sort by ->num */
    if (x->num != y->num)
      return (x->num > y->num) - (x->num < y->num);

    /* otherwise, sort by val */
    return (x->val > y->val) - (x->val < y->val);
}

A short example that sorts the test array (renamed arr):

#include <stdio.h>
#include <stdlib.h>

typedef struct test {
  int num;
  double val;
} test;

int compare (const void *a, const void *b)
{
    test *x = (test *)a,
         *y = (test *)b;

    /* if ->num not equal, sort by ->num */
    if (x->num != y->num)
      return (x->num > y->num) - (x->num < y->num);

    /* otherwise, sort by val */
    return (x->val > y->val) - (x->val < y->val);
}

int main()
{

  test arr[]={ {5,4.3}, {1,0.9}, {1,0.3}, {1,3.2}, {5,1.1}};
  size_t nmemb = sizeof arr/sizeof *arr;

  qsort (arr, nmemb, sizeof *arr, compare);

  for (size_t i = 0; i < nmemb; i++){
      printf ("%d: %f\n", arr[i].num, arr[i].val);
  }
}

Example Use/Output

$ ./bin/qsortstruct_test
1: 0.300000
1: 0.900000
1: 3.200000
5: 1.100000
5: 4.300000

Read the link I posted in the comment and the answer here and let me know if you have further questions.


问:
Need help on SFINAE on class template T
I'm writing a template class Foo<T> which I only want to allow certain types of T. I have been playing around for quite a while and now the class compiles, but in the presence of a second template non-type parameter, I couldn't figure out how to instantiate it correctly. How can I give it a default value so that I can simply call Foo<int> and so on?

#include <iostream>
#include <utility>
#include <type_traits>

template<typename T>
struct is_foo_type {
    using type = typename std::enable_if_t<
        // std::is_same_v<T, vec2>   ||
        // std::is_same_v<T, vec3>   ||
        // std::is_same_v<T, vec4>   ||
        // std::is_same_v<T, ivec2>  ||
        // std::is_same_v<T, ivec3>  ||
        // std::is_same_v<T, ivec4>  ||
        // std::is_same_v<T, mat2>   ||
        // std::is_same_v<T, mat3>   ||
        // std::is_same_v<T, mat4>   ||
        // std::is_same_v<T, mat2x2> ||
        // std::is_same_v<T, mat2x3> ||
        // std::is_same_v<T, mat2x4> ||
        // std::is_same_v<T, mat3x2> ||
        // std::is_same_v<T, mat3x3> ||
        // std::is_same_v<T, mat3x4> ||
        // std::is_same_v<T, mat4x2> ||
        // std::is_same_v<T, mat4x3> ||
        // std::is_same_v<T, mat4x4> ||
        std::is_same_v<T, int>    ||
        std::is_same_v<T, bool>   ||
        std::is_same_v<T, float>  ||
        std::is_same_v<T, char>
    >;
};

template<typename T, typename is_foo_type<T>::type = 0>
class Foo {
public:
    T _x;
    Foo() = default;
    Foo(const T& x) : _x(x) {};
    void Increment(const T& x) { _x += x; }
};

int main() {
    Foo<int> a{123};  // compiler error

    // using foo_int   = Foo<int>;    // compiler error
    // using foo_bool  = Foo<bool>;   // compiler error
    // using foo_float = Foo<float>;  // compiler error

    // using foo_var = std::variant<foo_int, foo_bool, foo_float>;

    // foo_var my_variant;
}
```

答:
Try adding multiple template

Syntax: template<typename T, typename V>.

And use it accordingly

Title: Need help on SFINAE on class template T


问:
Testing a Function by Passing Input Multiple Times
I'm learning Go with tests. I ended up with the below program from the end of chapter 2 in "Head First Go".

It gives the user three attempts to guess a number from 1 to 10:

guess.go

package main

import (
    "fmt"
    "math/rand"
    "time"
    "bufio"
    "os"
    "log"
    "strconv"
    "strings"
)

func generateRandomNumber() int {
    rand.Seed(time.Now().Unix())       // seed value based on time to generate non-deterministic random values
    randomNum := rand.Intn(10) + 1     // range: [0, 10); produces the same value without Seed(), i.e., pseudo-random
    return randomNum
}

func guess() int {
    var success bool = false
    target := generateRandomNumber()

    fmt.Println("Guess a number between 1 and 10")
    guess  := bufio.NewReader(os.Stdin)

    for attempts := 0; attempts < 3; attempts++ {
        fmt.Println("You have", 3-attempts, "guesses left")
        userVal, err := guess.ReadString('\n')
        if err != nil {
            log.Fatal(err)
        }

        input := strings.TrimSpace(userVal)
        answer, err := strconv.Atoi(input)
        if err != nil {
            log.Fatal(err)
        }

        if answer == target {
            fmt.Println("Congratulations !!")
            return answer
        } else if answer > target {
            fmt.Println("Your guess was HIGHER")
        } else if answer < target {
            fmt.Println("Your guess was LOWER")
        }
    }

    if !success {
        fmt.Printf("Sorry, you've run out of attempts... The correct value is %d\n", target)
        return target
    }
    return 0
}

func main() {
    guess()
}

```
<p><code>guess_test.go</code></p>
```package main

import (
    "testing"
)

func TestRandomNumber(t *testing.T) {
    want := generateRandomNumber()

    if 7 != want {
        t.Fail()
        t.Logf("Incorrect guess; The random number was %d", want)
    }
}

```

How can I test guess() by passing in three different inputs?

I would like to perform a test by comparing the return value of guess() with generateRandomNumber().

答:
You can change guess function to get reader from input, by this we able to pass it any reader we want: in main we pass stdin reader and in test we pass mock reader:

guess.go

package main

import (
    "bufio"
    "fmt"
    "log"
    "math/rand"
    "os"
    "strconv"
    "strings"
    "time"
)

func generateRandomNumber() int {
    rand.Seed(time.Now().Unix())   // seed value based on time to generate non-deterministic random values
    randomNum := rand.Intn(10) + 1 // range: [0, 10); produces the same value without Seed(), i.e., pseudo-random
    return randomNum
}

func guess(reader *bufio.Reader) (int, error) {
    target := generateRandomNumber()

    fmt.Println("Guess a number between 1 and 10")

    for attempts := 0; attempts < 3; attempts++ {
        fmt.Println("You have", 3-attempts, "guesses left")
        userVal, err := reader.ReadString('\n')
        if err != nil {
            log.Fatal(err)
        }

        input := strings.TrimSpace(userVal)
        answer, err := strconv.Atoi(input)
        if err != nil {
            log.Fatal(err)
        }

        if answer == target {
            fmt.Println("Congratulations !!")
            return answer, nil
        } else if answer > target {
            fmt.Println("Your guess was HIGHER")
        } else if answer < target {
            fmt.Println("Your guess was LOWER")
        }
    }

    fmt.Printf("Sorry, you've run out of attempts... The correct value is %d\n", target)
    return target, fmt.Errorf("attempts is over")
}

func main() {
    reader := bufio.NewReader(os.Stdin)
    guess(reader)
}
```
<p>for testing:</p>
<p><code>guess_test.go</code></p>
<pre class="lang-go prettyprint-override"><code>package main

import (
    "bufio"
    "fmt"
    "strings"
    "testing"
)

func TestRandomNumberOk(t *testing.T) {
    want := generateRandomNumber()
    msg := fmt.Sprintf("3\n4\n%d\n", want)
    reader := strings.NewReader(msg)
    r := bufio.NewReader(reader)
    _, err := guess(r)
    if err != nil {
        t.Errorf("guess must successfull")
    }
}

func TestRandomNumberFail(t *testing.T) {
    want := generateRandomNumber()
    msg := fmt.Sprintf("3\n4\n%d\n", want+1)
    reader := strings.NewReader(msg)
    r := bufio.NewReader(reader)
    _, err := guess(r)
    if err == nil {
        t.Errorf("guess must unsuccessfull")
    }
}
</code>```

I had to change your guess return value, because it's unknown when it's successful or not

Body:
I'm learning Go with tests. I ended up with the below program from the end of chapter 2 in "Head First Go".

It gives the user three attempts to guess a number from 1 to 10:

guess.go

package main

import (
    "fmt"
    "math/rand"
    "time"
    "bufio"
    "os"
    "log"
    "strconv"
    "strings"
)

func generateRandomNumber() int {
    rand.Seed(time.Now().Unix())       // seed value based on time to generate non-deterministic random values
    randomNum := rand.Intn(10) + 1     // range: [0, 10); produces the same value without Seed(), i.e., pseudo-random
    return randomNum
}

func guess() int {
    var success bool = false
    target := generateRandomNumber()

    fmt.Println("Guess a number between 1 and 10")
    guess  := bufio.NewReader(os.Stdin)

    for attempts := 0; attempts < 3; attempts++ {
        fmt.Println("You have", 3-attempts, "guesses left")
        userVal, err := guess.ReadString('\n')
        if err != nil {
            log.Fatal(err)
        }

        input := strings.TrimSpace(userVal)
        answer, err := strconv.Atoi(input)
        if err != nil {
            log.Fatal(err)
        }

        if answer == target {
            fmt.Println("Congratulations !!")
            return answer
        } else if answer > target {
            fmt.Println("Your guess was HIGHER")
        } else if answer < target {
            fmt.Println("Your guess was LOWER")
        }
    }

    if !success {
        fmt.Printf("Sorry, you've run out of attempts... The correct value is %d\n", target)
        return target
    }
    return 0
}

func main() {
    guess()
}

guess_test.go

package main

import (
    "testing"
)

func TestRandomNumber(t *testing.T) {
    want := generateRandomNumber()

    if 7 != want {
        t.Fail()
        t.Logf("Incorrect guess; The random number was %d", want)
    }
}

How can I test guess() by passing in three different inputs?

I would like to perform a test by comparing the return value of guess() with generateRandomNumber().

Body:
You can change guess function to get reader from input, by this we able to pass it any reader we want: in main we pass stdin reader and in test we pass mock reader:

guess.go

package main

import (
    "bufio"
    "fmt"
    "log"
    "math/rand"
    "os"
    "strconv"
    "strings"
    "time"
)

func generateRandomNumber() int {
    rand.Seed(time.Now().Unix())   // seed value based on time to generate non-deterministic random values
    randomNum := rand.Intn(10) + 1 // range: [0, 10); produces the same value without Seed(), i.e., pseudo-random
    return randomNum
}

func guess(reader *bufio.Reader) (int, error) {
    target := generateRandomNumber()

    fmt.Println("Guess a number between 1 and 10")

    for attempts := 0; attempts < 3; attempts++ {
        fmt.Println("You have", 3-attempts, "guesses left")
        userVal, err := reader.ReadString('\n')
        if err != nil {
            log.Fatal(err)
        }

        input := strings.TrimSpace(userVal)
        answer, err := strconv.Atoi(input)
        if err != nil {
            log.Fatal(err)
        }

        if answer == target {
            fmt.Println("Congratulations !!")
            return answer, nil
        } else if answer > target {
            fmt.Println("Your guess was HIGHER")
        } else if answer < target {
            fmt.Println("Your guess was LOWER")
        }
    }

    fmt.Printf("Sorry, you've run out of attempts... The correct value is %d\n", target)
    return target, fmt.Errorf("attempts is over")
}

func main() {
    reader := bufio.NewReader(os.Stdin)
    guess(reader)
}

for testing:

guess_test.go

package main

import (
    "bufio"
    "fmt"
    "strings"
    "testing"
)

func TestRandomNumberOk(t *testing.T) {
    want := generateRandomNumber()
    msg := fmt.Sprintf("3\n4\n%d\n", want)
    reader := strings.NewReader(msg)
    r := bufio.NewReader(reader)
    _, err := guess(r)
    if err != nil {
        t.Errorf("guess must successfull")
    }
}

func TestRandomNumberFail(t *testing.T) {
    want := generateRandomNumber()
    msg := fmt.Sprintf("3\n4\n%d\n", want+1)
    reader := strings.NewReader(msg)
    r := bufio.NewReader(reader)
    _, err := guess(r)
    if err == nil {
        t.Errorf("guess must unsuccessfull")
    }
}

I had to change your guess return value, because it's unknown when it's successful or not


问:
android dialog transparent
I want to get rid of the border in my dialog box and make it look absolutly transparent, as if the image is on the top of screen.

My dialog xml is -

```<code><?xml version="1.0" encoding="utf-8"?>
</code>```

```<code><ImageView android:id="@+id/ImageView01"
    android:layout_width="wrap_content" android:layout_height="wrap_content"
    android:layout_centerHorizontal="true" android:visibility="invisible"/>
</code>```

答:
try this:</p>

```<code>mDialog.getWindow().setBackgroundDrawable(new ColorDrawable(0));
</code>```

Title: android dialog transparent

Body:
I want to get rid of the border in my dialog box and make it look absolutly transparent, as if the image is on the top of screen.

My dialog xml is -

<?xml version="1.0" encoding="utf-8"?>

<ImageView android:id="@+id/ImageView01"
    android:layout_width="wrap_content" android:layout_height="wrap_content"
    android:layout_centerHorizontal="true" android:visibility="invisible"/>

Body:
try this:

mDialog.getWindow().setBackgroundDrawable(new ColorDrawable(0));


答:
std::enable_if_t<true> gives you a void type. Then you're trying to do something like

```<code>template<typename T, void = 0>
</code>```

which doesn't work for an obvious reason. You can kind of fix the problem with std::enable_if_t<..., int>.

But note that you're not doing SFINAE here. Substitution will be a hard error in your example - SFINAE works only in the immediate context.

Consider the following alternative implementation:

```<code>template<typename T>
struct is_foo_type : std::disjunction<
        std::is_same<T, int>,
        std::is_same<T, bool>,
        std::is_same<T, float>,
        std::is_same<T, char>
> {};

template<typename T, typename = std::enable_if_t<is_foo_type<T>::value>>
class Foo { ... };
</code>```

and note in which context std::enable_if is used.

In this particular case you could also use a non-type template parameter

```<code>template<typename T, std::enable_if_t<is_foo_type<T>::value, int> = 0>
class Foo { ... };
</code>```

to avoid the possibility of "overriding" substitution when the second type is provided explicitly, e.g. Foo<T, void>.

Title: Need help on SFINAE on class template T

Body:
I'm writing a template class Foo<T> which I only want to allow certain types of T. I have been playing around for quite a while and now the class compiles, but in the presence of a second template non-type parameter, I couldn't figure out how to instantiate it correctly. How can I give it a default value so that I can simply call Foo<int> and so on?

#include <iostream>
#include <utility>
#include <type_traits>

template<typename T>
struct is_foo_type {
    using type = typename std::enable_if_t<
        // std::is_same_v<T, vec2>   ||
        // std::is_same_v<T, vec3>   ||
        // std::is_same_v<T, vec4>   ||
        // std::is_same_v<T, ivec2>  ||
        // std::is_same_v<T, ivec3>  ||
        // std::is_same_v<T, ivec4>  ||
        // std::is_same_v<T, mat2>   ||
        // std::is_same_v<T, mat3>   ||
        // std::is_same_v<T, mat4>   ||
        // std::is_same_v<T, mat2x2> ||
        // std::is_same_v<T, mat2x3> ||
        // std::is_same_v<T, mat2x4> ||
        // std::is_same_v<T, mat3x2> ||
        // std::is_same_v<T, mat3x3> ||
        // std::is_same_v<T, mat3x4> ||
        // std::is_same_v<T, mat4x2> ||
        // std::is_same_v<T, mat4x3> ||
        // std::is_same_v<T, mat4x4> ||
        std::is_same_v<T, int>    ||
        std::is_same_v<T, bool>   ||
        std::is_same_v<T, float>  ||
        std::is_same_v<T, char>
    >;
};

template<typename T, typename is_foo_type<T>::type = 0>
class Foo {
public:
    T _x;
    Foo() = default;
    Foo(const T& x) : _x(x) {};
    void Increment(const T& x) { _x += x; }
};

int main() {
    Foo<int> a{123};  // compiler error

    // using foo_int   = Foo<int>;    // compiler error
    // using foo_bool  = Foo<bool>;   // compiler error
    // using foo_float = Foo<float>;  // compiler error

    // using foo_var = std::variant<foo_int, foo_bool, foo_float>;

    // foo_var my_variant;
}

Body:
std::enable_if_t<true> gives you a void type. Then you're trying to do something like

template<typename T, void = 0>

which doesn't work for an obvious reason. You can kind of fix the problem with std::enable_if_t<..., int>.

But note that you're not doing SFINAE here. Substitution will be a hard error in your example - SFINAE works only in the immediate context.

Consider the following alternative implementation:

template<typename T>
struct is_foo_type : std::disjunction<
        std::is_same<T, int>,
        std::is_same<T, bool>,
        std::is_same<T, float>,
        std::is_same<T, char>
> {};

template<typename T, typename = std::enable_if_t<is_foo_type<T>::value>>
class Foo { ... };

and note in which context std::enable_if is used.

In this particular case you could also use a non-type template parameter

template<typename T, std::enable_if_t<is_foo_type<T>::value, int> = 0>
class Foo { ... };

to avoid the possibility of "overriding" substitution when the second type is provided explicitly, e.g. Foo<T, void>.


问:
Deploying Environment Variables to Vercel with nextjs
I am new to next.js and experiencing issues while trying to deploy environment variables to Vercel.

We are trying to deploy Stripe Payment Gateway to Vercel

Downloaded the Stripe Payment Gateway Sample code from

https://github.com/tmarek-stripe/demo-react-stripe-js

This is a nextjs application with a .env file that has a public and secret key pair.
Everything works fine while running on localhost , also the projects work fine on Vercel when I include the .env file in the git repository

As soon as I include the .env file in gitignore and push the updates to the repository , the .env file would not be shown and I get 500 Server error while trying to make test payments

Error while making payments

Below is the code for payment intent.js

```<code>import Stripe from "stripe";

const stripe = new Stripe(process.env.SECRET_KEY);

export default async (req, res) => {
  if (req.method === "POST") {
    try {
      const { amount } = req.body;

      const paymentIntent = await stripe.paymentIntents.create({
        amount,
        currency: "usd"
      });

      res.status(200).send(paymentIntent.client_secret);
    } catch (err) {
      res.status(500).json({ statusCode: 500, message: err.message });
    }
  } else {
    res.setHeader("Allow", "POST");
    res.status(405).end("Method Not Allowed");
  }
};
</code>```

The .Env File looks like below

```<code>PUBLISHABLE_KEY=pk_test_key

SECRET_KEY=sk_test_Secret Key
</code>```

Read all the available articles online with no luck.

No changes were made to the code apart from Public and Secret Key in .env file

Please let me know how to hide the Environment Variables(as it contains the secret key) and at the same time use it in the production environment

Any help would be appreciated

Thanks in Advance

答:
Someone came up with a bash script to upload an .env file

```<code>while IFS== read -r name value
do
  echo "$value" | vercel env add "$name" "$2"
done < "$1"
</code>```

command:

```<code><script name> <file> <production | preview | development>
</code>```

and I also think it'd be better to have something like vercel env push [environment] [file]

SOURCE

Body:
I am new to next.js and experiencing issues while trying to deploy environment variables to Vercel.

We are trying to deploy Stripe Payment Gateway to Vercel

Downloaded the Stripe Payment Gateway Sample code from

https://github.com/tmarek-stripe/demo-react-stripe-js

This is a nextjs application with a .env file that has a public and secret key pair.
Everything works fine while running on localhost , also the projects work fine on Vercel when I include the .env file in the git repository

As soon as I include the .env file in gitignore and push the updates to the repository , the .env file would not be shown and I get 500 Server error while trying to make test payments

Error while making payments

Below is the code for payment intent.js

import Stripe from "stripe";

const stripe = new Stripe(process.env.SECRET_KEY);

export default async (req, res) => {
  if (req.method === "POST") {
    try {
      const { amount } = req.body;

      const paymentIntent = await stripe.paymentIntents.create({
        amount,
        currency: "usd"
      });

      res.status(200).send(paymentIntent.client_secret);
    } catch (err) {
      res.status(500).json({ statusCode: 500, message: err.message });
    }
  } else {
    res.setHeader("Allow", "POST");
    res.status(405).end("Method Not Allowed");
  }
};

The .Env File looks like below

PUBLISHABLE_KEY=pk_test_key

SECRET_KEY=sk_test_Secret Key

Read all the available articles online with no luck.

No changes were made to the code apart from Public and Secret Key in .env file

Please let me know how to hide the Environment Variables(as it contains the secret key) and at the same time use it in the production environment

Any help would be appreciated

Thanks in Advance

Body:
Someone came up with a bash script to upload an .env file

while IFS== read -r name value
do
  echo "$value" | vercel env add "$name" "$2"
done < "$1"

command:

<script name> <file> <production | preview | development>

and I also think it'd be better to have something like vercel env push [environment] [file]

SOURCE


问:
MySql: Select value of current and next row
I am trying to learn of a better way in achieving the desired result of a select query - details below, thank you in advance.

MySQL version: 5.7

Table:
id int(11)
product_number int(8)
service_group int (4)
datetime datetime
value int (6)

Indexes on all but value column.

MySql table has the following data:

```<code>id,product_number, service_group,datetime,value
1,1234,1,2022-02-10 00:00:00,0
2,1234,1,2022-02-10 00:01:30,25
3,1234,1,2022-02-10 00:02:30,11
4,1234,2,2022-02-10 01:00:30,0
5,1234,2,2022-02-10 01:01:30,65
6,1234,2,2022-02-10 01:02:30,55
</code>```

In essence, the value for each product within the service group is wrongly recorded, and the correct value for the "current" row is actually recorded against the next row for the product within the same service group - correct output should look like this:

```<code>id,product_number, service_group,datetime,value
1,1234,1,2022-02-10 00:00:00,25
2,1234,1,2022-02-10 00:01:30,11
3,1234,1,2022-02-10 00:02:30,0
4,1234,2,2022-02-10 01:00:30,65
5,1234,2,2022-02-10 01:01:30,55
6,1234,2,2022-02-10 01:02:30,0
</code>```

The below query is what seems to be hugely inefficient way of returning the correct results - what would be a better way to go about this in MySql? Thank you.

```<code>Select
    a.id,
    a.product_number,
    a.service_group,
    a.datetime,
    (
    Select b.value FROM products b
    Where b.product_number=a.product_number AND b.service_group=a.service_group
    AND b.datetime>a.datetime
    Order by b.datetime ASC
    Limit 1
    )
FROM products a```
```

答:
I think what you need in THIS case is the Windows LEAD() function and can be found Here for example and clarification

In summary, LEAD() looks at the NEXT possible record for the given column in question, LAG() looks at the prior.

So in this example, I am asking for the LEAD() of the record (the next one in line) and getting the VALUE column of that record.  The 1 represents how many records to skip ahead, in this case 1.  The last parameter 0 is what should be returned if no such record exists.

The second half of the clause with the ORDER BY clause identifies how you want the records returned, in this case the datetime sequence.

I included both the value and the NEXTVALUE so you could see the results, but can remove the extra column once you see and understand how it works.

But since you have each service group to its own, and dont want to carry-over the value from another, you need the PARTITION clause as well.  So I added that as an additional column... both so you can see how the results work with OR without it and the impact of the query you need.

```<code>select
        t.id,
        t.product_number,
        t.service_group,
        t.datetime,
        t.value,
--        lead (t.value, 1, 0)
--            over (order by t.datetime) as NextValue,
        -- without the ,1, 0 in the lead call as sample above
        -- you can see the NULLs are not getting the value
        -- from the next row when the service group changes.
        lead (t.value)
            over ( PARTITION BY
                        t.service_group
                    order by
                        t.datetime) as NextValuePerServiceGroup
    from
        Tmp1 t
    order by
        t.service_group,
        t.datetime

</code>```

Body:
I am trying to learn of a better way in achieving the desired result of a select query - details below, thank you in advance.

MySQL version: 5.7

Table:
id int(11)
product_number int(8)
service_group int (4)
datetime datetime
value int (6)

Indexes on all but value column.

MySql table has the following data:

id,product_number, service_group,datetime,value
1,1234,1,2022-02-10 00:00:00,0
2,1234,1,2022-02-10 00:01:30,25
3,1234,1,2022-02-10 00:02:30,11
4,1234,2,2022-02-10 01:00:30,0
5,1234,2,2022-02-10 01:01:30,65
6,1234,2,2022-02-10 01:02:30,55

In essence, the value for each product within the service group is wrongly recorded, and the correct value for the "current" row is actually recorded against the next row for the product within the same service group - correct output should look like this:

id,product_number, service_group,datetime,value
1,1234,1,2022-02-10 00:00:00,25
2,1234,1,2022-02-10 00:01:30,11
3,1234,1,2022-02-10 00:02:30,0
4,1234,2,2022-02-10 01:00:30,65
5,1234,2,2022-02-10 01:01:30,55
6,1234,2,2022-02-10 01:02:30,0

The below query is what seems to be hugely inefficient way of returning the correct results - what would be a better way to go about this in MySql? Thank you.

Select
    a.id,
    a.product_number,
    a.service_group,
    a.datetime,
    (
    Select b.value FROM products b
    Where b.product_number=a.product_number AND b.service_group=a.service_group
    AND b.datetime>a.datetime
    Order by b.datetime ASC
    Limit 1
    )
FROM products a```

Body:
I think what you need in THIS case is the Windows LEAD() function and can be found Here for example and clarification

In summary, LEAD() looks at the NEXT possible record for the given column in question, LAG() looks at the prior.

So in this example, I am asking for the LEAD() of the record (the next one in line) and getting the VALUE column of that record.  The 1 represents how many records to skip ahead, in this case 1.  The last parameter 0 is what should be returned if no such record exists.

The second half of the clause with the ORDER BY clause identifies how you want the records returned, in this case the datetime sequence.

I included both the value and the NEXTVALUE so you could see the results, but can remove the extra column once you see and understand how it works.

But since you have each service group to its own, and dont want to carry-over the value from another, you need the PARTITION clause as well.  So I added that as an additional column... both so you can see how the results work with OR without it and the impact of the query you need.

select
        t.id,
        t.product_number,
        t.service_group,
        t.datetime,
        t.value,
--        lead (t.value, 1, 0)
--            over (order by t.datetime) as NextValue,
        -- without the ,1, 0 in the lead call as sample above
        -- you can see the NULLs are not getting the value
        -- from the next row when the service group changes.
        lead (t.value)
            over ( PARTITION BY
                        t.service_group
                    order by
                        t.datetime) as NextValuePerServiceGroup
    from
        Tmp1 t
    order by
        t.service_group,
        t.datetime


问:
Eclipse doesn't show suggestions to import package for RestAssured project. How to fix this?
I am using Eclipse Version: 2019-06 (4.12.0). For my Rest Assured project, I have downloaded and added the JAR files from the path https://github.com/rest-assured/rest-assured/wiki/Downloads. For the keyword "RestAssured" Eclipse should suggest to import the package which is missing. Can anyone please help me in fixing this?

*package com.RestAssured;
public class Basic {

```<code>public static void main(String[] args) {
    // TODO Auto-generated method stub

    RestAssured.
}
</code>```

}*

[Java Build Path][1]
[1]: https://i.stack.imgur.com/sl0Dr.png

[Eclipse UI][2]
[2]: https://i.stack.imgur.com/62e5v.png

答: Try deleting the existing java plugin, if u are using java version above 1.8 and install both jdk and jre (1.8) and add those in the system External variable and check when creating a new project in eclipse, verify the execution environment is in JavaSE-1.8. Try this

Body:
I am using Eclipse Version: 2019-06 (4.12.0). For my Rest Assured project, I have downloaded and added the JAR files from the path https://github.com/rest-assured/rest-assured/wiki/Downloads. For the keyword "RestAssured" Eclipse should suggest to import the package which is missing. Can anyone please help me in fixing this?

*package com.RestAssured;
public class Basic {

public static void main(String[] args) {
    // TODO Auto-generated method stub

    RestAssured.
}

}*

[Java Build Path][1]
[1]: https://i.stack.imgur.com/sl0Dr.png

[Eclipse UI][2]
[2]: https://i.stack.imgur.com/62e5v.png


问:
INSERT 6000 Rows - best practice
I have a PHP script that calls an API method that can easily return 6k+ results.

I use PEAR DB_DataObject to write each row in a foreach loop to the DB.

The above script is batch processing 20 users at a time - and although some will only have a few results from the API others will have more. Worst case is that all have 1000's of results.

The loop to call the API seems to be ok, batches of 20 every 5 minutes works fine. My only concern is 1000's of mysql INSERTs for each user (with a long pause between each user for fresh API calls)

Is there a good way to do this? Or am I doing it a good way?!

答:
I have a few ideas, but you will have to verify them with testing.

If the table you are inserting to has indexes, try to make sure they are optimized for inserts.

Check out optimization options here:
http://dev.mysql.com/doc/refman/5.0/en/insert-speed.html

Consider mysqli directly, or Pear::MDB2 or PDO.  I understand that Pear::DB is fairly slow, though I don't use PEAR myself, so can't verify.

ContentLicense: CC BY-SA 2.5

Title: INSERT 6000 Rows - best practice

OwnerDisplayName: Eli


问:
Jquery submits form but does not fade my div
The title almost says it all. I have a jquery code i've written, im not good at it but this is what i achieved:

```<code>$("#myForm").submit(function(){

            //alert($(this).serialize());

            $.post("submit.php", $(this).serialize(), function(data){
                if(data == success) {

                $("#add_vote").fadeOut("fast");
                $("#verification_sent").fadeIn("fast");
                $("#wrong").fadeOut("fast");

                } else {

                $("#wrong").fadeIn("fast");

                }
            });

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

The form gets submitted well but the fadeIn and fadeOut's I have does not work. Do anyone know why?

答:
What is success in:

```<code>if(data == success) {
</code>```

Maybe you mean:

```<code>if(data == "success") {
</code>```

Or else you maybe have misunderstood the $.post function?

```<code> $.post("submit.php", $(this).serialize(), function(data){
</code>```

Lets break it up:

```<code> "submit.php" // the url (OK)
 $(this).serialize() // The data (OK)
 function(data){ // The callback on success
</code>```

And its only a helper function for the $.ajax method, Witch also have a error callback:

```<code>var ajaxObj = $.ajax({
  type: 'POST',
  url: "submit.php",
  data: $(this).serialize()
});
ajaxObj.success(function(){
    // Success
});
ajaxObj.error(function(){
    // Error
});
</code>```

Body:
The title almost says it all. I have a jquery code i've written, im not good at it but this is what i achieved:

$("#myForm").submit(function(){

            //alert($(this).serialize());

            $.post("submit.php", $(this).serialize(), function(data){
                if(data == success) {

                $("#add_vote").fadeOut("fast");
                $("#verification_sent").fadeIn("fast");
                $("#wrong").fadeOut("fast");

                } else {

                $("#wrong").fadeIn("fast");

                }
            });

            return false;
        });

The form gets submitted well but the fadeIn and fadeOut's I have does not work. Do anyone know why?

Body:
What is success in:

if(data == success) {

Maybe you mean:

if(data == "success") {

Or else you maybe have misunderstood the $.post function?

 $.post("submit.php", $(this).serialize(), function(data){

Lets break it up:

 "submit.php" // the url (OK)
 $(this).serialize() // The data (OK)
 function(data){ // The callback on success

And its only a helper function for the $.ajax method, Witch also have a error callback:

var ajaxObj = $.ajax({
  type: 'POST',
  url: "submit.php",
  data: $(this).serialize()
});
ajaxObj.success(function(){
    // Success
});
ajaxObj.error(function(){
    // Error
});


问:
Javascript scrollIntoView function not working in chrome
I have a function that use a HTML select element. It works by each option having number value. When the option is click I use that number to scroll to a div.

Something like this:

var options = document.getElementsByTagName("option");
var divs = document.getElementsByTagName("div");

function test() {
  var t = parseInt(this.value);
  divs[t].scrollIntoView({
    block: "center",
    behaviour: "smooth"
  });
}

window.addEventListener("load", function() {
  for (var i = 0; i < options.length; i++) {
    options[i].addEventListener("click", test);
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div{
height:50vh;
}</code>```

<select id="dropdown">
  <option value="0">Div 1</option>
  <option value="1">Div 2</option>
  <option value="2">Div 3</option>
  <option value="3">Div 4</option>
</select>

div 1

div 2

div 3

div 4

```

This works in Firefox and IE but not in chrome. The options have the function attached but when I click them nothing happens.

答:
I also had this problem in Chrome. This helped, put at the end of the page and into a separate script element:

```

Body:
I have a function that use a HTML select element. It works by each option having number value. When the option is click I use that number to scroll to a div.

Something like this:

var options = document.getElementsByTagName("option");
var divs = document.getElementsByTagName("div");

function test() {
  var t = parseInt(this.value);
  divs[t].scrollIntoView({
    block: "center",
    behaviour: "smooth"
  });
}

window.addEventListener("load", function() {
  for (var i = 0; i < options.length; i++) {
    options[i].addEventListener("click", test);
  }
});

div{
height:50vh;
}

<select id="dropdown">
  <option value="0">Div 1</option>
  <option value="1">Div 2</option>
  <option value="2">Div 3</option>
  <option value="3">Div 4</option>
</select>

div 1

div 2

div 3

div 4

This works in Firefox and IE but not in chrome. The options have the function attached but when I click them nothing happens.

Body:
I also had this problem in Chrome. This helped, put at the end of the page and into a separate script element:

<script>
    window.setTimeout( ()=>{ window.scrollTo(0,0) }, 50 );
</script>


问:
Script runtime execution time limit
My Google Apps Script is iterating through the user's Google Drive files and copying and sometimes moving files to other folders. The script is always stopped after certain minutes with no error message in the log.

EDITOR's NOTE: The time limit have varied over the time and might vary between "consumer" (free) and "Workspace" (paid) accounts but as of December 2022 most of the answers are still valid.

I am sorting tens or sometimes thousands files in one run.

Are there any settings or workarounds?

答:
As many people mentioned, the generic solution to this problem is to execute your method across multiple sessions. I found it to be a common problem that I have a bunch of iterations I need to loop over, and I don't want the hassle of writing/maintaining the boilerplate of creating new sessions.

Therefore I created a general solution:

```<code>/**
 * Executes the given function across multiple sessions to ensure there are no timeouts.
 *
 * See https://stackoverflow.com/a/71089403.
 *
 * @param {Int} items - The items to iterate over.
 * @param {function(Int)} fn - The function to execute each time. Takes in an item from `items`.
 * @param {String} resumeFunctionName - The name of the function (without arguments) to run between sessions. Typically this is the same name of the function that called this method.
 * @param {Int} maxRunningTimeInSecs - The maximum number of seconds a script should be able to run. After this amount, it will start a new session. Note: This must be set to less than the actual timeout as defined in https://developers.google.com/apps-script/guides/services/quotas (e.g. 6 minutes), otherwise it can't set up the next call.
 * @param {Int} timeBetweenIterationsInSeconds - The amount of time between iterations of sessions. Note that Google Apps Script won't honor this 100%, as if you choose a 1 second delay, it may actually take a minute or two before it actually executes.
 */
function iterateAcrossSessions(items, fn, resumeFunctionName, maxRunningTimeInSeconds = 5 * 60, timeBetweenIterationsInSeconds = 1) {
  const PROPERTY_NAME = 'iterateAcrossSessions_index';
  let scriptProperties = PropertiesService.getScriptProperties();
  let startTime = (new Date()).getTime();

  let startIndex = parseInt(scriptProperties.getProperty(PROPERTY_NAME));
  if (Number.isNaN(startIndex)) {
    startIndex = 0;
  }

  for (let i = startIndex; i < items.length; i++) {
    console.info(`[iterateAcrossSessions] Executing for i = ${i}.`)
    fn(items[i]);

    let currentTime = (new Date()).getTime();
    let elapsedTime = currentTime - startTime;
    let maxRunningTimeInMilliseconds = maxRunningTimeInSeconds * 1000;
    if (maxRunningTimeInMilliseconds <= elapsedTime) {
      let newTime = new Date(currentTime + timeBetweenIterationsInSeconds * 1000);
      console.info(`[iterateAcrossSessions] Creating new session for i = ${i+1} at ${newTime}, since elapsed time was ${elapsedTime}.`);
      scriptProperties.setProperty(PROPERTY_NAME, i+1);
      ScriptApp.newTrigger(resumeFunctionName).timeBased().at(newTime).create();
      return;
    }
  }

  console.log(`[iterateAcrossSessions] Done iterating over items.`);
  // Reset the property here to ensure that the execution loop could be restarted.
  scriptProperties.deleteProperty(PROPERTY_NAME);
}
</code>```

You can now use this pretty easily like so:

```<code>let ITEMS = ['A', 'B', 'C'];

function execute() {
  iterateAcrossSessions(
    ITEMS,
    (item) => {
      console.log(`Hello world ${item}`);
    },
    "execute");
}
</code>```

It'll automatically execute the internal lambda for each value in ITEMS, seamlessly spreading across sessions as needed.

For example, if you use a 0-second maxRunningTime it would run across 4 sessions with the following outputs:

```<code>[iterateAcrossSessions] Executing for i = 0.
Hello world A
[iterateAcrossSessions] Creating new session for i = 1.
</code>```
```<code>[iterateAcrossSessions] Executing for i = 1.
Hello world B
[iterateAcrossSessions] Creating new session for i = 2.
</code>```
```<code>[iterateAcrossSessions] Executing for i = 2.
Hello world C
[iterateAcrossSessions] Creating new session for i = 3.
</code>```
```<code>[iterateAcrossSessions] Done iterating over items.
</code>```

Title: Script runtime execution time limit

Body:
As many people mentioned, the generic solution to this problem is to execute your method across multiple sessions. I found it to be a common problem that I have a bunch of iterations I need to loop over, and I don't want the hassle of writing/maintaining the boilerplate of creating new sessions.

Therefore I created a general solution:

/**
 * Executes the given function across multiple sessions to ensure there are no timeouts.
 *
 * See https://stackoverflow.com/a/71089403.
 *
 * @param {Int} items - The items to iterate over.
 * @param {function(Int)} fn - The function to execute each time. Takes in an item from `items`.
 * @param {String} resumeFunctionName - The name of the function (without arguments) to run between sessions. Typically this is the same name of the function that called this method.
 * @param {Int} maxRunningTimeInSecs - The maximum number of seconds a script should be able to run. After this amount, it will start a new session. Note: This must be set to less than the actual timeout as defined in https://developers.google.com/apps-script/guides/services/quotas (e.g. 6 minutes), otherwise it can't set up the next call.
 * @param {Int} timeBetweenIterationsInSeconds - The amount of time between iterations of sessions. Note that Google Apps Script won't honor this 100%, as if you choose a 1 second delay, it may actually take a minute or two before it actually executes.
 */
function iterateAcrossSessions(items, fn, resumeFunctionName, maxRunningTimeInSeconds = 5 * 60, timeBetweenIterationsInSeconds = 1) {
  const PROPERTY_NAME = 'iterateAcrossSessions_index';
  let scriptProperties = PropertiesService.getScriptProperties();
  let startTime = (new Date()).getTime();

  let startIndex = parseInt(scriptProperties.getProperty(PROPERTY_NAME));
  if (Number.isNaN(startIndex)) {
    startIndex = 0;
  }

  for (let i = startIndex; i < items.length; i++) {
    console.info(`[iterateAcrossSessions] Executing for i = ${i}.`)
    fn(items[i]);

    let currentTime = (new Date()).getTime();
    let elapsedTime = currentTime - startTime;
    let maxRunningTimeInMilliseconds = maxRunningTimeInSeconds * 1000;
    if (maxRunningTimeInMilliseconds <= elapsedTime) {
      let newTime = new Date(currentTime + timeBetweenIterationsInSeconds * 1000);
      console.info(`[iterateAcrossSessions] Creating new session for i = ${i+1} at ${newTime}, since elapsed time was ${elapsedTime}.`);
      scriptProperties.setProperty(PROPERTY_NAME, i+1);
      ScriptApp.newTrigger(resumeFunctionName).timeBased().at(newTime).create();
      return;
    }
  }

  console.log(`[iterateAcrossSessions] Done iterating over items.`);
  // Reset the property here to ensure that the execution loop could be restarted.
  scriptProperties.deleteProperty(PROPERTY_NAME);
}

You can now use this pretty easily like so:

let ITEMS = ['A', 'B', 'C'];

function execute() {
  iterateAcrossSessions(
    ITEMS,
    (item) => {
      console.log(`Hello world ${item}`);
    },
    "execute");
}

It'll automatically execute the internal lambda for each value in ITEMS, seamlessly spreading across sessions as needed.

For example, if you use a 0-second maxRunningTime it would run across 4 sessions with the following outputs:

[iterateAcrossSessions] Executing for i = 0.
Hello world A
[iterateAcrossSessions] Creating new session for i = 1.

[iterateAcrossSessions] Executing for i = 1.
Hello world B
[iterateAcrossSessions] Creating new session for i = 2.

[iterateAcrossSessions] Executing for i = 2.
Hello world C
[iterateAcrossSessions] Creating new session for i = 3.

[iterateAcrossSessions] Done iterating over items.


问:
Spring Webflux: Nested Flatmap alternative
I have a scenario where second mono depended on firstMono and ThridMono call  Dependeded on second mono out.

I written the code as below.

```<code>  firstMono.flatMap{

    val secondMono = callWebservice(firstMono)

    val thrirdMono = secondMono.flatMap { secondMonoResponse ->
        if (secondMonoResponse.getName.equals("ABC")) {
            callAnotherWebService(secondMon)
        } else {
            secondMono
        }
    }
}
</code>```

How can I avoid the second flatMap here?.Is there a way I can do this without nested flatMap.I should be calling thrirdMono only condition met.

答:
The answer may vary depending on what exactly does each Mono perform.
Nevertheless, when I look on the snippet, I don't see the point of invoking flatMap{} on the firstMono, so it could probably look, as follows:

```<code>callWebservice(firstMono)
  .flatMap { secondMonoResponse ->
    if (secondMonoResponse.name == "ABC" ) {
      callAnotherWebService(secondMono)
    } else {
      secondMono
    }
  }
</code>```

On the other hand, a .zip method could be used here, as well:

```<code>val secondMono = callWebservice(firstMono)
Mono.zip(firstMono, callWebservice(firstMono))
  .flatMap {
    val secondMonoResponse = it.t2
    if (secondMonoResponse.name == "ABC" ) {
      callAnotherWebService(secondMono)
    } else {
      secondMono
    }
  }
</code>```

Note: I've removed val thrirdMono, because the above code snippet won't compile as the return type is Unit (instead of the Mono).

Body:
I have a scenario where second mono depended on firstMono and ThridMono call  Dependeded on second mono out.

I written the code as below.

  firstMono.flatMap{

    val secondMono = callWebservice(firstMono)

    val thrirdMono = secondMono.flatMap { secondMonoResponse ->
        if (secondMonoResponse.getName.equals("ABC")) {
            callAnotherWebService(secondMon)
        } else {
            secondMono
        }
    }
}

How can I avoid the second flatMap here?.Is there a way I can do this without nested flatMap.I should be calling thrirdMono only condition met.

Body:
The answer may vary depending on what exactly does each Mono perform.
Nevertheless, when I look on the snippet, I don't see the point of invoking flatMap{} on the firstMono, so it could probably look, as follows:

callWebservice(firstMono)
  .flatMap { secondMonoResponse ->
    if (secondMonoResponse.name == "ABC" ) {
      callAnotherWebService(secondMono)
    } else {
      secondMono
    }
  }

On the other hand, a .zip method could be used here, as well:

val secondMono = callWebservice(firstMono)
Mono.zip(firstMono, callWebservice(firstMono))
  .flatMap {
    val secondMonoResponse = it.t2
    if (secondMonoResponse.name == "ABC" ) {
      callAnotherWebService(secondMono)
    } else {
      secondMono
    }
  }

Note: I've removed val thrirdMono, because the above code snippet won't compile as the return type is Unit (instead of the Mono).


问:
How to delete Object if value of nested object property value < epoch
I have an object tree that contains the following values.

```<code>data = {
  TD2n9thHQgyvWdPhOkHQ: {
    heartbeat: 1644637961658,
    joinTime: 1644636756368,
  },
  IASJDAIODJiklk243oi: {
    heartbeat: 1644637961658,
    joinTime: 1644637961658,
  }
 }
</code>```

I am trying to check if the value of each heartbeat is 10 seconds less than the current time from epoch and if it is, delete the parent object.

Any help would be much appreciated!

答:
```<code>data = {
  TD2n9thHQgyvWdPhOkHQ: {
    heartbeat: 1644637961658,
    joinTime: 1644636756368,
  },
  IASJDAIODJiklk243oi: {
    heartbeat: 1644637961658,
    joinTime: 1644637961658,
  }
 }

for(let x in data) {
  // you have each object
  console.log(data[x])
  // each heartbeat
  console.log(data[x]['heartbeat']);
  // each of joining time
  console.log(data[x]['joinTime']);
  // you can delete object after your condition satisfy
  delete data[x];
};
</code>```

Body:
I have an object tree that contains the following values.

data = {
  TD2n9thHQgyvWdPhOkHQ: {
    heartbeat: 1644637961658,
    joinTime: 1644636756368,
  },
  IASJDAIODJiklk243oi: {
    heartbeat: 1644637961658,
    joinTime: 1644637961658,
  }
 }

I am trying to check if the value of each heartbeat is 10 seconds less than the current time from epoch and if it is, delete the parent object.

Any help would be much appreciated!


问:
How do I split a list on certain conditions in Haskell?
As a programming exercise I'm trying to build a function in Haskell where given a list it splits the list whenever an element is repeated. [1,2,3,3,4,5] would split into [[1,2,3],[3,4,5]] for example. My first idea was to split the list into a list of lists with single elements, where [1,2,3,3,4,5] would become [[1],[2],[3],[3],[4],[5]] and then merge lists only when the elements being compared are not equal, but implementing this has been a headache for me as I'm very new to Haskell and recursion has always given me trouble. I think something is wrong with the function I'm using to combine the lists, it will only ever return a list where all the elements that were broken apart are combined, where [1,2,3,3,4,5] becomes [[1],[2],[3],[3],[4],[5]] but my split_help function will transform this into [[1,2,3,3,4,5]] instead of [[1,2,3],[3,4,5]]

I've pasted my incomplete code below, it doesn't work right now but it should give the general idea of what I'm trying to accomplish. Any feedback on general Haskell code etiquette would also be welcome.

split_breaker breaks the list into a list of list and split_help is what I'm trying to use to combine unequal elements.

```<code>split_help x y
     | x /= y = x ++ y
     | otherwise = []

split_breaker :: Eq a => [a] -> [[a]]
split_breaker [] = []
split_breaker [x] = [[x]]
split_breaker (x:xs) = [x]:split_breaker xs

split_at_duplicate :: Eq a => [a] -> [[a]]
split_at_duplicate [x] = [[x]]
split_at_duplicate (x:xs) = foldl1 (split_help) (split_breaker [xs])
</code>```

答:
Here's a maximally lazy approach:

```<code>splitWhen :: (a -> a -> Bool) -> [a] -> [[a]]
splitWhen f = foldr go [[]] where
  go x acc = (x:xs):xss where
    xs:xss = case acc of
      (z:_):_ | f x z -> []:acc
      _ -> acc

splitAtDup :: Eq a => [a] -> [[a]]
splitAtDup = splitWhen (==)
</code>```

To verify the laziness, try this:

```<code>take 2 $ take 4 <$> splitAtDup (1:2:3:3:4:5:6:undefined)
</code>```

It can be fully evaluated to normal form as [[1,2,3],[3,4,5,6]].

Body:
As a programming exercise I'm trying to build a function in Haskell where given a list it splits the list whenever an element is repeated. [1,2,3,3,4,5] would split into [[1,2,3],[3,4,5]] for example. My first idea was to split the list into a list of lists with single elements, where [1,2,3,3,4,5] would become [[1],[2],[3],[3],[4],[5]] and then merge lists only when the elements being compared are not equal, but implementing this has been a headache for me as I'm very new to Haskell and recursion has always given me trouble. I think something is wrong with the function I'm using to combine the lists, it will only ever return a list where all the elements that were broken apart are combined, where [1,2,3,3,4,5] becomes [[1],[2],[3],[3],[4],[5]] but my split_help function will transform this into [[1,2,3,3,4,5]] instead of [[1,2,3],[3,4,5]]

I've pasted my incomplete code below, it doesn't work right now but it should give the general idea of what I'm trying to accomplish. Any feedback on general Haskell code etiquette would also be welcome.

split_breaker breaks the list into a list of list and split_help is what I'm trying to use to combine unequal elements.

split_help x y
     | x /= y = x ++ y
     | otherwise = []

split_breaker :: Eq a => [a] -> [[a]]
split_breaker [] = []
split_breaker [x] = [[x]]
split_breaker (x:xs) = [x]:split_breaker xs

split_at_duplicate :: Eq a => [a] -> [[a]]
split_at_duplicate [x] = [[x]]
split_at_duplicate (x:xs) = foldl1 (split_help) (split_breaker [xs])

Body:
Here's a maximally lazy approach:

splitWhen :: (a -> a -> Bool) -> [a] -> [[a]]
splitWhen f = foldr go [[]] where
  go x acc = (x:xs):xss where
    xs:xss = case acc of
      (z:_):_ | f x z -> []:acc
      _ -> acc

splitAtDup :: Eq a => [a] -> [[a]]
splitAtDup = splitWhen (==)

To verify the laziness, try this:

take 2 $ take 4 <$> splitAtDup (1:2:3:3:4:5:6:undefined)

It can be fully evaluated to normal form as [[1,2,3],[3,4,5,6]].


问:
Running an activity from a fragment
Im trying to run an activity from a button press in a fragment, however the app crashes when the button is pressed.

```<code>public class FitnessFragment extends Fragment {

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {

        View root = inflater.inflate(R.layout.fragment_fitness, container, false);

        Button btn1 = (Button) root
                .findViewById(R.id.trackCalories);

        btn1.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent intent = new Intent(getActivity(), video_activity.class);
                ((MainActivity) getActivity()).startActivity(intent);

            }
        });

        return root;
    }
}
</code>```

I'm currently struggling to grasp the concept of launching activities from fragments, any help would be appreciated.

答:
```<code>btn1.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {
      startActivity(new Intent(requireContext(), video_activity.class))
    }
});
</code>```

Title: Running an activity from a fragment

Body:
Im trying to run an activity from a button press in a fragment, however the app crashes when the button is pressed.

public class FitnessFragment extends Fragment {

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {

        View root = inflater.inflate(R.layout.fragment_fitness, container, false);

        Button btn1 = (Button) root
                .findViewById(R.id.trackCalories);

        btn1.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent intent = new Intent(getActivity(), video_activity.class);
                ((MainActivity) getActivity()).startActivity(intent);

            }
        });

        return root;
    }
}

I'm currently struggling to grasp the concept of launching activities from fragments, any help would be appreciated.


问:
firebase auth is not a function()
I am following the following github to test authentication on firebase on node.js, https://github.com/hvalls/node-firebase-auth-example

I am getting the firebase.auth() is not a function.

I have tried the following:

Remove Firebase-admin

Remove Firebase

Reinstall Firebase via Npm

I just cant figure out whats wrong.

```<code>user_service.js

const firebaseapp = require("firebase/app");
require("firebase/auth");

const apiKey = xxxx
const fb = firebaseapp.initializeApp({
  apiKey: apiKey,
});

exports.addUser = (email, password) =>
  fb.auth().createUserWithEmailAndPassword(email, password);

exports.authenticate = (email, password) =>{

    fb.auth().signInWithEmailAndPassword(email, password);
}
</code>```

Route.js

```<code>router.post('/now', function (req, res, next){
  console.log('Here');
  try {
    const u =  userService.authenticate(req.body.email, req.body.password);
  } catch (error) {
    console.log("Error : " + error);
    req.sendStatus(500).send(error);
  }
});
</code>```

答:
You should ideally use the Admin SDK on server. The error you are getting might be because you've installed Modular SDK (v9.0.0+) which does not use the name-spaced syntax. Try installing Admin SDK (firebase-admin) and refactoring the code as shown below:

```<code>router.post('/user', async function (req, res, next){
  try {
    const newUser = await userService.addUser(req.body.email, req.body.password);
    return res.json(newUser)
  } catch (error) {
    console.log("Error : " + error);
    req.sendStatus(500).send(error);
  }
});
</code>```
```<code>const admin = require("firebase-admin");

admin.initializeApp({
  // service account
});

exports.addUser = async (email, password) => {
  return admin.auth().createUser({ email, password });
}
</code>```

You cannot login user using Admin SDK (unless you are using session based auth) so after the user is created you should log the user in with signInWithEmailAndPassword() on your client application using client SDK.

Title: firebase auth is not a function()

Body:
I am following the following github to test authentication on firebase on node.js, https://github.com/hvalls/node-firebase-auth-example

I am getting the firebase.auth() is not a function.

I have tried the following:

Remove Firebase-admin

Remove Firebase

Reinstall Firebase via Npm

I just cant figure out whats wrong.

user_service.js

const firebaseapp = require("firebase/app");
require("firebase/auth");

const apiKey = xxxx
const fb = firebaseapp.initializeApp({
  apiKey: apiKey,
});

exports.addUser = (email, password) =>
  fb.auth().createUserWithEmailAndPassword(email, password);

exports.authenticate = (email, password) =>{

    fb.auth().signInWithEmailAndPassword(email, password);
}

Route.js

router.post('/now', function (req, res, next){
  console.log('Here');
  try {
    const u =  userService.authenticate(req.body.email, req.body.password);
  } catch (error) {
    console.log("Error : " + error);
    req.sendStatus(500).send(error);
  }
});

Body:
You should ideally use the Admin SDK on server. The error you are getting might be because you've installed Modular SDK (v9.0.0+) which does not use the name-spaced syntax. Try installing Admin SDK (firebase-admin) and refactoring the code as shown below:

router.post('/user', async function (req, res, next){
  try {
    const newUser = await userService.addUser(req.body.email, req.body.password);
    return res.json(newUser)
  } catch (error) {
    console.log("Error : " + error);
    req.sendStatus(500).send(error);
  }
});

const admin = require("firebase-admin");

admin.initializeApp({
  // service account
});

exports.addUser = async (email, password) => {
  return admin.auth().createUser({ email, password });
}

You cannot login user using Admin SDK (unless you are using session based auth) so after the user is created you should log the user in with signInWithEmailAndPassword() on your client application using client SDK.


问:
Dynamically building WHERE clauses in SQL statements
I have a question regarding SQL. I have the following SQL statement:

```<code>SELECT id, First, Last, E_Mail, Notes
FROM mytable
WHERE SOMETHING_SHOULD_BE_HERE IS NOT NULL;
</code>```

I know that the SOMETHING_SHOULD_BE_HERE should be a column(attribute) in my table. Is their a way I can put a variable that can refer to the column I'm trying to access? In my case their are 30 columns. Can I have a string for SOMETHING_SHOULD_BE_HERE that can be assigned in my program to the column in which I want to search?

Thanks

答:
The column can't be variable, but the value of the column can. The parser needs to know what to bind to.

If you elaborate on what you're trying to solve and which platform you're using it would allow for more complete answers.

Body:
I have a question regarding SQL. I have the following SQL statement:

SELECT id, First, Last, E_Mail, Notes
FROM mytable
WHERE SOMETHING_SHOULD_BE_HERE IS NOT NULL;

I know that the SOMETHING_SHOULD_BE_HERE should be a column(attribute) in my table. Is their a way I can put a variable that can refer to the column I'm trying to access? In my case their are 30 columns. Can I have a string for SOMETHING_SHOULD_BE_HERE that can be assigned in my program to the column in which I want to search?

Thanks


问:
Visual Studio Code showing "Java 11 or more recent is required to run. Please download and install a recent JDK"
Today Visual Studio Code started showing me a pop-up saying:

Java 11 or more recent is required to run. Please download and install a recent JDK.

I need to use the JDK 8 (working on Apache Beam and that's the last supported version). I have been working on that and haven't had any issues until this came up.

I have read through this article and implemented the points mentioned there.

Here is my workspace settings on Visual Studio Code (I have double-checked the paths)

```<code>{
    "java.configuration.updateBuildConfiguration": "disabled",
    "java.home": "/Library/Java/JavaVirtualMachines/adoptopenjdk-8.jdk/Contents/Home",
    "java.configuration.runtimes": [
        {
          "name": "JavaSE-1.8",
          "path": "/Library/Java/JavaVirtualMachines/adoptopenjdk-8.jdk/Contents/Home",
          "default": true
        },
        {
          "name": "JavaSE-11",
          "path": "/Library/Java/JavaVirtualMachines/adoptopenjdk-11.jdk/Contents/Home",
        }
      ]
}
</code>```

Other helpful information:

```<code>➜ echo $JAVA_HOME
/Library/Java/JavaVirtualMachines/adoptopenjdk-8.jdk/Contents/Home
</code>```

and

```<code>➜ which java
/usr/bin/java
</code>```

This started happening today even though I have been running JDK 8 on Visual Studio Code successfully for a while now. I don't remember updating Visual Studio Code, so I'm not sure as to why this is being displayed now since apparently the pop-up has been displayed since mid-April (asked on the vscode-java Gitter channel).

答:
Add this variable in your settings.json file.

```<code>"sonarlint.ls.javaHome": "/Library/Java/JavaVirtualMachines/temurin-11.jdk/Contents/Home"
</code>```

Body:
Today Visual Studio Code started showing me a pop-up saying:

Java 11 or more recent is required to run. Please download and install a recent JDK.

I need to use the JDK 8 (working on Apache Beam and that's the last supported version). I have been working on that and haven't had any issues until this came up.

I have read through this article and implemented the points mentioned there.

Here is my workspace settings on Visual Studio Code (I have double-checked the paths)

{
    "java.configuration.updateBuildConfiguration": "disabled",
    "java.home": "/Library/Java/JavaVirtualMachines/adoptopenjdk-8.jdk/Contents/Home",
    "java.configuration.runtimes": [
        {
          "name": "JavaSE-1.8",
          "path": "/Library/Java/JavaVirtualMachines/adoptopenjdk-8.jdk/Contents/Home",
          "default": true
        },
        {
          "name": "JavaSE-11",
          "path": "/Library/Java/JavaVirtualMachines/adoptopenjdk-11.jdk/Contents/Home",
        }
      ]
}

Other helpful information:

➜ echo $JAVA_HOME
/Library/Java/JavaVirtualMachines/adoptopenjdk-8.jdk/Contents/Home

and

➜ which java
/usr/bin/java

This started happening today even though I have been running JDK 8 on Visual Studio Code successfully for a while now. I don't remember updating Visual Studio Code, so I'm not sure as to why this is being displayed now since apparently the pop-up has been displayed since mid-April (asked on the vscode-java Gitter channel).

Body:
Add this variable in your settings.json file.

"sonarlint.ls.javaHome": "/Library/Java/JavaVirtualMachines/temurin-11.jdk/Contents/Home"


问:
SpriteBatch.draw(Sprite, ...) throws NullPointerException in LibGDX
The title is self-explanatory... Apparently the problem is in the flush method of the SpriteBatch class on the line where it says lastTexture.bind();. I did some surfing and found out it maybe because the sprite doesn't have a texture. So I ran some tests with if-statements and I literally wrote -

```<code>if(sprite.getTexture() != null) {
   sb.draw(sprite, ...);
}
</code>```

And it still went to the draw line and then threw this error! Any help would be appreciated...

答: I found out what was wrong. The problem was actually with my box textures which I was rendering before the player. Since they were stored in the lastTexture variable in my SpriteBatch while rendering the player, I got mislead and was trying to debug the wrong code. Hope this helps if anyone else faces the same problem!</p>

Body:
The title is self-explanatory... Apparently the problem is in the flush method of the SpriteBatch class on the line where it says lastTexture.bind();. I did some surfing and found out it maybe because the sprite doesn't have a texture. So I ran some tests with if-statements and I literally wrote -

if(sprite.getTexture() != null) {
   sb.draw(sprite, ...);
}

And it still went to the draw line and then threw this error! Any help would be appreciated...


问:
Google Sheets: Hide top menu and bottom sheet tabs bar?
I want to be able to hide Google Sheet's menu bar at the top as well as the sheet tabs bar at the bottom when sharing the Google Sheet publicly.

?rm=minimal to hide the menu works perfectly. I am stuck on how to hide the sheet tabs bar at the bottom.

I tried using &single=true&widget=true&headers=false but they do nothing for me.

答:
The only way to completely hide the sheet tabs bar is exporting the document as PDF/HTML.

Otherwise, the best solution would be to add "preview" at the end of the link and only make visible the sheet you want visitors to see.

Like this: https://docs.google.com/spreadsheets/d/123/preview

Since adding "preview" hides the sheet menu, visitors won't be able to see if there are more exisiting sheets.


问:
Override Orientation Change But NOT Restart The Activity AND Pass State Data
I want to be able to change the layout when a device is re-orientated to landscape or portrait. For speed and resource purposes (plus other issues applicable to my app) I do NOT want my app to be destroyed and restarted. I have several objects which I wish to retain between orientation changes as there is no benefit from destroying and re-creating them! I simply just want to change the position of some buttons and TextViews so that they suit the current orientation. Easy right?

Well no it isn't. To achieve the above I included in the app Manifest the configChange option for orientation change. Then I've implemented the onConfigurationChanged() where I determine and apply the appropriate layout. Simple yes?

But now take the textview I have in my layout. How on earth, using this particular method of responding to orientation changes, do I put the same text in the previous textview to the new textview? No instance data is passed to onConfigurationChanged() method. Also for some of the buttons, they could be disabled or enabled... I need to know this after orienatation change.

If I let Android destroy and restart my activity it's first going to create unnecessary work. All I want is to just move a few buttons and textviews.. NOT restart the whole app. That's just ludicrous!

Can anyone help me achieve what need?

答:
An easy way to maintain configuration-independent data is to make use of onRetainNonConfigurationInstance() and its companion method getLastNonConfigurationInstance(). Just return an object that contains all the data that you want to reuse when your activity is recreated.

In Honeycomb, or if you are using the Android compatibility package, you can just call Fragment.setRetainInstance(true) instead. See the docs.


问:
An abstract DAO method must be annotated with one and only one of the following annotations: Insert,Delete,Query,Update,RawQuery
```<code>@Dao
interface ArticleDAO {

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun upsert(article: Article) : Long

    @Query("SELECT * FROM articles")
    fun getAllArticles(): LiveData<List<Article>>

    @DELETE
    suspend fun deleteArticles(article: Article)
}
</code>```

Hi! On running this code, I get the following error:
An abstract DAO method must be annotated with one and only one of the following annotations: Insert,Delete,Query,Update,RawQuery
Please help me with this

答:
You entered wrong annotation

replace

```<code>@DELETE
</code>```

to

```<code>@Delete
</code>```

Body:
@Dao
interface ArticleDAO {

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun upsert(article: Article) : Long

    @Query("SELECT * FROM articles")
    fun getAllArticles(): LiveData<List
>

    @DELETE
    suspend fun deleteArticles(article: Article)
}

Hi! On running this code, I get the following error:
An abstract DAO method must be annotated with one and only one of the following annotations: Insert,Delete,Query,Update,RawQuery
Please help me with this

Body:
You entered wrong annotation

replace

@DELETE

to

@Delete


问:
Firebase auth.currentUser error using typescript
When configuring typescript with firebase, I am getting the following error: Argument of type 'User | null' is not assignable to parameter of type 'User'. Type 'null' is not assignable to type 'User'.

The error is here: auth.currentUser It is unclear to me what type it would be.

```<code>updateProfile(auth.currentUser, {
                    displayName: name
                }
</code>```

Full code:

```<code>import { getAuth, createUserWithEmailAndPassword, signOut, onAuthStateChanged, signInWithEmailAndPassword, updateProfile } from "firebase/auth";
import { useEffect, useState } from "react";
import FirebaseInitialization from "../Firebase/Firebase.init";

FirebaseInitialization()

interface IUseFirebaseProps {
}

const UseFirebase: React.FunctionComponent<IUseFirebaseProps> = (props) => {
    const [user, setUser] = useState({})
    const [error, setError] = useState('')
    const [admin, setAdmin] = useState(false)
    const [isLoading, setIsLoading] = useState(true)
    const auth = getAuth()

      // REGISTER WITH EMAIL AND PASSWORD
      const RegisterUser = (email: string, password:string, name:string, history: any) => {
        setIsLoading(true)
        createUserWithEmailAndPassword(auth, email, password)
            .then((userCredential) => {
                const newUser = { email, displayName: name };
                setUser(newUser);
                setError('')
                updateProfile(auth.currentUser, {
                    displayName: name
                }).then(() => {
                }).catch((error) => {
                });
                history.replace('/');
            })
            .catch((error) => {

                const errorMessage = error.message;
                setError(errorMessage)
            }).finally(() => setIsLoading(false));
    }
  return <h2>Firebase</h2>
};

export default UseFirebase;
</code>```

How can I solve this? can anyone help me?

答:
The value of auth.currentUser can be null. In this case you can pass User object directly from UserCredential object. Try refactoring the code as shown below:

```<code>const RegisterUser = async (email: string, password: string, name: string, history: any) => {
  setIsLoading(true)
  const userCredential = await createUserWithEmailAndPassword(auth, email, password)

  const newUser = {
    email,
    displayName: name
  };

  setUser(newUser);
  setError('')

  // Pass userCredential.user instead of auth.currentUser
  updateProfile(userCredential.user, {
    displayName: name
  }).then(() => {}).catch((error) => {});
    history.replace('/');
  })
}
</code>```

Body:
When configuring typescript with firebase, I am getting the following error: Argument of type 'User | null' is not assignable to parameter of type 'User'. Type 'null' is not assignable to type 'User'.

The error is here: auth.currentUser It is unclear to me what type it would be.

updateProfile(auth.currentUser, {
                    displayName: name
                }

Full code:

import { getAuth, createUserWithEmailAndPassword, signOut, onAuthStateChanged, signInWithEmailAndPassword, updateProfile } from "firebase/auth";
import { useEffect, useState } from "react";
import FirebaseInitialization from "../Firebase/Firebase.init";

FirebaseInitialization()

interface IUseFirebaseProps {
}

const UseFirebase: React.FunctionComponent<IUseFirebaseProps> = (props) => {
    const [user, setUser] = useState({})
    const [error, setError] = useState('')
    const [admin, setAdmin] = useState(false)
    const [isLoading, setIsLoading] = useState(true)
    const auth = getAuth()

      // REGISTER WITH EMAIL AND PASSWORD
      const RegisterUser = (email: string, password:string, name:string, history: any) => {
        setIsLoading(true)
        createUserWithEmailAndPassword(auth, email, password)
            .then((userCredential) => {
                const newUser = { email, displayName: name };
                setUser(newUser);
                setError('')
                updateProfile(auth.currentUser, {
                    displayName: name
                }).then(() => {
                }).catch((error) => {
                });
                history.replace('/');
            })
            .catch((error) => {

                const errorMessage = error.message;
                setError(errorMessage)
            }).finally(() => setIsLoading(false));
    }
  return
Firebase

};

export default UseFirebase;

How can I solve this? can anyone help me?

Body:
The value of auth.currentUser can be null. In this case you can pass User object directly from UserCredential object. Try refactoring the code as shown below:

const RegisterUser = async (email: string, password: string, name: string, history: any) => {
  setIsLoading(true)
  const userCredential = await createUserWithEmailAndPassword(auth, email, password)

  const newUser = {
    email,
    displayName: name
  };

  setUser(newUser);
  setError('')

  // Pass userCredential.user instead of auth.currentUser
  updateProfile(userCredential.user, {
    displayName: name
  }).then(() => {}).catch((error) => {});
    history.replace('/');
  })
}


问:
text output with color
Fellow programmers,
I am running a Monte Carlo type simulation in python that generates long strings of 0,1, and 2's and I'm trying to output them in a text or html file for further analysis.

I'd like to print these strings in an external file, and use different colors for the different digits.
Say, 0 = red, 1 = green, and 2 = two.

My knowledge of Python, and html is somehow limited. Any "pointers"(sorry for unintentional pun) and sample bits of code will be very welcome.

答:
just write to a file like this and open it in a webbrowser:

```<code>def write_red(f, str_):
    f.write('<p style="color:#ff0000">%s</p>' % str_)

def write_blue(f, str_):
    # ...

f = open('out.html', 'w')
f.write('<html>')

write_red(f, thing_i_want_to_be_red_in_output)

f.write('</html>')
f.close()
</code>```

Update: To make this answer complete, with the use of css, the output file can be much smaller.

```<code>style = """<style type='text/css'>
html {
  font-family: Courier;
}
r {
  color: #ff0000;
}
g {
  color: #00ff00;
}
b {
  color: #0000ff;
}
</style>"""

RED = 'r'
GREEN = 'g'
BLUE = 'b'

def write_html(f, type, str_):
    f.write('<%(type)s>%(str)s</%(type)s>' % {
            'type': type, 'str': str_ } )

f = open('out.html', 'w')
f.write('<html>')
f.write(style)

write_html(f, RED, 'My name is so foo..\n')
write_html(f, BLUE, '102838183820038.028391')

f.write('</html>')
</code>```

Title: text output with color

Body:
just write to a file like this and open it in a webbrowser:

def write_red(f, str_):
    f.write('<p style="color:#ff0000">%s</p>' % str_)

def write_blue(f, str_):
    # ...

f = open('out.html', 'w')
f.write('<html>')

write_red(f, thing_i_want_to_be_red_in_output)

f.write('</html>')
f.close()

Update: To make this answer complete, with the use of css, the output file can be much smaller.

style = """<style type='text/css'>
html {
  font-family: Courier;
}
r {
  color: #ff0000;
}
g {
  color: #00ff00;
}
b {
  color: #0000ff;
}
</style>"""

RED = 'r'
GREEN = 'g'
BLUE = 'b'

def write_html(f, type, str_):
    f.write('<%(type)s>%(str)s</%(type)s>' % {
            'type': type, 'str': str_ } )

f = open('out.html', 'w')
f.write('<html>')
f.write(style)

write_html(f, RED, 'My name is so foo..\n')
write_html(f, BLUE, '102838183820038.028391')

f.write('</html>')