问:
Cannot generate a safe linker search path CUDA
I want to add calls to the NVidia Monitoring Library to my CUDA application. However, the nvidia-ml library isn't part of CUDA; it's part of the device driver. Nevertheless, CUDA provides stubs for it. This appears to confuse CMake. I'm looking for a way to unconfuse CMake.

On the advice of my guru, I created a FindNvidiaML.cmake file

```<code># set the base location
set(NVIDIA_ML_PATHS
  /usr/lib64
  /usr/lib64/nvidia
)

#  Look for the library
find_library( NVIDIA_ML_LIBRARY
              NAMES
                nvidia-ml
              HINTS
                ${NVIDIA_ML_PATHS}
)

#  Make sure valid
if( NVIDIA_ML_LIBRARY )
    SET( NVIDIA_ML_FOUND TRUE )
endif()
</code>```

(NVIDIA_ML_LIBRARY has the value /usr/lib64/libnvidia-ml.so)

My main CMakeLists.txt file has this portion

```<code>  find_package(NvidiaML REQUIRED)
</code>```

The specific product illustrated here CMakeLists.txt file looks like this:

```<code>set(myTarget DspTests)
add_executable( ${myTarget}
               Global_unittest.cpp

               nvSMI_unittest.cpp

               BlackmanHarris_unittest.cpp
               BlackmanHarrisCU_unittest.cu

               FFT_unittest.cu

               FindPeakKernel_unittest.cu

               )

target_include_directories( ${myTarget} SYSTEM PRIVATE
                            ${CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES}
)

set_target_properties( ${myTarget} PROPERTIES
                       CUDA_SEPARABLE_COMPILATION ON
                       POSITION_INDEPENDENT_CODE ON
)

target_link_libraries( ${myTarget}
                       dsp cufft ${NVIDIA_ML_LIBRARY}
                       gtest gtestApp
                )

add_gtest( ${myTarget} )
</code>```

CMake output:

```<code>CMake Warning at dsp/unit/CMakeLists.txt:13 (add_executable):
  Cannot generate a safe linker search path for target DspTests because files
  in some directories may conflict with libraries in implicit directories:

    link library [libnvidia-ml.so] in /usr/lib64 may be hidden by files in:
      /usr/local/cuda/targets/x86_64-linux/lib/stubs

  Some of these libraries may not be found correctly.
</code>```

Searching, I find

```<code>$ find /usr/ -name 'libnvidia-ml*' -ls 2>/dev/null
51097542 1512 -rwxr-xr-x   1 root     root      1545404 Jun 11  2019 /usr/lib/libnvidia-ml.so.418.67
51102213    0 lrwxrwxrwx   1 root     root           22 Jun 11  2019 /usr/lib/libnvidia-ml.so.1 -> libnvidia-ml.so.418.67
51102218    0 lrwxrwxrwx   1 root     root           17 Jun 11  2019 /usr/lib/libnvidia-ml.so -> libnvidia-ml.so.1
34907591 1536 -rwxr-xr-x   1 root     root      1569688 Apr  6  2019 /usr/lib64/libnvidia-ml.so.418.67
34907590    0 lrwxrwxrwx   1 root     root           22 Jun 11  2019 /usr/lib64/libnvidia-ml.so.1 -> libnvidia-ml.so.418.67
34972797    0 lrwxrwxrwx   1 root     root           22 Jun 11  2019 /usr/lib64/libnvidia-ml.so -> libnvidia-ml.so.418.67
17152088   32 -rwxr-xr-x   1 root     root        31808 Apr 24  2019 /usr/local/cuda-10.1/targets/x86_64-linux/lib/stubs/libnvidia-ml.so
</code>```

This is not a duplicate of CMake cannot generate a safe linker search path - yocto 2.4 or CMake Warning: Cannot generate a safe linker search path for target although the symptoms are similar. It is possibly a duplicate of CMAKE - runtime library hidden files

Despite the warning, the code does link properly to the library in /usr/lib64, and it does run. So there is no error condition here. However, such a verbose warning in the output certainly gives the illusion of an error. Given the installation path of the NVidia driver, and the search paths required for CUDA building, and the actual duplicate libraries, the condition seems unavoidable.

The question is, how can I silence this warning?

Environment:

CentOS 7.3
gcc 7.3
CUDA 10.1
CMake 3.13.5

答:
The solution is to remove my FindNvidaML.cmake file. Turns out my guru's knowledge is dated and the intrisic support for CUDA in CMake, coupled with the stubs in CUDA 10.1 make this approach obsolete.

As the answers to other similar questions point out, the warning is describing the case where the code was linked against one library (in this case, explicitly /usr/lib64/libnvidia-ml.so) but at runtime may want to deduce a different library (found in /usr/local/cuda/targets/x86_64-linux/lib/stubs)

Changing the target CMakeList.txt file to be more generic results in a successful build and no warning:

```<code>target_link_libraries( ${myTarget}
                       dsp cufft nvidia-ml
                       gtest gtestApp
                )
</code>```

Body:
I want to add calls to the NVidia Monitoring Library to my CUDA application. However, the nvidia-ml library isn't part of CUDA; it's part of the device driver. Nevertheless, CUDA provides stubs for it. This appears to confuse CMake. I'm looking for a way to unconfuse CMake.

On the advice of my guru, I created a FindNvidiaML.cmake file

# set the base location
set(NVIDIA_ML_PATHS
  /usr/lib64
  /usr/lib64/nvidia
)

#  Look for the library
find_library( NVIDIA_ML_LIBRARY
              NAMES
                nvidia-ml
              HINTS
                ${NVIDIA_ML_PATHS}
)

#  Make sure valid
if( NVIDIA_ML_LIBRARY )
    SET( NVIDIA_ML_FOUND TRUE )
endif()

(NVIDIA_ML_LIBRARY has the value /usr/lib64/libnvidia-ml.so)

My main CMakeLists.txt file has this portion

  find_package(NvidiaML REQUIRED)

The specific product illustrated here CMakeLists.txt file looks like this:

set(myTarget DspTests)
add_executable( ${myTarget}
               Global_unittest.cpp

               nvSMI_unittest.cpp

               BlackmanHarris_unittest.cpp
               BlackmanHarrisCU_unittest.cu

               FFT_unittest.cu

               FindPeakKernel_unittest.cu

               )

target_include_directories( ${myTarget} SYSTEM PRIVATE
                            ${CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES}
)

set_target_properties( ${myTarget} PROPERTIES
                       CUDA_SEPARABLE_COMPILATION ON
                       POSITION_INDEPENDENT_CODE ON
)

target_link_libraries( ${myTarget}
                       dsp cufft ${NVIDIA_ML_LIBRARY}
                       gtest gtestApp
                )

add_gtest( ${myTarget} )

CMake output:

CMake Warning at dsp/unit/CMakeLists.txt:13 (add_executable):
  Cannot generate a safe linker search path for target DspTests because files
  in some directories may conflict with libraries in implicit directories:

    link library [libnvidia-ml.so] in /usr/lib64 may be hidden by files in:
      /usr/local/cuda/targets/x86_64-linux/lib/stubs

  Some of these libraries may not be found correctly.

Searching, I find

$ find /usr/ -name 'libnvidia-ml*' -ls 2>/dev/null
51097542 1512 -rwxr-xr-x   1 root     root      1545404 Jun 11  2019 /usr/lib/libnvidia-ml.so.418.67
51102213    0 lrwxrwxrwx   1 root     root           22 Jun 11  2019 /usr/lib/libnvidia-ml.so.1 -> libnvidia-ml.so.418.67
51102218    0 lrwxrwxrwx   1 root     root           17 Jun 11  2019 /usr/lib/libnvidia-ml.so -> libnvidia-ml.so.1
34907591 1536 -rwxr-xr-x   1 root     root      1569688 Apr  6  2019 /usr/lib64/libnvidia-ml.so.418.67
34907590    0 lrwxrwxrwx   1 root     root           22 Jun 11  2019 /usr/lib64/libnvidia-ml.so.1 -> libnvidia-ml.so.418.67
34972797    0 lrwxrwxrwx   1 root     root           22 Jun 11  2019 /usr/lib64/libnvidia-ml.so -> libnvidia-ml.so.418.67
17152088   32 -rwxr-xr-x   1 root     root        31808 Apr 24  2019 /usr/local/cuda-10.1/targets/x86_64-linux/lib/stubs/libnvidia-ml.so

This is not a duplicate of CMake cannot generate a safe linker search path - yocto 2.4 or CMake Warning: Cannot generate a safe linker search path for target although the symptoms are similar. It is possibly a duplicate of CMAKE - runtime library hidden files

Despite the warning, the code does link properly to the library in /usr/lib64, and it does run. So there is no error condition here. However, such a verbose warning in the output certainly gives the illusion of an error. Given the installation path of the NVidia driver, and the search paths required for CUDA building, and the actual duplicate libraries, the condition seems unavoidable.

The question is, how can I silence this warning?

Environment:

CentOS 7.3
gcc 7.3
CUDA 10.1
CMake 3.13.5

Body:
The solution is to remove my FindNvidaML.cmake file. Turns out my guru's knowledge is dated and the intrisic support for CUDA in CMake, coupled with the stubs in CUDA 10.1 make this approach obsolete.

As the answers to other similar questions point out, the warning is describing the case where the code was linked against one library (in this case, explicitly /usr/lib64/libnvidia-ml.so) but at runtime may want to deduce a different library (found in /usr/local/cuda/targets/x86_64-linux/lib/stubs)

Changing the target CMakeList.txt file to be more generic results in a successful build and no warning:

target_link_libraries( ${myTarget}
                       dsp cufft nvidia-ml
                       gtest gtestApp
                )


来源: stackexchange

问:
PHP Multidimensional Array - Copy the value to diffrent column key
i have a problem on this Multidimensional, i need to copy the value to different column key..

here's the array.

```
Array
(
    [0] => Array
        (
            [0] => item_type
            [1] => product_id
            [2] => sku
            [3] => name
            [4] => baseimage
            [5] => new_name
        )

    [1] => Array
        (
            [0] => product
            [1] => 12629
            [2] => 5102id.22755
            [3] => product name 1
            [4] => CC22755e.jpg
            [5] =>
        )

    [2] => Array
        (
            [0] => option
            [1] => 12629
            [2] => 22755.Red
            [3] => [Select Color] = Red
            [4] =>
            [5] =>

        )

    [3] => Array
        (
            [0] => option
            [1] => 12629
            [2] => 22755.Orange
            [3] => [Select Color] = Orange
            [4] =>
            [5] =>
        )

    [5] => Array
        (
            [0] => product
            [1] => 12631
            [2] => 0829id.23122
            [3] => product name 2
            [4] => CC23122b.jpg
            [5] =>
        )

    [6] => Array
        (
            [0] => option
            [1] => 12631
            [2] => 23122.Black
            [4] => [Select Color] = Black
            [5] =>
            [6] =>
        )

)
```

