问:
How to serve devpi with https?
I have an out-of-the-box devpi-server running on http://

I need to get it to work on https:// instead.

I already have the certificates for the domain.

I followed the documentation for nginx-site-config, and created the /etc/nginx/conf.d/domain.conf file that has the server{} block that points to my certificates (excerpt below).

However, my devpi-server --start --init is totally ignoring any/all nginx configurations.
How do i point the devpi-server to use the nginx configurations? Is it even possible, or am I totally missing the point?

/etc/nginx/conf.d/domain.conf file contents:

server {
    server_name localhost $hostname "";

    listen              8081 ssl default_server;
    listen              [::]:8081 ssl default_server;
    server_name         domain;
    ssl_certificate     /root/certs/domain/domain.crt;
    ssl_certificate_key /root/certs/domain/domain.key;
    ssl_protocols       TLSv1.1 TLSv1.2;
    ssl_ciphers         EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH;

    gzip             on;
    gzip_min_length  2000;
    gzip_proxied     any;
    gzip_types       application/json;

    proxy_read_timeout 60s;
    client_max_body_size 64M;

    # set to where your devpi-server state is on the filesystem
    root /root/.devpi/server;

    # try serving static files directly
    location ~ /\+f/ {
        # workaround to pass non-GET/HEAD requests through to the named location below
        error_page 418 = @proxy_to_app;
        if ($request_method !~ (GET)|(HEAD)) {
            return 418;
        }

        expires max;
        try_files /+files$uri @proxy_to_app;
    }
    # try serving docs directly
    location ~ /\+doc/ {
        try_files $uri @proxy_to_app;
    }
    location / {
        # workaround to pass all requests to / through to the named location below
        error_page 418 = @proxy_to_app;
        return 418;
    }
    location @proxy_to_app {
        proxy_pass https://localhost:8081;
        proxy_set_header X-outside-url $scheme://$host:$server_port;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-Proto https;
    }
}
```

答:
This is the answer I gave to the same question on superuser.

Devpi doesn't know anything about Nginx, it will just serve HTTP traffic. When we want to interact with a web-app via HTTPS instead, we as the client need to talk to a front-end which can handle it (Nginx) which will in turn communicate with our web-app. This application of Nginx is known as a reverse proxy. As a reverse proxy we can also benefit from Nginx's ability to serve static files more efficiently than getting our web-app to do it itself (hence the "try serving..." location blocks).

Here is a complete working Nginx config that I use for devpi. Note that this is /etc/nginx/nginx.conf file rather than a domain config like yours because I'm running Nginx and Devpi in docker with compose but you should be able to pull out what you need:

worker_processes 1;

events {
    worker_connections 1024;
}

http {
    # Define the location for devpi
    upstream pypi-backend {
        server localhost:8080;
    }

    # Redirect HTTP to HTTPS
    server {
        listen 80;
        listen [::]:80;
        server_name _;
        return 301 https://$host$request_uri;
    }

    server {
        listen 443 ssl;
        server_name example.co.uk; # This is the accessing address eg. https://example.co.uk

        root /devpi/server; # This is where your devpi server directory is
        gzip             on;
        gzip_min_length  2000;
        gzip_proxied     any;

        proxy_read_timeout 60s;
        client_max_body_size 64M;

        ssl_certificate             /etc/nginx/certs/cert.crt; Path to certificate
        ssl_certificate_key         /etc/nginx/certs/cert.key; Path to certificate key

        ssl_session_cache           builtin:1000  shared:SSL:10m;
        ssl_protocols               TLSv1 TLSv1.1 TLSv1.2;
        ssl_ciphers                 HIGH:!aNULL:!eNULL:!EXPORT:!CAMELLIA:!DES:!MD5:!PSK:!RC4;
        ssl_prefer_server_ciphers   on;

        access_log                  /var/log/nginx/pypi.access.log;

        # try serving static files directly
        location ~ /\+f/ {
            error_page 418 = @pypi_backend;
            if ($request_method !~ (GET)|(HEAD)) {
                return 418;
            }

            expires max;
            try_files /+files$uri @pypi_backend;
        }

        # try serving docs directly
        location ~ /\+doc/ {
            try_files $uri @pypi_backend;
        }

        location / {
            error_page 418 = @pypi_backend;
            return 418;
        }

        location @pypi_backend {
            proxy_pass              http://pypi-backend; # Using the upstream definition
            proxy_redirect          off;
            proxy_set_header        Host $host;
            proxy_set_header        X-Real-IP $remote_addr;
            proxy_set_header        X-outside-url $scheme://$host:$server_port;
            proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header        X-Forwarded-Host $server_name;
        }
    }
}

```

<p>With Nginx using this configuration and devpi running on <code>http://localhost:8080</code>, you should be able to access <code>https://localhost</code> or with your machine with appropriate DNS <code>https://example.co.uk</code>. A request will be:</p>

```client (HTTPS) > Nginx (HTTP) > devpi (HTTP) > Nginx (HTTPS) > client
```

This also means that you will need to make sure that Nginx is running yourself, as devpi start won't know any better. You should at the very least see an Nginx welcome page.

Title: How to serve devpi with https?

Body:
This is the answer I gave to the same question on superuser.

Devpi doesn't know anything about Nginx, it will just serve HTTP traffic. When we want to interact with a web-app via HTTPS instead, we as the client need to talk to a front-end which can handle it (Nginx) which will in turn communicate with our web-app. This application of Nginx is known as a reverse proxy. As a reverse proxy we can also benefit from Nginx's ability to serve static files more efficiently than getting our web-app to do it itself (hence the "try serving..." location blocks).

Here is a complete working Nginx config that I use for devpi. Note that this is /etc/nginx/nginx.conf file rather than a domain config like yours because I'm running Nginx and Devpi in docker with compose but you should be able to pull out what you need:

worker_processes 1;

events {
    worker_connections 1024;
}

http {
    # Define the location for devpi
    upstream pypi-backend {
        server localhost:8080;
    }

    # Redirect HTTP to HTTPS
    server {
        listen 80;
        listen [::]:80;
        server_name _;
        return 301 https://$host$request_uri;
    }

    server {
        listen 443 ssl;
        server_name example.co.uk; # This is the accessing address eg. https://example.co.uk

        root /devpi/server; # This is where your devpi server directory is
        gzip             on;
        gzip_min_length  2000;
        gzip_proxied     any;

        proxy_read_timeout 60s;
        client_max_body_size 64M;

        ssl_certificate             /etc/nginx/certs/cert.crt; Path to certificate
        ssl_certificate_key         /etc/nginx/certs/cert.key; Path to certificate key

        ssl_session_cache           builtin:1000  shared:SSL:10m;
        ssl_protocols               TLSv1 TLSv1.1 TLSv1.2;
        ssl_ciphers                 HIGH:!aNULL:!eNULL:!EXPORT:!CAMELLIA:!DES:!MD5:!PSK:!RC4;
        ssl_prefer_server_ciphers   on;

        access_log                  /var/log/nginx/pypi.access.log;

        # try serving static files directly
        location ~ /\+f/ {
            error_page 418 = @pypi_backend;
            if ($request_method !~ (GET)|(HEAD)) {
                return 418;
            }

            expires max;
            try_files /+files$uri @pypi_backend;
        }

        # try serving docs directly
        location ~ /\+doc/ {
            try_files $uri @pypi_backend;
        }

        location / {
            error_page 418 = @pypi_backend;
            return 418;
        }

        location @pypi_backend {
            proxy_pass              http://pypi-backend; # Using the upstream definition
            proxy_redirect          off;
            proxy_set_header        Host $host;
            proxy_set_header        X-Real-IP $remote_addr;
            proxy_set_header        X-outside-url $scheme://$host:$server_port;
            proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header        X-Forwarded-Host $server_name;
        }
    }
}

With Nginx using this configuration and devpi running on http://localhost:8080, you should be able to access https://localhost or with your machine with appropriate DNS https://example.co.uk. A request will be:

client (HTTPS) > Nginx (HTTP) > devpi (HTTP) > Nginx (HTTPS) > client

This also means that you will need to make sure that Nginx is running yourself, as devpi start won't know any better. You should at the very least see an Nginx welcome page.


来源: stackexchange

问:
How do i alter my Current code to read directly from the IDR register
Modify the code for ReadJoystick() to read the IDR register directly for the ports associated
with the joystick inputs. The aim is to minimise the number of reads to the register. The code in
the template makes an individual call for each of the inputs pins, even though some of the pins are
on the same ports.
You can refer to the HAL code for inspiration. Use the defined values in the HAL for addressing
registers rather than creating new ones.

Example Code Given to Me

```<code>GPIO_PinState HAL_GPIO_ReadPin(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin)
{
    GPIO_PinState bitstatus;
     /* Check the parameters */
    assert_param(IS_GPIO_PIN(GPIO_Pin));
if ((GPIOx->IDR & GPIO_Pin) != (uint32_t)GPIO_PIN_RESET)
{
    bitstatus = GPIO_PIN_SET;
}
else
{
    bitstatus = GPIO_PIN_RESET;
}
return bitstatus;
</code>```

}

Code I require to Alter

// REPLACE THE FOLLOW CODE WITH YOUR SOLUTION

```<code>uint8_t
ReadJoystick ()
{
  uint8_t JoystickPosition = 0;

  // Get current joystick value
  if (HAL_GPIO_ReadPin (JOY_A_GPIO_Port, JOY_A_Pin) == GPIO_PIN_RESET)
  {
    JoystickPosition = 'L';
  }
  else if (HAL_GPIO_ReadPin (JOY_B_GPIO_Port, JOY_B_Pin) ==
GPIO_PIN_RESET)
  {
JoystickPosition = 'U';
  }
  else if (HAL_GPIO_ReadPin (JOY_C_GPIO_Port, JOY_C_Pin) ==
 GPIO_PIN_RESET)
   {
     JoystickPosition = 'D';
   }
   else if (HAL_GPIO_ReadPin (JOY_D_GPIO_Port, JOY_D_Pin) ==
 GPIO_PIN_RESET)
    {
      JoystickPosition = 'R';
    }
   else if (HAL_GPIO_ReadPin (JOY_CTR_GPIO_Port, JOY_CTR_Pin) ==
GPIO_PIN_RESET)
  {
    JoystickPosition = 'C';
  }

  return JoystickPosition;
 }
</code>```

