问:
.htaccess remove www with GCP hosted site
I have a website hosted on GCP bucket and I use cloudflare for HTTPS.
How can I use .htaccess file to remove www. from all website pages and redirect them to HTTPS?

Basically, I want:

```<code>http://www.example.com/ redirect to https://example.com/
https://www.example.com/ redirect to https://example.com/

and any other pages like
https://www.example.com/about.html or http://www.example.com/about.html redirect to https://example.com/about.html
</code>```

I found the configuration for the .htaccess file that I need to add to the root directory of my website:

Catch all and redirect www to no-www (HTTPS):

```<code>RewriteEngine On
RewriteCond %{HTTP_HOST} ^www.example.com$ [NC]
RewriteRule ^(.*)$ https://example.com$1 [R=301,L]
</code>```

I replaced example.com with my domain name, put the file into the root directory of my GCP bucket and nothing happened. If I try to access my website by http://example.com I get DNS_PROBE_FINISHED_NXDOMAIN error. I tried to save .htaccess with ANSI and with UTF-8 with the same result.

How do I:

Remove www. from my website using .htaccess

Redirect users to https:// without www.

What encoding should I use for .htaccess? Does it matter?

Is this even possible with my GCP bucket hosted static website and cloudflare provided https://?

I tried setting up redirects through my domain registrar's control panel, but they don't support redirects with dns nameservers other than their own default ones.

答:
The simplest solution would be to use CloudFlare to take care of HTTPS and the www site redirection.

To force HTTPS, go to CloudFlare settings: SSL/TLS => Edge Certificates => Always Use HTTPS => On.

Always Use HTTPS:
  Redirect all requests with scheme "http" to "https". This applies to
  all http requests to the zone.

To redirect some locations to some other locations, you can create a page rule. See example https://support.cloudflare.com/hc/en-us/articles/200172286-Configuring-URL-forwarding-or-redirects-with-Cloudflare-Page-Rules

Body:
I have a website hosted on GCP bucket and I use cloudflare for HTTPS.
How can I use .htaccess file to remove www. from all website pages and redirect them to HTTPS?

Basically, I want:

http://www.example.com/ redirect to https://example.com/
https://www.example.com/ redirect to https://example.com/

and any other pages like
https://www.example.com/about.html or http://www.example.com/about.html redirect to https://example.com/about.html

I found the configuration for the .htaccess file that I need to add to the root directory of my website:

Catch all and redirect www to no-www (HTTPS):

RewriteEngine On
RewriteCond %{HTTP_HOST} ^www.example.com$ [NC]
RewriteRule ^(.*)$ https://example.com$1 [R=301,L]

I replaced example.com with my domain name, put the file into the root directory of my GCP bucket and nothing happened. If I try to access my website by http://example.com I get DNS_PROBE_FINISHED_NXDOMAIN error. I tried to save .htaccess with ANSI and with UTF-8 with the same result.

How do I:

Remove www. from my website using .htaccess

Redirect users to https:// without www.

What encoding should I use for .htaccess? Does it matter?

Is this even possible with my GCP bucket hosted static website and cloudflare provided https://?

I tried setting up redirects through my domain registrar's control panel, but they don't support redirects with dns nameservers other than their own default ones.


来源: stackexchange

问:
Unable to Group and Sum Properly
I have data similar to this Sample Data:

```<code>   Cities Country    Date Cases
1      BE       A 2/12/20    12
2      BD       A 2/12/20   244
3      BF       A 2/12/20     1
4               V 2/12/20    13
5               Q 2/13/20     2
6               D 2/14/20     4
7      GH       N 2/15/20     6
8      DA       N 2/15/20   624
9      AG       J 2/15/20   204
10     FS       U 2/16/20   433
11     FR       U 2/16/20    38
</code>```

I want to organize the data by on the date and country and then sum a country's daily case. However, I try something like, it reveal the total sum:

```<code>my_data %>%
  group_by(Country, Date)%>%
  summarize(Cases=sum(Cases))
</code>```

答:
We can also use aggregate

```<code>aggregate(Cases ~ Country + Date, my_data, sum)
</code>```

ContentLicense: CC BY-SA 4.0

Title: Unable to Group and Sum Properly

Body:
I have data similar to this Sample Data:

   Cities Country    Date Cases
1      BE       A 2/12/20    12
2      BD       A 2/12/20   244
3      BF       A 2/12/20     1
4               V 2/12/20    13
5               Q 2/13/20     2
6               D 2/14/20     4
7      GH       N 2/15/20     6
8      DA       N 2/15/20   624
9      AG       J 2/15/20   204
10     FS       U 2/16/20   433
11     FR       U 2/16/20    38

I want to organize the data by on the date and country and then sum a country's daily case. However, I try something like, it reveal the total sum:

my_data %>%
  group_by(Country, Date)%>%
  summarize(Cases=sum(Cases))

Body:
We can also use aggregate

aggregate(Cases ~ Country + Date, my_data, sum)


问:
Hide main Octave window while running script that shows a plot
I am currently displaying a plot using a script run from the Windows command line successfully. Is there a way to hide the main Octave window (GUI or CLI), but still show the plot and any message boxes? </p>

答:
```<code>$ cat prova.m
x=1:20;
plot(x)
pause(5)
</code>```

the graph is plot and the CLI is never shown

```<code>$ octave-cli prova.m
</code>```

Body:
$ cat prova.m
x=1:20;
plot(x)
pause(5)

the graph is plot and the CLI is never shown

$ octave-cli prova.m


问:
Javascript arrays not working in some instances for WebGL
I'm working on a OBJ file reader for WebGL and I'm having problems rendering the read triangles.
When I try to draw the triangles I get this error: [Error] WebGL: INVALID_OPERATION: drawArrays: attempt to access out of bounds arrays This is my source code:

```<code>function ObjModel(filename, shader, gl) {
  var readVertices = {}, readUVs = {}, readNormals = {};
  var verticesIdx = 0, uvIndices = 0, normalIndices = 0;

  var tmpVertices = {}, tmpUVs = {}, tmpNormals = {};
  var tmpVerticesIdx = 0;

  this.components = {};

  loadFileAsText(filename, (result) => {
    if(lines[i][0] == "v" && lines[i][1] == " ") {
        var floats = lines[i].split(" ");

        readVertices[verticesIdx + 0] = parseFloat(floats[1]);
        readVertices[verticesIdx + 1] = parseFloat(floats[2]);
        readVertices[verticesIdx + 2] = parseFloat(floats[3]);

        verticesIdx += 3;
      }

      if(lines[i][0] == "f") {
        var points = lines[i].split(" ");
        var point1 = points[1].split("/");
        var point2 = points[2].split("/");
        var point3 = points[3].split("/");

        tmpVertices[tmpVerticesIdx + 0] = readVertices[parseInt(point1[0]) - 1];
        tmpVertices[tmpVerticesIdx + 1] = readVertices[parseInt(point2[0]) - 1];
        tmpVertices[tmpVerticesIdx + 2] = readVertices[parseInt(point3[0]) - 1];

        tmpUVs[tmpVerticesIdx + 0] = readUVs[parseInt(point1[1]) - 1];
        tmpUVs[tmpVerticesIdx + 1] = readUVs[parseInt(point2[1]) - 1];
        tmpUVs[tmpVerticesIdx + 2] = readUVs[parseInt(point3[1]) - 1];

        tmpNormals[tmpVerticesIdx + 0] = readNormals[parseInt(point1[2]) - 1];
        tmpNormals[tmpVerticesIdx + 1] = readNormals[parseInt(point2[2]) - 1];
        tmpNormals[tmpVerticesIdx + 2] = readNormals[parseInt(point3[2]) - 1];

        tmpVerticesIdx += 3;
      }
    }

    this.components[0] = new ObjComponent(tmpVertices, tmpUVs, tmpNormals);

    this.cluster = new TriangleCluster(this.components[0].vertices, this.components[0].uvs, this.components[0].normals, 1, shader, gl);
  });
}
</code>```

The interesting part are the last two lines. The ObjComponent is this simple class:

```<code>function ObjComponent(vertices, uvs, normals) {
  this.vertices = vertices;
  this.uvs = uvs;
  this.normals = normals;
}
</code>```

That just contains the arrays for the vertices, uns and normals. The TriangleCluster is the class that draws the triangles.
With this code I get the errors message from above but setting the arrays by my self to some values works, so the somehow the arrays don't work. But I can access the elements of the tmpVertices. I printed the array content inside the render function of the TriangleCluster and the data is still ok

This is my TriangleCluster class:

```<code>function TriangleCluster(vertices, uvs, normals, triangleNumber, shader, gl) {
  shader.use();

  this.vertices = vertices;
  this.uvs = uvs;
  this.normals = normals;

  var verticesBuffer = new ArrayBufferFloat(this.vertices, gl);
  var verticesAttribLocation = new VertexAttribPointerFloat(shader.getProgram(), "vertex", 3, 3, 0, gl);

  var uvsBuffer = new ArrayBufferFloat(this.uvs, gl);
  var uvsAttribLocation = new VertexAttribPointerFloat(shader.getProgram(), "uv", 2, 2, 0, gl);

  var normalsBuffer = new ArrayBufferFloat(this.normals, gl);
  var normalsAttribLocation = new VertexAttribPointerFloat(shader.getProgram(), "normal", 3, 3, 0, gl);

  this.render = function() {
    verticesBuffer.bind();
    verticesAttribLocation.bind();
    uvsBuffer.bind();
    uvsAttribLocation.bind();
    normalsBuffer.bind();
    normalsAttribLocation.bind();

    this.texture.activate(gl.TEXTURE0);

    gl.drawArrays(gl.TRIANGLES, 0, triangleNumber * 3);
  }
}
</code>```

Could this behavior come from my ArrayBuffer class, where I create a new Float32Array that it doesn't work with the parseFloat?

So where is the problem, in the code?

答: The problem is, that for some reason JS doesn't like the array conversions.</p>

Body:
I'm working on a OBJ file reader for WebGL and I'm having problems rendering the read triangles.
When I try to draw the triangles I get this error: [Error] WebGL: INVALID_OPERATION: drawArrays: attempt to access out of bounds arrays This is my source code:

function ObjModel(filename, shader, gl) {
  var readVertices = {}, readUVs = {}, readNormals = {};
  var verticesIdx = 0, uvIndices = 0, normalIndices = 0;

  var tmpVertices = {}, tmpUVs = {}, tmpNormals = {};
  var tmpVerticesIdx = 0;

  this.components = {};

  loadFileAsText(filename, (result) => {
    if(lines[i][0] == "v" && lines[i][1] == " ") {
        var floats = lines[i].split(" ");

        readVertices[verticesIdx + 0] = parseFloat(floats[1]);
        readVertices[verticesIdx + 1] = parseFloat(floats[2]);
        readVertices[verticesIdx + 2] = parseFloat(floats[3]);

        verticesIdx += 3;
      }

      if(lines[i][0] == "f") {
        var points = lines[i].split(" ");
        var point1 = points[1].split("/");
        var point2 = points[2].split("/");
        var point3 = points[3].split("/");

        tmpVertices[tmpVerticesIdx + 0] = readVertices[parseInt(point1[0]) - 1];
        tmpVertices[tmpVerticesIdx + 1] = readVertices[parseInt(point2[0]) - 1];
        tmpVertices[tmpVerticesIdx + 2] = readVertices[parseInt(point3[0]) - 1];

        tmpUVs[tmpVerticesIdx + 0] = readUVs[parseInt(point1[1]) - 1];
        tmpUVs[tmpVerticesIdx + 1] = readUVs[parseInt(point2[1]) - 1];
        tmpUVs[tmpVerticesIdx + 2] = readUVs[parseInt(point3[1]) - 1];

        tmpNormals[tmpVerticesIdx + 0] = readNormals[parseInt(point1[2]) - 1];
        tmpNormals[tmpVerticesIdx + 1] = readNormals[parseInt(point2[2]) - 1];
        tmpNormals[tmpVerticesIdx + 2] = readNormals[parseInt(point3[2]) - 1];

        tmpVerticesIdx += 3;
      }
    }

    this.components[0] = new ObjComponent(tmpVertices, tmpUVs, tmpNormals);

    this.cluster = new TriangleCluster(this.components[0].vertices, this.components[0].uvs, this.components[0].normals, 1, shader, gl);
  });
}