Want this output, is this possible in Multidimensional Array?

```
Array
(
    [0] => Array
        (
            [0] => item_type
            [1] => product_id
            [2] => sku
            [3] => name
            [4] => baseimage
            [5] => new_name
        )

    [1] => Array
        (
            [0] => product
            [1] => 12629
            [2] => 5102id.22755
            [3] => product name 1
            [4] => CC22755e.jpg
            [5] =>
        )

    [2] => Array
        (
            [0] => option
            [1] => 12629
            [2] => 22755.Red
            [3] => [Select Color] = Red
            [4] =>
            [5] => **product name 1**

        )

    [3] => Array
        (
            [0] => option
            [1] => 12629
            [2] => 22755.Orange
            [3] => [Select Color] = Orange
            [4] =>
            [5] => **product name 1**
        )

    [5] => Array
        (
            [0] => product
            [1] => 12631
            [2] => 0829id.23122
            [3] => product name 2
            [4] => CC23122b.jpg
            [5] =>
        )

    [6] => Array
        (
            [0] => option
            [1] => 12631
            [2] => 23122.Black
            [3] => [Select Color] = Black
            [4] =>
            [5] => **product name 2**
        )

)
```

Hope's it possible...

答:
Your question is unclear but i think it's about:</p>

```<code>$name = $arr[0][3];
$arr[0][5] = $name;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
i have a problem on this Multidimensional, i need to copy the value to different column key..

here's the array.

Array
(
    [0] => Array
        (
            [0] => item_type
            [1] => product_id
            [2] => sku
            [3] => name
            [4] => baseimage
            [5] => new_name
        )

    [1] => Array
        (
            [0] => product
            [1] => 12629
            [2] => 5102id.22755
            [3] => product name 1
            [4] => CC22755e.jpg
            [5] =>
        )

    [2] => Array
        (
            [0] => option
            [1] => 12629
            [2] => 22755.Red
            [3] => [Select Color] = Red
            [4] =>
            [5] =>

        )

    [3] => Array
        (
            [0] => option
            [1] => 12629
            [2] => 22755.Orange
            [3] => [Select Color] = Orange
            [4] =>
            [5] =>
        )

    [5] => Array
        (
            [0] => product
            [1] => 12631
            [2] => 0829id.23122
            [3] => product name 2
            [4] => CC23122b.jpg
            [5] =>
        )

    [6] => Array
        (
            [0] => option
            [1] => 12631
            [2] => 23122.Black
            [4] => [Select Color] = Black
            [5] =>
            [6] =>
        )

)

Want this output, is this possible in Multidimensional Array?

Array
(
    [0] => Array
        (
            [0] => item_type
            [1] => product_id
            [2] => sku
            [3] => name
            [4] => baseimage
            [5] => new_name
        )

    [1] => Array
        (
            [0] => product
            [1] => 12629
            [2] => 5102id.22755
            [3] => product name 1
            [4] => CC22755e.jpg
            [5] =>
        )

    [2] => Array
        (
            [0] => option
            [1] => 12629
            [2] => 22755.Red
            [3] => [Select Color] = Red
            [4] =>
            [5] => **product name 1**

        )

    [3] => Array
        (
            [0] => option
            [1] => 12629
            [2] => 22755.Orange
            [3] => [Select Color] = Orange
            [4] =>
            [5] => **product name 1**
        )

    [5] => Array
        (
            [0] => product
            [1] => 12631
            [2] => 0829id.23122
            [3] => product name 2
            [4] => CC23122b.jpg
            [5] =>
        )

    [6] => Array
        (
            [0] => option
            [1] => 12631
            [2] => 23122.Black
            [3] => [Select Color] = Black
            [4] =>
            [5] => **product name 2**
        )

)

Hope's it possible...

Body:
Your question is unclear but i think it's about:

$name = $arr[0][3];
$arr[0][5] = $name;


问:
Bootstrap - Change the color of visited links
I would like that all the links change their color when they are visited. I am working with Bootstrap and this is what I have tried so far (that doesn't work properly) :

```<code><html lang="en">
    <head>
        <meta http-equiv="content-type" content="text/html; charset=UTF-8">
        <meta charset="unicode">
        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
        <link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">

        <!--[if lt IE 9]>
          <script src="//html5shim.googlecode.com/svn/trunk/html5.js"></script>
        <![endif]-->
        <link href="http://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" type="text/css" rel="stylesheet">

        <style type="text/css">
               a{
                 color:#d99a30 !important;
                 &:hover{ color:#37404e !important;}
                 &:visited{ color:#37404e !important;}
               }
        </style>
    </head>
    <body>
        <div class="container">
             <div class="col-md-8 col-md-offset-2">
                  <div class="row">
                       <div class="col-sm-12">
                            <h3><a href="some_link.html">Link</a></h3>
                       </div>
                  </div>
             </div>
        </div>
    </body>
</code>```

Thanks for your help

答:
```<code>a:link, a:visited {
     color:#FFFFFF;
}

a:hover {
    color: #2DC2E8;
}
</code>```

The above code worked for me... as I wanted a link that was 'visited' to appear as if it didn't with a hover.

Thanks !

ContentLicense: CC BY-SA 3.0

Body:
I would like that all the links change their color when they are visited. I am working with Bootstrap and this is what I have tried so far (that doesn't work properly) :

        <meta http-equiv="content-type" content="text/html; charset=UTF-8">
        <meta charset="unicode">
        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
        <link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">

        <link href="http://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" type="text/css" rel="stylesheet">

Link

Thanks for your help

Body:
a:link, a:visited {
     color:#FFFFFF;
}

a:hover {
    color: #2DC2E8;
}

The above code worked for me... as I wanted a link that was 'visited' to appear as if it didn't with a hover.

Thanks !


问:
Clustering Average depth of table vs partition
select system$clustering_depth('Table1','(Column1)');

It gives the average depth of the table according to the specified columns :in my case the value is 17501.1143.Which tells that this table is badly clustered .

select SYSTEM$CLUSTERING_INFORMATION('Table1','(Column1)');

Average overlap depth of each micro-partition in the table. : in my case the value is 16033 which tells that the table is badly clustered.

Question :1 The first value is for a table (17501.1143)and second value(16033) is for  a partition as per the snowflake documentation .

which one we should consider in order to analyse clustering for Table1?

Question :2  Theoretically they both represents the same ?if so ,why each of them has different values?

答:
Question #1: Both.  You want both of those numbers to get as close to 1 as possible for your clustering key.  If you are specifying a column on the table that isn't actually the cluster key, then it'll likely be badly clustered unless things were loaded in order of that column.

Question #2: I highly recommend reading this portion of the Snowflake Documentation to understand the difference between overlap and depth.  It shows a nice illustration.  https://docs.snowflake.com/en/user-guide/tables-clustering-micropartitions.html#clustering-depth


问:
Rust need help refactoring excessive functions
(i should mention im pretty new to rust)

hi! im building a 2d particle simulation game using a Vec to hold structs with the info on each particle. right now i need to write out a separate function every time i want to check if an element is touching something with a certain property. basically it searches around the particle in a circle by calculating the index of that position then compares that structs property to the target property like so:

```<code>//check around particle for corrodable particles
pub fn check_touch_corrode(screen: &mut Vec<Particle>, x_pos: usize) -> usize {
    if screen[calc::ul(x_pos)].corrode {return calc::ul(x_pos)}     //if particle can corrode return particle
    if screen[calc::u(x_pos)].corrode {return calc::u(x_pos)}
    if screen[calc::ur(x_pos)].corrode {return calc::ur(x_pos)}
    if screen[calc::l(x_pos)].corrode {return calc::l(x_pos)}
    if screen[calc::r(x_pos)].corrode {return calc::r(x_pos)}
    if screen[calc::dl(x_pos)].corrode {return calc::dl(x_pos)}
    if screen[calc::d(x_pos)].corrode {return calc::d(x_pos)}
    if screen[calc::dr(x_pos)].corrode {return calc::dr(x_pos)}
    x_pos                                                           //else return own position
}

//check around particle for flammable particle
pub fn check_touch_flammable(screen: &mut Vec<Particle>, x_pos: usize) -> usize {
    if screen[calc::ul(x_pos)].flammable {return calc::ul(x_pos)}   //if particle flammable return particle
    if screen[calc::u(x_pos)].flammable {return calc::u(x_pos)}
    if screen[calc::ur(x_pos)].flammable {return calc::ur(x_pos)}
    if screen[calc::l(x_pos)].flammable {return calc::l(x_pos)}
    if screen[calc::r(x_pos)].flammable {return calc::r(x_pos)}
    if screen[calc::dl(x_pos)].flammable {return calc::dl(x_pos)}
    if screen[calc::d(x_pos)].flammable {return calc::d(x_pos)}
    if screen[calc::dr(x_pos)].flammable {return calc::dr(x_pos)}
    x_pos                                                           //else return own position
}
</code>```

this isnt really scalable considering im planning on having hundreds of elements with all kinds of different properties and interactions. im really wondering if there is any way to reduce this down to one function. ive been messing around with it on my own for a while now and havent been able to make any progress. the issue im running into is that the comparison needs to be calculated in the function and cant be passed in as far as i can tell. is there any way to fix this? like make it so i pass something that says which field of the struct i want to compare after it calculates that the structs index?

答:
I would go in this direction, with iterators, filters, and predicates:</p>

```<code>fn neighbors(x_pos: usize) -> impl 'static + Iterator<Item=usize> {
    (0..8).map(move |n| match n {
        0 => calc_ul(x_pos),
        1 => calc_u(x_pos),
        // and so on for 2-7

        _ => panic!("shouldn't get hereA"),
    })
}

fn first_corrosive_neighbor(screen: &Vec<Particle>, x_pos: usize) -> Option<usize> {
    neighbors(x_pos).filter(|p| screen[*p].corrode).next()
}

fn first_flammable_neighbor(screen: &Vec<Particle>, x_pos: usize) -> Option<usize> {
    neighbors(x_pos).filter(|p| screen[*p].flammable).next()
}
</code>```

Body:
(i should mention im pretty new to rust)

hi! im building a 2d particle simulation game using a Vec to hold structs with the info on each particle. right now i need to write out a separate function every time i want to check if an element is touching something with a certain property. basically it searches around the particle in a circle by calculating the index of that position then compares that structs property to the target property like so:

//check around particle for corrodable particles
pub fn check_touch_corrode(screen: &mut Vec<Particle>, x_pos: usize) -> usize {
    if screen[calc::ul(x_pos)].corrode {return calc::ul(x_pos)}     //if particle can corrode return particle
    if screen[calc::u(x_pos)].corrode {return calc::u(x_pos)}
    if screen[calc::ur(x_pos)].corrode {return calc::ur(x_pos)}
    if screen[calc::l(x_pos)].corrode {return calc::l(x_pos)}
    if screen[calc::r(x_pos)].corrode {return calc::r(x_pos)}
    if screen[calc::dl(x_pos)].corrode {return calc::dl(x_pos)}
    if screen[calc::d(x_pos)].corrode {return calc::d(x_pos)}
    if screen[calc::dr(x_pos)].corrode {return calc::dr(x_pos)}
    x_pos                                                           //else return own position
}

//check around particle for flammable particle
pub fn check_touch_flammable(screen: &mut Vec<Particle>, x_pos: usize) -> usize {
    if screen[calc::ul(x_pos)].flammable {return calc::ul(x_pos)}   //if particle flammable return particle
    if screen[calc::u(x_pos)].flammable {return calc::u(x_pos)}
    if screen[calc::ur(x_pos)].flammable {return calc::ur(x_pos)}
    if screen[calc::l(x_pos)].flammable {return calc::l(x_pos)}
    if screen[calc::r(x_pos)].flammable {return calc::r(x_pos)}
    if screen[calc::dl(x_pos)].flammable {return calc::dl(x_pos)}
    if screen[calc::d(x_pos)].flammable {return calc::d(x_pos)}
    if screen[calc::dr(x_pos)].flammable {return calc::dr(x_pos)}
    x_pos                                                           //else return own position
}

this isnt really scalable considering im planning on having hundreds of elements with all kinds of different properties and interactions. im really wondering if there is any way to reduce this down to one function. ive been messing around with it on my own for a while now and havent been able to make any progress. the issue im running into is that the comparison needs to be calculated in the function and cant be passed in as far as i can tell. is there any way to fix this? like make it so i pass something that says which field of the struct i want to compare after it calculates that the structs index?

Body:
I would go in this direction, with iterators, filters, and predicates:

fn neighbors(x_pos: usize) -> impl 'static + Iterator<Item=usize> {
    (0..8).map(move |n| match n {
        0 => calc_ul(x_pos),
        1 => calc_u(x_pos),
        // and so on for 2-7

        _ => panic!("shouldn't get hereA"),
    })
}

fn first_corrosive_neighbor(screen: &Vec<Particle>, x_pos: usize) -> Option<usize> {
    neighbors(x_pos).filter(|p| screen[*p].corrode).next()
}

fn first_flammable_neighbor(screen: &Vec<Particle>, x_pos: usize) -> Option<usize> {
    neighbors(x_pos).filter(|p| screen[*p].flammable).next()
}


问:
IdentityServer4 refresh token issue
Does anyone know how I can request for refresh_token? I’m trying to get refresh_token when requesting for access_token. At the moment I’m getting this output.

```<code>{
“access_token”: “eyJhbGciOiJSU…Zp1eS1WLY2KW2cLvEHhfDfikAYhPEDbAHTvtQu_yBgRsRxhTTPA”,
“refresh_token”: null,
“expires_in”: “3600”,
“token_type”: “Bearer”,
“scope”: “app.api.whatever.full”
}
</code>```

Hence refresh_token is null. Now I know you can’t have refresh token with grant type of client credentials. Therefore I have created another two clients one with grant type of password and other of grant type of hybrid. I also set the scope for both to offline access. When requesting for a token I get invalid_client. I’m stuck and I have no idea how to resolve this issue.
This is how I’m requesting for token:

```<code>public async Task GetUserToken(string client_id, string client_secret, string username, string password, string scope)
{
var client = new HttpClient();

var dict = new Dictionary();
dict.Add(“client_id”, client_id);
dict.Add(“client_secret”, client_secret);
dict.Add(“grant_type”, “password”);
dict.Add(“scope”, scope);
dict.Add(“username”, username);
dict.Add(“password”, password);

client.BaseAddress = new Uri($”{Request.Scheme}://{Request.Host.Value}”);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(“application/json”));

var req = new HttpRequestMessage(HttpMethod.Post, “/connect/token”) { Content = new FormUrlEncodedContent(dict) };
var res = await client.SendAsync(req).ConfigureAwait(false);

if (res.IsSuccessStatusCode)
{
return Ok(res.Content.ReadAsStringAsync().Result);
}
return BadRequest();
}
</code>```

Can anyone point out where I'm I going wrong here?

答:
I was having the same issue - I had my client configured for the Resource Owner Password Credential flow (AllowGrantTypes = GrantTypes.ResourceOwnerPassword) & I had enabled refresh token generation for the client (AllowOfflineAccess = true). Even so, upon each access token request, the refresh_token field was returned with a null value.

Turns out that the calling client application also needs to add an additional scope to explicitly tell IdentityServer4 that it expects a refresh token to be sent. In addition to any scopes you specify when requesting an access token, also include offline_access in the space-separated list. Once I added this additional scope, the refresh token started coming through.

In your specific example, a potential edit could be:

```<code>dict.Add(“scope”, $"{scope} offline_access");
</code>```

You can use this link to read about this requirement in the IdentityServer4 documentation. The relevant information is in the last paragraph & in particular, this sentence:

To request a refresh token, the client needs to include the
  offline_access scope in the token request (and must be authorized to
  request for that scope).

Title: IdentityServer4 refresh token issue

Body:
Does anyone know how I can request for refresh_token? I’m trying to get refresh_token when requesting for access_token. At the moment I’m getting this output.

{
“access_token”: “eyJhbGciOiJSU…Zp1eS1WLY2KW2cLvEHhfDfikAYhPEDbAHTvtQu_yBgRsRxhTTPA”,
“refresh_token”: null,
“expires_in”: “3600”,
“token_type”: “Bearer”,
“scope”: “app.api.whatever.full”
}

Hence refresh_token is null. Now I know you can’t have refresh token with grant type of client credentials. Therefore I have created another two clients one with grant type of password and other of grant type of hybrid. I also set the scope for both to offline access. When requesting for a token I get invalid_client. I’m stuck and I have no idea how to resolve this issue.
This is how I’m requesting for token:

public async Task GetUserToken(string client_id, string client_secret, string username, string password, string scope)
{
var client = new HttpClient();

var dict = new Dictionary();
dict.Add(“client_id”, client_id);
dict.Add(“client_secret”, client_secret);
dict.Add(“grant_type”, “password”);
dict.Add(“scope”, scope);
dict.Add(“username”, username);
dict.Add(“password”, password);

client.BaseAddress = new Uri($”{Request.Scheme}://{Request.Host.Value}”);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(“application/json”));

var req = new HttpRequestMessage(HttpMethod.Post, “/connect/token”) { Content = new FormUrlEncodedContent(dict) };
var res = await client.SendAsync(req).ConfigureAwait(false);

if (res.IsSuccessStatusCode)
{
return Ok(res.Content.ReadAsStringAsync().Result);
}
return BadRequest();
}

Can anyone point out where I'm I going wrong here?

Body:
I was having the same issue - I had my client configured for the Resource Owner Password Credential flow (AllowGrantTypes = GrantTypes.ResourceOwnerPassword) & I had enabled refresh token generation for the client (AllowOfflineAccess = true). Even so, upon each access token request, the refresh_token field was returned with a null value.

Turns out that the calling client application also needs to add an additional scope to explicitly tell IdentityServer4 that it expects a refresh token to be sent. In addition to any scopes you specify when requesting an access token, also include offline_access in the space-separated list. Once I added this additional scope, the refresh token started coming through.

In your specific example, a potential edit could be:

dict.Add(“scope”, $"{scope} offline_access");

You can use this link to read about this requirement in the IdentityServer4 documentation. The relevant information is in the last paragraph & in particular, this sentence:

To request a refresh token, the client needs to include the
  offline_access scope in the token request (and must be authorized to
  request for that scope).


问:
Buffering issue on Open pipe, write to file
I've got a script that opens a process which kicks off an external program.  The external program writes to stdout and in the parent program I'm writing both to stdout and to file.  The print to stdout is immediate but the print to file is buffering. It must be waiting on some kind of Xk number before dumping it to file.  I've tried autoflush on the output file, the pipe, stdout, and also use stdbuf.  But nothing works as it only writes to the file in chunk messages.  Am I missing something?</p>

```<code>      my $output = "/home/output.log";
      open(OL,">$output");
      OL->autoflush(1);
      open(P,'-|',"stdbuf -o0 -e0 external_program.py 2>&1");
      $| = 1;
      P->autoflush(1);
      STDOUT->autoflush(1);
      while(<P>) {
        chomp;
        print OL "$_\n";
        print "$_\n";
      }
      close(OL);
      close(P);
</code>```

答:
Hakon, I did already have the 'python3.6 -u external_program.py' running.  I finally found something that works.  If I change the print to file to flush every time it writes a line then it works

so I replace the following:

```<code>    OL "$_\n";<br>
    with
    OL->printflush("$_\n");
</code>```

Body:
I've got a script that opens a process which kicks off an external program.  The external program writes to stdout and in the parent program I'm writing both to stdout and to file.  The print to stdout is immediate but the print to file is buffering. It must be waiting on some kind of Xk number before dumping it to file.  I've tried autoflush on the output file, the pipe, stdout, and also use stdbuf.  But nothing works as it only writes to the file in chunk messages.  Am I missing something?

      my $output = "/home/output.log";
      open(OL,">$output");
      OL->autoflush(1);
      open(P,'-|',"stdbuf -o0 -e0 external_program.py 2>&1");
      $| = 1;
      P->autoflush(1);
      STDOUT->autoflush(1);
      while(
) {
        chomp;
        print OL "$_\n";
        print "$_\n";
      }
      close(OL);
      close(P);

Body:
Hakon, I did already have the 'python3.6 -u external_program.py' running.  I finally found something that works.  If I change the print to file to flush every time it writes a line then it works

so I replace the following:

    OL "$_\n";<br>
    with
    OL->printflush("$_\n");


问:
Firebase Crashlytics stuck adding SDK
I'm trying to add the Crashlytics SDK to my Android app, but it seems to be having trouble communicating with the Firebase servers. I've followed all of the instructions per the docs, but the Crashlytics tab in my console has been stuck on this screen for about 6 or so hours:
crashlytics add sdk screen.

I would (ideally) get this to just work™, but if not then I'd like to be able to restart the process, but I also don't know how to do that.

Thanks in advance!!

答: I figured it out - I was mistakenly using the same appplicationID as another one of my projects, so Firebase was getting confused - making an entirely new project with a different applicationID fixed my problem.</p>

Title: Firebase Crashlytics stuck adding SDK


问:
Commercial-grade randomization for Poker game
I need some advice on how to tackle an algorithmic problem (ie. not programming per se). What follows are my needs and how I tried to meet them. Any comments for improvement would be welcome.

Let me first start off by explaining my goal. I would like to play some poker about a billion times. Maybe I'm trying to create the next PokerStars.net, maybe I'm just crazy.

I would like to create a program that can produce better randomized decks of cards, than say the typical program calling random(). These need to be production quality decks created from high quality random numbers. I've heard that commercial-grade poker servers use 64-bit vectors for every card, thus ensuring randomness for all the millions of poker games played daily.

I'd like to keep whatever I write simple. To that end, the program should only need one input to achieve the stated goal. I have decided that whenever the program begins, it will record the current time and use that as the starting point. I realize that this approach would not be feasible for commercial environments, but as long as it can hold up for a few billion games, better than simpler alternatives, I'll be happy.

I began to write pseudo-code to solve this problem, but ran into a thorny issue. It's clear to me, but it might not be to you, so please let me know.

Psuedo-code below:

```<code>    Start by noting the system time.
    Hash the current time (with MD5) around ten times (I chose the ten arbitrarily).
    Take the resulting hash, and use it as the seed to the language-dependent random() function.
    Call random() 52 times and store the results.
    Take the values produced by random() and hash them.
    Any hash function that produces at least 64-bits of output will do for this.
    Truncate (if the hash is too big) so the hashes will fit inside a 64-bit double.
    Find a way to map the 52 doubles (which should be random now, according to my calculations) into 52 different cards, so we can play some poker.
</code>```

My issue is with the last step. I cannot think of a way to properly map each 64-bit value to a corresponding card, without having to worry about two numbers being the same (unlikely) or losing any randomness (likely).

My first idea was to break 0x0000000000000000 - 0xFFFFFFFFFFFFFFFF into four even sections (to represent the suits). But there is no guarantee that we will find exactly thirteen cards per section, which would be bad.

Now that you know where I am stuck, how would you overcome this challenge?

-- Edited --

Reading bytes from /dev/random would work well actually. But that still leaves me lost on how to do the conversion? (assuming I read enough bytes for 52 cards).

My real desire is to take something simple and predictable, like the system time, and transform it into a randomized deck of cards. Seeding random() with the system time is a BAD way of going about doing this. Hence the hashing of the time and hashing the values that come out of random().

Hell, if I wanted to, I could hash the bytes from /dev/random, just for shizzles and giggles. Hashing improves the randomness of things, doesn't it? Isn't that why modern password managers store passwords that have been hashed thousands of times?

-- Edit 2 --

So I've read your answers and I find myself confused by the conclusion many of you are implying. I hinted at it in my first edit, but it's really throwing me for a loop. I'd just like to point it out and move on.

Rainbow tables exist which do funky math and clever magic to essentially act as a lookup table for common hashes that map to a particular password. It is my understanding that longer, better passwords are unlikely to show up in these rainbow tables. But the fact still stands that despite how common many user passwords are, the hashed passwords remain safe after being hashed thousands of times.

So is that a case where many deterministic operations have increased the randomness of the original password (or seems to?) I'm not saying I'm right, I'm just saying thats my feeling.

The second thing I want to point out is I'm doing this backwards.

What I mean is that you all are suggesting I take a sorted, predictable, non-random deck of cards and use the Fisher-Yates shuffle on it. I'm sure Fisher-Yates is a fine algorithm, but lets say you couldn't use it for whatever reason.

Could you take a random stream of bytes, say in the neighborhood of 416 bytes (52 cards with 8 bytes per card) and BAM produce an already random deck of cards? The bytes were random, so it shouldn't be too hard to do this.

Most people would start with a deck of 52 cards (random or not) and swap them around a bunch of times (by picking a random index to swap). If you can do that, then you can take 52 random numbers, run through them once, and produce the randomized deck.

As simply as I can describe it,
The algorithm to accepts a stream of randomized bytes and looks at each 8-byte chunk. It maps each chunk to a card.

Ex. 0x123 maps to the Ace of Spades
Ex. 0x456 maps to the King of Diamonds
Ex. 0x789 maps to the 3 of Clubs
.... and so on.

As long as we chose a good model for the mapping, this is fine. No shuffling required. The program will be reduced to two steps.

Step 1: Obtain a sufficient quantity of random bytes from a good source
Step 2: Split this stream of bytes into 52 chunks, one for each card in the deck
Step 2a: Run through the 52 chunks, converting them into card values according to our map.

Does that makes sense?

答: A ready-made, off the shelf poker hand evaluator can be found here. All feedback welcomed at the e-mail address found therein.</p>

ContentLicense: CC BY-SA 2.5

Body:
I need some advice on how to tackle an algorithmic problem (ie. not programming per se). What follows are my needs and how I tried to meet them. Any comments for improvement would be welcome.

Let me first start off by explaining my goal. I would like to play some poker about a billion times. Maybe I'm trying to create the next PokerStars.net, maybe I'm just crazy.

I would like to create a program that can produce better randomized decks of cards, than say the typical program calling random(). These need to be production quality decks created from high quality random numbers. I've heard that commercial-grade poker servers use 64-bit vectors for every card, thus ensuring randomness for all the millions of poker games played daily.

I'd like to keep whatever I write simple. To that end, the program should only need one input to achieve the stated goal. I have decided that whenever the program begins, it will record the current time and use that as the starting point. I realize that this approach would not be feasible for commercial environments, but as long as it can hold up for a few billion games, better than simpler alternatives, I'll be happy.

I began to write pseudo-code to solve this problem, but ran into a thorny issue. It's clear to me, but it might not be to you, so please let me know.

Psuedo-code below:

    Start by noting the system time.
    Hash the current time (with MD5) around ten times (I chose the ten arbitrarily).
    Take the resulting hash, and use it as the seed to the language-dependent random() function.
    Call random() 52 times and store the results.
    Take the values produced by random() and hash them.
    Any hash function that produces at least 64-bits of output will do for this.
    Truncate (if the hash is too big) so the hashes will fit inside a 64-bit double.
    Find a way to map the 52 doubles (which should be random now, according to my calculations) into 52 different cards, so we can play some poker.

My issue is with the last step. I cannot think of a way to properly map each 64-bit value to a corresponding card, without having to worry about two numbers being the same (unlikely) or losing any randomness (likely).

My first idea was to break 0x0000000000000000 - 0xFFFFFFFFFFFFFFFF into four even sections (to represent the suits). But there is no guarantee that we will find exactly thirteen cards per section, which would be bad.

Now that you know where I am stuck, how would you overcome this challenge?

-- Edited --

Reading bytes from /dev/random would work well actually. But that still leaves me lost on how to do the conversion? (assuming I read enough bytes for 52 cards).

My real desire is to take something simple and predictable, like the system time, and transform it into a randomized deck of cards. Seeding random() with the system time is a BAD way of going about doing this. Hence the hashing of the time and hashing the values that come out of random().

Hell, if I wanted to, I could hash the bytes from /dev/random, just for shizzles and giggles. Hashing improves the randomness of things, doesn't it? Isn't that why modern password managers store passwords that have been hashed thousands of times?

-- Edit 2 --

So I've read your answers and I find myself confused by the conclusion many of you are implying. I hinted at it in my first edit, but it's really throwing me for a loop. I'd just like to point it out and move on.

Rainbow tables exist which do funky math and clever magic to essentially act as a lookup table for common hashes that map to a particular password. It is my understanding that longer, better passwords are unlikely to show up in these rainbow tables. But the fact still stands that despite how common many user passwords are, the hashed passwords remain safe after being hashed thousands of times.

So is that a case where many deterministic operations have increased the randomness of the original password (or seems to?) I'm not saying I'm right, I'm just saying thats my feeling.

The second thing I want to point out is I'm doing this backwards.

What I mean is that you all are suggesting I take a sorted, predictable, non-random deck of cards and use the Fisher-Yates shuffle on it. I'm sure Fisher-Yates is a fine algorithm, but lets say you couldn't use it for whatever reason.

Could you take a random stream of bytes, say in the neighborhood of 416 bytes (52 cards with 8 bytes per card) and BAM produce an already random deck of cards? The bytes were random, so it shouldn't be too hard to do this.

Most people would start with a deck of 52 cards (random or not) and swap them around a bunch of times (by picking a random index to swap). If you can do that, then you can take 52 random numbers, run through them once, and produce the randomized deck.

As simply as I can describe it,
The algorithm to accepts a stream of randomized bytes and looks at each 8-byte chunk. It maps each chunk to a card.

Ex. 0x123 maps to the Ace of Spades
Ex. 0x456 maps to the King of Diamonds
Ex. 0x789 maps to the 3 of Clubs
.... and so on.

As long as we chose a good model for the mapping, this is fine. No shuffling required. The program will be reduced to two steps.

Step 1: Obtain a sufficient quantity of random bytes from a good source
Step 2: Split this stream of bytes into 52 chunks, one for each card in the deck
Step 2a: Run through the 52 chunks, converting them into card values according to our map.

Does that makes sense?


问:
How to add background-color in a section part?
Is there any other way to add background color in section tag? Except using body {background-color: blue;}, what is are other ways to add background color into section?

I am trying to add the section background color like this:

<!DOCTYPE html>

        <title>Testing</title>

```

There is no color showing on my browser.

答:
Or maybe they should try a little more color using gradient.

<!DOCTYPE html>

  <title>Testing</title>

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

```

Body:
Is there any other way to add background color in section tag? Except using body {background-color: blue;}, what is are other ways to add background color into section?

I am trying to add the section background color like this:

<!DOCTYPE html>

        <title>Testing</title>

There is no color showing on my browser.

Body:
Or maybe they should try a little more color using gradient.

<!DOCTYPE html>
<html>

<head>
  <title>Testing</title>
  <style>
    #ABC {
      background-image: linear-gradient(45deg,rgb(218,34,255) 30%,#9733ee 90%);
padding: 1em;
    border-radius: 3px;
    margin: 1em 0;
color: #fff;
    }
  </style>
</head>

<body>
  <section id="ABC">
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
  </section>
</body>

</html>


问:
Pyautogui not running on Mac? (Catalina)
I'm trying to run the following from terminal on my mac, but what's happening is
the code appears to run (I don't get any error message), python (as an app) on my mac bounces on my dock as if to open and then it doesn't do anything and then it stops running. I can't tell if this is a permissions issue or a Mac Catalina issue or an issue with my code!

```<code>import pyautogui as gui
count= 0
gui.click(1080,521)
while count<5:
    gui.FAILSAFE=True
    gui.write(f'This is a test {count}x')
    count += 1
    gui.press('enter')
</code>```

I've already tried to run the sudo command, I've also tried:

```<code>gui.moveTo(1080,521)
gui.dragTo(button='left')
</code>```

in place of the gui.click command, but nothing seems to be working!
Help?

答: Turns out this was a permissions issue - in Mac System Preferences I needed to give access to Terminal to control my mouse</p>

Body:
I'm trying to run the following from terminal on my mac, but what's happening is
the code appears to run (I don't get any error message), python (as an app) on my mac bounces on my dock as if to open and then it doesn't do anything and then it stops running. I can't tell if this is a permissions issue or a Mac Catalina issue or an issue with my code!

import pyautogui as gui
count= 0
gui.click(1080,521)
while count<5:
    gui.FAILSAFE=True
    gui.write(f'This is a test {count}x')
    count += 1
    gui.press('enter')

I've already tried to run the sudo command, I've also tried:

gui.moveTo(1080,521)
gui.dragTo(button='left')

in place of the gui.click command, but nothing seems to be working!
Help?


问:
How can override bootstrap classes with withStyles in material UI
I want to override some of bootstrap classes.Currently I'm using withStyles of material UI in this I can write css in Js format for my own classes.But I want to override bootstrap classes of some buttons, container etc...In material UI it will generate class names dynamically. I can do with scss but I'm using theme changer in my application.

I except the overriding of bootstrap classes by using withStyles of material UI.

答:
By using global styles of css in js we can override the styles of any third party library.

Please refer below link for overriding the global styles

https://material-ui.com/customization/globals/#global-css


问:
How can I alternate "visible" rows in an html table using jQuery
I have this code that does alternating rows for a html in jQuery:

```<code>function AlternateRowColors() {

    $("table.altRow1 tr").filter(function() {
    return true;
    }).filter(':even').addClass('alt');

    $("tr.alt td[rowspan]").each(function() {
    $(this).parent().nextAll().slice(0, this.rowSpan - 1).addClass('alt');
    });

    $('ins').css("background-color", "#cfc")
}
</code>```

This works great (feel free to add suggestions if anything is inefficient above).

The issue that I have now is that I have code that hides a bunch of rows (details on why are not really relevant for this question), the main point is that I want to have a function that can do alternative row colors to current visible rows.

I am hiding rows by simply adding a class to certain rows and them calling .hide() on that class.

Is there any suggestion to get alternative row colors (like the above code) but have it work on the visible rows so no matter what is hidden, the table always looks correct in terms of alt row coloring.

答:
I would suggest that you add a class to the visible rows as well in the code that you have to add the class to hidden rows. Say you add the class named visible. Then you can apply your alternating rows code above to the class visible:

```<code> $("table.altRow1 tr.visible").filter(function() {
</code>```

and so on.

Body:
I have this code that does alternating rows for a html in jQuery:

function AlternateRowColors() {

    $("table.altRow1 tr").filter(function() {
    return true;
    }).filter(':even').addClass('alt');

    $("tr.alt td[rowspan]").each(function() {
    $(this).parent().nextAll().slice(0, this.rowSpan - 1).addClass('alt');
    });

    $('ins').css("background-color", "#cfc")
}

This works great (feel free to add suggestions if anything is inefficient above).

The issue that I have now is that I have code that hides a bunch of rows (details on why are not really relevant for this question), the main point is that I want to have a function that can do alternative row colors to current visible rows.

I am hiding rows by simply adding a class to certain rows and them calling .hide() on that class.

Is there any suggestion to get alternative row colors (like the above code) but have it work on the visible rows so no matter what is hidden, the table always looks correct in terms of alt row coloring.

Body:
I would suggest that you add a class to the visible rows as well in the code that you have to add the class to hidden rows. Say you add the class named visible. Then you can apply your alternating rows code above to the class visible:

 $("table.altRow1 tr.visible").filter(function() {

and so on.


问:
cannot retrieve data from a column in a SQL database in android
I have been working on an app which has has a SQL database. I am trying to retrieve data in a specific column 'COL3' of SQL database "YEAR_DETAILS" when a button is pressed but I am getting a lot of errors can  someone tell me what is it that i am doing wrong.

```<code>public class AddTransaction extends AppCompatActivity {

    int type1 ;
    int type2;
    double amount;
    ArrayList<add_transaction_data> data;
    Context context;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_transaction);
        ActionBar actionBar = getSupportActionBar();
        assert actionBar != null;
        actionBar.hide();
        populateList();

        final ImageButton cancel = findViewById(R.id.at_btn_cancel);
        final EditText EditAmount = findViewById(R.id.at_enter_amount);
        ImageButton save = findViewById(R.id.at_btn_save);
        ImageButton income = findViewById(R.id.at_btn_income);
        ImageButton loan = findViewById(R.id.at_btn_loan);
        RecyclerView recyclerView = findViewById(R.id.at_btn_recyclerview);

        recyclerView.setLayoutManager(new GridLayoutManager(this , 5));
        recyclerView.setAdapter(new at_btn_adapter(data, new onClickRecyclerButtion() {
            @Override
            public void onPositionClicked(int position) {
                type1 = 2;
                type2 = position;

            }
        }));

        income.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                type1 = 1;
                type2 = -1;
            }
        });

        loan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                type1 = 1;
                type2 = -2;
            }
        });

        context = this;
        save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                System.out.println("it is  all cool here");
                DatabaseHelper1 databaseHelper1 = new DatabaseHelper1(getBaseContext());
                DatabaseHelper2 databaseHelper2 = new DatabaseHelper2(getBaseContext());
                double amount = Double.parseDouble(EditAmount.getText().toString());
                System.out.println(amount);
                Calendar c = Calendar.getInstance();
                int year = c.get(Calendar.YEAR);
                int month = c.get(Calendar.MONTH);
                String m = changeString(month);
                System.out.println(type1);
                double mRamount = -1;
                if(type1 == 1){
                   Cursor cursor = databaseHelper1.getRemainingAmount(m , String.valueOf(year));
                   mRamount= cursor.getDouble(3);
                   System.out.println(mRamount);//printing amount.
                }
                startActivity(new Intent(AddTransaction.this , MainActivity.class));
            }
        });

        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(AddTransaction.this , MainActivity.class));
            }
        });

    }

    void populateList(){
        data = new ArrayList<>();
        data.add(new add_transaction_data("Add" , R.drawable.ic_add_black_24dp));
        data.add(new add_transaction_data("Shopping" , R.drawable.at_ic_shopping));
        data.add(new add_transaction_data("Food" , R.drawable.at_ic_food));
        data.add(new add_transaction_data("Traveling" , R.drawable.at_ic_travel));
        data.add(new add_transaction_data("Education" , R.drawable.at_ic_education));
        data.add(new add_transaction_data("Energy" , R.drawable.at_ic_energy));
        data.add(new add_transaction_data("House" , R.drawable.at_ic_home));
        data.add(new add_transaction_data("Fitness" , R.drawable.at_ic_sports));
        data.add(new add_transaction_data("Personal" , R.drawable.at_ic_personal));
        data.add(new add_transaction_data("Other" , R.drawable.at_ic_other));
    }

    String changeString(int month){
        String m;
        switch (month){
            case 0:
                m = "January";
                break;
            case 1:
                m = "Feburary";
                break;
            case 2:
                m = "March";
                break;
            case 3:
                m = "April";
                break;
            case 4:
                m = "May";
                break;
            case 5:
                m = "June";
                break;
            case 6:
                m = "July";
                break;
            case 7:
                m = "August";
                break;
            case 8:
                m = "September";
                break;
            case 9:
                m = "October";
                break;
            case 10:
                m = "November";
                break;
            case 11:
                m = "December";
                break;
            default:
                m = " ";

        }
        return m;
    }

}