So I Understand that my current code is reading each pin although i've been asked to alter this to read directly from the IDR register. I'm really new to embedded systems programming and just looking for someone to guide me with altering this code

答:
Before I post my solution I need to advice against reading from registers directly. Whoever is giving you this task wants to be a smart-ass and thinks that calling the HAL_GPIO_ReadPin function results in some kind of unbearable overhead which is most definitely not true. In fact, if all the port defines from JOY_A_GPIO_Port to JOY_CTR_GPIO_Port are different and optimizations are turned on, then the compiler is very likely to produce optimal code. Furthermore replacing the function call with direct register reads reduces the reuse-ability of the application code.

Anyhow, lets apply some changes...

Lets start off with a 1:1 translation which uses direct register access:

```<code>uint8_t ReadJoystick()
{
  uint8_t JoystickPosition = 0u;

  // Get current joystick value
  if ((JOY_A_GPIO_Port->IDR & JOY_A_Pin) == GPIO_PIN_RESET)
    JoystickPosition = 'L';
  else if ((JOY_B_GPIO_Port->IDR & JOY_B_Pin) == GPIO_PIN_RESET)
    JoystickPosition = 'U';
  else if ((JOY_C_GPIO_Port->IDR & JOY_C_Pin) == GPIO_PIN_RESET)
    JoystickPosition = 'D';
  else if ((JOY_D_GPIO_Port->IDR & JOY_D_Pin) == GPIO_PIN_RESET)
    JoystickPosition = 'R';
  else if ((JOY_CTR_GPIO_Port->IDR & JOY_CTR_Pin) == GPIO_PIN_RESET)
    JoystickPosition = 'C';

  return JoystickPosition;
}
</code>```

In case you haven't fully understood the code yet:

xxx_Port->IDR reads the input data register for the whole port

A bitwise & masks the input and gives us only the specific pin we are
looking for

As I mentioned before this is not going to bring any performance improvements whatsoever.

However we might improve the code a little if some of the port defines are equal and point to the same memory address. In practice this is common because embedded designers are usually keen to join IO pins of an external device on a single port. E.g. lets assume JOY_A_GPIO_Port == JOY_B_GPIO_Port, then we could read the input data register of this port just once into a local variable like this:

```<code>uint8_t ReadJoystick()
{
  uint8_t JoystickPosition = 0;

  // Read input data register for AB once
  uint32_t ab_port = JOY_AB_GPIO_Port->IDR;

  // Get current joystick value
  if ((ab_port & JOY_A_Pin) == GPIO_PIN_RESET)
    JoystickPosition = 'L';
  else if ((ab_port & JOY_B_Pin) == GPIO_PIN_RESET)
    JoystickPosition = 'U';
  else if ((JOY_C_GPIO_Port->IDR & JOY_C_Pin) == GPIO_PIN_RESET)
    JoystickPosition = 'D';
  else if ((JOY_D_GPIO_Port->IDR & JOY_D_Pin) == GPIO_PIN_RESET)
    JoystickPosition = 'R';
  else if ((JOY_CTR_GPIO_Port->IDR & JOY_CTR_Pin) == GPIO_PIN_RESET)
    JoystickPosition = 'C';

  return JoystickPosition;
}
</code>```

This effectively just saved us one register read. Of course the more joystick pins there are on a single port the better.

/edit
ST provides an alternative function for reading a whole port in their "LL" library:

```<code>__STATIC_INLINE uint32_t LL_GPIO_ReadInputPort(GPIO_TypeDef *GPIOx)
{
  return (uint32_t)(READ_REG(GPIOx->IDR));
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Modify the code for ReadJoystick() to read the IDR register directly for the ports associated
with the joystick inputs. The aim is to minimise the number of reads to the register. The code in
the template makes an individual call for each of the inputs pins, even though some of the pins are
on the same ports.
You can refer to the HAL code for inspiration. Use the defined values in the HAL for addressing
registers rather than creating new ones.

Example Code Given to Me

GPIO_PinState HAL_GPIO_ReadPin(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin)
{
    GPIO_PinState bitstatus;
     /* Check the parameters */
    assert_param(IS_GPIO_PIN(GPIO_Pin));
if ((GPIOx->IDR & GPIO_Pin) != (uint32_t)GPIO_PIN_RESET)
{
    bitstatus = GPIO_PIN_SET;
}
else
{
    bitstatus = GPIO_PIN_RESET;
}
return bitstatus;

}

Code I require to Alter

// REPLACE THE FOLLOW CODE WITH YOUR SOLUTION

uint8_t
ReadJoystick ()
{
  uint8_t JoystickPosition = 0;

  // Get current joystick value
  if (HAL_GPIO_ReadPin (JOY_A_GPIO_Port, JOY_A_Pin) == GPIO_PIN_RESET)
  {
    JoystickPosition = 'L';
  }
  else if (HAL_GPIO_ReadPin (JOY_B_GPIO_Port, JOY_B_Pin) ==
GPIO_PIN_RESET)
  {
JoystickPosition = 'U';
  }
  else if (HAL_GPIO_ReadPin (JOY_C_GPIO_Port, JOY_C_Pin) ==
 GPIO_PIN_RESET)
   {
     JoystickPosition = 'D';
   }
   else if (HAL_GPIO_ReadPin (JOY_D_GPIO_Port, JOY_D_Pin) ==
 GPIO_PIN_RESET)
    {
      JoystickPosition = 'R';
    }
   else if (HAL_GPIO_ReadPin (JOY_CTR_GPIO_Port, JOY_CTR_Pin) ==
GPIO_PIN_RESET)
  {
    JoystickPosition = 'C';
  }

  return JoystickPosition;
 }

So I Understand that my current code is reading each pin although i've been asked to alter this to read directly from the IDR register. I'm really new to embedded systems programming and just looking for someone to guide me with altering this code

Body:
Before I post my solution I need to advice against reading from registers directly. Whoever is giving you this task wants to be a smart-ass and thinks that calling the HAL_GPIO_ReadPin function results in some kind of unbearable overhead which is most definitely not true. In fact, if all the port defines from JOY_A_GPIO_Port to JOY_CTR_GPIO_Port are different and optimizations are turned on, then the compiler is very likely to produce optimal code. Furthermore replacing the function call with direct register reads reduces the reuse-ability of the application code.

Anyhow, lets apply some changes...

Lets start off with a 1:1 translation which uses direct register access:

uint8_t ReadJoystick()
{
  uint8_t JoystickPosition = 0u;

  // Get current joystick value
  if ((JOY_A_GPIO_Port->IDR & JOY_A_Pin) == GPIO_PIN_RESET)
    JoystickPosition = 'L';
  else if ((JOY_B_GPIO_Port->IDR & JOY_B_Pin) == GPIO_PIN_RESET)
    JoystickPosition = 'U';
  else if ((JOY_C_GPIO_Port->IDR & JOY_C_Pin) == GPIO_PIN_RESET)
    JoystickPosition = 'D';
  else if ((JOY_D_GPIO_Port->IDR & JOY_D_Pin) == GPIO_PIN_RESET)
    JoystickPosition = 'R';
  else if ((JOY_CTR_GPIO_Port->IDR & JOY_CTR_Pin) == GPIO_PIN_RESET)
    JoystickPosition = 'C';

  return JoystickPosition;
}

In case you haven't fully understood the code yet:

xxx_Port->IDR reads the input data register for the whole port

A bitwise & masks the input and gives us only the specific pin we are
looking for

As I mentioned before this is not going to bring any performance improvements whatsoever.

However we might improve the code a little if some of the port defines are equal and point to the same memory address. In practice this is common because embedded designers are usually keen to join IO pins of an external device on a single port. E.g. lets assume JOY_A_GPIO_Port == JOY_B_GPIO_Port, then we could read the input data register of this port just once into a local variable like this:

uint8_t ReadJoystick()
{
  uint8_t JoystickPosition = 0;

  // Read input data register for AB once
  uint32_t ab_port = JOY_AB_GPIO_Port->IDR;

  // Get current joystick value
  if ((ab_port & JOY_A_Pin) == GPIO_PIN_RESET)
    JoystickPosition = 'L';
  else if ((ab_port & JOY_B_Pin) == GPIO_PIN_RESET)
    JoystickPosition = 'U';
  else if ((JOY_C_GPIO_Port->IDR & JOY_C_Pin) == GPIO_PIN_RESET)
    JoystickPosition = 'D';
  else if ((JOY_D_GPIO_Port->IDR & JOY_D_Pin) == GPIO_PIN_RESET)
    JoystickPosition = 'R';
  else if ((JOY_CTR_GPIO_Port->IDR & JOY_CTR_Pin) == GPIO_PIN_RESET)
    JoystickPosition = 'C';

  return JoystickPosition;
}

This effectively just saved us one register read. Of course the more joystick pins there are on a single port the better.

/edit
ST provides an alternative function for reading a whole port in their "LL" library:

__STATIC_INLINE uint32_t LL_GPIO_ReadInputPort(GPIO_TypeDef *GPIOx)
{
  return (uint32_t)(READ_REG(GPIOx->IDR));
}


问:
How to change Kendo autocomplete filed slimier as Angular material input fields?
I want to change the kendo autocomplete filed the same as the angular material inputs.

the kendo UI autocomplete field is like below

I want to change above kendo UI autocomplete field is like below

the HTML for the kendo UI autocomplete field is like below

```<code><div class="example-wrapper">
    <kendo-autocomplete [data]="listItems" [placeholder]="'e.g. Andorra'">
    </kendo-autocomplete>