The interesting part are the last two lines. The ObjComponent is this simple class:

function ObjComponent(vertices, uvs, normals) {
  this.vertices = vertices;
  this.uvs = uvs;
  this.normals = normals;
}

That just contains the arrays for the vertices, uns and normals. The TriangleCluster is the class that draws the triangles.
With this code I get the errors message from above but setting the arrays by my self to some values works, so the somehow the arrays don't work. But I can access the elements of the tmpVertices. I printed the array content inside the render function of the TriangleCluster and the data is still ok

This is my TriangleCluster class:

function TriangleCluster(vertices, uvs, normals, triangleNumber, shader, gl) {
  shader.use();

  this.vertices = vertices;
  this.uvs = uvs;
  this.normals = normals;

  var verticesBuffer = new ArrayBufferFloat(this.vertices, gl);
  var verticesAttribLocation = new VertexAttribPointerFloat(shader.getProgram(), "vertex", 3, 3, 0, gl);

  var uvsBuffer = new ArrayBufferFloat(this.uvs, gl);
  var uvsAttribLocation = new VertexAttribPointerFloat(shader.getProgram(), "uv", 2, 2, 0, gl);

  var normalsBuffer = new ArrayBufferFloat(this.normals, gl);
  var normalsAttribLocation = new VertexAttribPointerFloat(shader.getProgram(), "normal", 3, 3, 0, gl);

  this.render = function() {
    verticesBuffer.bind();
    verticesAttribLocation.bind();
    uvsBuffer.bind();
    uvsAttribLocation.bind();
    normalsBuffer.bind();
    normalsAttribLocation.bind();

    this.texture.activate(gl.TEXTURE0);

    gl.drawArrays(gl.TRIANGLES, 0, triangleNumber * 3);
  }
}

Could this behavior come from my ArrayBuffer class, where I create a new Float32Array that it doesn't work with the parseFloat?

So where is the problem, in the code?


问:
Is it possible to generate random numbers through physical process simulation?
Is it possible to generate random numbers through physical process simulation?

If I simulate the physical roll of a dice (i.e. you picking it up, shaking it in your hand, releasing it onto the table and recording which side ends up "up"...) will that produce a "random" number or would I just have a complex simulation which really accomplishes nothing.

答:
Yes, you would "just have a complex simulation which really accomplishes nothing".

Why simulate a random physical process, when you could actually use a real one?

There are stacks of questions about random number generators on SO. Here are just a few:

True random number generator

Do stateless random number generators exist?

What Type of Random Number Generator is Used in the Casino Gaming Industry?

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Jonathan Leffler

OwnerDisplayName: Mitch Wheat


问:
Is XSS input a threat if ONLY the same user will see it?
What exactly can a malicious user gain if the XSS input he enters will be viewed only by him? Is there anything he can gain?

I understand how XSS is a problem when the malicious user input will be viewed by all site users. But if each user view only his own input, his malicious input will be viewed only by him, so my questions:

can this affect other users indirectly in some way?

what can he gain from this?

答:
I think you're asking:

Can reflected (XSS) code have
an effect on other visitors prior to
distributing the link - i.e. during testing

and

What advantage such testing may
achieve for the malicious user

If I'm reading you correctly, my answer would be as follows:

XSS is about running client-side
code - usually JavaScript - in an
unsuspecting user's  browser and
will have no effect on other users
beyond what is achieved either by
distributing it via a link,
persuading a user to enter it
directly or finding a way for it to
persist on a given page.

If you are asking whether it could
cause some form of command execution
on the server, that would be code
injection or command injection rather
than XSS; the malicious user would
either need to be fortunate enough
to discover the site uses
Server-side JavaScript or be bad
enough at coding that they're
actually doing something entirely
different to what they thought!

Either way, this would require the
site to be vulnerable to this form
of injection and is beyond the scope
of what XSS is about.

If we're talking XSS, testing allows
the malicious user to properly craft
their final code / link so it is
as covert as possible and does
whatever evil deed they intend it
to.

Unless someone or some system is
keeping a watchful eye on the logs
for e.g. multiple strange HTTP requests,
the malicious user will be able to
perfect their exploit so that when
their tweet / email / whatever goes
viral it has the desired effect.

HTH

ContentLicense: CC BY-SA 3.0


问:
Coding exercise - grabbing garbage for each player movement python
Imagine a bi-dimensional grid (NxN) where each square has garbage in it, for each movement described by N, S, E, W (for north, south, east and west), the player moves accordingly and grabs the garbage there was in that square.

If the input = 'NESW' the output should be = 4
- 1 for square the player started
- 1 going north, 1 going East, 1 going South and 0 going West because he reaches the initial square where he started which is already "cleaned"

For input = 'NSNSNSNS' output = 2 for the same reason.

I'm having trouble counting the garbage and knowing if the player already went to that place.

```<code>def total_garbage(positions):
  garbage = 0
  N, S, E, W = 0, 0, 0, 0

  for direction in positions:

    if direction.upper() == 'N':
      N += 1
      garbage += 1
    elif direction.upper() == 'S':
      S += 1
      garbage += 1
    elif direction.upper() == 'E':
      E += 1
      garbage += 1
    elif direction.upper() == 'W':
      W += 1
      garbage += 1

  if N == S and E == W and E != 0 and W != 0:
    return garbage
  elif N == S and E == 0 and W == 0:
    return (garbage - min(N,S))

qp = total_garbage(['N','E','S','W'])
print(qp)
</code>```

This is what I have so far, it was just to start and try some stuff, but haven't been very successful :/

答:
since your grid is two dimensional, model it as a 2D grid - so choose a starting location (say (0,0)) and each direction alters that location - so from (0,0):

N becomes (0,-1)

S becomes (0,1)

E becomes (1,0)

W becomes (-1,0)

and so on

You store the locations you have visited in a python set - and before you go to a new location, you check if that location isn't already in a set. That is if you want only one piece of garbage per location - if you want eventually to have mutliple pieces, you can model the grid as a dictionary; but as a set -

```<code>def total_garbage(positions):

    # Create a dictionary translating direction to co-ordinate changes
    deltas = {'N':(0,-1),'S':{0,1),'E':(1,0),'W':(-1,0)}

    cleaned_locations = set()
    start_location = (0,0)
    garbage = 0

    for direction in positions:
        dx, dy = deltas[direction]
        x,y = start_location
        nx, xy = x + dx, y+dx

       # Count this site so long as it isn't already cleaned.
       if (nx, ny) not in cleaned:
          garbage += 1
          cleaned.add((nx,ny))
      else:
          return garbage

qp = total_garbage(['N','E','S','W'])
print(qp)
</code>```

Body:
Imagine a bi-dimensional grid (NxN) where each square has garbage in it, for each movement described by N, S, E, W (for north, south, east and west), the player moves accordingly and grabs the garbage there was in that square.

If the input = 'NESW' the output should be = 4
- 1 for square the player started
- 1 going north, 1 going East, 1 going South and 0 going West because he reaches the initial square where he started which is already "cleaned"

For input = 'NSNSNSNS' output = 2 for the same reason.

I'm having trouble counting the garbage and knowing if the player already went to that place.

def total_garbage(positions):
  garbage = 0
  N, S, E, W = 0, 0, 0, 0

  for direction in positions:

    if direction.upper() == 'N':
      N += 1
      garbage += 1
    elif direction.upper() == 'S':
      S += 1
      garbage += 1
    elif direction.upper() == 'E':
      E += 1
      garbage += 1
    elif direction.upper() == 'W':
      W += 1
      garbage += 1

  if N == S and E == W and E != 0 and W != 0:
    return garbage
  elif N == S and E == 0 and W == 0:
    return (garbage - min(N,S))

qp = total_garbage(['N','E','S','W'])
print(qp)

This is what I have so far, it was just to start and try some stuff, but haven't been very successful :/

Body:
since your grid is two dimensional, model it as a 2D grid - so choose a starting location (say (0,0)) and each direction alters that location - so from (0,0):

N becomes (0,-1)

S becomes (0,1)

E becomes (1,0)

W becomes (-1,0)

and so on

You store the locations you have visited in a python set - and before you go to a new location, you check if that location isn't already in a set. That is if you want only one piece of garbage per location - if you want eventually to have mutliple pieces, you can model the grid as a dictionary; but as a set -

def total_garbage(positions):

    # Create a dictionary translating direction to co-ordinate changes
    deltas = {'N':(0,-1),'S':{0,1),'E':(1,0),'W':(-1,0)}

    cleaned_locations = set()
    start_location = (0,0)
    garbage = 0

    for direction in positions:
        dx, dy = deltas[direction]
        x,y = start_location
        nx, xy = x + dx, y+dx

       # Count this site so long as it isn't already cleaned.
       if (nx, ny) not in cleaned:
          garbage += 1
          cleaned.add((nx,ny))
      else:
          return garbage

qp = total_garbage(['N','E','S','W'])
print(qp)


问:
Use variables in json path expressions
I have a feature file to retrieve the data from csv file for the given parameter. In order to do it, I need to use a variable in the JsonPath expression to retrieve data for given parameter. I tried may ways, but using variable in jsonPath is not working. I'm using 0.9.4 version

I tried the below ways:

```<code> * def userId = get[0] testData[?(@.UserType=='${userType}')].UserId
     * def userId = get[0] testData[?(@.UserType==userType)].UserId
     * def userId = get[0] testData[?(@.UserType=='#(userType)')].UserId(I suppose this can only be used in json/xml)
</code>```

Below hard coded value works fine:

```<code> * def userId = get[0] testData[?(@.UserType=='SuperAdmin')].UserId
</code>```

Called feature:

Feature: Utility to extract the various types of data from excel datasource

Background:

```<code> * def DataUtility = Java.type('com.org.utils.DataUtility')
 * def dataUtils = new DataUtility()
     * def testData = read('classpath:testdata/TestData.csv')
</code>```

Scenario: Retrieve userId for a given user type

```<code>      * def userId = get[0] testData[?(@.UserType=='${userType}')].UserId
</code>```

Calling feature:

```<code> * table params
 |   userType   |
 | 'SuperAdmin' |

     * def extractedData = call read('DataExtractor.feature') params
     * def userID = extractedData[0].userId
</code>```

答:
I have tried using variables in Json Path.
Example:

```<code>String elementPath = "$.[" + i + "].item.value";
</code>```

In this statement, i is a loop variable. After this pass it to the read api of DocumentContext.
It has worked perfectly fine for me.
I am using JsonPath & DocumentContext from jayway to achieve this.

```<code>import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.JsonPath;
</code>```

Title: Use variables in json path expressions

Body:
I have a feature file to retrieve the data from csv file for the given parameter. In order to do it, I need to use a variable in the JsonPath expression to retrieve data for given parameter. I tried may ways, but using variable in jsonPath is not working. I'm using 0.9.4 version