</code>```

Database helper:

```<code>

public class DatabaseHelper1 extends SQLiteOpenHelper {

    private static final int version = 3;
    private static final String name = "YEAR_DETAILS";
    private static final String COL0 = "YEAR";
    private static final String COL1 = "MONTH";
    private static final String COL2 = "SPENT";
    private static final String COL3 = "REMAINING";
    private static final String TAG = "Database Helper 1";

    public DatabaseHelper1(@Nullable Context context) {
        super(context, name, null, version);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        Log.d(TAG , "Database 1 is being created");
        String create_table = "CREATE TABLE "+name+"("+
                COL0+" INTEGER, "+
                COL1+" TEXT, "+
                COL2+" DOUBLE, "+
                COL3+" DOUBLE);";
        db.execSQL(create_table);
    }

    @Override
    public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS "+name);
        onCreate(db);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    }

    private boolean createMonth(String month , String year){
        Log.d(TAG , "month row is being created");
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(COL0 , year);
        contentValues.put(COL1 , month);
        contentValues.put(COL2 , 0.0);
        contentValues.put(COL3 , 0.0);
        long result = db.insert(name,null , contentValues);
        return result != -1;
    }

    public boolean spentChange(String month , String year , Double newAmount){
        Log.d(TAG , "spent amount is being changed");
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(COL2 , newAmount);
        long result = db.update(name, values , "MONTH = ? AND YEAR = ?", new String[]{month , year});
        return  result != -1;
    }

    public boolean remainingChange(String month ,String year, Double newAmount){
        Log.d(TAG , "Remaining amount is being changed");
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues =new ContentValues();
        contentValues.put(COL3 , newAmount);
        long result = db.update(name , contentValues , "MONTH = ? AND YEAR = ?" , new String[]{month , year});
        return result != -1;
    }

    public void checkExistance(String month, String year){
        Log.d(TAG , "Checking if month already exits");
        SQLiteDatabase database = this.getWritableDatabase();
        Cursor cur =  database.query(name , null , "MONTH = ? AND YEAR = ?" , new String[]{month , year} , null , null , null);
        System.out.println(cur);
        if(cur.getCount() <= 0) {
            boolean b = createMonth(month , year);
            if(b)
                Log.d(TAG , "checkExistance: failed to create month");
            else
                Log.d(TAG, "checkExistance: month created successfully");
        }
    }

    public Cursor getdata(){
        SQLiteDatabase db = this.getWritableDatabase();
        String query = "SELECT * FROM YEAR_DETAILS;";
        return db.rawQuery(query , null);
    }

    public Cursor getSpentAmount(String month , String year){
        SQLiteDatabase db = this.getReadableDatabase();
        String query = "SELECT * FROM YEAR_DETAILS WHERE MONTH = " + month+ " AND YEAR = "+year;
        return db.rawQuery(query , null);
    }

    public Cursor getRemainingAmount(String month , String year){
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cur =  db.query(name , new String[]{COL3} , "MONTH = ? AND YEAR = ?" , new String[]{month , year} , null , null , null);
        return cur;
    }

}