</div>
</code>```

the HTML for the material UI is like below.

```<code><mat-form-field class="example-full-width">
    <input type="text" placeholder="Groups"  matInput [formControl]="queryField">
</mat-form-field>
</code>```

is it possible to do that?

答:
If you are using kendo, you can wrap kendo components in material design.

you can install kendo-theme-material in your project.

```<code>npm install --save @progress/kendo-theme-material
</code>```

And in your angular.json file add path to kendo-theme-material.

```<code>{
  "apps": [
    {
      "styles": [
        "node_modules/@progress/kendo-theme-material/dist/all.css"
      ]
    }
  ]
}
</code>```

It will convert all your kendo components in material design.

Body:
I want to change the kendo autocomplete filed the same as the angular material inputs.

the kendo UI autocomplete field is like below

I want to change above kendo UI autocomplete field is like below

the HTML for the kendo UI autocomplete field is like below

    <kendo-autocomplete [data]="listItems" [placeholder]="'e.g. Andorra'">
    </kendo-autocomplete>

the HTML for the material UI is like below.

<mat-form-field class="example-full-width">
    <input type="text" placeholder="Groups"  matInput [formControl]="queryField">
</mat-form-field>

is it possible to do that?

Body:
If you are using kendo, you can wrap kendo components in material design.

you can install kendo-theme-material in your project.

npm install --save @progress/kendo-theme-material

And in your angular.json file add path to kendo-theme-material.

{
  "apps": [
    {
      "styles": [
        "node_modules/@progress/kendo-theme-material/dist/all.css"
      ]
    }
  ]
}

It will convert all your kendo components in material design.


问:
Configure Docker to use a proxy server
I have installed docker on windows , when I try to run hello-world for testing on docker. I get following error

Unable to find image

My computer is using proxy server for communication. I need to configure that server in the docker. I know proxy server address and port. Where I need to update this setting. I tried using https://docs.docker.com/network/proxy/#set-the-environment-variables-manually.
It is  not working.

答:
The answer of Alexandre Mélard at question Cannot download Docker images behind a proxy works, here is the simplified version:

Find out the systemd script or init.d script path of the docker service by running:service docker status or systemctl status docker, for example in Ubuntu16.04 it's at /lib/systemd/system/docker.service

Edit the script for example sudo vim /lib/systemd/system/docker.service by adding the following in the [Service] section:

```<code> Environment="HTTP_PROXY=http://<proxy_host>:<port>"
 Environment="HTTPS_PROXY=http://<proxy_host>:<port>"
 Environment="NO_PROXY=<no_proxy_host_or_ip>,<e.g.:172.10.10.10>"
</code>```

Reload and restart the daemon: sudo systemctl daemon-reload && sudo systemctl restart docker or sudo service docker restart

Verify: docker info | grep -i proxy should show something like:

```<code>HTTP Proxy: http://10.10.10.10:3128
HTTPS Proxy: http://10.10.10.10:3128
</code>```

This adds the proxy for docker pull, which is the problem of the question. If for running or building docker a proxy is needed, either configure ~/.docker/config as the official docs explained, or change Dockerfile so there is proxy inside the container.

Title: Configure Docker to use a proxy server

Body:
The answer of Alexandre Mélard at question Cannot download Docker images behind a proxy works, here is the simplified version:

Find out the systemd script or init.d script path of the docker service by running:service docker status or systemctl status docker, for example in Ubuntu16.04 it's at /lib/systemd/system/docker.service

Edit the script for example sudo vim /lib/systemd/system/docker.service by adding the following in the [Service] section:

 Environment="HTTP_PROXY=http://<proxy_host>:<port>"
 Environment="HTTPS_PROXY=http://<proxy_host>:<port>"
 Environment="NO_PROXY=<no_proxy_host_or_ip>,<e.g.:172.10.10.10>"

Reload and restart the daemon: sudo systemctl daemon-reload && sudo systemctl restart docker or sudo service docker restart

Verify: docker info | grep -i proxy should show something like:

HTTP Proxy: http://10.10.10.10:3128
HTTPS Proxy: http://10.10.10.10:3128

This adds the proxy for docker pull, which is the problem of the question. If for running or building docker a proxy is needed, either configure ~/.docker/config as the official docs explained, or change Dockerfile so there is proxy inside the container.


问:
Spring MVC Annotated Controller
I have a controller which has a few actions, which are triggered by hitting various buttons on the page.  I would like to have a default action, but am unsure how to annotate the method.  Here is an example:

```<code>@Controller
@RequestMapping("/view.jsp")
public class ExampleController {

    @RequestMapping(method = RequestMethod.GET)
    public ModelAndView displayResults() {
        ModelAndView mav = new ModelAndView("view");
        mav.addObject("queryResults", methodToQueryDBForListing());
        return mav;
    }

    @RequestMapping(method = RequestMethod.POST, params="submit=Action 1")
    public ModelAndView action1(@RequestParam("selectedItemKey") String key) {
        ModelAndView mav = new ModelAndView("action1");
        //Business logic
        return mav;
    }

    @RequestMapping(method = RequestMethod.POST, params="submit=Action 2")
    public ModelAndView action2(@RequestParam("selectedItemKey") String key) {
        ModelAndView mav = new ModelAndView("action2");
        //Business logic
        return mav;
    }

    //A few more methods which basically do what action1 and action2 do
}
</code>```

How can I annotate a method which will act on a POST with any submit button pressed with no key selected?

I have tried:

```<code>@RequestMethod(method = RequestMethod.POST, params="!selectedItemKey")
@RequestMethod(method = RequestMethod.POST)
</code>```

I'd really hate it if I had to set required = false on each of the methods which take RequestParams and then conditionally check to see if one comes in or not...  Is there a way to annotate this to work properly?

答:
I'm not so familiar with annotated spring-mvc but I can remember that when extending a MultiActionController you can specify a default entry point by defining the following spring config:

```<code><bean name="myController"
class="foo.bar.MyController">
<property name="methodNameResolver">
    <bean class="org.springframework.web.servlet.mvc.multiaction.ParameterMethodNameResolver">
        <property name="defaultMethodName" value="init" />
    </bean>
</property>
</code>```

```<code>
package foo.bar

public class MyController extends MultiActionController {

    /**
     * Called when no parameter was passed.
     */
    public ModelAndView init(HttpServletRequest request,
            HttpServletResponse response) {
        return new ModelAndView("myDefaultView");
    }

    /**
     * action=method1
     */
    public void method1(HttpServletRequest request,
            HttpServletResponse response) {
        return new ModelAndView("method1");
    }

    /**
     * action=method2
     */
    public void method2(HttpServletRequest request,
            HttpServletResponse response) {
        return new ModelAndView("method2");
    }
}
</code>```

So maybe in this instance you could solve this by configuring your controller over spring config instead of using annotations.

ContentLicense: CC BY-SA 3.0

Title: Spring MVC Annotated Controller

Body:
I have a controller which has a few actions, which are triggered by hitting various buttons on the page.  I would like to have a default action, but am unsure how to annotate the method.  Here is an example:

@Controller
@RequestMapping("/view.jsp")
public class ExampleController {

    @RequestMapping(method = RequestMethod.GET)
    public ModelAndView displayResults() {
        ModelAndView mav = new ModelAndView("view");
        mav.addObject("queryResults", methodToQueryDBForListing());
        return mav;
    }

    @RequestMapping(method = RequestMethod.POST, params="submit=Action 1")
    public ModelAndView action1(@RequestParam("selectedItemKey") String key) {
        ModelAndView mav = new ModelAndView("action1");
        //Business logic
        return mav;
    }

    @RequestMapping(method = RequestMethod.POST, params="submit=Action 2")
    public ModelAndView action2(@RequestParam("selectedItemKey") String key) {
        ModelAndView mav = new ModelAndView("action2");
        //Business logic
        return mav;
    }

    //A few more methods which basically do what action1 and action2 do
}

How can I annotate a method which will act on a POST with any submit button pressed with no key selected?

I have tried:

@RequestMethod(method = RequestMethod.POST, params="!selectedItemKey")
@RequestMethod(method = RequestMethod.POST)

I'd really hate it if I had to set required = false on each of the methods which take RequestParams and then conditionally check to see if one comes in or not...  Is there a way to annotate this to work properly?

Body:
I'm not so familiar with annotated spring-mvc but I can remember that when extending a MultiActionController you can specify a default entry point by defining the following spring config:

<bean name="myController"
class="foo.bar.MyController">
<property name="methodNameResolver">
    <bean class="org.springframework.web.servlet.mvc.multiaction.ParameterMethodNameResolver">
        <property name="defaultMethodName" value="init" />
    </bean>
</property>

package foo.bar

public class MyController extends MultiActionController {

    /**
     * Called when no parameter was passed.
     */
    public ModelAndView init(HttpServletRequest request,
            HttpServletResponse response) {
        return new ModelAndView("myDefaultView");
    }

    /**
     * action=method1
     */
    public void method1(HttpServletRequest request,
            HttpServletResponse response) {
        return new ModelAndView("method1");
    }

    /**
     * action=method2
     */
    public void method2(HttpServletRequest request,
            HttpServletResponse response) {
        return new ModelAndView("method2");
    }
}

So maybe in this instance you could solve this by configuring your controller over spring config instead of using annotations.


问:
How to get state of input field by clicking at parent  element?
I have an input checkbox field inside a label tag in html with bootstrap 4 and Angular 7. And i am calling a function on click on input checkbox and passing its state "($event.target.checked)" as one of the arguments. But all i receive is "undefined". On other hand if i call the function directly from input:checkbox i.e. without  tag ass the parent element then it works perfectly fine. But i need the former option to work.

Case 1:
">div>

label (click)="onChange('father', $event.target.checked, 'diabetes')" class="btn btn-sm rounded-pill position-relative mb-2 mx-2">
  input type="checkbox" name="diabetes" autocomplete="off"> Father
  /label
  "

Case 2:
">div>

input type="checkbox" (click)="onChange('father', $event.target.checked, 'diabetes')" name="" id="">Father
  /div>"

When i console both the above in my function, i receive undefined in 1st case with label outside the input field and it works just fine without label as shown in case 2 and provides true and false as results. Can anyone help me to get true and false values in case 1 also.

答:
That's because you listen to click eventd on your checkbox.

Intsead, you should listen to (change) event :

```<code>(change)="onChange('father', $event, 'diabetes')"
</code>```

This way, the function will be called everytime the value of the checkbox changes.

Title: How to get state of input field by clicking at parent <label> element?

Body:
That's because you listen to click eventd on your checkbox.

Intsead, you should listen to (change) event :

(change)="onChange('father', $event, 'diabetes')"

This way, the function will be called everytime the value of the checkbox changes.


问:
efficient python array to numpy array conversion
I get a big array (image with 12 Mpix) in the array format from the python standard lib.
Since I want to perform operations on those array, I wish to convert it to a numpy array.
I tried the following:

```<code>import numpy
import array
from datetime import datetime
test = array.array('d', [0]*12000000)
t = datetime.now()
numpy.array(test)
print datetime.now() - t
</code>```

I get a result between one or two seconds: equivalent to a loop in python.

Is there a more efficient way of doing this conversion?

答:
asarray(x) is almost always the best choice for any array-like object.

array and fromiter are slow because they perform a copy. Using asarray allows this copy to be elided:

>>> import array
>>> import numpy as np
>>> test = array.array('d', [0]*12000000)
```