I tried the below ways:

 * def userId = get[0] testData[?(@.UserType=='${userType}')].UserId
     * def userId = get[0] testData[?(@.UserType==userType)].UserId
     * def userId = get[0] testData[?(@.UserType=='#(userType)')].UserId(I suppose this can only be used in json/xml)

Below hard coded value works fine:

 * def userId = get[0] testData[?(@.UserType=='SuperAdmin')].UserId

Called feature:

Feature: Utility to extract the various types of data from excel datasource

Background:

 * def DataUtility = Java.type('com.org.utils.DataUtility')
 * def dataUtils = new DataUtility()
     * def testData = read('classpath:testdata/TestData.csv')

Scenario: Retrieve userId for a given user type

      * def userId = get[0] testData[?(@.UserType=='${userType}')].UserId

Calling feature:

 * table params
 |   userType   |
 | 'SuperAdmin' |

     * def extractedData = call read('DataExtractor.feature') params
     * def userID = extractedData[0].userId

Body:
I have tried using variables in Json Path.
Example:

String elementPath = "$.[" + i + "].item.value";

In this statement, i is a loop variable. After this pass it to the read api of DocumentContext.
It has worked perfectly fine for me.
I am using JsonPath & DocumentContext from jayway to achieve this.

import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.JsonPath;


问:
How to show specific variable in jQuery from JSON REST-API?
After using the get method I am getting following JSON.

API link https://infocityonline.com/tennis/rest-api/?id=bitcoin

I want to show JSON id value in #id and symbol value in #symbol div.

Right now my code is just showing data in the console.

<!DOCTYPE html>

```

```[
    {
        "id": "bitcoin",
        "symbol": "btc",
        "name": "Bitcoin",
        "image": "https://assets.coingecko.com/coins/images/1/large/bitcoin.png?1547033579",
        "current_price": 9409.45,
        "market_cap": 173153275856,
        "market_cap_rank": 1,
        "total_volume": 30609526190,
        "high_24h": 9582.42,
        "low_24h": 9350.51,
        "price_change_24h": -29.23718676,
        "price_change_percentage_24h": -0.30976,
        "market_cap_change_24h": -986277704.740356,
        "market_cap_change_percentage_24h": -0.56637,
        "circulating_supply": 18388787.0,
        "total_supply": 21000000.0,
        "ath": 19665.39,
        "ath_change_percentage": -52.07157,
        "ath_date": "2017-12-16T00:00:00.000Z",
        "atl": 67.81,
        "atl_change_percentage": 13799.79978,
        "atl_date": "2013-07-06T00:00:00.000Z",
        "roi": null,
        "last_updated": "2020-05-29T18:15:23.854Z"
    }
]

```

答:
You can do something like this

```<code>$.ajax(settings).done(function (response) {
response = JSON.parse(response)
 document.getElementById('id').innerHTML = response[0].id;
document.getElementById('symbol').innerHTML = response[0].symbol
});
</code>```

Here is the codepen: https://codepen.io/kishin-karra/pen/VwvoeLm

Body:
After using the get method I am getting following JSON.

API link https://infocityonline.com/tennis/rest-api/?id=bitcoin

I want to show JSON id value in #id and symbol value in #symbol div.

Right now my code is just showing data in the console.

<!DOCTYPE html>

[
    {
        "id": "bitcoin",
        "symbol": "btc",
        "name": "Bitcoin",
        "image": "https://assets.coingecko.com/coins/images/1/large/bitcoin.png?1547033579",
        "current_price": 9409.45,
        "market_cap": 173153275856,
        "market_cap_rank": 1,
        "total_volume": 30609526190,
        "high_24h": 9582.42,
        "low_24h": 9350.51,
        "price_change_24h": -29.23718676,
        "price_change_percentage_24h": -0.30976,
        "market_cap_change_24h": -986277704.740356,
        "market_cap_change_percentage_24h": -0.56637,
        "circulating_supply": 18388787.0,
        "total_supply": 21000000.0,
        "ath": 19665.39,
        "ath_change_percentage": -52.07157,
        "ath_date": "2017-12-16T00:00:00.000Z",
        "atl": 67.81,
        "atl_change_percentage": 13799.79978,
        "atl_date": "2013-07-06T00:00:00.000Z",
        "roi": null,
        "last_updated": "2020-05-29T18:15:23.854Z"
    }
]

Body:
You can do something like this

$.ajax(settings).done(function (response) {
response = JSON.parse(response)
 document.getElementById('id').innerHTML = response[0].id;
document.getElementById('symbol').innerHTML = response[0].symbol
});

Here is the codepen: https://codepen.io/kishin-karra/pen/VwvoeLm


问:
Wrong number of items passed 5, placement implies 1
I am trying to create a line graph and scatter plot on the same figure. There should be two lines and two scatterplots.

```<code>datamax['datamax'] = datamax2015['Data_Value']
datamin['datamin'] = datamin2015['Data_Value']

ax = plt.gca()
datamax.plot(kind='line',x='Date',y='Data_Value',color='red',ax=ax)
datamin.plot(kind='line',x='Date',y='Data_Value', color='blue',ax=ax)
datamax.plot(kind='scatter',x='Date',y='breakup',color='red',ax=ax)
datamin.plot(kind='scatter',x='Date',y='breakdown', color='blue',ax=ax)

plt.ylabel("Temperature (degrees C)",color='navy')
plt.xlabel("Date",color='navy',labelpad=15)
plt.title('Record high and low temperatures by day (2005-2014)', alpha=1.0,color='brown',y=1.08)
ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.35),
          fancybox=False,labels=['Record high','Record low'])
plt.xticks(rotation=30)
plt.fill_between(range(len(datamax['Date'])), datamax['Data_Value'], datamin['Data_Value'],color='yellow',alpha=0.8)
plt.show()
</code>```

However, I keep getting the error:

ValueError: Wrong number of items passed 5, placement implies 1

When I modify the code to this:

```<code>datamax['datamax'] = datamax2015['Data_Value']
datamin['datamin'] = datamin2015['Data_Value']
datamax['breakup'] = datamax[datamax['datamax']>datamax['Data_Value']]
datamin['breakdown'] = datamin[datamin['datamin']<datamin['Data_Value']]

ax = plt.gca()
datamax.plot(kind='line',x='Date',y='Data_Value',color='red',ax=ax)
datamin.plot(kind='line',x='Date',y='Data_Value', color='blue',ax=ax)

plt.ylabel("Temperature (degrees C)",color='navy')
plt.xlabel("Date",color='navy',labelpad=15)
plt.title('Record high and low temperatures by day (2005-2014)', alpha=1.0,color='brown',y=1.08)
ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.35),
          fancybox=False,labels=['Record high','Record low'])
plt.xticks(rotation=30)
plt.fill_between(range(len(datamax['Date'])), datamax['Data_Value'], datamin['Data_Value'],color='yellow',alpha=0.8)
plt.show()
</code>```

The code works, and gives me the output:

Could anybody let me know what I'm doing wrong?

This line is giving me the error: datamax['breakup'] = datamax[datamax['datamax']>datamax['Data_Value']]

答:
You are using the whole of the dataframe and assigning it to a single column. I think you need the following condition</p>

```<code>datamax['breakup'] = datamax['datamax'][datamax['datamax']>datamax['Data_Value']]
datamin['breakdown'] = datamin['datamin'][datamin['datamin']<datamin['Data_Value']]
</code>```

Body:
I am trying to create a line graph and scatter plot on the same figure. There should be two lines and two scatterplots.

datamax['datamax'] = datamax2015['Data_Value']
datamin['datamin'] = datamin2015['Data_Value']

ax = plt.gca()
datamax.plot(kind='line',x='Date',y='Data_Value',color='red',ax=ax)
datamin.plot(kind='line',x='Date',y='Data_Value', color='blue',ax=ax)
datamax.plot(kind='scatter',x='Date',y='breakup',color='red',ax=ax)
datamin.plot(kind='scatter',x='Date',y='breakdown', color='blue',ax=ax)

plt.ylabel("Temperature (degrees C)",color='navy')
plt.xlabel("Date",color='navy',labelpad=15)
plt.title('Record high and low temperatures by day (2005-2014)', alpha=1.0,color='brown',y=1.08)
ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.35),
          fancybox=False,labels=['Record high','Record low'])
plt.xticks(rotation=30)
plt.fill_between(range(len(datamax['Date'])), datamax['Data_Value'], datamin['Data_Value'],color='yellow',alpha=0.8)
plt.show()

However, I keep getting the error:

ValueError: Wrong number of items passed 5, placement implies 1

When I modify the code to this:

datamax['datamax'] = datamax2015['Data_Value']
datamin['datamin'] = datamin2015['Data_Value']
datamax['breakup'] = datamax[datamax['datamax']>datamax['Data_Value']]
datamin['breakdown'] = datamin[datamin['datamin']<datamin['Data_Value']]

ax = plt.gca()
datamax.plot(kind='line',x='Date',y='Data_Value',color='red',ax=ax)
datamin.plot(kind='line',x='Date',y='Data_Value', color='blue',ax=ax)

plt.ylabel("Temperature (degrees C)",color='navy')
plt.xlabel("Date",color='navy',labelpad=15)
plt.title('Record high and low temperatures by day (2005-2014)', alpha=1.0,color='brown',y=1.08)
ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.35),
          fancybox=False,labels=['Record high','Record low'])
plt.xticks(rotation=30)
plt.fill_between(range(len(datamax['Date'])), datamax['Data_Value'], datamin['Data_Value'],color='yellow',alpha=0.8)
plt.show()

The code works, and gives me the output:

Could anybody let me know what I'm doing wrong?

This line is giving me the error: datamax['breakup'] = datamax[datamax['datamax']>datamax['Data_Value']]

Body:
You are using the whole of the dataframe and assigning it to a single column. I think you need the following condition

datamax['breakup'] = datamax['datamax'][datamax['datamax']>datamax['Data_Value']]
datamin['breakdown'] = datamin['datamin'][datamin['datamin']<datamin['Data_Value']]


问:
why do i get two user ids when creating a user in firebase using swift?
when i sign up a user in my ios app it generates a user id and adds that to the data base with the users name and surname and username but it is generating a user id and another random number/id and i dont know what that is for:

i dont know what the Roy... is and dont know where its coming from.
so when i try and access the users uid to access the information such as the name and surname i keep getting the following error because its using the wc7... number and not the other one:

Listener at /Users/wc7VyejKlDNfcAhFu3AkIX9Y9on1/Username failed: permission_denied

this is my code that i use to try and access the users information:

```<code>func fetchUsersData() {

    guard let currentUser = Auth.auth().currentUser?.uid else { return }
    print("Current user id is \(currentUser)")

    Database.database().reference().child("Users").child(currentUser).child(USER_NAME).observeSingleEvent(of: .value) { (snapshot) in
        guard let username = snapshot.value as? String else {return}
        self.navigationItem.title = username
    }
}
</code>```

how do i fix this?

答:
That code is for the Firebase Real Time Database and the screen shot is for Cloud Firestore. They are totally different and unrelated.

If you want to read the data shown in your screenshot you need to use the Cloud Firestore documentation.

The documentID 'Roy...' happens when you don't assign a document an ID... it will generate one automatically.

Also, change your Firestore structure to use the users uid as the documentID. So it would look like this

```<code>users //the collection
   uid_0 //the document with documentID = a users uid
      first_name: "Hank"
      last_name: "Jones"
      user_name: "Hankster"
   uid_1
      first_name: "Leroy"
      last_name: "Jenkins"
      user_name: "Leeeerrroooyyy"