</code>```

Error:

2020-05-29 21:40:06.971 30591-30591/com.carrot.wallet E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.carrot.wallet, PID: 30591
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.carrot.wallet/com.carrot.wallet.MainActivity}: android.view.InflateException: Binary XML file line #10 in com.carrot.wallet:layout/activity_main: Binary XML file line #10 in com.carrot.wallet:layout/activity_main: Error inflating class fragment
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3387)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3526)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2122)
        at android.os.Handler.dispatchMessage(Handler.java:107)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7695)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:516)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)
     Caused by: android.view.InflateException: Binary XML file line #10 in

答:
Add getWritableDatabase:

```<code> private SQLiteDatabase db;
</code>```

and

```<code>@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_transaction);
        db = new MyHelper(this).getWritableDatabase();
        ActionBar actionBar = getSupportActionBar();
        assert actionBar != null;
        actionBar.hide();
        populateList();
</code>```

Body:
I have been working on an app which has has a SQL database. I am trying to retrieve data in a specific column 'COL3' of SQL database "YEAR_DETAILS" when a button is pressed but I am getting a lot of errors can  someone tell me what is it that i am doing wrong.

public class AddTransaction extends AppCompatActivity {

    int type1 ;
    int type2;
    double amount;
    ArrayList<add_transaction_data> data;
    Context context;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_transaction);
        ActionBar actionBar = getSupportActionBar();
        assert actionBar != null;
        actionBar.hide();
        populateList();

        final ImageButton cancel = findViewById(R.id.at_btn_cancel);
        final EditText EditAmount = findViewById(R.id.at_enter_amount);
        ImageButton save = findViewById(R.id.at_btn_save);
        ImageButton income = findViewById(R.id.at_btn_income);
        ImageButton loan = findViewById(R.id.at_btn_loan);
        RecyclerView recyclerView = findViewById(R.id.at_btn_recyclerview);

        recyclerView.setLayoutManager(new GridLayoutManager(this , 5));
        recyclerView.setAdapter(new at_btn_adapter(data, new onClickRecyclerButtion() {
            @Override
            public void onPositionClicked(int position) {
                type1 = 2;
                type2 = position;

            }
        }));

        income.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                type1 = 1;
                type2 = -1;
            }
        });

        loan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                type1 = 1;
                type2 = -2;
            }
        });

        context = this;
        save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                System.out.println("it is  all cool here");
                DatabaseHelper1 databaseHelper1 = new DatabaseHelper1(getBaseContext());
                DatabaseHelper2 databaseHelper2 = new DatabaseHelper2(getBaseContext());
                double amount = Double.parseDouble(EditAmount.getText().toString());
                System.out.println(amount);
                Calendar c = Calendar.getInstance();
                int year = c.get(Calendar.YEAR);
                int month = c.get(Calendar.MONTH);
                String m = changeString(month);
                System.out.println(type1);
                double mRamount = -1;
                if(type1 == 1){
                   Cursor cursor = databaseHelper1.getRemainingAmount(m , String.valueOf(year));
                   mRamount= cursor.getDouble(3);
                   System.out.println(mRamount);//printing amount.
                }
                startActivity(new Intent(AddTransaction.this , MainActivity.class));
            }
        });

        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(AddTransaction.this , MainActivity.class));
            }
        });

    }

    void populateList(){
        data = new ArrayList<>();
        data.add(new add_transaction_data("Add" , R.drawable.ic_add_black_24dp));
        data.add(new add_transaction_data("Shopping" , R.drawable.at_ic_shopping));
        data.add(new add_transaction_data("Food" , R.drawable.at_ic_food));
        data.add(new add_transaction_data("Traveling" , R.drawable.at_ic_travel));
        data.add(new add_transaction_data("Education" , R.drawable.at_ic_education));
        data.add(new add_transaction_data("Energy" , R.drawable.at_ic_energy));
        data.add(new add_transaction_data("House" , R.drawable.at_ic_home));
        data.add(new add_transaction_data("Fitness" , R.drawable.at_ic_sports));
        data.add(new add_transaction_data("Personal" , R.drawable.at_ic_personal));
        data.add(new add_transaction_data("Other" , R.drawable.at_ic_other));
    }

    String changeString(int month){
        String m;
        switch (month){
            case 0:
                m = "January";
                break;
            case 1:
                m = "Feburary";
                break;
            case 2:
                m = "March";
                break;
            case 3:
                m = "April";
                break;
            case 4:
                m = "May";
                break;
            case 5:
                m = "June";
                break;
            case 6:
                m = "July";
                break;
            case 7:
                m = "August";
                break;
            case 8:
                m = "September";
                break;
            case 9:
                m = "October";
                break;
            case 10:
                m = "November";
                break;
            case 11:
                m = "December";
                break;
            default:
                m = " ";

        }
        return m;
    }

}

Database helper:

public class DatabaseHelper1 extends SQLiteOpenHelper {

    private static final int version = 3;
    private static final String name = "YEAR_DETAILS";
    private static final String COL0 = "YEAR";
    private static final String COL1 = "MONTH";
    private static final String COL2 = "SPENT";
    private static final String COL3 = "REMAINING";
    private static final String TAG = "Database Helper 1";

    public DatabaseHelper1(@Nullable Context context) {
        super(context, name, null, version);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        Log.d(TAG , "Database 1 is being created");
        String create_table = "CREATE TABLE "+name+"("+
                COL0+" INTEGER, "+
                COL1+" TEXT, "+
                COL2+" DOUBLE, "+
                COL3+" DOUBLE);";
        db.execSQL(create_table);
    }

    @Override
    public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS "+name);
        onCreate(db);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    }

    private boolean createMonth(String month , String year){
        Log.d(TAG , "month row is being created");
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(COL0 , year);
        contentValues.put(COL1 , month);
        contentValues.put(COL2 , 0.0);
        contentValues.put(COL3 , 0.0);
        long result = db.insert(name,null , contentValues);
        return result != -1;
    }

    public boolean spentChange(String month , String year , Double newAmount){
        Log.d(TAG , "spent amount is being changed");
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(COL2 , newAmount);
        long result = db.update(name, values , "MONTH = ? AND YEAR = ?", new String[]{month , year});
        return  result != -1;
    }

    public boolean remainingChange(String month ,String year, Double newAmount){
        Log.d(TAG , "Remaining amount is being changed");
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues =new ContentValues();
        contentValues.put(COL3 , newAmount);
        long result = db.update(name , contentValues , "MONTH = ? AND YEAR = ?" , new String[]{month , year});
        return result != -1;
    }

    public void checkExistance(String month, String year){
        Log.d(TAG , "Checking if month already exits");
        SQLiteDatabase database = this.getWritableDatabase();
        Cursor cur =  database.query(name , null , "MONTH = ? AND YEAR = ?" , new String[]{month , year} , null , null , null);
        System.out.println(cur);
        if(cur.getCount() <= 0) {
            boolean b = createMonth(month , year);
            if(b)
                Log.d(TAG , "checkExistance: failed to create month");
            else
                Log.d(TAG, "checkExistance: month created successfully");
        }
    }

    public Cursor getdata(){
        SQLiteDatabase db = this.getWritableDatabase();
        String query = "SELECT * FROM YEAR_DETAILS;";
        return db.rawQuery(query , null);
    }

    public Cursor getSpentAmount(String month , String year){
        SQLiteDatabase db = this.getReadableDatabase();
        String query = "SELECT * FROM YEAR_DETAILS WHERE MONTH = " + month+ " AND YEAR = "+year;
        return db.rawQuery(query , null);
    }

    public Cursor getRemainingAmount(String month , String year){
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cur =  db.query(name , new String[]{COL3} , "MONTH = ? AND YEAR = ?" , new String[]{month , year} , null , null , null);
        return cur;
    }

}

Error:

2020-05-29 21:40:06.971 30591-30591/com.carrot.wallet E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.carrot.wallet, PID: 30591
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.carrot.wallet/com.carrot.wallet.MainActivity}: android.view.InflateException: Binary XML file line #10 in com.carrot.wallet:layout/activity_main: Binary XML file line #10 in com.carrot.wallet:layout/activity_main: Error inflating class fragment
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3387)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3526)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2122)
        at android.os.Handler.dispatchMessage(Handler.java:107)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7695)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:516)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)
     Caused by: android.view.InflateException: Binary XML file line #10 in

Body:
Add getWritableDatabase:

 private SQLiteDatabase db;

and

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_transaction);
        db = new MyHelper(this).getWritableDatabase();
        ActionBar actionBar = getSupportActionBar();
        assert actionBar != null;
        actionBar.hide();
        populateList();


问:
Python: write outer product using map and reduce
Suppose I have a matrix

```<code>import numpy as np
from functools import reduce
np.random.seed(123)
X = np.random.normal(size=(5, 2))
</code>```

and I want to compute X^t X without using numpy functions and using map, reduce and lambda functions. Since we can write X^t X as a sum of outer products, my goal would be:

```<code>def outer_product(x):
    """Computes outer product of a vector with itself"""
    pass