<pre class="lang-py prettyprint-override"><code># very slow - this makes multiple copies that grow each time
>>> %timeit np.fromiter(test, dtype=test.typecode)
626 ms ± 3.97 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

# fast memory copy
>>> %timeit np.array(test)
63.5 ms ± 639 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

# which is equivalent to doing the fast construction followed by a copy
>>> %timeit np.asarray(test).copy()
63.4 ms ± 371 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

# so doing just the construction is way faster
>>> %timeit np.asarray(test)
1.73 µs ± 70.2 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

# marginally faster, but at the expense of verbosity and type safety if you
# get the wrong type
>>> %timeit np.frombuffer(test, dtype=test.typecode)
1.07 µs ± 27.3 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

</code>```

Body:
I get a big array (image with 12 Mpix) in the array format from the python standard lib.
Since I want to perform operations on those array, I wish to convert it to a numpy array.
I tried the following:

import numpy
import array
from datetime import datetime
test = array.array('d', [0]*12000000)
t = datetime.now()
numpy.array(test)
print datetime.now() - t

I get a result between one or two seconds: equivalent to a loop in python.

Is there a more efficient way of doing this conversion?

Body:
asarray(x) is almost always the best choice for any array-like object.

array and fromiter are slow because they perform a copy. Using asarray allows this copy to be elided:

>>> import array
>>> import numpy as np
>>> test = array.array('d', [0]*12000000)

# very slow - this makes multiple copies that grow each time
>>> %timeit np.fromiter(test, dtype=test.typecode)
626 ms ± 3.97 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

# fast memory copy
>>> %timeit np.array(test)
63.5 ms ± 639 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

# which is equivalent to doing the fast construction followed by a copy
>>> %timeit np.asarray(test).copy()
63.4 ms ± 371 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

# so doing just the construction is way faster
>>> %timeit np.asarray(test)
1.73 µs ± 70.2 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

# marginally faster, but at the expense of verbosity and type safety if you
# get the wrong type
>>> %timeit np.frombuffer(test, dtype=test.typecode)
1.07 µs ± 27.3 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)


问:
How add a new account in App Services "MySql In App" on Microsoft Azure
I want to import a data base on Azure and I need to connect this one to my website but i need the identifiant and password. Azure is using phpMyAdmin for configure the data base and at the begining i was connected with "azure" id.
So now i want to create a new account to connect me at my data base MySQL in app.

I'm already try to add a new line in the file : MYSQLCONNSTR_localdb.ini and delete this file : MYSQLCONNSTR_localdb.txt but it's doesn't works. Now i can't log with phpMyAdmin because the password is encrypted.

line at the begining: Database=localdb;Data Source=127.0.0.1:49383;User Id=azure;Password=6#vWHD_$

And i try to add this : Database=localdb;Data Source=127.0.0.1:49383;User Id=Admin;Password=test

How i can have the password encrypted? Or create a new account to connect me on to MySql with PhpMyAdmin ?

答: If you want to change the authentification, you need first to create a new user in phpMyAdmin after you just have to change the file MYSQLCONNSTR_localdb.iniwith your new account then save it. After delete the file MYSQLCONNSTR_localdb.txtand restart the web app and you are connected with your new account.


问:
If using multiple UserPool's "App clients", do I need to add them all to IdentityPool's "Authentication providers"?
I'm writing a web app which is using AWS Cognito UserPools for user authentication and IdentityPools for granting direct access to an S3 bucket.

This JavaScript web app has its own App client ID in the UserPool with which it interacts with it.

I also have a couple of Lambda functions doing some admin functions towards the UserPool and IdentityPool. These lambda functions have their own App client ID.

I used to have only a single Authentication provider added to the IdentityPool, with the same App Client ID that the lambda functions have set.

In this setup, the web app was having issues. I was able to authenticate towards the UserPool, but when the identity token was sent to the IdentityPool, I received an error "Token is not from a supported provider of this identity pool.". I believe this was because the aud parameter of the JWT was set to the UserPool ID which was not added to the IdentityPool

I eventually realized that I could get rid of the error if I added another "Authentication provider" to the IdentityPool, filling in the same UserPool ID and the other App client ID.

My question now is - is this the correct approach? Am I perhaps misunderstanding the App client ID meaning and usage? Am I way off base with my approach?

答: Yes that sounds like a perfectly good approach. If you don't encounter any security or functional issues it is the "correct" approach. </p>


问:
Can you console.log inside our config/environment.js?
Is there any possible to console the value from .env file to our config/environment.js?

答: Yes. The value will be printed out to the terminal when you run npm start or ember test or ember serve not to the browser console as config/environment.js is evaluated during the building of your app.


问:
Change the background colour of a mindmap object by using labels
I want to do: change the background colour of all objects with the label <folder> to blue

```<code>
@startmindmap

skinparam backgroundColor transparent

* layer 1
 * layer 2
  * obj
  * obj
  * <&folder> obj folder
 * layer 2
  * <&folder> obj folder
@endmindmap

</code>```

If anyone has experience of this, I would gladly accept any 'pearls of wisdom' they are willing to impart.

答:
this method may work. (PlantUML Web Server not work)

```<code>@startmindmap

skinparam backgroundColor transparent

sprite $my_right_arrow [16x16/16]  {
    FFFFFFFFFFFFFFFF
    FFFFFFFFFFFFFFFF
    FFFFFFFFFFFFFFFF
    FFFFFFFFFFFFFFFF
    FFFFFFFFFFFFFFFF
    FFFFFFFFFF0FFFFF
    FFFFFFFFFF00FFFF
    FF00000000000FFF
    FF000000000000FF
    FF00000000000FFF
    FFFFFFFFFF00FFFF
    FFFFFFFFFF0FFFFF
    FFFFFFFFFFFFFFFF
    FFFFFFFFFFFFFFFF
    FFFFFFFFFFFFFFFF
    FFFFFFFFFFFFFFFF
}

* layer 1
 * layer 2
  * obj
  * obj
  * <color:00ffff> <&folder> obj folder
 * layer 2
  * <color:00ffff> <&folder> obj folder
  * <back:00ffff> <&folder> obj folder
  ' backgroundColor not work!
  * <color:00ffff> <$my_right_arrow> <color:000000> <size:30> test
@endmindmap
</code>```

reference: http://plantuml.com/en/sprite

Body:
I want to do: change the background colour of all objects with the label <folder> to blue

@startmindmap

skinparam backgroundColor transparent

* layer 1
 * layer 2
  * obj
  * obj
  * <&folder> obj folder
 * layer 2
  * <&folder> obj folder
@endmindmap

If anyone has experience of this, I would gladly accept any 'pearls of wisdom' they are willing to impart.

Body:
this method may work. (PlantUML Web Server not work)

@startmindmap

skinparam backgroundColor transparent

sprite $my_right_arrow [16x16/16]  {
    FFFFFFFFFFFFFFFF
    FFFFFFFFFFFFFFFF
    FFFFFFFFFFFFFFFF
    FFFFFFFFFFFFFFFF
    FFFFFFFFFFFFFFFF
    FFFFFFFFFF0FFFFF
    FFFFFFFFFF00FFFF
    FF00000000000FFF
    FF000000000000FF
    FF00000000000FFF
    FFFFFFFFFF00FFFF
    FFFFFFFFFF0FFFFF
    FFFFFFFFFFFFFFFF
    FFFFFFFFFFFFFFFF
    FFFFFFFFFFFFFFFF
    FFFFFFFFFFFFFFFF
}

* layer 1
 * layer 2
  * obj
  * obj
  * <color:00ffff> <&folder> obj folder
 * layer 2
  * <color:00ffff> <&folder> obj folder
  * <back:00ffff> <&folder> obj folder
  ' backgroundColor not work!
  * <color:00ffff> <$my_right_arrow> <color:000000> <size:30> test
@endmindmap

reference: http://plantuml.com/en/sprite


问:
PHP7.1 mcrypt alternative
Mcrypt function has been deprecated as of PHP 7.1.0.

My deprecated string encode / decode functions:

```<code>$key: secret key
$str: string

$encoded = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($key), $str, MCRYPT_MODE_CBC, md5(md5($key))));

$decoded = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($key), base64_decode($str), MCRYPT_MODE_CBC, md5(md5($key))), "\0");
</code>```

Can you suggest some alternatives?

答:
```<code>echo encrypt_openssl($str, $key);