</code>```

and then the code to read a specific user name based on a uid is this

```<code>func readUserName() {
    let users = self.db.collection("users")
    let thisUser = users.document(the users uid)
    thisUser.getDocument(completion: { documentSnapshot, error in
        if let error = error {
            print(error.localizedDescription)
            return
        }

        guard let snap = documentSnapshot else { return }
        let docId = snap.documentID
        let userName = snap.get("user_name") as? String ?? "No Name"
        print(userName)
    })
}
</code>```

Also note that you will need to be authenticated to Firestore to read any data or adjust the Security Rules to allow anyone to read. That's not generally a good idea but when you're just getting started it's ok.

Body:
when i sign up a user in my ios app it generates a user id and adds that to the data base with the users name and surname and username but it is generating a user id and another random number/id and i dont know what that is for:

i dont know what the Roy... is and dont know where its coming from.
so when i try and access the users uid to access the information such as the name and surname i keep getting the following error because its using the wc7... number and not the other one:

Listener at /Users/wc7VyejKlDNfcAhFu3AkIX9Y9on1/Username failed: permission_denied

this is my code that i use to try and access the users information:

func fetchUsersData() {

    guard let currentUser = Auth.auth().currentUser?.uid else { return }
    print("Current user id is \(currentUser)")

    Database.database().reference().child("Users").child(currentUser).child(USER_NAME).observeSingleEvent(of: .value) { (snapshot) in
        guard let username = snapshot.value as? String else {return}
        self.navigationItem.title = username
    }
}

how do i fix this?

Body:
That code is for the Firebase Real Time Database and the screen shot is for Cloud Firestore. They are totally different and unrelated.

If you want to read the data shown in your screenshot you need to use the Cloud Firestore documentation.

The documentID 'Roy...' happens when you don't assign a document an ID... it will generate one automatically.

Also, change your Firestore structure to use the users uid as the documentID. So it would look like this

users //the collection
   uid_0 //the document with documentID = a users uid
      first_name: "Hank"
      last_name: "Jones"
      user_name: "Hankster"
   uid_1
      first_name: "Leroy"
      last_name: "Jenkins"
      user_name: "Leeeerrroooyyy"

and then the code to read a specific user name based on a uid is this

func readUserName() {
    let users = self.db.collection("users")
    let thisUser = users.document(the users uid)
    thisUser.getDocument(completion: { documentSnapshot, error in
        if let error = error {
            print(error.localizedDescription)
            return
        }

        guard let snap = documentSnapshot else { return }
        let docId = snap.documentID
        let userName = snap.get("user_name") as? String ?? "No Name"
        print(userName)
    })
}

Also note that you will need to be authenticated to Firestore to read any data or adjust the Security Rules to allow anyone to read. That's not generally a good idea but when you're just getting started it's ok.


问:
CTABLES with percentage of missings (sysmis + user missing)
I have a SPSS ctables statement that looks somewhat like this

```<code>CTABLES
  /TABLE (foo + bar) [C][ROWPCT.VALIDN PCT40.1, TOTALS[VALIDN F40.0, MISSING, TOTALN F40.0]]
  /CLABELS ROWLABELS=OPPOSITE
  /CATEGORIES VARIABLES=foo bar
    ORDER=A KEY=VALUE EMPTY=INCLUDE TOTAL=YES POSITION=AFTER MISSING=INCLUDE.
</code>```

foo and bar are likert-scaled variables with identical categories.

I got ctables to include the number of system missings. What I need though is the percentage of system missings (or maybe the percentage of system and user missings) with respect to the total number of cases. Is there a way to achieve this by means of SPSS syntax (PCOMPUTE maybe?) or via python?

Regards

答:
I could not find a way to do this with CTABLES syntax, including PCOMPUTE, but a colleague did provide a Python solution. If you have the Python Essentials installed (which are installed by default on recent versions), copy and paste the following code into a syntax window, and after running CTABLES, run it.

```<code>preserve.
set printback none.
begin program python3.
import SpssClient
SpssClient.StartClient()
OutputDoc = SpssClient.GetDesignatedOutputDoc()
OutputItems = OutputDoc.GetOutputItems()
for index in range(OutputItems.Size()):
    OutputItem = OutputItems.GetItemAt(index)
    if OutputItem.GetType() == SpssClient.OutputItemType.PIVOT:
      PivotTable = OutputItem.GetSpecificType()
      ColLabels = PivotTable.ColumnLabelArray()
      for i in range(0,ColLabels.GetNumRows()):
        for j in range(ColLabels.GetNumColumns()):
          try:
            colText=ColLabels.GetValueAt(i,j)
            if colText == "Missing":
              MissingColumn=j
            if colText == "Valid N":
              ValidNColumn=j
            if colText == "Total N":
              TotalNColumn=j
          except:
            pass

      DataCells = PivotTable.DataCellArray()
      for i in range(DataCells.GetNumRows()):
        MissingVal=(DataCells.GetValueAt(i,MissingColumn))
        ValidN=(DataCells.GetValueAt(i,ValidNColumn))
        TotalN=(DataCells.GetValueAt(i,TotalNColumn))
        val= str( 100 * float(MissingVal)/float(TotalN) )
        DataCells.SetValueAt(i,MissingColumn,val)
        DataCells.SetNumericFormatAtWithDecimal(i,MissingColumn,"##.#%",1)

SpssClient.StopClient()
end program.
restore.
</code>```

Here's what the result looks like with a small example dataset:

Body:
I have a SPSS ctables statement that looks somewhat like this

CTABLES
  /TABLE (foo + bar) [C][ROWPCT.VALIDN PCT40.1, TOTALS[VALIDN F40.0, MISSING, TOTALN F40.0]]
  /CLABELS ROWLABELS=OPPOSITE
  /CATEGORIES VARIABLES=foo bar
    ORDER=A KEY=VALUE EMPTY=INCLUDE TOTAL=YES POSITION=AFTER MISSING=INCLUDE.

foo and bar are likert-scaled variables with identical categories.

I got ctables to include the number of system missings. What I need though is the percentage of system missings (or maybe the percentage of system and user missings) with respect to the total number of cases. Is there a way to achieve this by means of SPSS syntax (PCOMPUTE maybe?) or via python?

Regards

Body:
I could not find a way to do this with CTABLES syntax, including PCOMPUTE, but a colleague did provide a Python solution. If you have the Python Essentials installed (which are installed by default on recent versions), copy and paste the following code into a syntax window, and after running CTABLES, run it.

preserve.
set printback none.
begin program python3.
import SpssClient
SpssClient.StartClient()
OutputDoc = SpssClient.GetDesignatedOutputDoc()
OutputItems = OutputDoc.GetOutputItems()
for index in range(OutputItems.Size()):
    OutputItem = OutputItems.GetItemAt(index)
    if OutputItem.GetType() == SpssClient.OutputItemType.PIVOT:
      PivotTable = OutputItem.GetSpecificType()
      ColLabels = PivotTable.ColumnLabelArray()
      for i in range(0,ColLabels.GetNumRows()):
        for j in range(ColLabels.GetNumColumns()):
          try:
            colText=ColLabels.GetValueAt(i,j)
            if colText == "Missing":
              MissingColumn=j
            if colText == "Valid N":
              ValidNColumn=j
            if colText == "Total N":
              TotalNColumn=j
          except:
            pass

      DataCells = PivotTable.DataCellArray()
      for i in range(DataCells.GetNumRows()):
        MissingVal=(DataCells.GetValueAt(i,MissingColumn))
        ValidN=(DataCells.GetValueAt(i,ValidNColumn))
        TotalN=(DataCells.GetValueAt(i,TotalNColumn))
        val= str( 100 * float(MissingVal)/float(TotalN) )
        DataCells.SetValueAt(i,MissingColumn,val)
        DataCells.SetNumericFormatAtWithDecimal(i,MissingColumn,"##.#%",1)

SpssClient.StopClient()
end program.
restore.

Here's what the result looks like with a small example dataset:


问:
List C++ Move to front;
Hello i need to find the earliest note in one-Way listy
Unfortunately i can`t use list container.
Here some code

```<code>Struct

    struct Sterminarz
{
    Sterminarz *next=NULL;
    int year;
    int month;
    int day;
    int hour;
    string note;

};
</code>```

Function which look for earliest note

```<code>  void findEarliest(Sterminarz *head)
{
    Sterminarz *p, *min;
    min = head;
    int counter = 0;

    for(p=head->next;p;p=p->next)
    {
        if (p->hour < min->hour)
        {
            min = p;
            counter++;
            printNote(min, counter);

        }
    }

}
</code>```

And i don't know how to move earliest element to the beginning of the list without list container.

答:
Try something like this:

struct Sterminarz
{
    Sterminarz *next = NULL;
    int year;
    int month;
    int day;
    int hour;
    string note;

    bool operator<(const Sterminarz &rhs) const {
        if (year < rhs.year) return true;
        if (year > rhs.year) return false;

        if (month < rhs.month) return true;
        if (month > rhs.month) return false;

        if (day < rhs.day) return true;
        if (day > rhs.day) return false;

        return (hour < rhs.hour);

        /* alternatively:
        return std::tie(year, month, day, hour) < std::tie(rhs.year, rhs.month, rhs.day, rhs.hour);
        */
    }

    /* or, if you just want to compare hours by themselves
    bool operator<(const Sterminarz &rhs) const {
        return (hour < rhs.hour);
    }
    */
};

Sterminarz* findEarliest(Sterminarz *head, Sterminarz** beforeEarliest)
{
    if (beforeEarliest)
        *beforeEarliest = NULL;

    if (!head)
        return NULL;

    Sterminarz *p, *previous = head, *earliest = head;
    int counter = 0;

    for(p = head->next; p; p = p->next)
    {
        if (*p < *earliest)
        {
            earliest = p;
            if (beforeEarliest) *beforeEarliest = previous;
            counter++;
            printNote(earliest, counter);
        }
        previous = p;
    }

    return earliest;
}
```

<p>And then you can do this to move the earliest node to the front of the list:</p>

<pre class="lang-cpp prettyprint-override"><code>Sterminarz *head;
...
Sterminarz *beforeEarliest;
Sterminarz *earliest = findEarliest(head, &beforeEarliest);
if (earliest != head)
{
    beforeEarliest->next = earliest->next;
    earliest->next = head;
    head = earliest;
}
</code>```

Live Demo

Title: List C++ Move to front;