map(outer_product, X)
</code>```

However I can't seem to find an efficient way of writing all of these with map reduce.

My Attempt

```<code>def outer(x):
    xxx = np.repeat(x, len(x))
    yyy = np.array(list(x) * len(x))
    return np.reshape(list(map(lambda x, y: x*y, xxx, yyy)), (len(x), len(x)))
</code>```

so that

```<code>outer(X[0, ])
</code>```

And then I've written the covariance matrix as follows

```<code>def cov(X):
    return np.array(reduce(lambda x, y: x + y, list(map(outer, X)))) / np.size(X, 0)
</code>```

答:
To answer your question, outer product can be defined as nested map such as

```<code>outer = lambda V: np.array(list(map(lambda x: list(map(lambda y: x*y, V)), V)))

X = np.random.normal(size=(5, 2))
>>> outer(X[1])
array([[ 0.08007683, -0.42624902], [-0.42624902,  2.26892377]])
</code>```

Actually, it is simpler to use list comprehension

```<code>outer = lambda V: np.array([[x*x1 for a in V] for x1 in V])
</code>```

will give you same result. Then you can map to your matrix like

```<code>>>> list(map(outer, X))
[array([[ 1.17859381, -1.08274874],
       [-1.08274874,  0.99469794]]), array([[ 0.08007683, -0.42624902],
       [-0.42624902,  2.26892377]]), array([[ 0.33477825, -0.9555216 ],
       [-0.9555216 ,  2.72724264]]), array([[5.88877215, 1.04083337],
       [1.04083337, 0.18396604]]), array([[ 1.60259461, -1.0972381 ],
       [-1.0972381 ,  0.75123892]])]