function encrypt_openssl($msg, $key, $iv = null) {
        $iv_size = openssl_cipher_iv_length('AES-256-CBC');
        if (!$iv) {
            $iv = openssl_random_pseudo_bytes($iv_size);
        }
        $encryptedMessage = openssl_encrypt($msg, 'AES-256-CBC', $key, OPENSSL_RAW_DATA, $iv);
        return base64_encode($iv . $encryptedMessage);
    }
</code>```

mcrypt may be removed in PHP 7.1  alternative openssl

Title: PHP7.1 mcrypt alternative

Body:
Mcrypt function has been deprecated as of PHP 7.1.0.

My deprecated string encode / decode functions:

$key: secret key
$str: string

$encoded = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($key), $str, MCRYPT_MODE_CBC, md5(md5($key))));

$decoded = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($key), base64_decode($str), MCRYPT_MODE_CBC, md5(md5($key))), "\0");

Can you suggest some alternatives?

Body:
echo encrypt_openssl($str, $key);

function encrypt_openssl($msg, $key, $iv = null) {
        $iv_size = openssl_cipher_iv_length('AES-256-CBC');
        if (!$iv) {
            $iv = openssl_random_pseudo_bytes($iv_size);
        }
        $encryptedMessage = openssl_encrypt($msg, 'AES-256-CBC', $key, OPENSSL_RAW_DATA, $iv);
        return base64_encode($iv . $encryptedMessage);
    }

mcrypt may be removed in PHP 7.1  alternative openssl


问:
Values vanishing after leaving function
I'm writing a function to insert into a tree and the data can be seen (printed) after insertion within the function but when trying to see it in main nothing happens.

node *tree = NULL;
insert(tree, 4321);
printf("outer: %d\n", tree->data);

void insert(node* tree, int data) {
  if (tree == NULL) {
    tree = new_node(data);
    printf("inner: %d\n", tree->data);
  }
}
```

<p>This gives:</p>

```inner: 4321
```

<p>It should be:</p>

```inner: 4321
outer: 4321
```

答:
You initialize tree as a pointer

```<code>node *tree = NULL;
</code>```

This means, that the content of the variable is a memory location where your tree is stored.

When you pass that memory location to a function, it's value gets copied to the local variable inside the function.

When you call

```<code>tree = new_node(data);
</code>```

what you're doing is assigning a new memory location to the local variable of the tree pointer inside your function. The pointer outside your function still has the same value and points to a memory location with no nodes.

What you'll need to do in order to edit the node inside your function is either define some kind of setter for your node, or set the data property explicitly with tree->data = xxx. This will alter the content of the memory tree is pointing to rather than altering its memory location.

Title: Values vanishing after leaving function

Body:
I'm writing a function to insert into a tree and the data can be seen (printed) after insertion within the function but when trying to see it in main nothing happens.

node *tree = NULL;
insert(tree, 4321);
printf("outer: %d\n", tree->data);

void insert(node* tree, int data) {
  if (tree == NULL) {
    tree = new_node(data);
    printf("inner: %d\n", tree->data);
  }
}

This gives:

inner: 4321

It should be:

inner: 4321
outer: 4321

Body:
You initialize tree as a pointer

node *tree = NULL;

This means, that the content of the variable is a memory location where your tree is stored.

When you pass that memory location to a function, it's value gets copied to the local variable inside the function.

When you call

tree = new_node(data);

what you're doing is assigning a new memory location to the local variable of the tree pointer inside your function. The pointer outside your function still has the same value and points to a memory location with no nodes.

What you'll need to do in order to edit the node inside your function is either define some kind of setter for your node, or set the data property explicitly with tree->data = xxx. This will alter the content of the memory tree is pointing to rather than altering its memory location.


问:
Scrollbars based on the content of a jpanel
I have a jpanel that is 500x500 and acts as a canvas (draw all over it). Scrollbars kick in (as needed) at 510x510 on the panel (which it will never reach visually, but will surpass based on content) and 500x500 is represented as 1:1 (scale)

Below is a representation of a line zoomed in, as can be seen, the view window stays same and no scrollbars popup, setting scrollbars to always results in disabled bars.

JScrollPane scrollPanel = new JScrollPane(JPanel,
                ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
                ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
```

How would I go about having the scrollbars read the contents of this panel and become scrollable? I cannot find anything relevant for this

The attached panel gets bigger, but the scrollbar doesnt read this change. Is there some sort of update i need to call which i dont have (Thinking on it I dont explicitly have anything calling an update? but could not find anything relevant on this either)

答:
What you need is to implement scrollable interface for your panel, that is placed in the JScrollPane and override the method getPreferredSize(). Here is the example

```<code>import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Rectangle;

import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.Scrollable;
import javax.swing.WindowConstants;
import javax.swing.plaf.basic.BasicComboBoxRenderer;

public class ZoomPanel extends JPanel implements Scrollable {

    private static final int DEFAULT_SIZE = 500;

    private float zoom = 1f;

    @Override
    public Dimension getPreferredSize() {
        int size = Math.round(zoom * DEFAULT_SIZE);
        return new Dimension(size, size);
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        int size = Math.round(zoom * DEFAULT_SIZE);
        g.drawOval(0, 0, size, size);
    }

    private static class ZoomRenderer extends BasicComboBoxRenderer {

        @Override
        public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
            Object val = value;
            if (value instanceof Number) {
                val = Math.round(((Number) value).doubleValue() * 100) + "%";
            }
            return super.getListCellRendererComponent(list, val, index, isSelected, cellHasFocus);
        }
    }

    public static void main(String[] args) {
        JFrame frm = new JFrame("Zoom panel");
        ZoomPanel z = new ZoomPanel();
        JScrollPane scroller = new JScrollPane(z);
        Float[] zooms = {.5f, .75f, 1f, 1.5f, 2f, 4f};
        JComboBox<Float> combo = new JComboBox<>(zooms);
        combo.setSelectedIndex(2);
        combo.setRenderer(new ZoomRenderer());
        combo.addActionListener(e -> {
            Float v = (Float) combo.getSelectedItem();
            if (v != null) {
                z.zoom = v;
                scroller.revalidate();
                scroller.repaint();
            }
        });
        JPanel comboPanel = new JPanel();
        comboPanel.add(combo);
        frm.add(comboPanel, BorderLayout.NORTH);
        frm.add(scroller);
        frm.pack();
        frm.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frm.setLocationRelativeTo(null);
        frm.setVisible(true);
    }

    @Override
    public Dimension getPreferredScrollableViewportSize() {
        return getPreferredSize();
    }

    @Override
    public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction) {
        return 5;
    }

    @Override
    public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction) {
        return 20;
    }

    @Override
    public boolean getScrollableTracksViewportWidth() {
        return false;
    }

    @Override
    public boolean getScrollableTracksViewportHeight() {
        return false;
    }
}
</code>```

Body:
I have a jpanel that is 500x500 and acts as a canvas (draw all over it). Scrollbars kick in (as needed) at 510x510 on the panel (which it will never reach visually, but will surpass based on content) and 500x500 is represented as 1:1 (scale)

Below is a representation of a line zoomed in, as can be seen, the view window stays same and no scrollbars popup, setting scrollbars to always results in disabled bars.

JScrollPane scrollPanel = new JScrollPane(JPanel,
                ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
                ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);

How would I go about having the scrollbars read the contents of this panel and become scrollable? I cannot find anything relevant for this

The attached panel gets bigger, but the scrollbar doesnt read this change. Is there some sort of update i need to call which i dont have (Thinking on it I dont explicitly have anything calling an update? but could not find anything relevant on this either)

Body:
What you need is to implement scrollable interface for your panel, that is placed in the JScrollPane and override the method getPreferredSize(). Here is the example

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Rectangle;

import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.Scrollable;
import javax.swing.WindowConstants;
import javax.swing.plaf.basic.BasicComboBoxRenderer;

public class ZoomPanel extends JPanel implements Scrollable {

    private static final int DEFAULT_SIZE = 500;

    private float zoom = 1f;

    @Override
    public Dimension getPreferredSize() {
        int size = Math.round(zoom * DEFAULT_SIZE);
        return new Dimension(size, size);
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        int size = Math.round(zoom * DEFAULT_SIZE);
        g.drawOval(0, 0, size, size);
    }

    private static class ZoomRenderer extends BasicComboBoxRenderer {

        @Override
        public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
            Object val = value;
            if (value instanceof Number) {
                val = Math.round(((Number) value).doubleValue() * 100) + "%";
            }
            return super.getListCellRendererComponent(list, val, index, isSelected, cellHasFocus);
        }
    }

    public static void main(String[] args) {
        JFrame frm = new JFrame("Zoom panel");
        ZoomPanel z = new ZoomPanel();
        JScrollPane scroller = new JScrollPane(z);
        Float[] zooms = {.5f, .75f, 1f, 1.5f, 2f, 4f};
        JComboBox<Float> combo = new JComboBox<>(zooms);
        combo.setSelectedIndex(2);
        combo.setRenderer(new ZoomRenderer());
        combo.addActionListener(e -> {
            Float v = (Float) combo.getSelectedItem();
            if (v != null) {
                z.zoom = v;
                scroller.revalidate();
                scroller.repaint();
            }
        });
        JPanel comboPanel = new JPanel();
        comboPanel.add(combo);
        frm.add(comboPanel, BorderLayout.NORTH);
        frm.add(scroller);
        frm.pack();
        frm.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frm.setLocationRelativeTo(null);
        frm.setVisible(true);
    }

    @Override
    public Dimension getPreferredScrollableViewportSize() {
        return getPreferredSize();
    }

    @Override
    public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction) {
        return 5;
    }

    @Override
    public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction) {
        return 20;
    }

    @Override
    public boolean getScrollableTracksViewportWidth() {
        return false;
    }

    @Override
    public boolean getScrollableTracksViewportHeight() {
        return false;
    }
}


问:
How to endorse that a string is a version of something or not?
FYI, It is not duplicate please remove this tag.

I have tried packaging.version.Version it does not work on 1.0.2h and 192.168.0.3.

Question

I am getting versions of different libraries/binaries in a list. And this list includes some garbage values of version along with correct one. I want to write a python code that can separate correct ones from the version list.

Please suggest a logic or python library which can do the following

Psuedo Code

Correct_verList = []

verList = ['2.6.36', '1.2.dfgdf', '1.sdfsdgsdsf', '3.0/0+3*/1,-/0/0,//O*K1', 'so.802', '5.0(side)', '6.2*20hm' , '192.168.0.222', '1.33', '0.97a', '1.0.2h', '2.4.2b3']

#Psuedo Code
for ver in verList:
    if ver is the correct version:
         Correct_verList.append(ver)

print(Correct_verList)
```