Body:
Hello i need to find the earliest note in one-Way listy
Unfortunately i can`t use list container.
Here some code

Struct

    struct Sterminarz
{
    Sterminarz *next=NULL;
    int year;
    int month;
    int day;
    int hour;
    string note;

};

Function which look for earliest note

  void findEarliest(Sterminarz *head)
{
    Sterminarz *p, *min;
    min = head;
    int counter = 0;

    for(p=head->next;p;p=p->next)
    {
        if (p->hour < min->hour)
        {
            min = p;
            counter++;
            printNote(min, counter);

        }
    }

}

And i don't know how to move earliest element to the beginning of the list without list container.

Body:
Try something like this:

struct Sterminarz
{
    Sterminarz *next = NULL;
    int year;
    int month;
    int day;
    int hour;
    string note;

    bool operator<(const Sterminarz &rhs) const {
        if (year < rhs.year) return true;
        if (year > rhs.year) return false;

        if (month < rhs.month) return true;
        if (month > rhs.month) return false;

        if (day < rhs.day) return true;
        if (day > rhs.day) return false;

        return (hour < rhs.hour);

        /* alternatively:
        return std::tie(year, month, day, hour) < std::tie(rhs.year, rhs.month, rhs.day, rhs.hour);
        */
    }

    /* or, if you just want to compare hours by themselves
    bool operator<(const Sterminarz &rhs) const {
        return (hour < rhs.hour);
    }
    */
};

Sterminarz* findEarliest(Sterminarz *head, Sterminarz** beforeEarliest)
{
    if (beforeEarliest)
        *beforeEarliest = NULL;

    if (!head)
        return NULL;

    Sterminarz *p, *previous = head, *earliest = head;
    int counter = 0;

    for(p = head->next; p; p = p->next)
    {
        if (*p < *earliest)
        {
            earliest = p;
            if (beforeEarliest) *beforeEarliest = previous;
            counter++;
            printNote(earliest, counter);
        }
        previous = p;
    }

    return earliest;
}

And then you can do this to move the earliest node to the front of the list:

Sterminarz *head;
...
Sterminarz *beforeEarliest;
Sterminarz *earliest = findEarliest(head, &beforeEarliest);
if (earliest != head)
{
    beforeEarliest->next = earliest->next;
    earliest->next = head;
    head = earliest;
}

Live Demo


问:
passing custom parameters to facebook fan page tab
I'm unable to get custom parameters send to my facebook fan page tab.

I'm using php and is passing like this:

http://www.facebook.com/pages/{page-name}/?sk=APP_ID&pass=1

but I'm unable to read the parameter pass

Sreejith

答:
Facebook passes in your data as part of the signed_Request data.
Here is how you would retrieve it using PHP:

```<code><?php
require 'facebook.php';
$app_id = "YOUR APP ID HERE";
$app_secret = "YOUR SECRET KEY HERE";

$facebook = new Facebook(array(
        'appId' => $app_id,
        'secret' => $app_secret,
        'cookie' => true
));

// THE MAGIC SAUCE
$signed_request = $facebook->getSignedRequest();

$page_id = $signed_request["page"]["id"];
$like_status = $signed_request["page"]["liked"];
// HERE IS A STRING OF YOUR APP DATA.
$app_data = $signed_request["app_data"];

echo '$app_data = '.$app_data;
?>
</code>```

This example requires the Facebook PHP api and will write your app_data into the browser window where you can marvel in all its glory.

Body:
Facebook passes in your data as part of the signed_Request data.
Here is how you would retrieve it using PHP:

<?php
require 'facebook.php';
$app_id = "YOUR APP ID HERE";
$app_secret = "YOUR SECRET KEY HERE";

$facebook = new Facebook(array(
        'appId' => $app_id,
        'secret' => $app_secret,
        'cookie' => true
));

// THE MAGIC SAUCE
$signed_request = $facebook->getSignedRequest();

$page_id = $signed_request["page"]["id"];
$like_status = $signed_request["page"]["liked"];
// HERE IS A STRING OF YOUR APP DATA.
$app_data = $signed_request["app_data"];

echo '$app_data = '.$app_data;
?>

This example requires the Facebook PHP api and will write your app_data into the browser window where you can marvel in all its glory.


答:
You could create an array as Ahmet proposed in the comments, but if you do not want to you could do this like this:

x, y = 0, 0 # this will be our position
visited_idx = set() # indexes where we have already gathered garbage
for direction in positions:
    if direction.upper() == 'N':
      y += 1
    elif direction.upper() == 'S':
      y -= 1
    elif direction.upper() == 'E':
      x += 1
    elif direction.upper() == 'W':
      x -= 1

    current_idx = (x,y)
    # You wrote that there is no garbage in the first cell hence the second codition
    if current_idx not in visited_idx and current_idx != (0,0):
        visited_idx.add(current_idx)

units_of_garbage_gathered = len(visited_idx)
```

Title: Coding exercise - grabbing garbage for each player movement python


问:
GCP Bigquery - query empty values from a record type value
I'm trying to query all resources that has empty records on a specific column but I'm unable to make it work. Here's the query that I'm using:

```<code>SELECT
  service.description,
  project.labels,
  cost AS cost
FROM
  `xxxxxx.xxxxx.xxxx.xxxx`
WHERE
  service.description = 'BigQuery' ;
</code>```

Here's the results:

As you can see, I'm getting everything with that query, but as mentioned, I'm looking to get resources with empty records only for example record 229,230 so on.

Worth to mention that schema for the column I'm trying to query is:

```<code>project.labels  RECORD  REPEATED
</code>```

The above was mentioned because I tried using several combinations of WHERE but everything ends up in error.

答:
To identify empty repeated record - you can use ARRAY_LENGTH in WHERE clause like in below example

```<code>WHERE ARRAY_LENGTH(project.labels) = 0
</code>```

Body:
I'm trying to query all resources that has empty records on a specific column but I'm unable to make it work. Here's the query that I'm using:

SELECT
  service.description,
  project.labels,
  cost AS cost
FROM
  `xxxxxx.xxxxx.xxxx.xxxx`
WHERE
  service.description = 'BigQuery' ;

Here's the results:

As you can see, I'm getting everything with that query, but as mentioned, I'm looking to get resources with empty records only for example record 229,230 so on.

Worth to mention that schema for the column I'm trying to query is:

project.labels  RECORD  REPEATED

The above was mentioned because I tried using several combinations of WHERE but everything ends up in error.

Body:
To identify empty repeated record - you can use ARRAY_LENGTH in WHERE clause like in below example

WHERE ARRAY_LENGTH(project.labels) = 0


问:
.Split method in React
```<code>
const timeHorizonValues = [
  { value: "SHORT", description: "", key: "1" },
  { value: "AVERAGE", description: "", key: "2" },
  { value: "LONGEST", description: "", key: "3" },
];

const liquidityNeedValues = [
  {
    value: "VERY_IMPORTANT",
    description: "",
    key: "1",
  },
  {
    value: "SOMEWHAT_IMPORTANT",
    description: "",
    key: "2",
  },
  {
    value: "NOT_IMPORTANT",
    description: "I",
    key: "3",
  },
];

// VALUES OF liquidityNeedValues + timeHorizonValues = COMBINED IN blahBlahBlahValues. NEW VALUE = value: "NOT_IMPORTANT/LONGEST"

const blahBlahBlahValues =
  {
    value: "NOT_IMPORTANT/LONGEST",
    description:
      "hey there.",
    key: "1",
  },
  {
    value: "NOT_IMPORTANT/LONGEST_1",
    description: "25 years",
    key: "2",
  },
  {
    value: "NOT_IMPORTANT/LONGEST_2",
    description: "80 years",
    key: "3",
  },
  {
    value: "NOT_IMPORTANT/LONGEST_3",
    description: "70 years",
    key: "4",
  },
  {
    value: "NOT_IMPORTANT/AVERAGE",
    description: "200 years",
    key: "5",
  },
  {
    value: "SOMEWHAT_IMPORTANT/SHORT",
    description:
      "Under 5 years",
    key: "6",
  },
];

let hello = {
      timeHorizon: values.timeHorizon,
      liquidityNeeds: values.liquidityNeeds,
    };
</code>```

So to give some context, I am currently displaying two questions.timeHorizonValues+ liquidityNeedValues. I combined these two values/questions and created blahBlahBlahValues. On the frontend I am combining these two values, but the backend still needs to receive them as separate values how the where initially.

I need to be pulling the values for both timeHorizon and liquidityNeeds from blahBlahBlahValues already did this and then setting those as the values to the timeHorizon and liquidityNeeds in the hello object. I need to use the .split() method for strings as a way to separate the values from the single string. I need some help trying to solve this.  The frontend is merging these two fields but the backend expects them as two individual values! thank you for your help!

答:
Your question needs to be reworked as what your asking for doesn't line up with your code. I am guessing you are looking for something like this:

```<code>const newValues = blahBlahBlahValues.map( item => {
   const tempValues = item.value.split("/");
  return {timeHorizon:tempValues [0],liquidityNeeds:tempValues [1]};
}
</code>```

Now you can iterate newValues and submit to your backend.

```<code>newValues.forEach(item => console.log(item.timeHorizon));
</code>```

Updated:

```<code>  const newValues = items.map(item => {
    const tempValues = item.value.split("/");
    return {
      timeHorizon: {
        value: tempValues[1],
        description: item.description,
        key: item.key
      },
      liquidityNeeds: {
        value: tempValues[0],
        description: item.description,
        key: item.key
      }
    };
  });
  newValues.forEach(item => {
    console.log("timeHorizon");
    console.log(item.timeHorizon);
    console.log("liquidityNeeds");
    console.log(item.liquidityNeeds);
  });
</code>```

Title: .Split method in React

Body:
const timeHorizonValues = [
  { value: "SHORT", description: "", key: "1" },
  { value: "AVERAGE", description: "", key: "2" },
  { value: "LONGEST", description: "", key: "3" },
];

const liquidityNeedValues = [
  {
    value: "VERY_IMPORTANT",
    description: "",
    key: "1",
  },
  {
    value: "SOMEWHAT_IMPORTANT",
    description: "",
    key: "2",
  },
  {
    value: "NOT_IMPORTANT",
    description: "I",
    key: "3",
  },
];

// VALUES OF liquidityNeedValues + timeHorizonValues = COMBINED IN blahBlahBlahValues. NEW VALUE = value: "NOT_IMPORTANT/LONGEST"

const blahBlahBlahValues =
  {
    value: "NOT_IMPORTANT/LONGEST",
    description:
      "hey there.",
    key: "1",
  },
  {
    value: "NOT_IMPORTANT/LONGEST_1",
    description: "25 years",
    key: "2",
  },
  {
    value: "NOT_IMPORTANT/LONGEST_2",
    description: "80 years",
    key: "3",
  },
  {
    value: "NOT_IMPORTANT/LONGEST_3",
    description: "70 years",
    key: "4",
  },
  {
    value: "NOT_IMPORTANT/AVERAGE",
    description: "200 years",
    key: "5",
  },
  {
    value: "SOMEWHAT_IMPORTANT/SHORT",
    description:
      "Under 5 years",
    key: "6",
  },
];

let hello = {
      timeHorizon: values.timeHorizon,
      liquidityNeeds: values.liquidityNeeds,
    };

So to give some context, I am currently displaying two questions.timeHorizonValues+ liquidityNeedValues. I combined these two values/questions and created blahBlahBlahValues. On the frontend I am combining these two values, but the backend still needs to receive them as separate values how the where initially.

I need to be pulling the values for both timeHorizon and liquidityNeeds from blahBlahBlahValues already did this and then setting those as the values to the timeHorizon and liquidityNeeds in the hello object. I need to use the .split() method for strings as a way to separate the values from the single string. I need some help trying to solve this.  The frontend is merging these two fields but the backend expects them as two individual values! thank you for your help!

Body:
Your question needs to be reworked as what your asking for doesn't line up with your code. I am guessing you are looking for something like this:

const newValues = blahBlahBlahValues.map( item => {
   const tempValues = item.value.split("/");
  return {timeHorizon:tempValues [0],liquidityNeeds:tempValues [1]};
}

Now you can iterate newValues and submit to your backend.

newValues.forEach(item => console.log(item.timeHorizon));

Updated:

  const newValues = items.map(item => {
    const tempValues = item.value.split("/");
    return {
      timeHorizon: {
        value: tempValues[1],
        description: item.description,
        key: item.key
      },
      liquidityNeeds: {
        value: tempValues[0],
        description: item.description,
        key: item.key
      }
    };
  });
  newValues.forEach(item => {
    console.log("timeHorizon");
    console.log(item.timeHorizon);
    console.log("liquidityNeeds");
    console.log(item.liquidityNeeds);
  });


问:
Python redis server. Expand the number of redis databases
I am using a python redis server. My application needs more than 16 databases, which is the maximum number of databases allowed by redis.

Is there a method to expand the number of redis databases to reach, say, 30 databases?

In an alternative method, I copy the redis dump and paste it into another directory. After that I, create another redis dump.

How can I deal with the two redis dumps in the same script (program)?

答:
yes you must go to redis.conf file and edit it.
this file usually is in this path:
/etc/redis.conf
in this file you see a section like this:

```<code>databases 16
</code>```

you can increase this number to 30.
after saving this file you must restart your device with this command:

```<code>sudo systemctl restart redis
</code>```

and after that you can check status of redis server:

```<code>sudo systemctl status redis
</code>```

you can see more on this link:
https://www.linode.com/docs/databases/redis/install-and-configure-redis-on-centos-7/

Body:
yes you must go to redis.conf file and edit it.
this file usually is in this path:
/etc/redis.conf
in this file you see a section like this:

databases 16

you can increase this number to 30.
after saving this file you must restart your device with this command:

sudo systemctl restart redis

and after that you can check status of redis server:

sudo systemctl status redis

you can see more on this link:
https://www.linode.com/docs/databases/redis/install-and-configure-redis-on-centos-7/


问:
Client is not defined when trying to get Channels
I'm trying to lock a channel between two times, but all I get is an error. I'm quite new to making discord bots, so this is my first one. Where are my errors, how can I fix them, and why does my code not work?

Error:

    ReferenceError: client is not defined
    at getChannel (C:\Users\<User>\DISCORDBOT\main.js:42:2)
    at checkTime (C:\Users\<User>\DISCORDBOT\main.js:48:3)
    at Object.<anonymous> (C:\Users\<user>\DISCORDBOT\main.js:53:1)
    at Module._compile (internal/modules/cjs/loader.js:1138:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10)
    at Module.load (internal/modules/cjs/loader.js:986:32)
    at Function.Module._load (internal/modules/cjs/loader.js:879:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
    at internal/main/run_main_module.js:17:47
```

<p>Code:</p>

<pre class="lang-js prettyprint-override"><code>var Discord = require('discord.io');
var auth = require('./auth.json');
// Initialize Discord Bot
var bot = new Discord.Client({
  token: auth.token,
  autorun: true
});
bot.on('ready', function (evt) {
  bot.sendMessage({
    to: '<ID>',
    message: 'Bot Running!'
  });
})
bot.on('message', function (user, userID, channelID, message, evt) {
  // Our bot needs to know if it will execute a command
  // It will listen for messages that will start with `!`
  if (message.substring(0, 1) == '?') {
    var args = message.substring(1).split(' ');
    var cmd = args[0];

    args = args.splice(1);
    switch (cmd) {
      // !ping
      case 'ping':
        bot.sendMessage({
          to: channelID,
          message: 'Pong!'
        });
        break;
      case 'getinfo':
        bot.sendMessage({
          to: channelID,
          message: 'User Requested Channel data. User: ' + user + ', UserID: ' + userID + ', in ChannelID: ' + channelID
        });
        break;
      // Just add any case commands if you want to..
    }
  }
});

function getChannel(ID) {
  client.channels.get(ID)
}
function checkTime() {
  var today = new Date().getHours();
  console.log(today)
  if (today >= 7 && today <= 22) {
    getChannel("<ID>").updateOverwrite(getChannel("<ID>").guild.roles.everyone, { VIEW_CHANNEL: false });
  } else {

  }
}
checkTime()
</code>```

edit:
I got a new error:

```<code>TypeError: Cannot read property 'get' of undefined
    at getChannel (C:\Users\<User>\DISCORDBOT\main.js:42:15)
    at checkTime (C:\Users\<user>\DISCORDBOT\main.js:48:3)
    at Object.<anonymous> (C:\Users\<User>\DISCORDBOT\main.js:53:1)
    at Module._compile (internal/modules/cjs/loader.js:1138:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10)
    at Module.load (internal/modules/cjs/loader.js:986:32)
    at Function.Module._load (internal/modules/cjs/loader.js:879:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
    at internal/main/run_main_module.js:17:47
</code>```

It seems like it can't get the channel... Anyone know a fix?
I don't know how much of the API, and I really don't understand at all. Sorry if you see very apparent errors that I overlook

答:
That is because you defined it as bot not client

function getChannel(ID) {
    bot.channels.get(ID)
}
```

Body:
I'm trying to lock a channel between two times, but all I get is an error. I'm quite new to making discord bots, so this is my first one. Where are my errors, how can I fix them, and why does my code not work?

Error:

    ReferenceError: client is not defined
    at getChannel (C:\Users\<User>\DISCORDBOT\main.js:42:2)
    at checkTime (C:\Users\<User>\DISCORDBOT\main.js:48:3)
    at Object.<anonymous> (C:\Users\<user>\DISCORDBOT\main.js:53:1)
    at Module._compile (internal/modules/cjs/loader.js:1138:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10)
    at Module.load (internal/modules/cjs/loader.js:986:32)
    at Function.Module._load (internal/modules/cjs/loader.js:879:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
    at internal/main/run_main_module.js:17:47

Code:

var Discord = require('discord.io');
var auth = require('./auth.json');
// Initialize Discord Bot
var bot = new Discord.Client({
  token: auth.token,
  autorun: true
});
bot.on('ready', function (evt) {
  bot.sendMessage({
    to: '<ID>',
    message: 'Bot Running!'
  });
})
bot.on('message', function (user, userID, channelID, message, evt) {
  // Our bot needs to know if it will execute a command
  // It will listen for messages that will start with `!`
  if (message.substring(0, 1) == '?') {
    var args = message.substring(1).split(' ');
    var cmd = args[0];

    args = args.splice(1);
    switch (cmd) {
      // !ping
      case 'ping':
        bot.sendMessage({
          to: channelID,
          message: 'Pong!'
        });
        break;
      case 'getinfo':
        bot.sendMessage({
          to: channelID,
          message: 'User Requested Channel data. User: ' + user + ', UserID: ' + userID + ', in ChannelID: ' + channelID
        });
        break;
      // Just add any case commands if you want to..
    }
  }
});

function getChannel(ID) {
  client.channels.get(ID)
}
function checkTime() {
  var today = new Date().getHours();
  console.log(today)
  if (today >= 7 && today <= 22) {
    getChannel("<ID>").updateOverwrite(getChannel("<ID>").guild.roles.everyone, { VIEW_CHANNEL: false });
  } else {

  }
}
checkTime()

edit:
I got a new error:

TypeError: Cannot read property 'get' of undefined
    at getChannel (C:\Users\<User>\DISCORDBOT\main.js:42:15)
    at checkTime (C:\Users\<user>\DISCORDBOT\main.js:48:3)
    at Object.<anonymous> (C:\Users\<User>\DISCORDBOT\main.js:53:1)
    at Module._compile (internal/modules/cjs/loader.js:1138:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10)
    at Module.load (internal/modules/cjs/loader.js:986:32)
    at Function.Module._load (internal/modules/cjs/loader.js:879:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
    at internal/main/run_main_module.js:17:47

It seems like it can't get the channel... Anyone know a fix?
I don't know how much of the API, and I really don't understand at all. Sorry if you see very apparent errors that I overlook


问:
InlineShapes.AddOLEObject without opening the MSWord UI
I am trying to use VBA to add an embedded OLE (Empty MSWord document, Icon:=True) from an open MSWord document without opening the User Interface for the newly created Empty MSWord document).  The following VBA replaces the second paragraph in the current document with the MSWord OLE Icon, But it opens the MSWord Icon document in its own window.

Sub InsertOLEobject()
    ActiveDocument.InlineShapes.AddOLEObject _
    ClassType:="Word.Document", DisplayAsIcon:=True, _
    Range:=ActiveDocument.Paragraphs(2).Range 'Replaces the second paragraph with the MSWord Icon
End Sub
```

<p>Can anyone give me some advice?</p>

<p>The following is the latest VBA code to do what I wanted to do.  The InlineShapes.AddOLEObject will not open the Word User Interface if you use an existing file. I was just hoping for a more elegant way without creating a file that needs to be deleted.</p>

<pre class="lang-vb prettyprint-override"><code>Sub InsertOLEobject()
    Dim docNewBlank As Document
    Set docNewBlank = Documents.Add
    Set DocA = ActiveDocument
    With docNewBlank
        'Centering the paragraph within the blank document
        .Paragraphs(1).Alignment = wdAlignParagraphCenter
        'Saved the file to a temporary scratch location
        .SaveAs FileName:="c:\temp\Blank.doc"
        .Close 'Close the word document
    End With

    'Add the embedded MSWord OLE Icon
    ActiveDocument.InlineShapes.AddOLEObject _
        ClassType:="Word.Document", _
        FileName:="c:\Temp\Blank.doc", _
        DisplayAsIcon:=True, _
        IconLabel:="Blank.doc", _
        IconFileName:="WINWORD.EXE", _
        Range:=ActiveDocument.Paragraphs(2).Range
        'Set the filename of your choice
        'Set the Range to the destination of the ole icon
        'Set the icon to the path of your WINWORD.EXE
End Sub
</code>```

答:
FWIW I'm not sure I have followed exactly what you are trying to do, but I wonder whether this will do what you need (except the document isn't quite empty and will be a .docx rather than a .doc):</p>

```<code>Sub embedNearlyEmptyWordDoc()
Dim appFullName As String
' Windows only, perhaps there is a better place to get this string
appFullName = Application.Path & Application.PathSeparator & "winword.exe"
With ActiveDocument
' insert a space somewhere "safe" (not necessarily where I have put it
  .Range(0, 0).Text = " "
  .Range(0, 1).Copy
  .Range(0, 0).Text = ""
End With
' Alter this to put the doc where you want
ActiveDocument.Paragraphs(2).Range.PasteSpecial IconIndex:=0, Link:=False, Placement:=wdInLine, DisplayAsIcon:=True, DataType:=wdPasteOLEObject, IconFileName:=appFullName, IconLabel:="Blank.docx"
End Sub
</code>```

Body:
I am trying to use VBA to add an embedded OLE (Empty MSWord document, Icon:=True) from an open MSWord document without opening the User Interface for the newly created Empty MSWord document).  The following VBA replaces the second paragraph in the current document with the MSWord OLE Icon, But it opens the MSWord Icon document in its own window.

Sub InsertOLEobject()
    ActiveDocument.InlineShapes.AddOLEObject _
    ClassType:="Word.Document", DisplayAsIcon:=True, _
    Range:=ActiveDocument.Paragraphs(2).Range 'Replaces the second paragraph with the MSWord Icon
End Sub

Can anyone give me some advice?

The following is the latest VBA code to do what I wanted to do.  The InlineShapes.AddOLEObject will not open the Word User Interface if you use an existing file. I was just hoping for a more elegant way without creating a file that needs to be deleted.

Sub InsertOLEobject()
    Dim docNewBlank As Document
    Set docNewBlank = Documents.Add
    Set DocA = ActiveDocument
    With docNewBlank
        'Centering the paragraph within the blank document
        .Paragraphs(1).Alignment = wdAlignParagraphCenter
        'Saved the file to a temporary scratch location
        .SaveAs FileName:="c:\temp\Blank.doc"
        .Close 'Close the word document
    End With

    'Add the embedded MSWord OLE Icon
    ActiveDocument.InlineShapes.AddOLEObject _
        ClassType:="Word.Document", _
        FileName:="c:\Temp\Blank.doc", _
        DisplayAsIcon:=True, _
        IconLabel:="Blank.doc", _
        IconFileName:="WINWORD.EXE", _
        Range:=ActiveDocument.Paragraphs(2).Range
        'Set the filename of your choice
        'Set the Range to the destination of the ole icon
        'Set the icon to the path of your WINWORD.EXE
End Sub

Body:
FWIW I'm not sure I have followed exactly what you are trying to do, but I wonder whether this will do what you need (except the document isn't quite empty and will be a .docx rather than a .doc):

Sub embedNearlyEmptyWordDoc()
Dim appFullName As String
' Windows only, perhaps there is a better place to get this string
appFullName = Application.Path & Application.PathSeparator & "winword.exe"
With ActiveDocument
' insert a space somewhere "safe" (not necessarily where I have put it
  .Range(0, 0).Text = " "
  .Range(0, 1).Copy
  .Range(0, 0).Text = ""
End With
' Alter this to put the doc where you want
ActiveDocument.Paragraphs(2).Range.PasteSpecial IconIndex:=0, Link:=False, Placement:=wdInLine, DisplayAsIcon:=True, DataType:=wdPasteOLEObject, IconFileName:=appFullName, IconLabel:="Blank.docx"
End Sub


问:
Karate - Is there a way where I can use a variable in string regex
Karate - Is there a way where I can use a variable in string regex. Something similar as below

```<code>match each productCodes == "#regex (?i).*+codes+.*"
</code>```

Any alternative or best practice would be appreciated. I am trying to get an string array from response for doing a match each (which gives me a string at a time) and compare to a string variable coming from another call.

答:
Sample Code:

```<code>Feature: Regex Match

Scenario:
    * def act = ["abcd","bcde","cdef","defg"]
    * def exp = "c"
    * match each act == ('#regex (?i).*' + exp +'.*')
</code>```

Related link: https://github.com/intuit/karate/blob/master/README.md#enclosed-javascript

Body:
Karate - Is there a way where I can use a variable in string regex. Something similar as below

match each productCodes == "#regex (?i).*+codes+.*"

Any alternative or best practice would be appreciated. I am trying to get an string array from response for doing a match each (which gives me a string at a time) and compare to a string variable coming from another call.

Body:
Sample Code:

Feature: Regex Match

Scenario:
    * def act = ["abcd","bcde","cdef","defg"]
    * def exp = "c"
    * match each act == ('#regex (?i).*' + exp +'.*')

Related link: https://github.com/intuit/karate/blob/master/README.md#enclosed-javascript


问:
Make a simple 2D library with OpenGL
I would like to create a 'simple' 2D library with OpenGL. I want to use OpenGL because I know I will learn lot of things that's why I don't want to use a higher level library (like SDL).

I know there is some library to make OpenGL a bit easier:

freeglut: I saw a recent release (freeglut 3.2.1 in 29 September 2019) but is it still used?

glfw: it seems more modern but seems too high level

I don't know if we can compare these libraries but what is the 'best' library (between glfw/freeglut) for learning?

There is also GLEW but I don't understand what is it.. Is it required? I just know it's unrelated with freeglut or glfw..

答:
What is the 'best' library (between glfw/freeglut) for learning?

The best library is not using any if you really want to learn all the details.

You will need to learn how to load OpenGL functions on the fly based on the OpenGL version and extensions you want. You also will learn how to use your windowing system (e.g. Win32, X11, etc.) to create a window suitable for OpenGL rendering.

Typically most developers avoid some or all of that by using a library that loads OpenGL functions (e.g. GLEW) and/or creates the native window (e.g. SDL, glfw, glut; which typically work for several platforms), but you can do it by yourself if you really want.

A good option is to pick SDL and use it only for window initialization. That leaves you to load the OpenGL functions you use, which is fairly easy. Then, when you need input, you can use the SDL input subsystem too.

Title: Make a simple 2D library with OpenGL


问:
Is there a more concise way to pass function result as shown here
I'd like to call my function that creates the object to be passed to a method on the same line, but if I do I get an initial value of reference to non-const must be an lvalue compile-time error. To get it to compile I need to declare a temporary holder variable and set it equal to the factory method resul.

I realize this is because the reference is simply an address of a storage location, but is C++ really not able to recognize the construct and create a temporary holder variable? I am not a great C++ coder, so I assume I am missing something or that there is a gap in my knowledge, or both - and I hope you can help. I am using GCC, and C++ 11, with VS Code as my editor.

```<code>class Bar {};

class Foo {
  const Baz add(Bar& bar) { /* .... */ }
};

void doIt() {
   Baz baz;
   // what compiles...
   Bar bar = createBar();
   baz.add(bar);

   // What I'd like... but it gives me "initial value of reference to non-const must be an lvalue"
   // baz.add(createBar());
}
</code>```

答:
Change the signature to:

```<code>Baz add(Bar bar) { /* .... */ }
</code>```

Since you need to retain the value (to put it in a vector) you must have ownership of the object.  You've declared that you take a reference to avoid making a copy, but you do make a copy -- when you put it in the vector!

Instead, take the object by value, and then the caller can move-construct the argument, and add() can move-construct the vector element.  (C++17 further guarantees move-elision in some of these cases, so the object could be directly constructed in the vector.)

There is no point in returning the Baz object as const since it's not yours anymore; the caller can decide if they want to receive it as const.

Your doIt() becomes:

```<code>void doIt() {
    // Argument is move-constructed from the temporary.
    baz.add(createBar());
}
</code>```

In your method:

```<code>Baz Foo::add(Bar bar) {
    // Perform your checks, then...
    the_vector.emplace_back(std::move(bar));

    return some_baz;
}
</code>```

The general advice is that if your function needs to take ownership of an object, it should receive it by value.  This allows the caller to decide what they want to do: make a copy because they still need the original, or move the original into the argument and let the callee steal the state.

Body:
I'd like to call my function that creates the object to be passed to a method on the same line, but if I do I get an initial value of reference to non-const must be an lvalue compile-time error. To get it to compile I need to declare a temporary holder variable and set it equal to the factory method resul.

I realize this is because the reference is simply an address of a storage location, but is C++ really not able to recognize the construct and create a temporary holder variable? I am not a great C++ coder, so I assume I am missing something or that there is a gap in my knowledge, or both - and I hope you can help. I am using GCC, and C++ 11, with VS Code as my editor.

class Bar {};

class Foo {
  const Baz add(Bar& bar) { /* .... */ }
};

void doIt() {
   Baz baz;
   // what compiles...
   Bar bar = createBar();
   baz.add(bar);

   // What I'd like... but it gives me "initial value of reference to non-const must be an lvalue"
   // baz.add(createBar());
}

Body:
Change the signature to:

Baz add(Bar bar) { /* .... */ }

Since you need to retain the value (to put it in a vector) you must have ownership of the object.  You've declared that you take a reference to avoid making a copy, but you do make a copy -- when you put it in the vector!

Instead, take the object by value, and then the caller can move-construct the argument, and add() can move-construct the vector element.  (C++17 further guarantees move-elision in some of these cases, so the object could be directly constructed in the vector.)

There is no point in returning the Baz object as const since it's not yours anymore; the caller can decide if they want to receive it as const.

Your doIt() becomes:

void doIt() {
    // Argument is move-constructed from the temporary.
    baz.add(createBar());
}

In your method:

Baz Foo::add(Bar bar) {
    // Perform your checks, then...
    the_vector.emplace_back(std::move(bar));

    return some_baz;
}

The general advice is that if your function needs to take ownership of an object, it should receive it by value.  This allows the caller to decide what they want to do: make a copy because they still need the original, or move the original into the argument and let the callee steal the state.


问:
How to access key/pair values within objects inside of an array in Ansible?
So, we are wanting to propagate a list of logged-in users to our hosts.
We have a batch script that does this for us and parses it to JSON format.

```<code>    - name: Process win_shell output
      set_fact:
        qusers: "{{ qusers_ps.stdout | from_json }}"

    - debug:
        var: qusers
        verbosity: 2
</code>```

This debug outputs the following:

```<code>{
    "qusers": {
        "Server1": []
    },
    "_ansible_verbose_always": true,
    "_ansible_no_log": false,
    "changed": false
}
{
    "qusers": {
        "Server2": [
            {
                "USERNAME": "user102",
                "SESSIONNAME": "rdp-tcp#0",
                "ID": "6",
                "STATE": "Active",
                "IDLE TIME": "32",
                "LOGON TIME": "5/29/2020 9:13 AM"
            }
        ]
    },
    "_ansible_verbose_always": true,
    "_ansible_no_log": false,
    "changed": false
}
{
    "qusers": {
        "Server3": [
            {
                "USERNAME": "user183",
                "SESSIONNAME": "",
                "ID": "49",
                "STATE": "Disc",
                "IDLE TIME": "14:34",
                "LOGON TIME": "5/28/2020 7:58 AM"
            },
            {
                "USERNAME": "user103",
                "SESSIONNAME": "",
                "ID": "51",
                "STATE": "Disc",
                "IDLE TIME": "18:26",
                "LOGON TIME": "5/28/2020 8:18 AM"
            },
            {
                "USERNAME": "user148",
                "SESSIONNAME": "",
                "ID": "52",
                "STATE": "Disc",
                "IDLE TIME": "17:10",
                "LOGON TIME": "5/28/2020 9:08 AM"
            }
        ]
    },
    "_ansible_verbose_always": true,
    "_ansible_no_log": false,
    "changed": false
}
</code>```

So you can see that debug returns JSON with the server name as the root element, and then an array of objects with key/pair values.
We need to be able to query values within these array objects, such as 'USERNAME' and 'IDLE TIME' for each server. I've been able to do this statically (shown below) to grab the user of the first array object, but I can't figure out how to do this dynamically.

```<code>    - name: Test selecting JSON output and register as array
      debug:
        msg: "{{ item.value }}"
      loop: "{{ q('dict', qusers) }}"
      register: user_op

    - name: Set array variable
      set_fact:
        user_array: "{{ user_op.results }}"

    - name: Print item value # Prints array object as is
      debug:
        msg: "{{ item.item.value }} "
      with_items: "{{ user_array }}"

    - name: Test pulling JSON from array with conditional # This one works, but only grabs the first user
      debug:
        msg: "{{ item.item.value[0]['USERNAME'] }} is logged into {{item.item.key }}"
      with_items: "{{ user_array }}"
      when: item.item.value != []
</code>```

The last play is the only time I've ever been able to reach a specific key/pair element. How do I modify this to dynamically perform this operation for every user session object in the array instead of only the first, and without hard coding numbers??

答:
I cannot easily reproduce your play loop over your three hosts, so I made a demo with your example data and a prompt allowing to choose which host to display. Of course this will be taken in charge directly for you when you repoduce this in your current playbook.

The idea is to:

transform the dict to a list as you already did using dict2items (same result as the dict lookup you used).

grab only the first item of the list as this is your data model

grab the key of the item as the name of the current server to display

grab the value of the item and loop over it since it is our list of users

display the info we need without even carring about the list being empty or not. Empty list means empty loop therefore nothing will happen in that case.

Below my MCVE and a play for the third element. You can play yourself for the other ones. As you can see this can actually fit in a single task once you have loaded the info from your json output.

---
- hosts: localhost
  gather_facts: false

  vars_prompt:
    - name: host
      prompt: "display host ? (1-3)"
      private: no
      default: 1

  vars:
    "qusers1": {
      "Server1": []
    }
    "qusers2": {
      "Server2": [
        {
          "USERNAME": "user102",
          "SESSIONNAME": "rdp-tcp#0",
          "ID": "6",
          "STATE": "Active",
          "IDLE TIME": "32",
          "LOGON TIME": "5/29/2020 9:13 AM"
        }
      ]
    }
    "qusers3": {
      "Server3": [
      {
        "USERNAME": "user183",
        "SESSIONNAME": "",
        "ID": "49",
        "STATE": "Disc",
        "IDLE TIME": "14:34",
        "LOGON TIME": "5/28/2020 7:58 AM"
      },
      {
        "USERNAME": "user103",
        "SESSIONNAME": "",
        "ID": "51",
        "STATE": "Disc",
        "IDLE TIME": "18:26",
        "LOGON TIME": "5/28/2020 8:18 AM"
      },
      {
        "USERNAME": "user148",
        "SESSIONNAME": "",
        "ID": "52",
        "STATE": "Disc",
        "IDLE TIME": "17:10",
        "LOGON TIME": "5/28/2020 9:08 AM"
      }
      ]
    }

  tasks:
    - name: Load the relevent host data for demo to be in same condition as in original play
      set_fact:
        qusers: "{{ lookup('vars', 'qusers' +  host) }}"

    - name: Show info about users
      vars:
        host_users_info: "{{ (qusers | dict2items).0 }}"
        servername: "{{ host_users_info.key }}"
        loguedin_users: "{{ host_users_info.value }}"
      debug:
        msg: "{{ item.USERNAME }} is logged into {{ servername }} and is idle for {{ item['IDLE TIME'] }}"
      loop: "{{ loguedin_users }}"
```

<p>Which gives for element 3</p>

```$ ansible-playbook test.yml
display host ? (1-3) [1]: 3

PLAY [localhost] ************************************************************************************************************************************

TASK [Load the relevent host data for demo to be in same condition as in original play] *************************************************************
ok: [localhost]

TASK [Show info about users] ************************************************************************************************************************
ok: [localhost] => (item={'USERNAME': 'user183', 'SESSIONNAME': '', 'ID': '49', 'STATE': 'Disc', 'IDLE TIME': '14:34', 'LOGON TIME': '5/28/2020 7:58 AM'}) => {
    "msg": "user183 is logged into Server3 and is idle for 14:34"
}
ok: [localhost] => (item={'USERNAME': 'user103', 'SESSIONNAME': '', 'ID': '51', 'STATE': 'Disc', 'IDLE TIME': '18:26', 'LOGON TIME': '5/28/2020 8:18 AM'}) => {
    "msg": "user103 is logged into Server3 and is idle for 18:26"
}
ok: [localhost] => (item={'USERNAME': 'user148', 'SESSIONNAME': '', 'ID': '52', 'STATE': 'Disc', 'IDLE TIME': '17:10', 'LOGON TIME': '5/28/2020 9:08 AM'}) => {
    "msg": "user148 is logged into Server3 and is idle for 17:10"
}

PLAY RECAP ******************************************************************************************************************************************
localhost                  : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
```

Body:
So, we are wanting to propagate a list of logged-in users to our hosts.
We have a batch script that does this for us and parses it to JSON format.

    - name: Process win_shell output
      set_fact:
        qusers: "{{ qusers_ps.stdout | from_json }}"

    - debug:
        var: qusers
        verbosity: 2

This debug outputs the following:

{
    "qusers": {
        "Server1": []
    },
    "_ansible_verbose_always": true,
    "_ansible_no_log": false,
    "changed": false
}
{
    "qusers": {
        "Server2": [
            {
                "USERNAME": "user102",
                "SESSIONNAME": "rdp-tcp#0",
                "ID": "6",
                "STATE": "Active",
                "IDLE TIME": "32",
                "LOGON TIME": "5/29/2020 9:13 AM"
            }
        ]
    },
    "_ansible_verbose_always": true,
    "_ansible_no_log": false,
    "changed": false
}
{
    "qusers": {
        "Server3": [
            {
                "USERNAME": "user183",
                "SESSIONNAME": "",
                "ID": "49",
                "STATE": "Disc",
                "IDLE TIME": "14:34",
                "LOGON TIME": "5/28/2020 7:58 AM"
            },
            {
                "USERNAME": "user103",
                "SESSIONNAME": "",
                "ID": "51",
                "STATE": "Disc",
                "IDLE TIME": "18:26",
                "LOGON TIME": "5/28/2020 8:18 AM"
            },
            {
                "USERNAME": "user148",
                "SESSIONNAME": "",
                "ID": "52",
                "STATE": "Disc",
                "IDLE TIME": "17:10",
                "LOGON TIME": "5/28/2020 9:08 AM"
            }
        ]
    },
    "_ansible_verbose_always": true,
    "_ansible_no_log": false,
    "changed": false
}

So you can see that debug returns JSON with the server name as the root element, and then an array of objects with key/pair values.
We need to be able to query values within these array objects, such as 'USERNAME' and 'IDLE TIME' for each server. I've been able to do this statically (shown below) to grab the user of the first array object, but I can't figure out how to do this dynamically.

    - name: Test selecting JSON output and register as array
      debug:
        msg: "{{ item.value }}"
      loop: "{{ q('dict', qusers) }}"
      register: user_op

    - name: Set array variable
      set_fact:
        user_array: "{{ user_op.results }}"

    - name: Print item value # Prints array object as is
      debug:
        msg: "{{ item.item.value }} "
      with_items: "{{ user_array }}"

    - name: Test pulling JSON from array with conditional # This one works, but only grabs the first user
      debug:
        msg: "{{ item.item.value[0]['USERNAME'] }} is logged into {{item.item.key }}"
      with_items: "{{ user_array }}"
      when: item.item.value != []

The last play is the only time I've ever been able to reach a specific key/pair element. How do I modify this to dynamically perform this operation for every user session object in the array instead of only the first, and without hard coding numbers??

Body:
I cannot easily reproduce your play loop over your three hosts, so I made a demo with your example data and a prompt allowing to choose which host to display. Of course this will be taken in charge directly for you when you repoduce this in your current playbook.

The idea is to:

transform the dict to a list as you already did using dict2items (same result as the dict lookup you used).

grab only the first item of the list as this is your data model

grab the key of the item as the name of the current server to display

grab the value of the item and loop over it since it is our list of users

display the info we need without even carring about the list being empty or not. Empty list means empty loop therefore nothing will happen in that case.

Below my MCVE and a play for the third element. You can play yourself for the other ones. As you can see this can actually fit in a single task once you have loaded the info from your json output.

---
- hosts: localhost
  gather_facts: false

  vars_prompt:
    - name: host
      prompt: "display host ? (1-3)"
      private: no
      default: 1

  vars:
    "qusers1": {
      "Server1": []
    }
    "qusers2": {
      "Server2": [
        {
          "USERNAME": "user102",
          "SESSIONNAME": "rdp-tcp#0",
          "ID": "6",
          "STATE": "Active",
          "IDLE TIME": "32",
          "LOGON TIME": "5/29/2020 9:13 AM"
        }
      ]
    }
    "qusers3": {
      "Server3": [
      {
        "USERNAME": "user183",
        "SESSIONNAME": "",
        "ID": "49",
        "STATE": "Disc",
        "IDLE TIME": "14:34",
        "LOGON TIME": "5/28/2020 7:58 AM"
      },
      {
        "USERNAME": "user103",
        "SESSIONNAME": "",
        "ID": "51",
        "STATE": "Disc",
        "IDLE TIME": "18:26",
        "LOGON TIME": "5/28/2020 8:18 AM"
      },
      {
        "USERNAME": "user148",
        "SESSIONNAME": "",
        "ID": "52",
        "STATE": "Disc",
        "IDLE TIME": "17:10",
        "LOGON TIME": "5/28/2020 9:08 AM"
      }
      ]
    }

  tasks:
    - name: Load the relevent host data for demo to be in same condition as in original play
      set_fact:
        qusers: "{{ lookup('vars', 'qusers' +  host) }}"

    - name: Show info about users
      vars:
        host_users_info: "{{ (qusers | dict2items).0 }}"
        servername: "{{ host_users_info.key }}"
        loguedin_users: "{{ host_users_info.value }}"
      debug:
        msg: "{{ item.USERNAME }} is logged into {{ servername }} and is idle for {{ item['IDLE TIME'] }}"
      loop: "{{ loguedin_users }}"

Which gives for element 3

$ ansible-playbook test.yml
display host ? (1-3) [1]: 3

PLAY [localhost] ************************************************************************************************************************************

TASK [Load the relevent host data for demo to be in same condition as in original play] *************************************************************
ok: [localhost]

TASK [Show info about users] ************************************************************************************************************************
ok: [localhost] => (item={'USERNAME': 'user183', 'SESSIONNAME': '', 'ID': '49', 'STATE': 'Disc', 'IDLE TIME': '14:34', 'LOGON TIME': '5/28/2020 7:58 AM'}) => {
    "msg": "user183 is logged into Server3 and is idle for 14:34"
}
ok: [localhost] => (item={'USERNAME': 'user103', 'SESSIONNAME': '', 'ID': '51', 'STATE': 'Disc', 'IDLE TIME': '18:26', 'LOGON TIME': '5/28/2020 8:18 AM'}) => {
    "msg": "user103 is logged into Server3 and is idle for 18:26"
}
ok: [localhost] => (item={'USERNAME': 'user148', 'SESSIONNAME': '', 'ID': '52', 'STATE': 'Disc', 'IDLE TIME': '17:10', 'LOGON TIME': '5/28/2020 9:08 AM'}) => {
    "msg": "user148 is logged into Server3 and is idle for 17:10"
}

PLAY RECAP ******************************************************************************************************************************************
localhost                  : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0


问:
How can I define a keyboard shortcut for inserting a multilevel list in Word?
I know the keyboard shortcut to start a flat list (ctrl+shift+l), but apparently there is none for multilevel lists (at least I found nothing after hours of Googling)..

I tried to define one myself, but couldn't find where.

Any ideas? Thank you!

答: I found the way to edit list styles after you create them. Home > Styles > Expand the styles > Hover over the A icon with a checkmark and it should say Modify Styles > Sort order: Alphabetical > Find your style by name > Select it and click Modify. Then you can assign a shortcut as shown above.</p>


问:
Strange problem on certain Android devices when combining CarouFredSel with iScroll
I am developing a website that will have a carousel on a page using iScroll 4. I noticed a strange problem on Android 2.2 and 2.3 devices. I did not notice it on Android 2.1 or Android 3 or any non-Android device. This problem happens whether I use iScroll 3 or iScroll 4.

When I press the back or forward buttons, the carousel does not properly update. The images don't scroll, or they only scroll partway. If I press the forward button enough times, it may disappear as if I have reached the end of the list (as a result of my style on the "disabled" class), and likewise with the back button.

If I scroll the page up or down, then the carousel will update and work fine for a while. Does anyone know why this is happening or what to do about it?

You can see an example at http://jsfiddle.net/R4NWE/. If you want to access the example directly using a mobile browser, you can do so at http://fiddle.jshell.net/R4NWE/show/.

答:
I figured out a solution. I put this in the "scroll" option that I am passing to CarouFredSel:</p>

```<code>onAfter: function() {
    var transform = $("#scroller").css("-webkit-transform");
    $carousel.closest("#scroller").css("-webkit-transform", transform);
}
</code>```

Body:
I figured out a solution. I put this in the "scroll" option that I am passing to CarouFredSel:

onAfter: function() {
    var transform = $("#scroller").css("-webkit-transform");
    $carousel.closest("#scroller").css("-webkit-transform", transform);
}