</code>```

Your reduce part is quite nice and concise by the way. I don't think that part requires any further refactoring.

Body:
Suppose I have a matrix

import numpy as np
from functools import reduce
np.random.seed(123)
X = np.random.normal(size=(5, 2))

and I want to compute X^t X without using numpy functions and using map, reduce and lambda functions. Since we can write X^t X as a sum of outer products, my goal would be:

def outer_product(x):
    """Computes outer product of a vector with itself"""
    pass

map(outer_product, X)

However I can't seem to find an efficient way of writing all of these with map reduce.

My Attempt

def outer(x):
    xxx = np.repeat(x, len(x))
    yyy = np.array(list(x) * len(x))
    return np.reshape(list(map(lambda x, y: x*y, xxx, yyy)), (len(x), len(x)))

so that

outer(X[0, ])

And then I've written the covariance matrix as follows

def cov(X):
    return np.array(reduce(lambda x, y: x + y, list(map(outer, X)))) / np.size(X, 0)

Body:
To answer your question, outer product can be defined as nested map such as

outer = lambda V: np.array(list(map(lambda x: list(map(lambda y: x*y, V)), V)))

X = np.random.normal(size=(5, 2))
>>> outer(X[1])
array([[ 0.08007683, -0.42624902], [-0.42624902,  2.26892377]])

Actually, it is simpler to use list comprehension

outer = lambda V: np.array([[x*x1 for a in V] for x1 in V])

will give you same result. Then you can map to your matrix like

>>> list(map(outer, X))
[array([[ 1.17859381, -1.08274874],
       [-1.08274874,  0.99469794]]), array([[ 0.08007683, -0.42624902],
       [-0.42624902,  2.26892377]]), array([[ 0.33477825, -0.9555216 ],
       [-0.9555216 ,  2.72724264]]), array([[5.88877215, 1.04083337],
       [1.04083337, 0.18396604]]), array([[ 1.60259461, -1.0972381 ],
       [-1.0972381 ,  0.75123892]])]

Your reduce part is quite nice and concise by the way. I don't think that part requires any further refactoring.


问:
React Need help Syncfusion data grid
Iam new to react and I am trying to make the following.

I want to create a simple username and password form,
then add the data from username and password form and display it in a grid in the same page. Then update the grid every time I add a user (user name and password).

So here is my form where i get the user name only :

```<code>        <div >
              <form onSubmit={this.handleSubmit}>
                  <label htmlFor="username">Enter username</label>
                  <input id="username" name="username" type="text" />
                  <button>Send data!</button>
              </form>
            </div>