<p><strong>Expected Output</strong></p>

```Correct_verList = [1.33, 0.97a, 2.6.36, 1.0.2h, 2.4.2b3]
```

答:
What you are looking for is called regular expression. This link provide you documentation on python's regular expression.

This regular expression could do the job : '(([0-9]+[.]){1,2}([0-9]*([0-9]|[a-z]){0,2}[0-9]+)'

What you could do is to use the findall() method and test if the result is the same string you tested. The code would be like (I have not tested it) :

```<code>import re
Correct_verList = []

verList = ['2.6.36', '3.0/0+3*/1,-/0/0,//O*K1', 'so.802', '5.0(side)', '6.2*20hm' , '192.168.0.222', '1.33', '0.97a', '1.0.2h', '2.4.2b3']

for ver in verList:
    a=re.findall('(([0-9]+[.]){1,2}([0-9]*([0-9]|[a-z]){0,2}[0-9]+)',ver)
    if len(a)!=0:
       if a[0][0]==ver:
           Correct_verList.append(ver)
print(Correct_verList)

</code>```

Body:
FYI, It is not duplicate please remove this tag.

I have tried packaging.version.Version it does not work on 1.0.2h and 192.168.0.3.

Question

I am getting versions of different libraries/binaries in a list. And this list includes some garbage values of version along with correct one. I want to write a python code that can separate correct ones from the version list.

Please suggest a logic or python library which can do the following

Psuedo Code

Correct_verList = []

verList = ['2.6.36', '1.2.dfgdf', '1.sdfsdgsdsf', '3.0/0+3*/1,-/0/0,//O*K1', 'so.802', '5.0(side)', '6.2*20hm' , '192.168.0.222', '1.33', '0.97a', '1.0.2h', '2.4.2b3']

#Psuedo Code
for ver in verList:
    if ver is the correct version:
         Correct_verList.append(ver)

print(Correct_verList)

Expected Output

Correct_verList = [1.33, 0.97a, 2.6.36, 1.0.2h, 2.4.2b3]

Body:
What you are looking for is called regular expression. This link provide you documentation on python's regular expression.

This regular expression could do the job : '(([0-9]+[.]){1,2}([0-9]*([0-9]|[a-z]){0,2}[0-9]+)'

What you could do is to use the findall() method and test if the result is the same string you tested. The code would be like (I have not tested it) :

import re
Correct_verList = []

verList = ['2.6.36', '3.0/0+3*/1,-/0/0,//O*K1', 'so.802', '5.0(side)', '6.2*20hm' , '192.168.0.222', '1.33', '0.97a', '1.0.2h', '2.4.2b3']

for ver in verList:
    a=re.findall('(([0-9]+[.]){1,2}([0-9]*([0-9]|[a-z]){0,2}[0-9]+)',ver)
    if len(a)!=0:
       if a[0][0]==ver:
           Correct_verList.append(ver)
print(Correct_verList)


问:
Uncaught TypeError: Cannot read property 'init' of undefined in Javascript while submitting form
I'm trying to make a social networking mini web app using python web.py module.
I made a registration form in html, but when I fill the details and submit them, the browser console shows the following output:

```<code>Uncaught TypeError: $(...).ready(...) is not a function
at scripty.js:22
loaded
jquery-3.4.1.min.js:2 Uncaught TypeError: Cannot read property 'init' of undefined
at HTMLDocument.<anonymous> (scripty.js:4)
at e (jquery-3.4.1.min.js:2)
at t (jquery-3.4.1.min.js:2)
</code>```

I've searched for similar problems but their solutions doesn't seem to work for this case.

Here is my "scripty.js" file code

```<code>$(document).ready(function () {
    console.log("loaded");

    $.material.init();

    $(document).on("submit", "#register-form", function (e) {
        e.preventDefault();
        console.log("form submitted");

        let form = $('#register-form').serialize(); //get the form data

        //send an ajax request over to the route /postregisteration
        $.ajax({
            url: '/postregisteration',
            type: 'POST',
            data: form,
            success: function (response) {
                console.log(response);
            }
        });
    });
})();

</code>```

And here is the controller.py file code in python

```<code>import web
from Models import RegisterModel

urls = (
    '/', 'Home',
    '/register', 'Register',
    '/postregistration', 'PostRegistration'
)

render =  web.template.render("Views/Templates", base="MainLayout")

app = web.application(urls, globals())

# Classes/Routes
# Each class will be controlling a route

class Home:
    def GET(self):
        return render.Home()

class Register:
    def GET(self):
        return render.Register()

class PostRegistration:
    def POST(self):
        data = web.input()
        print(data.username)

        reg_model = RegisterModel.RegisterModel.insert_user(data)
        return data.username

if __name__=="__main__":
    app.run()
</code>```

After clicking submit, it just prints
"loaded" and shows the error on browser console.

But it must also show
"form submitted".

Any help would be appreciable.

答:
Here's your script with the end line bug fixed, material removed and with comments added that explain what each line does.</p>

```<code>// Wait until the page has fully loaded before applying the script
$(document).ready(function () {
    // Bind a function to the submit form
    $(document).on("submit", "#register-form", function (e) {
        // Prevent the default form post behavior to prevent the page from reloading
        e.preventDefault();

        // Get the form data
        var form = $('#register-form').serialize();

        // Send an ajax request over to the route /postregisteration
        $.ajax({
            url: '/postregisteration',
            type: 'POST',
            data: form,
            success: function (response) {
                console.log("form submitted");
                console.log(response);
            }
        });
    });
});
</code>```

Body:
I'm trying to make a social networking mini web app using python web.py module.
I made a registration form in html, but when I fill the details and submit them, the browser console shows the following output:

Uncaught TypeError: $(...).ready(...) is not a function
at scripty.js:22
loaded
jquery-3.4.1.min.js:2 Uncaught TypeError: Cannot read property 'init' of undefined
at HTMLDocument.<anonymous> (scripty.js:4)
at e (jquery-3.4.1.min.js:2)
at t (jquery-3.4.1.min.js:2)

I've searched for similar problems but their solutions doesn't seem to work for this case.

Here is my "scripty.js" file code

$(document).ready(function () {
    console.log("loaded");

    $.material.init();

    $(document).on("submit", "#register-form", function (e) {
        e.preventDefault();
        console.log("form submitted");

        let form = $('#register-form').serialize(); //get the form data

        //send an ajax request over to the route /postregisteration
        $.ajax({
            url: '/postregisteration',
            type: 'POST',
            data: form,
            success: function (response) {
                console.log(response);
            }
        });
    });
})();

And here is the controller.py file code in python

import web
from Models import RegisterModel

urls = (
    '/', 'Home',
    '/register', 'Register',
    '/postregistration', 'PostRegistration'
)

render =  web.template.render("Views/Templates", base="MainLayout")

app = web.application(urls, globals())

# Classes/Routes
# Each class will be controlling a route

class Home:
    def GET(self):
        return render.Home()

class Register:
    def GET(self):
        return render.Register()

class PostRegistration:
    def POST(self):
        data = web.input()
        print(data.username)

        reg_model = RegisterModel.RegisterModel.insert_user(data)
        return data.username

if __name__=="__main__":
    app.run()

After clicking submit, it just prints
"loaded" and shows the error on browser console.

But it must also show
"form submitted".

Any help would be appreciable.

Body:
Here's your script with the end line bug fixed, material removed and with comments added that explain what each line does.

// Wait until the page has fully loaded before applying the script
$(document).ready(function () {
    // Bind a function to the submit form
    $(document).on("submit", "#register-form", function (e) {
        // Prevent the default form post behavior to prevent the page from reloading
        e.preventDefault();

        // Get the form data
        var form = $('#register-form').serialize();

        // Send an ajax request over to the route /postregisteration
        $.ajax({
            url: '/postregisteration',
            type: 'POST',
            data: form,
            success: function (response) {
                console.log("form submitted");
                console.log(response);
            }
        });
    });
});


问:
Convert a byte [] to Image<Bgr, Byte>
I am trying to convert a byte array to an image. There are many references on the web to do so such as this SO post and this emgu forum and emgu official docs.

However I am getting an error when I implement the solutions according to the SO post and the Emgu docs that reads

Cannot convert from System.Drawing.Bitmap to byte[*,*,*,*]

```<code>public Image<Bgr, Byte> CreateImageFromBytesArray(byte[] bytes)
{
    using (var ms = new MemoryStream(bytes))
    {
        Bitmap bmp = new Bitmap(ms);
        Image<Bgr, Byte> img = new Image<Bgr, Byte>(bmp); //EXCEPTION HERE
        return img;
    }
}
</code>```

Any suggestions on how to make this work?

答:
```<code>public Image<Bgr, Byte> CreateImageFromBytesArray(byte[] bytes)
{
    Image<Bgr, Byte> image = new Image<Bgr, Byte>(width, height);
    image.Bytes = bytes
    return image;
}
</code>```

Title: Convert a byte [] to Image<Bgr, Byte>

Body:
I am trying to convert a byte array to an image. There are many references on the web to do so such as this SO post and this emgu forum and emgu official docs.

However I am getting an error when I implement the solutions according to the SO post and the Emgu docs that reads

Cannot convert from System.Drawing.Bitmap to byte[*,*,*,*]

public Image<Bgr, Byte> CreateImageFromBytesArray(byte[] bytes)
{
    using (var ms = new MemoryStream(bytes))
    {
        Bitmap bmp = new Bitmap(ms);
        Image<Bgr, Byte> img = new Image<Bgr, Byte>(bmp); //EXCEPTION HERE
        return img;
    }
}

Any suggestions on how to make this work?


问:
How to set variables in "Where" clause when reading cassandra table by spark streaming?
I'm doing some statistics using spark streaming and cassandra. When reading cassandra tables by spark-cassandra-connector and make the cassandra row RDD to a DStreamRDD by ConstantInputDStream, the "CurrentDate" variable in where clause still stays the same day as the program starts.

The purpose is to analyze the total score by some dimensions till current date, but now the code runs analysis just till the day it start running. I run the code in 2019-05-25 and data inserted into table after that time cannot be take in.

The code I use is like below:

```<code>  class TestJob extends Serializable {

  def test(ssc : StreamingContext) : Unit={

    val readTableRdd = ssc.cassandraTable(Configurations.getInstance().keySpace1,Constants.testTable)
      .select(
        "code",
        "date",
        "time",
        "score"
      ).where("date<= ?",new Utils().getCurrentDate())

    val DStreamRdd = new ConstantInputDStream(ssc,readTableRdd)

    DStreamRdd.foreachRDD{r=>
    //DO SOMETHING
    }
  }
}

      object GetSSC extends Serializable {
      def getSSC() : StreamingContext ={
        val conf = new SparkConf()
          .setMaster(Configurations.getInstance().sparkHost)
          .setAppName(Configurations.getInstance().appName)
          .set("spark.cassandra.connection.host", Configurations.getInstance().casHost)
          .set("spark.cleaner.ttl", "3600")
          .set("spark.default.parallelism","3")
          .set("spark.ui.port","5050")
          .set("spark.serializer","org.apache.spark.serializer.KryoSerializer")
        val sc = new SparkContext(conf)
        sc.setLogLevel("WARN")
        @transient lazy val ssc = new StreamingContext(sc,Seconds(30))
        ssc
      }
    }

    object Main {
    val logger : Log = LogFactory.getLog(Main.getClass)
    def main(args : Array[String]) : Unit={
    val ssc = GetSSC.getSSC()
    try{
      new TestJob().test(ssc)
      ssc.start()
      ssc.awaitTermination()
    }catch {
      case e : Exception =>
        logger.error(Main.getClass.getSimpleName+"error :
    "+e.printStackTrace())
    }
  }
}
</code>```

Table used in this Demo like:

```<code>    CREATE TABLE test.test_table (
       code text PRIMARY KEY, //UUID
       date text, // '20190520'
       time text, // '12:00:00'
       score int); // 90
</code>```

Any help is appreciated!

答: In general, RDDs that are returned by Spark Cassandra Connector aren't the streaming RDDs - there is no such functionality in Cassandra that will allow to subscribe to the changes feed and analyze it. You can implement something like by explicitly looping and fetching the data, but it will require careful design of the tables, but it's hard to say something without digging more deeply into requirements for latency, amount of data, etc.</p>

Body:
I'm doing some statistics using spark streaming and cassandra. When reading cassandra tables by spark-cassandra-connector and make the cassandra row RDD to a DStreamRDD by ConstantInputDStream, the "CurrentDate" variable in where clause still stays the same day as the program starts.

The purpose is to analyze the total score by some dimensions till current date, but now the code runs analysis just till the day it start running. I run the code in 2019-05-25 and data inserted into table after that time cannot be take in.