</code>```

I want to know how to do this exactly ?
Do i have to create a son file then map it and display it in a grid?
Or can i just save it in the state variable , then display every update ?
Or there is another solution for that?

Edit:  Following is my code,

```<code>    import React from "react";
    import {GridComponent, ColumnsDirective, Page , Inject} from '@syncfusion/ej2-react-grids';
    import productsApi from './getJson'
    import ddata from '../pages/source.json'

      export default class products extends React.Component  {
        constructor() {

          super();
          this.handleSubmit = this.handleSubmit.bind(this);
          this.state =
                  {
                    QrCode : '',
                    newProducts : []
                  }

              }

              // this one is not working at all
        componentDidMount(){
          productsApi.getAll().then( data => {
            this.setState({
              newProducts : data

            } )
           },
           )

        }

        handleSubmit(event) {
          event.preventDefault();
          this.setState({
            QrCode: event.target.elements.username.value}
            );
        }

        render() {

          return (
          <div >

            <div >
                  <form onSubmit={this.handleSubmit}>
                      <label htmlFor="username">Enter username</label>
                      <input id="username" name="username" type="text" />
                      <button>Send data!</button>
                  </form>
                </div>

                <div style={{margin: '10%', marginTop : '5%'}}>

                <GridComponent dataSource={ddata}  allowPaging={true} pageSettings= {{pageSize:100}}>

                    <Inject  services ={[Page]}/>
                </GridComponent>
                </div>

            </div>

          );
        }
      }
</code>```

Here is my sample json,

```<code>[
    {
        "id":0,
        "Qr":1234567891,
        "Stat":"A",
        "name":"Hello world"

    },
    {
        "id":0,
        "Qr":1234567891,
        "Stat":"A",
        "name":"Hello world"

    },
    {
        "id":0,
        "Qr":1234567891,
        "Stat":"A",
        "name":"Hello world"

    },
    {
        "id":0,
        "Qr":1234567891,
        "Stat":"A",
        "name":"Hello world"

    },
    {
        "id":0,
        "Qr":1234567891,
        "Stat":"A",
        "name":"Hello world"

    },
    {
        "id":0,
        "Qr":1234567891,
        "Stat":"A",
        "name":"Hello world"

    }

]
</code>```

I hope you can help me solve that problem .
Thank you

答:
Please check this example where I used material ui for input field and table.

```<code>import React, {useState} from 'react';
import {makeStyles} from '@material-ui/core/styles';
import Table from '@material-ui/core/Table';
import TableBody from '@material-ui/core/TableBody';
import TableCell from '@material-ui/core/TableCell';
import TableContainer from '@material-ui/core/TableContainer';
import TableHead from '@material-ui/core/TableHead';
import TableRow from '@material-ui/core/TableRow';
import Paper from '@material-ui/core/Paper';
import TextField from "@material-ui/core/TextField";
import Button from "@material-ui/core/Button";