The code I use is like below:

  class TestJob extends Serializable {

  def test(ssc : StreamingContext) : Unit={

    val readTableRdd = ssc.cassandraTable(Configurations.getInstance().keySpace1,Constants.testTable)
      .select(
        "code",
        "date",
        "time",
        "score"
      ).where("date<= ?",new Utils().getCurrentDate())

    val DStreamRdd = new ConstantInputDStream(ssc,readTableRdd)

    DStreamRdd.foreachRDD{r=>
    //DO SOMETHING
    }
  }
}

      object GetSSC extends Serializable {
      def getSSC() : StreamingContext ={
        val conf = new SparkConf()
          .setMaster(Configurations.getInstance().sparkHost)
          .setAppName(Configurations.getInstance().appName)
          .set("spark.cassandra.connection.host", Configurations.getInstance().casHost)
          .set("spark.cleaner.ttl", "3600")
          .set("spark.default.parallelism","3")
          .set("spark.ui.port","5050")
          .set("spark.serializer","org.apache.spark.serializer.KryoSerializer")
        val sc = new SparkContext(conf)
        sc.setLogLevel("WARN")
        @transient lazy val ssc = new StreamingContext(sc,Seconds(30))
        ssc
      }
    }

    object Main {
    val logger : Log = LogFactory.getLog(Main.getClass)
    def main(args : Array[String]) : Unit={
    val ssc = GetSSC.getSSC()
    try{
      new TestJob().test(ssc)
      ssc.start()
      ssc.awaitTermination()
    }catch {
      case e : Exception =>
        logger.error(Main.getClass.getSimpleName+"error :
    "+e.printStackTrace())
    }
  }
}

Table used in this Demo like:

    CREATE TABLE test.test_table (
       code text PRIMARY KEY, //UUID
       date text, // '20190520'
       time text, // '12:00:00'
       score int); // 90

Any help is appreciated!


问:
Firebase: Event Property Data not shown in Firebase
I am sending some custom properties to firebase when I trigger an event but they do not appear in Firebase.

I have enabled the debug view and the data does arrive perfectly fine in the debug stream.

Debug View: http://imgur.com/a/DRLG5

Analytics: http://imgur.com/a/IyJbL

Am I missing something?

答: I had exactly the same problem but after a few days, my custom parameters now have values. It's so strange but after 4 days, all the custom parameters suddenly have values and everything works just fine!</p>


问:
Deleting N matching patterns using sed, awk, perl etc
I have this situation, the file contains

```<code>abcd
line1
line2
line3
vwxyz
abcd
vwxyz
abcd
vwxyz
abcd
vwxyz
line4
line5
</code>```

I would like to delete whenever I find matching 2 lines of

```<code>abcd
vwxyz
</code>```

to be deleted so that it becomes

```<code>abcd
line1
line2
line3
vwxyz
line4
line5
</code>```

I have search numerous stackoverflow suggestions of pattern matching but never encountered pattern matching of 2 lines

I have triend sed -i '/abcd|vwxyz/d' file1 but that didn't work as expected...

Any help is appreciated using awk, sed, perl, pyhon etc

答:
With Perl, the simplest solution is to load the entire input into memory.

```<code>perl -0777pe's/abcd\nvwxyz\n//g'
</code>```

If reading a line at a time, the generic solution in these types of problems is to keep a buffer of past lines.

```<code>if (!eof()) {
   my @buf = scalar(<>);
   while (<>) {
      if ($buf[-1] =~ /^abcd$/ && /^vwxyz$/) {
         @buf = ();
      } else {
         print(shift(@buf));
         push(@buf, $_);
      }
   }

   print @buf;
}
</code>```

Body:
I have this situation, the file contains

abcd
line1
line2
line3
vwxyz
abcd
vwxyz
abcd
vwxyz
abcd
vwxyz
line4
line5

I would like to delete whenever I find matching 2 lines of

abcd
vwxyz

to be deleted so that it becomes

abcd
line1
line2
line3
vwxyz
line4
line5

I have search numerous stackoverflow suggestions of pattern matching but never encountered pattern matching of 2 lines

I have triend sed -i '/abcd|vwxyz/d' file1 but that didn't work as expected...

Any help is appreciated using awk, sed, perl, pyhon etc

Body:
With Perl, the simplest solution is to load the entire input into memory.

perl -0777pe's/abcd\nvwxyz\n//g'

If reading a line at a time, the generic solution in these types of problems is to keep a buffer of past lines.

if (!eof()) {
   my @buf = scalar(<>);
   while (<>) {
      if ($buf[-1] =~ /^abcd$/ && /^vwxyz$/) {
         @buf = ();
      } else {
         print(shift(@buf));
         push(@buf, $_);
      }
   }

   print @buf;
}


问:
Can I create a WCF service without using attributes?
The way you seem to declare WCF services is to create an interface in C# or VB, and then tag it with ServiceContractAttribute and it's methods with OperationContractAttribute.

The issue is, I'd like to try creating one from IronRuby or IronPython, which (to my knowledge) don't support attributes.

Is this possible?

答: AFAIK you can't yet in IronRuby.  It's one of those interop things that are on the back burner while language compatibility is worked on.  There's still alot of discussion needed about how to do this... but it is something that those of us working on IronRuby would like to see.</p>

OwnerDisplayName: Orion Edwards

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: TheProkrammer


问:
replace new line in a different file with an underscore (without using with)
I posted a question yesterday in similar regards to this but didn't quite gauge the response I wanted because I wasn't specific enough. Basically the function takes a .txt file as the argument and returns a string with all \n characters replaced with an '_' on the same line. I want to do this without using WITH. I thought I did this correctly but when I run it and check the file, nothing has changed. Any pointers?

This is what I did:

```<code>def one_line(filename):
    wordfile = open(filename)
    text_str = wordfile.read().replace("\n", "_")
    wordfile.close()
    return text_str

one_line("words.txt")
</code>```

but to no avail. I open the text file and it remains the same.

The contents of the textfile are:

```<code>I like to eat
pancakes every day

</code>```

and the output that's supposed to be shown is:

```<code>>>> one_line("words.txt")
’I like to eat_pancakes every day_’
</code>```

答:
You are missing some steps. After you obtain the updated string, you need to write it back to the file, example below without using with

```<code>def one_line(filename):
    wordfile = open(filename)
    text_str = wordfile.read().replace("\n", "_")
    wordfile.close()
    return text_str

def write_line(s):
    # Open the file in write mode
    wordfile = open("words.txt", 'w')

    # Write the updated string to the file
    wordfile.write(s)

    # Close the file
    wordfile.close()

s = one_line("words.txt")
write_line(s)
</code>```

Or using with

```<code>with open("file.txt",'w') as wordfile:

    #Write the updated string to the file
    wordfile.write(s)
</code>```

Body:
I posted a question yesterday in similar regards to this but didn't quite gauge the response I wanted because I wasn't specific enough. Basically the function takes a .txt file as the argument and returns a string with all \n characters replaced with an '_' on the same line. I want to do this without using WITH. I thought I did this correctly but when I run it and check the file, nothing has changed. Any pointers?

This is what I did:

def one_line(filename):
    wordfile = open(filename)
    text_str = wordfile.read().replace("\n", "_")
    wordfile.close()
    return text_str

one_line("words.txt")

but to no avail. I open the text file and it remains the same.

The contents of the textfile are:

I like to eat
pancakes every day

and the output that's supposed to be shown is:

>>> one_line("words.txt")
’I like to eat_pancakes every day_’

Body:
You are missing some steps. After you obtain the updated string, you need to write it back to the file, example below without using with

def one_line(filename):
    wordfile = open(filename)
    text_str = wordfile.read().replace("\n", "_")
    wordfile.close()
    return text_str

def write_line(s):
    # Open the file in write mode
    wordfile = open("words.txt", 'w')

    # Write the updated string to the file
    wordfile.write(s)

    # Close the file
    wordfile.close()

s = one_line("words.txt")
write_line(s)

Or using with

with open("file.txt",'w') as wordfile:

    #Write the updated string to the file
    wordfile.write(s)


问:
How to structure the data of a lottery draw application in Firestore?
I am developing an application in react-native + Cloud Firestore, which aims to generate random numbers/tickets for each user who fill out a form. These numbers will allow the user to participate in an electronic lottery and compete for the prizes of a promotion.

These numbers should be separated by series, for example:

```<code>Series 1 - numbers can range from 0 to 99,999 thousand.
Series 2 - numbers can range from 0 to 99,999 thousand.
Series N - numbers can range from 0 to 99,999 thousand.
</code>```

The system requirements are:

The series and numbers generated for each user must be maintained (numbers saved for the Client);

Each promotion must also contain the generated numbers and series (Numbers generated in the Promotion, Total);

In a first structure in Cloud Firestore, we created a structure as follows:

```<code>Promotion - Series - Number
(random doc) - 01 - 00131 ...
(random doc) - 01 - 97879 ...
(random doc) - 09 - 99999
</code>```

Promotion is a collection, the Series is a promotion sub-collection, and Number is a Series sub-collection.

However, in this way many queries have been made in the firestore API, for example, to obtain the available numbers to be generated within a series, so that a new number can be generated.

Another approach we have found is that the subcollection of numbers could be an array within the Series collection. This would reduce queries.

Will the 100,000 number array exceed the maximum 1mb document size?
It could be used a structure with map, for example, to write beyond the number other properties as follows:

```<code>Promotion - Series - Numbers: Map?
</code>```

答:
"Will the 100,000 number array exceed the maximum 1mb document size?"

Each number in the array will consume 8 bytes, so just the array values will be ~800KB, then with some overhead for the document and field name you should still be under the limit.

You will, however, need to ensure you go into Single Field Indexes in the UI and create an exemption for the array field as each array value consumes 2 index entries (and the whole array consumes 2 itself), so you will definitely exceed the 20K index entries per document limit. Note: This means you won't be able to query the array.

"However, in this way many queries have been made in the firestore API, for example, to obtain the available numbers to be generated within a series, so that a new number can be generated."

I'm guessing these 2 unwritten assumptions:

The same number cannot be given to more than a single client

Most, if not all of the numbers in a series will be assigned

If 2 isn't true, you could just generate a number, see if it exists and if so regenerate and try again. This becomes more costly if most or all of the numbers will be assigned.

An alternative is to do a hybrid approach.

For 100,000 numbers, create 1000 documents that own 100 numbers each and store those 100 numbers in an array called ticket_number:

```<code>/promotions/<series number>/numbers/<nnnn>
--> ticket_number: [nnnn01, nnnn02, ..., (nnnn+1)00]
</code>```

On each document have a boolean field called available that is set to true if numbers in that range are still available. If they are not, delete the field or set it to false

Use the method outlined here to select a random document from these documents where full == true. From this document select a random ticket number from the array, removing it and updating the document.

Eventually, all values will be selected this way, while only needing to read and write a single document for each ticket (as well as writing selected number/series into a separate document).

Write rate considerations

Note that it is recommended to have a maximum sustained rate of 1 write per second per document. In the single document approach, this would mean either a slow assignment of numbers or some upstream batching mechanism.

By using the hybrid approach you can shard across more documents to increase the write rate possible. In the example I give above, that's 1000 writes per second.

Body:
I am developing an application in react-native + Cloud Firestore, which aims to generate random numbers/tickets for each user who fill out a form. These numbers will allow the user to participate in an electronic lottery and compete for the prizes of a promotion.

These numbers should be separated by series, for example:

Series 1 - numbers can range from 0 to 99,999 thousand.
Series 2 - numbers can range from 0 to 99,999 thousand.
Series N - numbers can range from 0 to 99,999 thousand.

The system requirements are:

The series and numbers generated for each user must be maintained (numbers saved for the Client);

Each promotion must also contain the generated numbers and series (Numbers generated in the Promotion, Total);

In a first structure in Cloud Firestore, we created a structure as follows:

Promotion - Series - Number
(random doc) - 01 - 00131 ...
(random doc) - 01 - 97879 ...
(random doc) - 09 - 99999

Promotion is a collection, the Series is a promotion sub-collection, and Number is a Series sub-collection.

However, in this way many queries have been made in the firestore API, for example, to obtain the available numbers to be generated within a series, so that a new number can be generated.

Another approach we have found is that the subcollection of numbers could be an array within the Series collection. This would reduce queries.

Will the 100,000 number array exceed the maximum 1mb document size?
It could be used a structure with map, for example, to write beyond the number other properties as follows:

Promotion - Series - Numbers: Map?

Body:
"Will the 100,000 number array exceed the maximum 1mb document size?"

Each number in the array will consume 8 bytes, so just the array values will be ~800KB, then with some overhead for the document and field name you should still be under the limit.

You will, however, need to ensure you go into Single Field Indexes in the UI and create an exemption for the array field as each array value consumes 2 index entries (and the whole array consumes 2 itself), so you will definitely exceed the 20K index entries per document limit. Note: This means you won't be able to query the array.

"However, in this way many queries have been made in the firestore API, for example, to obtain the available numbers to be generated within a series, so that a new number can be generated."

I'm guessing these 2 unwritten assumptions:

The same number cannot be given to more than a single client

Most, if not all of the numbers in a series will be assigned

If 2 isn't true, you could just generate a number, see if it exists and if so regenerate and try again. This becomes more costly if most or all of the numbers will be assigned.

An alternative is to do a hybrid approach.

For 100,000 numbers, create 1000 documents that own 100 numbers each and store those 100 numbers in an array called ticket_number:

/promotions/<series number>/numbers/<nnnn>
--> ticket_number: [nnnn01, nnnn02, ..., (nnnn+1)00]

On each document have a boolean field called available that is set to true if numbers in that range are still available. If they are not, delete the field or set it to false

Use the method outlined here to select a random document from these documents where full == true. From this document select a random ticket number from the array, removing it and updating the document.

Eventually, all values will be selected this way, while only needing to read and write a single document for each ticket (as well as writing selected number/series into a separate document).

Write rate considerations

Note that it is recommended to have a maximum sustained rate of 1 write per second per document. In the single document approach, this would mean either a slow assignment of numbers or some upstream batching mechanism.

By using the hybrid approach you can shard across more documents to increase the write rate possible. In the example I give above, that's 1000 writes per second.


问:
How to map entire JSON object as value into new JSON key using JOLT?
my goal is to map a JSON object into as value in a new JSON object key. Such as example:

My starting JSON:

```<code>{
 "old_key_1" : "some_json_structure_1",
 "old_key_2" : "some_json_structure_2",
 "old_key_3" : "some_json_structure_3"
}
</code>```

My goal JSON:

```<code>{
 "new_key_1" :
  {
    "old_key_1" : "some_json_structure_1",
    "old_key_2" : "some_json_structure_2",
    "old_key_3" : "some_json_structure_3"
  }
}
</code>```

How is it possible using JOLT: if I understand well I have to use a shift spec but I didn't understand how?

Can anyone can help me?

Thank you in advance

答:
Wrapping into new object:</p>

```<code>[
  {
    "operation": "shift",
    "spec": {
      "*": {
        "@": "new_key_1.&" //the "&" means go up the tree 0 levels, grab what is there and subtitute it in
      }
    }
  }
]
</code>```

Body:
my goal is to map a JSON object into as value in a new JSON object key. Such as example:

My starting JSON:

{
 "old_key_1" : "some_json_structure_1",
 "old_key_2" : "some_json_structure_2",
 "old_key_3" : "some_json_structure_3"
}

My goal JSON:

{
 "new_key_1" :
  {
    "old_key_1" : "some_json_structure_1",
    "old_key_2" : "some_json_structure_2",
    "old_key_3" : "some_json_structure_3"
  }
}

How is it possible using JOLT: if I understand well I have to use a shift spec but I didn't understand how?

Can anyone can help me?

Thank you in advance

Body:
Wrapping into new object:

[
  {
    "operation": "shift",
    "spec": {
      "*": {
        "@": "new_key_1.&" //the "&" means go up the tree 0 levels, grab what is there and subtitute it in
      }
    }
  }
]