export default function FormExample() {
    const [rows, setRows] = useState([]);
    const [row, setRow] = useState({
        username: '',
        password: ''
    });

    function changeHandler(event) {
        setRow({...row, [event.target.name]: event.target.value});
    }

    return (
        <div>
            <form noValidate autoComplete="off">
                <TextField id="username" name="username" label="Username" onChange={changeHandler}/>
                <TextField id="password" name="password" label="Password" onChange={changeHandler}/>
                <Button variant="contained" color="primary" onClick={() => {
                    let data = [...rows];
                    data.push(row);
                    setRows(data);
                }}>
                    Save
                </Button>
            </form>

            <h3>User List</h3>
            <TableContainer component={Paper}>
                <Table aria-label="simple table">
                    <TableHead>
                        <TableRow>
                            <TableCell>Username</TableCell>
                            <TableCell>Password</TableCell>
                        </TableRow>
                    </TableHead>
                    <TableBody>
                        {rows.map((row) => (
                            <TableRow key={row.name}>
                                <TableCell>{row.username}</TableCell>
                                <TableCell>{row.password}</TableCell>
                            </TableRow>
                        ))}
                    </TableBody>
                </Table>
            </TableContainer>
        </div>
    );
}
</code>```

Title: React Need help Syncfusion data grid

Body:
Iam new to react and I am trying to make the following.

I want to create a simple username and password form,
then add the data from username and password form and display it in a grid in the same page. Then update the grid every time I add a user (user name and password).

So here is my form where i get the user name only :

              <form onSubmit={this.handleSubmit}>
                  Enter username
                  <input id="username" name="username" type="text" />
                  <button>Send data!</button>
              </form>

I want to know how to do this exactly ?
Do i have to create a son file then map it and display it in a grid?
Or can i just save it in the state variable , then display every update ?
Or there is another solution for that?

Edit:  Following is my code,

    import React from "react";
    import {GridComponent, ColumnsDirective, Page , Inject} from '@syncfusion/ej2-react-grids';
    import productsApi from './getJson'
    import ddata from '../pages/source.json'

      export default class products extends React.Component  {
        constructor() {

          super();
          this.handleSubmit = this.handleSubmit.bind(this);
          this.state =
                  {
                    QrCode : '',
                    newProducts : []
                  }

              }

              // this one is not working at all
        componentDidMount(){
          productsApi.getAll().then( data => {
            this.setState({
              newProducts : data

            } )
           },
           )

        }

        handleSubmit(event) {
          event.preventDefault();
          this.setState({
            QrCode: event.target.elements.username.value}
            );
        }

        render() {

          return (

                  <form onSubmit={this.handleSubmit}>
                      Enter username
                      <input id="username" name="username" type="text" />
                      <button>Send data!</button>
                  </form>

                <GridComponent dataSource={ddata}  allowPaging={true} pageSettings= {{pageSize:100}}>

                    <Inject  services ={[Page]}/>
                </GridComponent>

          );
        }
      }

Here is my sample json,

[
    {
        "id":0,
        "Qr":1234567891,
        "Stat":"A",
        "name":"Hello world"

    },
    {
        "id":0,
        "Qr":1234567891,
        "Stat":"A",
        "name":"Hello world"

    },
    {
        "id":0,
        "Qr":1234567891,
        "Stat":"A",
        "name":"Hello world"

    },
    {
        "id":0,
        "Qr":1234567891,
        "Stat":"A",
        "name":"Hello world"

    },
    {
        "id":0,
        "Qr":1234567891,
        "Stat":"A",
        "name":"Hello world"

    },
    {
        "id":0,
        "Qr":1234567891,
        "Stat":"A",
        "name":"Hello world"

    }

]

I hope you can help me solve that problem .
Thank you

Body:
Please check this example where I used material ui for input field and table.

import React, {useState} from 'react';
import {makeStyles} from '@material-ui/core/styles';
import Table from '@material-ui/core/Table';
import TableBody from '@material-ui/core/TableBody';
import TableCell from '@material-ui/core/TableCell';
import TableContainer from '@material-ui/core/TableContainer';
import TableHead from '@material-ui/core/TableHead';
import TableRow from '@material-ui/core/TableRow';
import Paper from '@material-ui/core/Paper';
import TextField from "@material-ui/core/TextField";
import Button from "@material-ui/core/Button";

export default function FormExample() {
    const [rows, setRows] = useState([]);
    const [row, setRow] = useState({
        username: '',
        password: ''
    });

    function changeHandler(event) {
        setRow({...row, [event.target.name]: event.target.value});
    }

    return (
        <div>
            <form noValidate autoComplete="off">
                <TextField id="username" name="username" label="Username" onChange={changeHandler}/>
                <TextField id="password" name="password" label="Password" onChange={changeHandler}/>
                <Button variant="contained" color="primary" onClick={() => {
                    let data = [...rows];
                    data.push(row);
                    setRows(data);
                }}>
                    Save
                </Button>
            </form>

            <h3>User List</h3>
            <TableContainer component={Paper}>
                <Table aria-label="simple table">
                    <TableHead>
                        <TableRow>
                            <TableCell>Username</TableCell>
                            <TableCell>Password</TableCell>
                        </TableRow>
                    </TableHead>
                    <TableBody>
                        {rows.map((row) => (
                            <TableRow key={row.name}>
                                <TableCell>{row.username}</TableCell>
                                <TableCell>{row.password}</TableCell>
                            </TableRow>
                        ))}
                    </TableBody>
                </Table>
            </TableContainer>
        </div>
    );
}


问:
Using Google Maps Javascript API pinch-to-zoom on my own image
I'm trying to create a mobile-friendly web page that will allow a user to drag an  around in a
. I've got this working using the image.ontouchstart method. Now I want to make it so the user can pinch-to-zoom when viewing this from an iOS device (I'm currently browsing to my page locally from my iPad). From the research I've done so far, it seems like the way to go is to use the Google Maps Javascript API.

My question is:

It is possible to use the Google Maps Javascript API to leverage it's pinch-to-zoom capabilities on a regular image, and not just a map?

Every example I've seen sets up a google.maps.Map object and specifies a latitude/longitude. I just need it to work for any given  I place into my
. Does anyone know if this is possible, or know of any examples I could look at? Or maybe there is an easier way to do it on a regular image than using the Google API?

答:
I believe your options are fairly limited.  But if you can tolerate the user being aware that the map is underneath your image (because they'll see it for a split second after every zoom) then as a starting point, take a look at the answer at any technology to preview high definition photo, can zoom in and out like google maps.

It assumes you are starting with a high-definition image and that you don't want to load the whole image completely into the mobile browser just to display it completely zoomed out.  As you zoom in, the appropriate elements of the image (which has been broken into tiles) will be loaded.

I do not believe that there is an easy way to use the API as an image browser without having the maps at least hidden out of view under the image overlay, but this will give you a starting point at least to see what is (and perhaps isn't) possible.


问:
Instagram Public Api ( __a=1 ) is banned. Any alternative?
I used instagram public api (adding __a=1 to parameters of an url) to get a post detail (caption ,imageUrl, postType, likes, comments , viewsCount). But it seems that Instagram banned that recently and returned a 403. It also asks for login when I try to directly open a post by its usrl.

I tried to use the instagram private api (https://mgp25.github.io/) for getting post details, but after some requests instargam banned that too:

"throttled by instagram because of too many api requests"

Do you have any offer for an alternative?

答: Actually it is not really banned but now redirects with 302 to auth page. It seems like auth is required when Instagram account and query geoIPs are different. Alternative is to use official API. No scraping can be done, because the profile link now also requires authentication. You can do authenticated scraping but you are limited to 200 queries ( that Instagram sends to get data) per hour.</p>


问:
How do you check if string ends with another string in Ada?
There are canonical answers to this question for every popular language, even though that answer usually boils down to: "Use string.endsWith() from the standard library". For Ada, as far as I can find in the docs for the Fixed String package, there is no string.endswith function.

So, given two fixed strings A and B, how do you check if A ends with B?

```<code>declare
   A : constant String := "John Johnson";
   B : constant String := "son";
begin
   if A.Ends_With(B) then -- this doesn't compile
      Put_Line ("Yay!");
   end if;
end
</code>```

My intent is to establish a standard answer for Ada.

答:
Here is an example without any explicit loops.</p>

```<code>with Ada.Assertions; use Ada.Assertions;
with Ada.Text_IO; use Ada.Text_IO;

procedure Main is
   function Ends_With(Source : String; Pattern : String) return Boolean is
      result : Boolean := False;
   begin
      if Pattern'Length <= Source'Length then
         if Pattern'Length > 0 then
            result := Source((Source'Last - Pattern'Length + 1)..Source'Last) = Pattern;
         else
            result := True;
         end if;
      end if;
      return result;
   end Ends_With;

begin

   Assert (Ends_With ("John Johnson", "son") = True);

   Assert (Ends_With (""  , ""  ) = True);
   Assert (Ends_With (" " , ""  ) = True);
   Assert (Ends_With (""  , " " ) = False);
   Assert (Ends_With (" " , " " ) = True);

   Assert (Ends_With (""  , "n" ) = False);
   Assert (Ends_With ("n"  , "" ) = True);

   Assert (Ends_With ("n ", "n ") = True);
   Assert (Ends_With (" n", "n" ) = True);
   Assert (Ends_With ("n" , " n") = False);
   Assert (Ends_With (" n", " n") = True);

   Put_Line("All OK");
end Main;
</code>```

Body:
There are canonical answers to this question for every popular language, even though that answer usually boils down to: "Use string.endsWith() from the standard library". For Ada, as far as I can find in the docs for the Fixed String package, there is no string.endswith function.

So, given two fixed strings A and B, how do you check if A ends with B?

declare
   A : constant String := "John Johnson";
   B : constant String := "son";
begin
   if A.Ends_With(B) then -- this doesn't compile
      Put_Line ("Yay!");
   end if;
end

My intent is to establish a standard answer for Ada.

Body:
Here is an example without any explicit loops.

with Ada.Assertions; use Ada.Assertions;
with Ada.Text_IO; use Ada.Text_IO;

procedure Main is
   function Ends_With(Source : String; Pattern : String) return Boolean is
      result : Boolean := False;
   begin
      if Pattern'Length <= Source'Length then
         if Pattern'Length > 0 then
            result := Source((Source'Last - Pattern'Length + 1)..Source'Last) = Pattern;
         else
            result := True;
         end if;
      end if;
      return result;
   end Ends_With;

begin

   Assert (Ends_With ("John Johnson", "son") = True);

   Assert (Ends_With (""  , ""  ) = True);
   Assert (Ends_With (" " , ""  ) = True);
   Assert (Ends_With (""  , " " ) = False);
   Assert (Ends_With (" " , " " ) = True);

   Assert (Ends_With (""  , "n" ) = False);
   Assert (Ends_With ("n"  , "" ) = True);

   Assert (Ends_With ("n ", "n ") = True);
   Assert (Ends_With (" n", "n" ) = True);
   Assert (Ends_With ("n" , " n") = False);
   Assert (Ends_With (" n", " n") = True);

   Put_Line("All OK");
end Main;


问:
String and Final
What is difference between in the following statements

```<code>String name = "Tiger";

final String name ="Tiger";
</code>```

Although the String class is final class, why do we need to create a String "CONSTANT" variable as final?

答:
To deduce that String objects are Final by default is in itself a vague statement. The basics of Java dictate that if an instance variable is not pointing to a memory location it becomes eligible for Garbage collection. The same thing happens with the String objects. They are immutable but their references can be changed. To overcome this we can use "Final String s1 = "Final String" " the final keyword won't allow any assignment to s1 except at the time of First Declaration, making it truly immutable.

```<code>public class DemoStringF
{
    String s1; //Declaring an Instance Variable to type String.

    public static void main(String... args)
    {
        DemoStringF d = new DemoStringF ();
        d.s1 = "Intializing s1 here"; //Initializing the s1

          System.out.println("Value ref. by s1 is " +d.s1); //Displays the String
                                                            by which s1 is
                                                            initialized.

         System.out.println("Value of s1 is " +d.s1.hashCode()); //Displays the
                                                                 value of the s1.

         d.s1 = d.s1.concat(" Adding String to s1"); //Changing the value ref. by
                                                       s1.
        System.out.println("Value ref. by s1 after concat() is " +d.s1);
                                                    //Displays a new value of s1.

        System.out.println("Value of s1 is " +d.s1.hashCode()); //Displays
                                                            the value of the s1.
    }

    }
</code>```

Title: String and Final

Body:
What is difference between in the following statements

String name = "Tiger";

final String name ="Tiger";

Although the String class is final class, why do we need to create a String "CONSTANT" variable as final?

Body:
To deduce that String objects are Final by default is in itself a vague statement. The basics of Java dictate that if an instance variable is not pointing to a memory location it becomes eligible for Garbage collection. The same thing happens with the String objects. They are immutable but their references can be changed. To overcome this we can use "Final String s1 = "Final String" " the final keyword won't allow any assignment to s1 except at the time of First Declaration, making it truly immutable.

public class DemoStringF
{
    String s1; //Declaring an Instance Variable to type String.

    public static void main(String... args)
    {
        DemoStringF d = new DemoStringF ();
        d.s1 = "Intializing s1 here"; //Initializing the s1

          System.out.println("Value ref. by s1 is " +d.s1); //Displays the String
                                                            by which s1 is
                                                            initialized.

         System.out.println("Value of s1 is " +d.s1.hashCode()); //Displays the
                                                                 value of the s1.

         d.s1 = d.s1.concat(" Adding String to s1"); //Changing the value ref. by
                                                       s1.
        System.out.println("Value ref. by s1 after concat() is " +d.s1);
                                                    //Displays a new value of s1.

        System.out.println("Value of s1 is " +d.s1.hashCode()); //Displays
                                                            the value of the s1.
    }

    }