问:
How do I get href values of a specific Link Text into a list so I can change them into a full URL?
I want to scrape the href value of all links on a webpage By.LinkText("Click Here") into a list so I can change the beginning of the hrefs to something like "www.mysite.com/" to be able to access the sites at a later time.

The links are not in a single div but instead, are spread throughout the webpage which confuses me if xpath is usable in this case so I would like to use link text

答:
```<code>    List<String> link_list = new ArrayList<>();

   List<WebElement> link_elements = driver.findElements(By.LinkText("Click Here"));

   if (!link_elements.isEmpty())
   {
        for (WebElement e : link_elements) {
            String thishref = e.getAttribute("href");
            if (thishref==null){thishref = "";}

            if (link_list.contains(thishref)||"".equals(thishref))
            {

            }
            else
            {
                link_list.add(thishref);
            }
        }
</code>```


来源: stackexchange

问:
How to animate a gradient border on input focus?
I am trying to animate a gradient border on input focus. The example below is what I want to achieve, but how can I extend it to a gradient border?

Thanks for any help!

:focus{outline: none;}

.wrapper{position: relative; width:200px}
input[type="text"]{width: 100%; box-sizing: border-box}

.effect-9 ~ .focus-border:before,
.effect-9 ~ .focus-border:after{content: ""; position: absolute; top: 0; right: 0; width: 0; height: 2px; background-color: #3399FF; transition: 0.2s; transition-delay: 0.2s;}
.effect-9 ~ .focus-border:after{top: auto; bottom: 0; right: auto; left: 0; transition-delay: 0.6s;}
.effect-9 ~ .focus-border i:before,
.effect-9 ~ .focus-border i:after{content: ""; position: absolute; top: 0; left: 0; width: 2px; height: 0; background-color: #3399FF; transition: 0.2s;}
.effect-9 ~ .focus-border i:after{left: auto; right: 0; top: auto; bottom: 0; transition-delay: 0.4s;}
.effect-9:focus ~ .focus-border:before,
.effect-9:focus ~ .focus-border:after{width: 100%; transition: 0.2s; transition-delay: 0.6s;}
.effect-9:focus ~ .focus-border:after{transition-delay: 0.2s;}
.effect-9:focus ~ .focus-border i:before,
.effect-9:focus ~ .focus-border i:after{height: 100%; transition: 0.2s;}
.effect-9:focus ~ .focus-border i:after{transition-delay: 0.4s;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper">
  <input class="effect-9" type="text">
  <span class="focus-border">
    <i></i>
  </span>
</div></code>```

答:
```<code>:focus{outline: none;}

.wrapper{position: relative; width:500px; }
input[type="text"]{width: 100%; height: 60px; box-sizing: border-box;font-size: 20px; padding: 0 10px;}

.effect-9 ~ .focus-border:before,
.effect-9 ~ .focus-border:after{content: ""; position: absolute; top: 0; right: 0; width: 0; height: 2px; background: linear-gradient(to right, rgba(75,105,142,0.65) 0%,rgba(0,0,0,0) 100%); transition: 0.2s; transition-delay: 0.2s;}
.effect-9 ~ .focus-border:after{top: auto; bottom: 0; right: auto; left: 0; transition-delay: 0.6s;}
.effect-9 ~ .focus-border i:before,
.effect-9 ~ .focus-border i:after{content: ""; position: absolute; top: 0; left: 0; width: 2px; height: 0; background: linear-gradient(to bottom, rgba(75,105,142,0.65) 0%,rgba(0,0,0,0) 100%); transition: 0.2s;}
.effect-9 ~ .focus-border i:after{left: auto; right: 0; top: auto; bottom: 0; transition-delay: 0.4s;}
.effect-9:focus ~ .focus-border:before,
.effect-9:focus ~ .focus-border:after{width: 100%; transition: 0.2s; transition-delay: 0.6s;}
.effect-9:focus ~ .focus-border:after{transition-delay: 0.2s;}
.effect-9:focus ~ .focus-border i:before,
.effect-9:focus ~ .focus-border i:after{height: 100%; transition: 0.2s;}
.effect-9:focus ~ .focus-border i:after{transition-delay: 0.4s;}
</code>```

check if it is what you are looking for, made some height and width change for visibility

ContentLicense: CC BY-SA 4.0

Body:
I am trying to animate a gradient border on input focus. The example below is what I want to achieve, but how can I extend it to a gradient border?

Thanks for any help!

:focus{outline: none;}

.wrapper{position: relative; width:200px}
input[type="text"]{width: 100%; box-sizing: border-box}

.effect-9 ~ .focus-border:before,
.effect-9 ~ .focus-border:after{content: ""; position: absolute; top: 0; right: 0; width: 0; height: 2px; background-color: #3399FF; transition: 0.2s; transition-delay: 0.2s;}
.effect-9 ~ .focus-border:after{top: auto; bottom: 0; right: auto; left: 0; transition-delay: 0.6s;}
.effect-9 ~ .focus-border i:before,
.effect-9 ~ .focus-border i:after{content: ""; position: absolute; top: 0; left: 0; width: 2px; height: 0; background-color: #3399FF; transition: 0.2s;}
.effect-9 ~ .focus-border i:after{left: auto; right: 0; top: auto; bottom: 0; transition-delay: 0.4s;}
.effect-9:focus ~ .focus-border:before,
.effect-9:focus ~ .focus-border:after{width: 100%; transition: 0.2s; transition-delay: 0.6s;}
.effect-9:focus ~ .focus-border:after{transition-delay: 0.2s;}
.effect-9:focus ~ .focus-border i:before,
.effect-9:focus ~ .focus-border i:after{height: 100%; transition: 0.2s;}
.effect-9:focus ~ .focus-border i:after{transition-delay: 0.4s;}

  <input class="effect-9" type="text">

Body:
:focus{outline: none;}

.wrapper{position: relative; width:500px; }
input[type="text"]{width: 100%; height: 60px; box-sizing: border-box;font-size: 20px; padding: 0 10px;}

.effect-9 ~ .focus-border:before,
.effect-9 ~ .focus-border:after{content: ""; position: absolute; top: 0; right: 0; width: 0; height: 2px; background: linear-gradient(to right, rgba(75,105,142,0.65) 0%,rgba(0,0,0,0) 100%); transition: 0.2s; transition-delay: 0.2s;}
.effect-9 ~ .focus-border:after{top: auto; bottom: 0; right: auto; left: 0; transition-delay: 0.6s;}
.effect-9 ~ .focus-border i:before,
.effect-9 ~ .focus-border i:after{content: ""; position: absolute; top: 0; left: 0; width: 2px; height: 0; background: linear-gradient(to bottom, rgba(75,105,142,0.65) 0%,rgba(0,0,0,0) 100%); transition: 0.2s;}
.effect-9 ~ .focus-border i:after{left: auto; right: 0; top: auto; bottom: 0; transition-delay: 0.4s;}
.effect-9:focus ~ .focus-border:before,
.effect-9:focus ~ .focus-border:after{width: 100%; transition: 0.2s; transition-delay: 0.6s;}
.effect-9:focus ~ .focus-border:after{transition-delay: 0.2s;}
.effect-9:focus ~ .focus-border i:before,
.effect-9:focus ~ .focus-border i:after{height: 100%; transition: 0.2s;}
.effect-9:focus ~ .focus-border i:after{transition-delay: 0.4s;}

check if it is what you are looking for, made some height and width change for visibility


问:
disabling hyperlink in displayTag
I am using displayTag table decorator to display my JSP page.

The page has a table with columns. One of the columns is Action which has 2 hyperlinks displayed.
One is pay and the other is close. Each row will have 5 columns action being th last columns with hyperlinks.

This is the action display code in JSP

```<code><display-el:column property="action" sortable="false" title=" "
                            class="defaultTextCentered" style="width:6%" sortName="action" />
</code>```

Below is my decorator code

```<code>public String getAction() {
renderPayLink();
}

private void renderPayLink() {

            decoratedVal.append("<a href=\"javascript:newPopup('");
            decoratedVal.append(getContextPath());
            decoratedVal.append("/abc/taxPaymentInternal.html?iSeqNo=");
            decoratedVal.append(abc.getISeqNumber());
            decoratedVal.append("&iPeriod=");
            decoratedVal.append(abc.getIDate());
            decoratedVal.append("', 800, 700)\" title=\"Pay\">Pay</a>");
            decoratedVal.append("  ");

    }
</code>```

So the link when clicked will open a popup window and have the user enter couple details and submit. While this popup is open i can still goto the main browser and click the pay again which refreshes the popup and make me resubmit the info again. i have to stop this happenning by disabling the pay button once i click in the browser and then open the popup. How can i achieve this?

Replaced pay with

```<code>  decoratedVal.append("', 800, 700)\" title=\"Pay\" ");
            decoratedVal.append("onclick=\"this.setAttribute(");
            decoratedVal.append("\'style\', \'pointer-events:none; cursor:default;\'); this.setAttribute(");
            decoratedVal.append("\'href\', \'\')\">Pay</a>");
            decoratedVal.append("  ");
</code>```

Getting "Unable to get property 'setAttribute' of undefined or null reference" error from f12 debug.

```<code>   <a title="Pay" onclick="this.setAttribute('style', 'pointer-events:none; cursor:default;'); this.setAttribute('href', '')" href="javascript:newPopup('/mei/invoicing/launchConfirmPaymentInternal.html?invoiceSeqNo=131946&invoicePeriod=02-11-2017', 800, 700)">Pay</a>
</code>```

答:
One way is to disable the  tag when you click on it.

Simple solution:

You could replace this line:

decoratedVal.append("', 800, 700)\" title=\"Pay\">Pay");

with those:

```<code>decoratedVal.append("', 800, 700)\" title=\"Pay\")
decoratedVal.append("onclick=\"this.setAttribute(")
decoratedVal.append("\'style\', \'pointer-events:none; cursor:default;\'); this.setAttribute(");
decoratedVal.append("\'href\', \'\')\">Pay</a>");
</code>```

Please note that the link will be available again on page refresh. If you need another way to activate it, you would need to do it manually.

More elegant solution:

If you have a stylesheet, like a CSS file, you could create this class there:

```<code>.disabledLink{
    pointer-events: none;
    cursor: default;
}
</code>```

And in the onclick event of your link tag, replace the setAttribute with addClass('disabledLink'). That also makes it easier to remove, with a removeClass('disabledLink')

Title: disabling hyperlink in displayTag

Body:
I am using displayTag table decorator to display my JSP page.

The page has a table with columns. One of the columns is Action which has 2 hyperlinks displayed.
One is pay and the other is close. Each row will have 5 columns action being th last columns with hyperlinks.

This is the action display code in JSP

<display-el:column property="action" sortable="false" title=" "
                            class="defaultTextCentered" style="width:6%" sortName="action" />

Below is my decorator code

public String getAction() {
renderPayLink();
}

private void renderPayLink() {

            decoratedVal.append("Pay");
            decoratedVal.append("  ");

    }

So the link when clicked will open a popup window and have the user enter couple details and submit. While this popup is open i can still goto the main browser and click the pay again which refreshes the popup and make me resubmit the info again. i have to stop this happenning by disabling the pay button once i click in the browser and then open the popup. How can i achieve this?

Replaced pay with

  decoratedVal.append("', 800, 700)\" title=\"Pay\" ");
            decoratedVal.append("onclick=\"this.setAttribute(");
            decoratedVal.append("\'style\', \'pointer-events:none; cursor:default;\'); this.setAttribute(");
            decoratedVal.append("\'href\', \'\')\">Pay");
            decoratedVal.append("  ");

Getting "Unable to get property 'setAttribute' of undefined or null reference" error from f12 debug.

   Pay

Body:
One way is to disable the <a> tag when you click on it.

Simple solution:

You could replace this line:

decoratedVal.append("', 800, 700)\" title=\"Pay\">Pay</a>");

with those:

decoratedVal.append("', 800, 700)\" title=\"Pay\")
decoratedVal.append("onclick=\"this.setAttribute(")
decoratedVal.append("\'style\', \'pointer-events:none; cursor:default;\'); this.setAttribute(");
decoratedVal.append("\'href\', \'\')\">Pay</a>");

Please note that the link will be available again on page refresh. If you need another way to activate it, you would need to do it manually.

More elegant solution:

If you have a stylesheet, like a CSS file, you could create this class there:

.disabledLink{
    pointer-events: none;
    cursor: default;
}

And in the onclick event of your link tag, replace the setAttribute with addClass('disabledLink'). That also makes it easier to remove, with a removeClass('disabledLink')


问:
My DoSomething lambda task does not return a value
This snippet does not compile. How to properly use the lambda function?

I have tried sending an integer to the function in various places. It does not return a proper value.

I would like the DoSomething routine to select various possible subtasks for a parallel task application.

I have been trying to follow examples of setting up tasks:

```<code> Dim action As Action(Of Object)
        action = Sub(obj As Object)
                     MessageBox.Show("Task manager " + vbCrLf +
                     "Current ID " + Task.CurrentId.ToString + vbCrLf + "Object " + obj.ToString + vbCrLf + "Thread ID " + Thread.CurrentThread.ManagedThreadId.ToString)
             End Sub
    Dim t1 As New Task(action, "Control 1")
    Dim t3 As New Task(action, "Control 2")
    Dim t4 As New Task(action, "Control 3")

    t1.Start()
    t1.Wait()

    t3.Start()
    t3.Wait()

    t4.Start()
    t4.Wait()

    Dim t As Task = Task.Factory.StartNew(action, "Control 4")

    Dim t5 = Function(ctr As Integer) ctr + 2
    MessageBox.Show("Answer " + t5(6).ToString)
</code>```

These work, but the last effort to make a function call is failing.

```<code> Dim DoSomething As Action(Of Integer)
        DoSomething = Function(index As Integer)
                          Select Case index
                              Case 0
                                  Return "FirstName"
                              Case 1
                                  Return "LastName"
                              Case 2
                                  Return "CompanyName"
                              Case Else
                                  Return "LastName"
                          End Select
                      End Function

    If DoSomething(1).ToString = "FirstName" Then
        MessageBox.Show("Hello world")
    End If
</code>```

I expect a match in the case statement, but the return value is nonexistent, "function does not return a value" or returns the path of the subroutine call.

答:
If you want DoSomething to return a String value, it must be defined as a Func(Of Integer, String).  As an Action(Of Integer) it is treated like a subroutine.

```<code>    Dim DoSomething As Func(Of Integer, String)
    DoSomething = Function(index As Integer)
                      Select Case index
                          Case 0
                              Return "FirstName"
                          Case 1
                              Return "LastName"
                          Case 2
                              Return "CompanyName"
                          Case Else
                              Return "LastName"
                      End Select
                  End Function
</code>```

Note that it won't show the Hello World message box because passing 1 will yield "LastName".

This would be more appropriate of a way to write the value of DoSomething if it was never meant to return a string and was supposed to truly be an Action(of Integer):

```<code>    Dim DoSomethingAsAction As Action(Of Integer)
    DoSomethingAsAction = Sub(index As Integer)
                              Select Case index
                                  Case 0
                                      MsgBox("Hello World!")
                              End Select
                          End Sub

    DoSomethingAsAction.Invoke(0)
</code>```

Body:
This snippet does not compile. How to properly use the lambda function?

I have tried sending an integer to the function in various places. It does not return a proper value.

I would like the DoSomething routine to select various possible subtasks for a parallel task application.

I have been trying to follow examples of setting up tasks:

 Dim action As Action(Of Object)
        action = Sub(obj As Object)
                     MessageBox.Show("Task manager " + vbCrLf +
                     "Current ID " + Task.CurrentId.ToString + vbCrLf + "Object " + obj.ToString + vbCrLf + "Thread ID " + Thread.CurrentThread.ManagedThreadId.ToString)
             End Sub
    Dim t1 As New Task(action, "Control 1")
    Dim t3 As New Task(action, "Control 2")
    Dim t4 As New Task(action, "Control 3")

    t1.Start()
    t1.Wait()

    t3.Start()
    t3.Wait()

    t4.Start()
    t4.Wait()

    Dim t As Task = Task.Factory.StartNew(action, "Control 4")

    Dim t5 = Function(ctr As Integer) ctr + 2
    MessageBox.Show("Answer " + t5(6).ToString)

These work, but the last effort to make a function call is failing.

 Dim DoSomething As Action(Of Integer)
        DoSomething = Function(index As Integer)
                          Select Case index
                              Case 0
                                  Return "FirstName"
                              Case 1
                                  Return "LastName"
                              Case 2
                                  Return "CompanyName"
                              Case Else
                                  Return "LastName"
                          End Select
                      End Function

    If DoSomething(1).ToString = "FirstName" Then
        MessageBox.Show("Hello world")
    End If

I expect a match in the case statement, but the return value is nonexistent, "function does not return a value" or returns the path of the subroutine call.

Body:
If you want DoSomething to return a String value, it must be defined as a Func(Of Integer, String).  As an Action(Of Integer) it is treated like a subroutine.

    Dim DoSomething As Func(Of Integer, String)
    DoSomething = Function(index As Integer)
                      Select Case index
                          Case 0
                              Return "FirstName"
                          Case 1
                              Return "LastName"
                          Case 2
                              Return "CompanyName"
                          Case Else
                              Return "LastName"
                      End Select
                  End Function

Note that it won't show the Hello World message box because passing 1 will yield "LastName".

This would be more appropriate of a way to write the value of DoSomething if it was never meant to return a string and was supposed to truly be an Action(of Integer):

    Dim DoSomethingAsAction As Action(Of Integer)
    DoSomethingAsAction = Sub(index As Integer)
                              Select Case index
                                  Case 0
                                      MsgBox("Hello World!")
                              End Select
                          End Sub

    DoSomethingAsAction.Invoke(0)


问:
How to get sum of the Y position of instantiated objects?
I am trying to make my finish line to be proportional as objects so when there is Y position of last object is on -50 I want to finish line be at -55 so when user finish the game he goes to next level.

For now i have gameobject on screen and i need to manually move the object.

I am making obstacles with this code:

```<code>       for (int i = 0; i < 3; i++)
    {
        Instantiate(obstacles[0], new Vector3(obstacles[0].transform.position.x, startSpawn, obstacles[0].transform.position.z), Quaternion.identity);
        startSpawn -= deltaY;
    }
</code>```

So my question is how i can read the Y of the last object instantiated and add few numbers to instantiate finish like right after the last object is passed?

答:
Add a field that tracks the last object created:

```<code>public GameObject lastObjectCreated;
</code>```

Assign to it each iteration of the instantiation loop (the assignment of the last iteration will be remembered):

```<code>for (int i = 0; i < 3; i++)
{
    lastObjectCreated = Instantiate(obstacles[0], new Vector3(obstacles[0].transform.position.x, startSpawn, obstacles[0].transform.position.z), Quaternion.identity);
    startSpawn -= deltaY;
}
</code>```

When you want to read its y position, read lastObjectCreated.transform.position.y:

```<code>float yPosition = lastObjectCreated.transform.position.y;
</code>```

Body:
I am trying to make my finish line to be proportional as objects so when there is Y position of last object is on -50 I want to finish line be at -55 so when user finish the game he goes to next level.

For now i have gameobject on screen and i need to manually move the object.

I am making obstacles with this code:

       for (int i = 0; i < 3; i++)
    {
        Instantiate(obstacles[0], new Vector3(obstacles[0].transform.position.x, startSpawn, obstacles[0].transform.position.z), Quaternion.identity);
        startSpawn -= deltaY;
    }

So my question is how i can read the Y of the last object instantiated and add few numbers to instantiate finish like right after the last object is passed?

Body:
Add a field that tracks the last object created:

public GameObject lastObjectCreated;

Assign to it each iteration of the instantiation loop (the assignment of the last iteration will be remembered):

for (int i = 0; i < 3; i++)
{
    lastObjectCreated = Instantiate(obstacles[0], new Vector3(obstacles[0].transform.position.x, startSpawn, obstacles[0].transform.position.z), Quaternion.identity);
    startSpawn -= deltaY;
}

When you want to read its y position, read lastObjectCreated.transform.position.y:

float yPosition = lastObjectCreated.transform.position.y;


问:
white text stand out in the grey background
I have a div tag with background-color: #FFFFFF and opacity: 0.08. Inside it is a span tag with the colour white. What can I do to make the white text stand out in the grey background in the parent div? It seems that i cannot increase parent's opacity

答:
You could use text-shadow as well along with RGBA Fiddle

HTML:

```<code><div>
  <span>text</span>
</div>
</code>```

CSS:

```<code>div {
  background-color: rgba(255, 255, 255, 0.08);
}

span {
  color: #FFF;
  text-shadow: 0px 1px 10px black;
  font-size: 30px;
}
</code>```

Body:
You could use text-shadow as well along with RGBA Fiddle

HTML:

<div>
  <span>text</span>
</div>

CSS:

div {
  background-color: rgba(255, 255, 255, 0.08);
}

span {
  color: #FFF;
  text-shadow: 0px 1px 10px black;
  font-size: 30px;
}


问:
How to not showing the coordinates (x,y) when mouse move?
I'm able to make a svg file using gnuplot. when I click any place in the plot, the (x,y) coordinates will show up, when the mouse move, the coordinates change, when I click the plot again, the coordinate disappear.

How to not display the coordinates when mouse click and move?
Thanks!

I have tried:

```<code>set mouse noruler

set mouse mouseformat 6

set mouse mouseformat ""

set mouse clipboardformat 6
</code>```

The code is:

```<code>set term svg mouse jsdir "http://.../TEST/"

set output "test.svg"

plot 'test.data' using 1:2:3 with labels hypertext point pt 7
</code>```

答:
I think I initially misunderstood your question (1st answer now deleted). Let me try again.

You are describing the default behaviour of mousing support in gnuplot+svg.

(1) Simple option: If you don't want any of this, do not include the mouse keyword when you select the terminal.

(2) Infinitely customizable option: The javascript mousing behaviour is implemented in a separate file gnuplot_svg.js. Several versions exist, but you could edit or replace any of them to suit your needs.  The most recent version is here:
    gnuplot_svg.js

(3) Possible compromise:  The *.svg file produced by gnuplot contains lines like this:

```<code><g id="gnuplot_canvas" onclick="gnuplot_svg.toggleCoordBox(evt)" onmousemove="gnuplot_svg.moveCoordBox(evt)">
</code>```

If you want to disable only the response to mouse clicks, or to mouse movement, edit these lines to remove the corresponding onclick or onmousemove directives.

Body:
I'm able to make a svg file using gnuplot. when I click any place in the plot, the (x,y) coordinates will show up, when the mouse move, the coordinates change, when I click the plot again, the coordinate disappear.

How to not display the coordinates when mouse click and move?
Thanks!

I have tried:

set mouse noruler

set mouse mouseformat 6

set mouse mouseformat ""

set mouse clipboardformat 6

The code is:

set term svg mouse jsdir "http://.../TEST/"

set output "test.svg"

plot 'test.data' using 1:2:3 with labels hypertext point pt 7

Body:
I think I initially misunderstood your question (1st answer now deleted). Let me try again.

You are describing the default behaviour of mousing support in gnuplot+svg.

(1) Simple option: If you don't want any of this, do not include the mouse keyword when you select the terminal.

(2) Infinitely customizable option: The javascript mousing behaviour is implemented in a separate file gnuplot_svg.js. Several versions exist, but you could edit or replace any of them to suit your needs.  The most recent version is here:
    gnuplot_svg.js

(3) Possible compromise:  The *.svg file produced by gnuplot contains lines like this:

<g id="gnuplot_canvas" onclick="gnuplot_svg.toggleCoordBox(evt)" onmousemove="gnuplot_svg.moveCoordBox(evt)">

If you want to disable only the response to mouse clicks, or to mouse movement, edit these lines to remove the corresponding onclick or onmousemove directives.


问:
Why does C not decrement the stack pointer if a variable leaves the scope?
```<code>#include <stdio.h>
void main() {
    {
        int x;
        printf("%p\n", &x);
    }
    {
        int x;
        printf("%p\n", &x);
    }
}
</code>```

I would think running this that it would output the same thing twice. When it declares the first variable, it increments the stack pointer, but then leaves the scope, so it decrements it, and then just repeats the process the second time, so int x would occupy the same memory location on the stack both times.

But this isn't the case. The stack pointer is not decremented and int x in both cases occupy different locations in the stack. In fact, the first int x is still reachable even though its scope is gone.

```<code>#include <stdio.h>
void main() {
    {
        int x = 10;
        printf("%p\n", &x);
    }
    {
        int x = 25;
        printf("%p\n", &x);
    }
    {
        int x = 71;
        printf("%p\n", &x);

        int *p = &x;
        printf("%i %i %i\n", *(p + 2), *(p + 1), *p);
    }
}
</code>```

Why is this? What am I misunderstanding?

答:
As a practical matter, when a stack does exist (as Broman's answer points out, there is no requirement for a stack to exist, although there is a requirement to support recursion) compilers will typically generate code that adjusts the stack pointer only once on function entry, and once again on function exit, even if there are sub-scopes within the function that limit individual variables' lifetimes.

This might seem bizarre if you're used to writing assembly language by hand.  The most basic reason for it is, it means each variable that lives on the stack has a "stack slot" with a fixed location throughout the entire function, which gives the compiler maximum flexibility in moving machine instructions around for optimization.

Body:
#include <stdio.h>
void main() {
    {
        int x;
        printf("%p\n", &x);
    }
    {
        int x;
        printf("%p\n", &x);
    }
}

I would think running this that it would output the same thing twice. When it declares the first variable, it increments the stack pointer, but then leaves the scope, so it decrements it, and then just repeats the process the second time, so int x would occupy the same memory location on the stack both times.

But this isn't the case. The stack pointer is not decremented and int x in both cases occupy different locations in the stack. In fact, the first int x is still reachable even though its scope is gone.

#include <stdio.h>
void main() {
    {
        int x = 10;
        printf("%p\n", &x);
    }
    {
        int x = 25;
        printf("%p\n", &x);
    }
    {
        int x = 71;
        printf("%p\n", &x);

        int *p = &x;
        printf("%i %i %i\n", *(p + 2), *(p + 1), *p);
    }
}

Why is this? What am I misunderstanding?


问:
How to get programmatically the current GKE project id from one of its clusters?
I'd like to get the current GKE project id from within one of its clusters via the Java client or the GCloud API itself.

I'm running java containers in a GKE cluster of a specific Google Cloud project

I initialize the ClusterManagerClient with the appropriate ClusterManagerSettings

-> Is it possible to fetch this specific project id with this client?

(I'm expecting that there would be a global context within each GKE cluster where we could know the current project we're running on).

Thank you

答:
As John Hanley mentioned in his comment above, you can use the instance metadata on the node in your cluster to determine the project that the node is a part of. The easiest way to see it is to use curl from a shell (either on the node or in a container).

If you want the project name, it can be seen at:

```<code>curl "http://metadata.google.internal/computeMetadata/v1/project/project-id" -H "Metadata-Flavor: Google"
</code>```

And if you want the project number, it can be seen at:

```<code>curl "http://metadata.google.internal/computeMetadata/v1/project/numeric-project-id" -H "Metadata-Flavor: Google"
</code>```

This isn't part of the container API surface, so the ClusterManagerClient isn't the right API client to use. You need to create a client to fetch the instance metadata, which I would expect might be part of the compute client libraries, or you can just make a local HTTP request if you add the right headers (as shown above) since you don't need any special client authentication / authorization to access the local metadata.

Body:
As John Hanley mentioned in his comment above, you can use the instance metadata on the node in your cluster to determine the project that the node is a part of. The easiest way to see it is to use curl from a shell (either on the node or in a container).

If you want the project name, it can be seen at:

curl "http://metadata.google.internal/computeMetadata/v1/project/project-id" -H "Metadata-Flavor: Google"

And if you want the project number, it can be seen at:

curl "http://metadata.google.internal/computeMetadata/v1/project/numeric-project-id" -H "Metadata-Flavor: Google"

This isn't part of the container API surface, so the ClusterManagerClient isn't the right API client to use. You need to create a client to fetch the instance metadata, which I would expect might be part of the compute client libraries, or you can just make a local HTTP request if you add the right headers (as shown above) since you don't need any special client authentication / authorization to access the local metadata.


问:
join and count query in flutter sqflite
I have 2 tables one with names and id's and another with id's and dates,
I am trying to figure out how to create the helper method to query the two tables and return the list of names with the number of dates associated to their id.

```<code>Name Table
   id  Name
    1 John
    2 Tom
    3 Frank

Date Table
   id  Date
    1 1/3/19
    1 1/4/19
    1 1/5/19
    2 1/4/19

    Results:
    Name  Count
    John  3
    Tom   1
    Frank 0
</code>```

This is as far as I have gotten just pulling back all the names.

```<code>  Future<List> queryAllNames() async {
    Database db = await database;
    List<Map> names =
        await db.query(Names, columns: [id, Name]);
    if (names.length > 0) {
      return names;
    }
    return null;
  }
</code>```

I have figured out the raw query I need from sqlite

```<code>select Name.name,  count(Date.date) from Name left join Date using(id) group by Name.name;
</code>```

But still not able to translate to at sqflite helper method.

答: There is a rawQuery() method. Check out Raw SQL queries</p>

Title: join and count query in flutter sqflite

Body:
I have 2 tables one with names and id's and another with id's and dates,
I am trying to figure out how to create the helper method to query the two tables and return the list of names with the number of dates associated to their id.

Name Table
   id  Name
    1 John
    2 Tom
    3 Frank

Date Table
   id  Date
    1 1/3/19
    1 1/4/19
    1 1/5/19
    2 1/4/19

    Results:
    Name  Count
    John  3
    Tom   1
    Frank 0

This is as far as I have gotten just pulling back all the names.

  Future<List> queryAllNames() async {
    Database db = await database;
    List<Map> names =
        await db.query(Names, columns: [id, Name]);
    if (names.length > 0) {
      return names;
    }
    return null;
  }

I have figured out the raw query I need from sqlite

select Name.name,  count(Date.date) from Name left join Date using(id) group by Name.name;

But still not able to translate to at sqflite helper method.


问:
How to run react native code inside injected javascript in webview?
I have a react native function that downloads video by the help of "rn-fetch-blob" and save to document directory which is working fine.

I want to achieve this functionality by the help of webview as it runs in code in separate thread.

Below is my code:

```<code>    downloadVideo() {
        let videoPathToDownload = 'http://XXXXXXXXXXX/0fgqhjcr6my.mp4';
        RNFetchBlob
            .config({
                fileCache: true,
                appendExt: 'mp4'
            })
            .fetch('GET', videoPathToDownload)
            .then((res) => {
                console.log('The file saved to ', res.path())
            })
    }

    render() {
        return (
            <View style={{flex: 1}}>
            <WebView
                javaScriptEnabled={true}
                domStorageEnabled={true}
                injectedJavaScript={}
                source={{ uri: "https://www.google.com" }}
                style={{ marginTop: 20  }}
             />
            </View>
        );
    }
</code>```

I want to call the downloadVideo() function from webview inside injectedJS  or by any means possible.

Please Help.

答:
Use react native WebView:

```<code><WebView
    ref={(ref) => { this.webview = ref; }}
    source={{ uri: this.state.webViewUrl }}
    originWhitelist={['*']}
    javaScriptEnabledAndroid={true}
    injectedJavaScript={jsCode}
    onMessage={this._onMessage} // only if you want connection back
/>
</code>```

and you can pass js code:

```<code>const jsCode = `
    document.querySelector('button').addEventListener("click", function() {
        alert('Hello Web')
    });
    true;
    `
</code>```

Body:
I have a react native function that downloads video by the help of "rn-fetch-blob" and save to document directory which is working fine.

I want to achieve this functionality by the help of webview as it runs in code in separate thread.

Below is my code:

    downloadVideo() {
        let videoPathToDownload = 'http://XXXXXXXXXXX/0fgqhjcr6my.mp4';
        RNFetchBlob
            .config({
                fileCache: true,
                appendExt: 'mp4'
            })
            .fetch('GET', videoPathToDownload)
            .then((res) => {
                console.log('The file saved to ', res.path())
            })
    }

    render() {
        return (
            <View style={{flex: 1}}>
            <WebView
                javaScriptEnabled={true}
                domStorageEnabled={true}
                injectedJavaScript={}
                source={{ uri: "https://www.google.com" }}
                style={{ marginTop: 20  }}
             />
            </View>
        );
    }

I want to call the downloadVideo() function from webview inside injectedJS  or by any means possible.

Please Help.

Body:
Use react native WebView:

<WebView
    ref={(ref) => { this.webview = ref; }}
    source={{ uri: this.state.webViewUrl }}
    originWhitelist={['*']}
    javaScriptEnabledAndroid={true}
    injectedJavaScript={jsCode}
    onMessage={this._onMessage} // only if you want connection back
/>

and you can pass js code:

const jsCode = `
    document.querySelector('button').addEventListener("click", function() {
        alert('Hello Web')
    });
    true;
    `


问:
pmrep command execution in Informatica cloud
Can anyone tell me is it possible to execute pmrep commands in Informatica Cloud services to import and export workflow object?

pmrep connect -r MY_REP -d MY_DOMAIN -n MY_USER -x MY_PASSWORD
./pmrep objectexport -o workflow -f $FOLDER -n $WORKFLOW -m -s -b -r -u ${EXPORTDIR}/${FOLDER}_${WORKFLOW}.xml

答:
That's not possible in Informatica cloud, you don't have access to the repository it's hosted by Informatica.

You need to use REST API to import and export objects from IICS repository, the document is in the following link.

https://network.informatica.com/docs/DOC-17563


问:
PHP URL Rewriting for the link
I have delete link in a table for each row.
When I click on that link, I pass the id to a page which deletes that row using that id.
My last portion of my url looks like delete_row.php?id=5
Can I show only the delete_row.php with out showing the ?id=5

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script language="javascript" type="text/javascript">
     function redirect(URL)
     {
       document.location="delete_row.php";
       return false;
     }
</script>
</head>

<body>
<?php
$con = mysql_connect("localhost","root","root");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("test", $con);

$result = mysql_query("SELECT * FROM users");
?>
<table border="1">
<th>Name</th>
<th>Age</th>
<th> </th>
<?php
while($row = mysql_fetch_array($result))
  {?>
  <tr>
  <td><?php echo $row['name'];?></td>
  <td><?php echo $row['age'];?></td>
  <td><a href="javascript:" onclick="return redirect('delete_row.php?id=<?php echo $row['id']; ?>');">Delete</a></td>
  </tr>
  <?php } ?>
</table>
<?php
mysql_close($con);
?>
</body>
</html>
</code>```

This is the PHP part with file name delete_row.php

```<code><?php
$con = mysql_connect("localhost","root","root");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
mysql_select_db("test", $con);
if(isset($_REQUEST['id']))
$id = $_REQUEST['id'];
mysql_query("DELETE FROM users WHERE id='$id'");
mysql_close($con);
?>
</code>```

The error which i am getting is
Notice: Undefined variable: id in C:\MYXAMPP\delete_row.php on line 13

答:
Will this work for you?

```<code><a href="delete_row.php" onclick="this.href = this.href + '?id=5'">Delete</a>
</code>```

You could also do this:

```<code><script language="javascript" type="text/javascript">
     function redirect(URL)
     {
       if(confirm('Are you sure you wish to delete this item?'))
           document.location=URL;
       return false;
     }
</script>
<a href="javascript:" onclick="return redirect('delete_row.php?id=5');">Delete</a>
</code>```

ContentLicense: CC BY-SA 3.0

Title: PHP URL Rewriting for the link

Body:
I have delete link in a table for each row.
When I click on that link, I pass the id to a page which deletes that row using that id.
My last portion of my url looks like delete_row.php?id=5
Can I show only the delete_row.php with out showing the ?id=5

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>

<?php
$con = mysql_connect("localhost","root","root");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("test", $con);

$result = mysql_query("SELECT * FROM users");
?>

Name
Age

<?php
while($row = mysql_fetch_array($result))
  {?>

  <?php echo $row['name'];?>
  <?php echo $row['age'];?>
  <a href="javascript:" onclick="return redirect('delete_row.php?id=<?php echo $row['id']; ?>');">Delete

  <?php } ?>

<?php
mysql_close($con);
?>

This is the PHP part with file name delete_row.php

<?php
$con = mysql_connect("localhost","root","root");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
mysql_select_db("test", $con);
if(isset($_REQUEST['id']))
$id = $_REQUEST['id'];
mysql_query("DELETE FROM users WHERE id='$id'");
mysql_close($con);
?>

The error which i am getting is
Notice: Undefined variable: id in C:\MYXAMPP\delete_row.php on line 13

Body:
Will this work for you?

<a href="delete_row.php" onclick="this.href = this.href + '?id=5'">Delete</a>

You could also do this:

<script language="javascript" type="text/javascript">
     function redirect(URL)
     {
       if(confirm('Are you sure you wish to delete this item?'))
           document.location=URL;
       return false;
     }
</script>
<a href="javascript:" onclick="return redirect('delete_row.php?id=5');">Delete</a>


问:
How to write a function using for and if
I'm trying to write a code for calculating the number of factors for an arbitrary integer number but unfortunately when I run that I receive a false answer

I have tried for loop without defining function in this case and I got the result.Contrary to that, when I define a function I can't see the proper result

```<code>r = 0
def factor(a):
    global r
    for i in range(1, a + 1):
        if a % i == 0:
        r += 1
        return r

a = int(input())
factor(a)
</code>```

for example 18 has 6 factors but I receive just 1.

答:
Use print to check your code. Indentation in Python matters. Also, global is not needed.</p>

```<code>def factor(a):
    r = 0
    for i in range(1, a + 1):
        if a % i == 0:
            print('i', i)
            r += 1
    return r

a = int(input())
print(factor(a))
</code>```

Body:
I'm trying to write a code for calculating the number of factors for an arbitrary integer number but unfortunately when I run that I receive a false answer

I have tried for loop without defining function in this case and I got the result.Contrary to that, when I define a function I can't see the proper result

r = 0
def factor(a):
    global r
    for i in range(1, a + 1):
        if a % i == 0:
        r += 1
        return r

a = int(input())
factor(a)

for example 18 has 6 factors but I receive just 1.

Body:
Use print to check your code. Indentation in Python matters. Also, global is not needed.

def factor(a):
    r = 0
    for i in range(1, a + 1):
        if a % i == 0:
            print('i', i)
            r += 1
    return r

a = int(input())
print(factor(a))


问:
Can I make class properties method parameters c#
I am attempting to pass the names of a class's properties to parameters within a method. Currently I am duplicating the the method and changing the Sundries property and Customers[i] property. This method is required approximately 4 times so preferably doing it once would be much neater. I am then using a single modal pop up to load the different tables depending on what property of the customer class is called.

How do I make the Customer class properties available as a parameter in the BindList Method?

I have seen some posts on dictionary and func but unsure of how to use them.

*Note: static List Cust;

(In another method: Cust = CustomerList)

```<code>   public class Customer
    {
        public string CustName { get; set; }
        public string CustPhone { get; set; }
        public string CustAddress { get; set; }
        public string CustHistory { get; set; }
    }
</code>```

*also: Parameters are just examples as I don't know what to put.

```<code>  public void BindLists(sundries.prop sundparm, Customer.prop custparm)
    {
        SundriesRepo sundries = new SundriesRepo();
        List<string> TempList = new List<string>();
        TempList = sundries.sundparm;

        lblEdit.Text = "History Edit";

        List<string> Used = new List<string>();
        List<string> NotUsed = new List<string>();

        if (Patients.Count > 0)
        {
            for (int i = 0; i < Cust.Count; i++)
            {
                string result = Cust[i].custparm;

                if (result != null)
                {
                    Used.Add(result);
                }
            }
            NotUsed = TempList.Except(Used).ToList();
        }

        listNotUsed.DataSource = NotUsed;
        listNotUsed.DataBind();
        listUsed.DataSource = Used;
        listUsed.DataBind();

        modPopExt1.Show();
    }
</code>```

and the HTML is:

```<code>                <asp:Panel runat="server" ID="modPan" CssClass="modPan">
                    <div id="modPanHeader">
                        <asp:Label runat="server" ID="lblEdit"></asp:Label>
                    </div>
                    <div id="divfloat" class="divfloat">
                        <div id="divList" style="float: left" class="float">
                            <asp:ListBox runat="server" ID="listNotUsed" CssClass="listBox"></asp:ListBox>
                        </div>
                        <div id="divPatient" style="float: right" class="float">
                            <asp:ListBox runat="server" ID="listUsed" CssClass="listBox"></asp:ListBox>
                        </div>
                        <div class="divModPanBtnClose">
                            <asp:Button runat="server" ID="modPanBtnClose" Text="Close"/>
                        </div>
                    </div>
                </asp:Panel>
                <asp:ModalPopupExtender runat="server" ID="modPopExt1" PopupControlID="modPan" CancelControlID="modPanBtnClose"
                    TargetControlID="lblEdit"></asp:ModalPopupExtender>
</code>```

I can not write a parameter to be accepted at "String result = Cust[i].custparm;"

答:
If I understand correctly, you are asking if you can pass a class's properties as method parameters.

Of course, you can.
Or simply pass/make the method expect a Customer instance.

```<code>var prop1 = null;
var prop2 =null;
var prop3 = null;
var prop4 = null;

//Which ever prop gets value

public void BindLists(string prop1 = null, string prop2= null, string prop3 =null, string prop4 =null)
{
  //check which ever is not null
  //Since you say one of them will be having the value.
  enter rest code here
}

//calling side
Customer cust = new Customer();
BindLists(prop1 = value, prop2 = value, prop3=value, prop4 = value) //default will be null
</code>```

Body:
I am attempting to pass the names of a class's properties to parameters within a method. Currently I am duplicating the the method and changing the Sundries property and Customers[i] property. This method is required approximately 4 times so preferably doing it once would be much neater. I am then using a single modal pop up to load the different tables depending on what property of the customer class is called.

How do I make the Customer class properties available as a parameter in the BindList Method?

I have seen some posts on dictionary and func but unsure of how to use them.

*Note: static List Cust;

(In another method: Cust = CustomerList)

   public class Customer
    {
        public string CustName { get; set; }
        public string CustPhone { get; set; }
        public string CustAddress { get; set; }
        public string CustHistory { get; set; }
    }

*also: Parameters are just examples as I don't know what to put.

  public void BindLists(sundries.prop sundparm, Customer.prop custparm)
    {
        SundriesRepo sundries = new SundriesRepo();
        List<string> TempList = new List<string>();
        TempList = sundries.sundparm;

        lblEdit.Text = "History Edit";

        List<string> Used = new List<string>();
        List<string> NotUsed = new List<string>();

        if (Patients.Count > 0)
        {
            for (int i = 0; i < Cust.Count; i++)
            {
                string result = Cust[i].custparm;

                if (result != null)
                {
                    Used.Add(result);
                }
            }
            NotUsed = TempList.Except(Used).ToList();
        }

        listNotUsed.DataSource = NotUsed;
        listNotUsed.DataBind();
        listUsed.DataSource = Used;
        listUsed.DataBind();

        modPopExt1.Show();
    }

and the HTML is:

                <asp:Panel runat="server" ID="modPan" CssClass="modPan">

                        <asp:Label runat="server" ID="lblEdit"></asp:Label>

                            <asp:ListBox runat="server" ID="listNotUsed" CssClass="listBox"></asp:ListBox>

                            <asp:ListBox runat="server" ID="listUsed" CssClass="listBox"></asp:ListBox>

                            <asp:Button runat="server" ID="modPanBtnClose" Text="Close"/>

                </asp:Panel>
                <asp:ModalPopupExtender runat="server" ID="modPopExt1" PopupControlID="modPan" CancelControlID="modPanBtnClose"
                    TargetControlID="lblEdit"></asp:ModalPopupExtender>

I can not write a parameter to be accepted at "String result = Cust[i].custparm;"

Body:
If I understand correctly, you are asking if you can pass a class's properties as method parameters.

Of course, you can.
Or simply pass/make the method expect a Customer instance.

var prop1 = null;
var prop2 =null;
var prop3 = null;
var prop4 = null;

//Which ever prop gets value

public void BindLists(string prop1 = null, string prop2= null, string prop3 =null, string prop4 =null)
{
  //check which ever is not null
  //Since you say one of them will be having the value.
  enter rest code here
}

//calling side
Customer cust = new Customer();
BindLists(prop1 = value, prop2 = value, prop3=value, prop4 = value) //default will be null


问:
Mocha/Chai test keeps producing error "cannot read property 'length' of undefined," but the function works in the app itself
Problem summary:

I wrote a function called getImagePathsFromCatalog that takes a string representing the location of a catalog (XML) file. It reads product info from the catalog file and produces an array "map"(*) consisting of productIds (key), each with an array of their associated images (value).

In my application, this runs fine and always returns the expected output, which should look something like this (formatted for readability):

```<code>[
'TEST-123': [ 'products/TEST-123.jpg' ],
'TEST-12345': [ 'products/Equipment/TEST-12345.jpg',
              'products/Equipment/TEST-12345_1.jpg' ]
]
</code>```

Background Info:

I have tried using various syntax to construct the it block (using async/await, using .then); using return and expect; using various Chai methods (be, should, assert, etc.); assigning the resolve value of the promise to a let for use in the assertion; using done; and some other things I'm sure I'm forgetting.

I have also tried different expectations, including to.be.array, to.be.ok, to.exist, and etc., but all end in the same error.

I have installed and am importing all of the required libraries and functions: chai, chai-as-promised, chai-arrays, chai-asserttype, chai.expect (etc.) and am also "using" them, as in chai.use(chaiAsPromised), etc.

(*) Note: Due to project specs, I have to use an array that behaves more or less like a map, rather than using an actual map object. I know this may cause issues with tests like to.be.array, but it shouldn't prevent me from expecting things like the result existing or coming back non-null (at least I wouldn't think it would?.)

Code:

```<code>describe('catalogImages.getImagePathsFromCatalog(catalogFile)', function () {
    it('function should return an array', function() {
        catalogImages.getImagePathsFromCatalog('../imports/catalog.xml')
        .then(catalogImagePathsMap => {
            return expect(catalogImagePathsMap).to.be.array();
        });
    });
});
</code>```

Expected and actual result summary:

Expected result: Some tests (even just basic assertions about the existence or non-null/non-undefined status of the result) should pass.

Actual result: All tests written for this function return the same error ("cannot read property 'length' of undefined").

I've been researching this error and haven't found a solution that works for me yet. Thank you in advance for any assistance.

答:
Looking at the chai expect documentation, it looks like array expectations are managed through the following syntax:

```<code>expect(foo).to.be.an('array');
</code>```

Can you try this? You may need to update to the latest chai version.

Body:
Problem summary:

I wrote a function called getImagePathsFromCatalog that takes a string representing the location of a catalog (XML) file. It reads product info from the catalog file and produces an array "map"(*) consisting of productIds (key), each with an array of their associated images (value).

In my application, this runs fine and always returns the expected output, which should look something like this (formatted for readability):

[
'TEST-123': [ 'products/TEST-123.jpg' ],
'TEST-12345': [ 'products/Equipment/TEST-12345.jpg',
              'products/Equipment/TEST-12345_1.jpg' ]
]

Background Info:

I have tried using various syntax to construct the it block (using async/await, using .then); using return and expect; using various Chai methods (be, should, assert, etc.); assigning the resolve value of the promise to a let for use in the assertion; using done; and some other things I'm sure I'm forgetting.

I have also tried different expectations, including to.be.array, to.be.ok, to.exist, and etc., but all end in the same error.

I have installed and am importing all of the required libraries and functions: chai, chai-as-promised, chai-arrays, chai-asserttype, chai.expect (etc.) and am also "using" them, as in chai.use(chaiAsPromised), etc.

(*) Note: Due to project specs, I have to use an array that behaves more or less like a map, rather than using an actual map object. I know this may cause issues with tests like to.be.array, but it shouldn't prevent me from expecting things like the result existing or coming back non-null (at least I wouldn't think it would?.)

Code:

describe('catalogImages.getImagePathsFromCatalog(catalogFile)', function () {
    it('function should return an array', function() {
        catalogImages.getImagePathsFromCatalog('../imports/catalog.xml')
        .then(catalogImagePathsMap => {
            return expect(catalogImagePathsMap).to.be.array();
        });
    });
});

Expected and actual result summary:

Expected result: Some tests (even just basic assertions about the existence or non-null/non-undefined status of the result) should pass.

Actual result: All tests written for this function return the same error ("cannot read property 'length' of undefined").

I've been researching this error and haven't found a solution that works for me yet. Thank you in advance for any assistance.

Body:
Looking at the chai expect documentation, it looks like array expectations are managed through the following syntax:

expect(foo).to.be.an('array');

Can you try this? You may need to update to the latest chai version.


问:
How to call two separate functions on dictionaries and lists?
I'm doing the practice project in chapter 5 of automate the boring stuff. It asks to define a function with two parameters (a dictionary and a list) and for the numerical dictionary values to be updated with each common occurrence between the dictionary key and list value.

I've tried defining a function to return a listed inventory based on value key pairs when a dictionary is passed as a parameter (first practice project). Then  I created a second function to account for additional items to be added to the dictionary inventory, passed as a list.

```<code>backpack = {'gold coin':42, 'rope':1}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']

def addToInventory(inventory, addedItems):
    for item in addedItems:
        inventory.setdefault(item,0)
        inventory[item] = inventory[item] + 1

def displayInventory(inv):
    print('Inventory:')
    itemTotal = 0
    for k, v in inv.items():
        print(v, k, sep= ' ')
        itemTotal += v
    print('Total number of items:' + str(itemTotal))

backpack = addToInventory(backpack, dragonLoot)
displayInventory(backpack)
</code>```

I receive the following error:

```<code>for k, v in inv.items():
AttributeError: 'NoneType' object has no attribute 'items'
</code>```

I've tried but cant see the fault, especially since the first project, returning the value-key inventory, worked OK and is essentially the same as the displayInventory() function.

I could have found a solution easily  but want to see where I am going wrong specifically. Thanks

答:
In your addToInventory function, you are not returning the modified dictionary but you are expecting it to be returned when you call it in your code at the end.  Because nothing is returned in the function, it defaults to returning None so your displayInventory function is trying to loop over a NoneType variable.  Because a dictionary is passed by reference in Python, you can modify the dictionary without having to return anything.  Simply remove the assignment to backpack after you call addToInventory:

```<code>addToInventory(backpack, dragonLoot)
</code>```

When you do that, we thus get the expected output:

```<code>Inventory:
45 gold coin
1 rope
1 dagger
1 ruby
Total number of items:48
</code>```

Body:
I'm doing the practice project in chapter 5 of automate the boring stuff. It asks to define a function with two parameters (a dictionary and a list) and for the numerical dictionary values to be updated with each common occurrence between the dictionary key and list value.

I've tried defining a function to return a listed inventory based on value key pairs when a dictionary is passed as a parameter (first practice project). Then  I created a second function to account for additional items to be added to the dictionary inventory, passed as a list.

backpack = {'gold coin':42, 'rope':1}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']

def addToInventory(inventory, addedItems):
    for item in addedItems:
        inventory.setdefault(item,0)
        inventory[item] = inventory[item] + 1

def displayInventory(inv):
    print('Inventory:')
    itemTotal = 0
    for k, v in inv.items():
        print(v, k, sep= ' ')
        itemTotal += v
    print('Total number of items:' + str(itemTotal))

backpack = addToInventory(backpack, dragonLoot)
displayInventory(backpack)

I receive the following error:

for k, v in inv.items():
AttributeError: 'NoneType' object has no attribute 'items'

I've tried but cant see the fault, especially since the first project, returning the value-key inventory, worked OK and is essentially the same as the displayInventory() function.

I could have found a solution easily  but want to see where I am going wrong specifically. Thanks

Body:
In your addToInventory function, you are not returning the modified dictionary but you are expecting it to be returned when you call it in your code at the end.  Because nothing is returned in the function, it defaults to returning None so your displayInventory function is trying to loop over a NoneType variable.  Because a dictionary is passed by reference in Python, you can modify the dictionary without having to return anything.  Simply remove the assignment to backpack after you call addToInventory:

addToInventory(backpack, dragonLoot)

When you do that, we thus get the expected output:

Inventory:
45 gold coin
1 rope
1 dagger
1 ruby
Total number of items:48


问:
Autonumber value of last inserted row - MS Access / VBA
I have a JET table with an auto-number as the primary key, and I would like to know how I can retrieve this number after inserting a row.  I have thought of using MAX() to retrieve the row with the highest value, but am not sure how reliable this would be.  Some sample code:

```<code>Dim query As String
Dim newRow As Integer
query = "INSERT INTO InvoiceNumbers (date) VALUES (" & NOW() & ");"
newRow = CurrentDb.Execute(query)
</code>```

Now I know that this wouldn't work, since Execute() won't return the value of the primary key, but this is basically the kind of code I am looking for.  I will need to use the primary key of the new row to update a number of rows in another table.

What would be the simplest / most readable way of doing this?

答:
Both of the examples immediately above didn't work for me.  Opening a recordset on the table and adding a record does work to add the record, except:

```<code>myLong = CLng(rs!AutoNumberField)
</code>```

returns Null if put between rs.AddNew and rs.Update.  If put after rs.Update, it does return something, but it's always wrong, and always the same incorrect value.  Looking at the table directly after adding the new record shows an autonumber field value different than the one returned by the above statement.

```<code>myLong = DLookup("AutoNumberField","TableName","SomeCriteria")
</code>```

will work properly, as long as it's done after rs.Update, and there are any other fields which can uniquely identify the record.

Body:
I have a JET table with an auto-number as the primary key, and I would like to know how I can retrieve this number after inserting a row.  I have thought of using MAX() to retrieve the row with the highest value, but am not sure how reliable this would be.  Some sample code:

Dim query As String
Dim newRow As Integer
query = "INSERT INTO InvoiceNumbers (date) VALUES (" & NOW() & ");"
newRow = CurrentDb.Execute(query)

Now I know that this wouldn't work, since Execute() won't return the value of the primary key, but this is basically the kind of code I am looking for.  I will need to use the primary key of the new row to update a number of rows in another table.

What would be the simplest / most readable way of doing this?

Body:
Both of the examples immediately above didn't work for me.  Opening a recordset on the table and adding a record does work to add the record, except:

myLong = CLng(rs!AutoNumberField)

returns Null if put between rs.AddNew and rs.Update.  If put after rs.Update, it does return something, but it's always wrong, and always the same incorrect value.  Looking at the table directly after adding the new record shows an autonumber field value different than the one returned by the above statement.

myLong = DLookup("AutoNumberField","TableName","SomeCriteria")

will work properly, as long as it's done after rs.Update, and there are any other fields which can uniquely identify the record.


答:
Yes, but it's awkward, the following is an example :-

```<code>-- Create the original data
DROP TABLE IF EXISTS original;
CREATE TABLE IF NOT EXISTS original (COL_0 TEXT, COL_1 TEXT, COL_2 TEXT, COL_3 TEXT, COL_4 TEXT, COL_5 TEXT, COL_6 TEXT, COL_7 TEXT);
INSERT INTO original VALUES
    (null,null,'Spoon','','Fork','','Knife',''),
    ('Location','Market Postocde','Trade Price','Retail Price','Trade Price','Retail Price','Trade Price','Reatail Price'),
    ('Market A','AAA111',0.5,1,0.6,1.1,0.55,'NA'),
    ('Market B','BBB111',0.7,2,0.8,1.5,'NA','NA')
;
SELECT * FROM original;

-- Prepare to create the transformed
DROP TABLE IF EXISTS transformed;
CREATE TABLE IF NOT EXISTS transformed (COL_0 TEXT, COL_1 TEXT, COL_2 TEXT, COL_3 TEXT, COL_4 TEXT);

WITH
    item1 AS (SELECT COL_2 FROM original WHERE (length(COL_0) < 1 AND LENGTH(COL_1) < 1) OR (COL_0 IS NULL AND COL_1 IS NULL) ),
    item2 AS (SELECT COL_4 FROM original WHERE (length(COL_0) < 1 AND LENGTH(COL_1) < 1) OR (COL_0 IS NULL AND COL_1 IS NULL)),
    item3 AS (SELECT COL_6 FROM original WHERE (length(COL_0) < 1 AND LENGTH(COL_1) < 1) OR (COL_0 IS NULL AND COL_1 IS NULL)),

    full1 AS (SELECT COL_0, COL_1,(SELECT * FROM item1),COL_2,COl_3 FROM original WHERE length(COL_1) = 6),
    full2 AS (SELECT COL_0, COL_1,(SELECT * FROM item2),COL_4,COL_5 FROM original WHERE length(COL_1) = 6),
    full3 AS (SELECT COL_0, COL_1,(SELECT * FROM item3),COL_6,COL_7 FROM original WHERE length(COL_1) = 6),

    reformed AS (SELECT * FROM full1 UNION SELECT * FROM full2 UNION SELECT * FROM full3)

    INSERT INTO transformed SELECT * FROM reformed
;

SELECT * FROM transformed;
</code>```

Explanation

Stage 1 - Create the Original Data

As per the comments the original data is created, the result of the select being :-

The above has also been run using :-

i.e. col_0 and COL_1 can be either blank or null when the row contains two items.

Stage 2 - Preparation

The next phase creates a table called transformed in which to receive the transformed data (i.e. a table with 5 columns).

Stage 3 - The Transformation

This creates 2 sets of 3 Common Table Expression (i.e. there are 3 items) and a final CTE (reformed) that merges the 2nd set of CTE's, which is then passed to an INSERT into the prepared result table, named transformed.

The first set, just the specific items are generated by processing the original table and only selecting the column where the item will be found, i.e. rows where COl_0 and COL_1 are an empty string or are null.

The second set gets the columns with the data respective to the item AND the item from the respective item? CTE. The criteria for inclusion is that that market code is 6 characters in length.

The reformed CTE merges the three CTE's from the second set into a single CTE.

Lastly the reformed CTE is used to load the transformed table.

It has been assumed that the headings are not required as this would typically not be stored as actual data.

The result being :-

Title: Is it possible to transform my table into a different format using SQLlite?

Body:
I am trying to transform a table into a different format in this image.

Image :

Attached below are the data. I have a table on my database whose column headers are currently defined as col_0 ... col_7.

+----------+------------------+-------------+--------------+-------------+--------------+-------------+--------------+
|  col_0   |      col_1       |    col_2    |    col_3     |    col_4    |    col_5     |    col_6    |    col_7     |
+----------+------------------+-------------+--------------+-------------+--------------+-------------+--------------+
|          |                  | Spoon       |              | Fork        |              | Knife       |              |
| Location | Market Postcode  | Trade Price | Retail Price | Trade Price | Retail Price | Trade Price | Retail Price |
| Market A | AAA111           | 0.5         | 1            | 0.6         | 1.1          | 0.55        | NA           |
| Market B | BBB111           | 0.7         | 2            | 0.8         | 1.5          | NA          | NA           |
+----------+------------------+-------------+--------------+-------------+--------------+-------------+--------------+

I want that to be transformed in a way that I can see the trade and retail prices of each product for markets A and B.

+----------+------------------+---------+-------------+--------------+
|  col_0   |      col_1       |  col_2  |    col_3    |    col_4     |
+----------+------------------+---------+-------------+--------------+
| Location | Market Post Code | Product | Trade Price | Retail Price |
| Market A | AAA111           | Spoon   | 0.5         | 1            |
| Market A | AAA111           | Fork    | 0.6         | 1.1          |
| Market A | AAA111           | Knife   | 0.55        | NA           |
| Market B | BBB111           | Spoon   | 0.7         | 2            |
| Market B | BBB111           | Fork    | 0.8         | 1.5          |
| Market B | BBB111           | Knife   | NA          | NA           |
+----------+------------------+---------+-------------+--------------+

I am very new to SQL and SQL lite and it would be nice if someone could assist me with this?

Thank you

Body:
Yes, but it's awkward, the following is an example :-

-- Create the original data
DROP TABLE IF EXISTS original;
CREATE TABLE IF NOT EXISTS original (COL_0 TEXT, COL_1 TEXT, COL_2 TEXT, COL_3 TEXT, COL_4 TEXT, COL_5 TEXT, COL_6 TEXT, COL_7 TEXT);
INSERT INTO original VALUES
    (null,null,'Spoon','','Fork','','Knife',''),
    ('Location','Market Postocde','Trade Price','Retail Price','Trade Price','Retail Price','Trade Price','Reatail Price'),
    ('Market A','AAA111',0.5,1,0.6,1.1,0.55,'NA'),
    ('Market B','BBB111',0.7,2,0.8,1.5,'NA','NA')
;
SELECT * FROM original;

-- Prepare to create the transformed
DROP TABLE IF EXISTS transformed;
CREATE TABLE IF NOT EXISTS transformed (COL_0 TEXT, COL_1 TEXT, COL_2 TEXT, COL_3 TEXT, COL_4 TEXT);

WITH
    item1 AS (SELECT COL_2 FROM original WHERE (length(COL_0) < 1 AND LENGTH(COL_1) < 1) OR (COL_0 IS NULL AND COL_1 IS NULL) ),
    item2 AS (SELECT COL_4 FROM original WHERE (length(COL_0) < 1 AND LENGTH(COL_1) < 1) OR (COL_0 IS NULL AND COL_1 IS NULL)),
    item3 AS (SELECT COL_6 FROM original WHERE (length(COL_0) < 1 AND LENGTH(COL_1) < 1) OR (COL_0 IS NULL AND COL_1 IS NULL)),

    full1 AS (SELECT COL_0, COL_1,(SELECT * FROM item1),COL_2,COl_3 FROM original WHERE length(COL_1) = 6),
    full2 AS (SELECT COL_0, COL_1,(SELECT * FROM item2),COL_4,COL_5 FROM original WHERE length(COL_1) = 6),
    full3 AS (SELECT COL_0, COL_1,(SELECT * FROM item3),COL_6,COL_7 FROM original WHERE length(COL_1) = 6),

    reformed AS (SELECT * FROM full1 UNION SELECT * FROM full2 UNION SELECT * FROM full3)

    INSERT INTO transformed SELECT * FROM reformed
;

SELECT * FROM transformed;

Explanation

Stage 1 - Create the Original Data

As per the comments the original data is created, the result of the select being :-

The above has also been run using :-

i.e. col_0 and COL_1 can be either blank or null when the row contains two items.

Stage 2 - Preparation

The next phase creates a table called transformed in which to receive the transformed data (i.e. a table with 5 columns).

Stage 3 - The Transformation

This creates 2 sets of 3 Common Table Expression (i.e. there are 3 items) and a final CTE (reformed) that merges the 2nd set of CTE's, which is then passed to an INSERT into the prepared result table, named transformed.

The first set, just the specific items are generated by processing the original table and only selecting the column where the item will be found, i.e. rows where COl_0 and COL_1 are an empty string or are null.

The second set gets the columns with the data respective to the item AND the item from the respective item? CTE. The criteria for inclusion is that that market code is 6 characters in length.

The reformed CTE merges the three CTE's from the second set into a single CTE.

Lastly the reformed CTE is used to load the transformed table.

It has been assumed that the headings are not required as this would typically not be stored as actual data.

The result being :-


问:
How to count unique occurences of column in Big Query
Given a table such as:

```<code>| ID | Value  |
|-------------|
| 1  | "some" |
| 1  | "some" |
| 1  | "value"|
| 2  | "some" |
| 3  | "some" |
| 3  | "value |
| 3  | "value |
</code>```

How can I count the number of unique occurrences of value for each ID?

So you end up with a table such as:

```<code>| ID | Value  | number |
|-------------|--------|
| 1  | "some" |   2    |
|    | "value"|   1    |
| 2  | "some" |   1    |
| 3  | "some" |   1    |
|    | "value |   2    |
</code>```

I attempted to use OVER(PARTITION BY ID order by Value) to separate the table by IDs and count the separate values. However this counts the number of unique occurences, but then adds them together. So I end up with a table such as:

```<code>| ID | Value  | number |
|-------------|--------|
| 1  | "some" |   2    |
| 1  | "some" |   2    |
| 1  | "value"|   3    |
| 2  | "some" |   1    |
| 3  | "some" |   1    |
| 3  | "value |   3    |
| 3  | "value |   3    |
</code>```

Is there a way to count the unique values like the second example I gave?

答:
Below is for BigQuery Standard SQL    </p>

```<code>#standardSQL
SELECT id, value, COUNT(1) number
FROM `project.dataset.table`
GROUP BY id, value
</code>```

<p>with result   </p>

```<code>Row id  value   number
1   1   some    2
2   1   value   1
3   2   some    1
4   3   value   2
5   3   some    1
</code>```

Body:
Given a table such as:

| ID | Value  |
|-------------|
| 1  | "some" |
| 1  | "some" |
| 1  | "value"|
| 2  | "some" |
| 3  | "some" |
| 3  | "value |
| 3  | "value |

How can I count the number of unique occurrences of value for each ID?

So you end up with a table such as:

| ID | Value  | number |
|-------------|--------|
| 1  | "some" |   2    |
|    | "value"|   1    |
| 2  | "some" |   1    |
| 3  | "some" |   1    |
|    | "value |   2    |

I attempted to use OVER(PARTITION BY ID order by Value) to separate the table by IDs and count the separate values. However this counts the number of unique occurences, but then adds them together. So I end up with a table such as:

| ID | Value  | number |
|-------------|--------|
| 1  | "some" |   2    |
| 1  | "some" |   2    |
| 1  | "value"|   3    |
| 2  | "some" |   1    |
| 3  | "some" |   1    |
| 3  | "value |   3    |
| 3  | "value |   3    |

Is there a way to count the unique values like the second example I gave?

Body:
Below is for BigQuery Standard SQL

#standardSQL
SELECT id, value, COUNT(1) number
FROM `project.dataset.table`
GROUP BY id, value

with result

Row id  value   number
1   1   some    2
2   1   value   1
3   2   some    1
4   3   value   2
5   3   some    1


问:
Big query make a quick backup with many tables
Currently I'm copying tables with something like this:

```<code>#!/bin/sh
export SOURCE_DATASET="BQPROJECTID:BQSOURCEDATASET"
export DEST_PREFIX="TARGETBQPROJECTID:TARGETBQDATASET._YOUR_PREFIX"
for f in `bq ls -n TOTAL_NUMBER_OF_TABLES $SOURCE_DATASET |grep TABLE | awk '{print $1}'`
do
  export CLONE_CMD="bq --nosync cp $SOURCE_DATASET.$f $DEST_PREFIX$f"
  echo $CLONE_CMD
  echo `$CLONE_CMD`
done
</code>```

(script from here), but it takes ~20min (because of ~600 tables). Maybe there is another way (preferably faster), to make a backup?

答:
As a suggestion you may use  Scheduling queries to schedule recurring queries in BigQuery, with this option you will be able to schedule your backups on a daily, weekly, monthly or custom periodicity, leaving the backups of your tables for nights or weekends. You can find more information about it in the following link.

But remember, the time that you backup takes will depend on your tables size.

Well, due to you mentioned that Scheduling queries is not an option for you, another option you can try is run your cp command in the background, this because you are working with a for loop and you are waiting to finish each process, instead of that you can run multiple process in background to get better performance. I made a simple script to test it and it works! First I made test without background process:

```<code>#!/bin/bash
start_global=$(date +'%s');
for ((i=0;i<100;i++))
do
    start=$(date +'%s');
    bq --location=US cp -a -f -n [SOURCE_PROJECT_ID]:[DATASET].[TABLE]
    [TARGET_PROJECT_ID]:[DATASET].[TABLE]
    echo "It took  $(($(date +'%s') - $start)) seconds to iteration umber:
    $i"
done
echo "It took $(($(date +'%s') - $start_global)) seconds to the entire
process"
</code>```

It takes me around 5 seconds per table copied (160 Mb approx), so I spend more less 10 minutes in that process, so I modified the script to use background process:

```<code>#!/bin/bash
start_global=$(date +'%s');
for ((i=0;i<100;i++))
do
    bq --location=US cp -a -f -n [SOURCE_PROJECT_ID]:[DATASET].[TABLE]
    [TARGET_PROJECT_ID]:[DATASET].[TABLE]  &
    pid_1=$!  # Get background process id
done
if  wait $pid_1
then
    echo -e "Processes termination successful"
else
    echo -e "Error"
fi
echo "It took $(($(date +'%s') - $start_global)) seconds to the entire
process"
</code>```

In this way  I only spend 3 minutes to finish the execution.

You may adapt this idea to your implementation, just consider the quotas for Copy jobs, you can check it here.

Body:
Currently I'm copying tables with something like this:

#!/bin/sh
export SOURCE_DATASET="BQPROJECTID:BQSOURCEDATASET"
export DEST_PREFIX="TARGETBQPROJECTID:TARGETBQDATASET._YOUR_PREFIX"
for f in `bq ls -n TOTAL_NUMBER_OF_TABLES $SOURCE_DATASET |grep TABLE | awk '{print $1}'`
do
  export CLONE_CMD="bq --nosync cp $SOURCE_DATASET.$f $DEST_PREFIX$f"
  echo $CLONE_CMD
  echo `$CLONE_CMD`
done

(script from here), but it takes ~20min (because of ~600 tables). Maybe there is another way (preferably faster), to make a backup?

Body:
As a suggestion you may use  Scheduling queries to schedule recurring queries in BigQuery, with this option you will be able to schedule your backups on a daily, weekly, monthly or custom periodicity, leaving the backups of your tables for nights or weekends. You can find more information about it in the following link.

But remember, the time that you backup takes will depend on your tables size.

Well, due to you mentioned that Scheduling queries is not an option for you, another option you can try is run your cp command in the background, this because you are working with a for loop and you are waiting to finish each process, instead of that you can run multiple process in background to get better performance. I made a simple script to test it and it works! First I made test without background process:

#!/bin/bash
start_global=$(date +'%s');
for ((i=0;i<100;i++))
do
    start=$(date +'%s');
    bq --location=US cp -a -f -n [SOURCE_PROJECT_ID]:[DATASET].[TABLE]
    [TARGET_PROJECT_ID]:[DATASET].[TABLE]
    echo "It took  $(($(date +'%s') - $start)) seconds to iteration umber:
    $i"
done
echo "It took $(($(date +'%s') - $start_global)) seconds to the entire
process"

It takes me around 5 seconds per table copied (160 Mb approx), so I spend more less 10 minutes in that process, so I modified the script to use background process:

#!/bin/bash
start_global=$(date +'%s');
for ((i=0;i<100;i++))
do
    bq --location=US cp -a -f -n [SOURCE_PROJECT_ID]:[DATASET].[TABLE]
    [TARGET_PROJECT_ID]:[DATASET].[TABLE]  &
    pid_1=$!  # Get background process id
done
if  wait $pid_1
then
    echo -e "Processes termination successful"
else
    echo -e "Error"
fi
echo "It took $(($(date +'%s') - $start_global)) seconds to the entire
process"

In this way  I only spend 3 minutes to finish the execution.

You may adapt this idea to your implementation, just consider the quotas for Copy jobs, you can check it here.


问:
React-Bootstrap 1.0.0-beta.6 offset and Form Col not working
I just install react-bootstrap v1.0.0-beta.6 and the Grid system is not working. I copied the following code from their documentation but it is not working.

I am trying to centralize the form in the screen by using offsets and I also want some of the form fields to be adjacent each other.

```<code>class RegistrationPage extends Component {
  render() {
    return (
      <Container>
        <Row center>
          <Col md={{ span: 4, offset: 4}}>
            <Form>
              <Form.Row>
                <Form.Group as={Col} controlId="formGridEmail">
                  <Form.Label>Email</Form.Label>
                  <Form.Control type="email" placeholder="Enter email" />
                </Form.Group>

                <Form.Group as={Col} controlId="formGridPassword">
                  <Form.Label>Password</Form.Label>
                  <Form.Control type="password" placeholder="Password" />
                </Form.Group>
              </Form.Row>

              <Form.Group controlId="formGridAddress1">
                <Form.Label>Address</Form.Label>
                <Form.Control placeholder="1234 Main St" />
              </Form.Group>

              <Form.Group controlId="formGridAddress2">
                <Form.Label>Address 2</Form.Label>
                <Form.Control placeholder="Apartment, studio, or floor" />
              </Form.Group>

              <Form.Row>
                <Form.Group as={Col} controlId="formGridCity">
                  <Form.Label>City</Form.Label>
                  <Form.Control />
                </Form.Group>

                <Form.Group as={Col} controlId="formGridState">
                  <Form.Label>State</Form.Label>
                  <Form.Control as="select">
                    <option>Choose...</option>
                    <option>...</option>
                  </Form.Control>
                </Form.Group>

                <Form.Group as={Col} controlId="formGridZip">
                  <Form.Label>Zip</Form.Label>
                  <Form.Control />
                </Form.Group>
              </Form.Row>

              <Form.Group id="formGridCheckbox">
                <Form.Check type="checkbox" label="Check me out" />
              </Form.Group>

              <Button variant="primary" type="submit">
                Submit
              </Button>
            </Form>
          </Col>
        </Row>
      </Container>
    );
  }
}
</code>```

Here is the result...

Notice how the form does not have columns and the form is not centralized.

I am using  "bootstrap": "^4.3.1"

答: I just had this answered on the gitHub page. I installed bootstrap but had not imported it in my index.js as shown here</p>

Body:
I just install react-bootstrap v1.0.0-beta.6 and the Grid system is not working. I copied the following code from their documentation but it is not working.

I am trying to centralize the form in the screen by using offsets and I also want some of the form fields to be adjacent each other.

class RegistrationPage extends Component {
  render() {
    return (
      <Container>
        <Row center>
          <Col md={{ span: 4, offset: 4}}>
            <Form>
              <Form.Row>
                <Form.Group as={Col} controlId="formGridEmail">
                  <Form.Label>Email</Form.Label>
                  <Form.Control type="email" placeholder="Enter email" />
                </Form.Group>

                <Form.Group as={Col} controlId="formGridPassword">
                  <Form.Label>Password</Form.Label>
                  <Form.Control type="password" placeholder="Password" />
                </Form.Group>
              </Form.Row>

              <Form.Group controlId="formGridAddress1">
                <Form.Label>Address</Form.Label>
                <Form.Control placeholder="1234 Main St" />
              </Form.Group>

              <Form.Group controlId="formGridAddress2">
                <Form.Label>Address 2</Form.Label>
                <Form.Control placeholder="Apartment, studio, or floor" />
              </Form.Group>

              <Form.Row>
                <Form.Group as={Col} controlId="formGridCity">
                  <Form.Label>City</Form.Label>
                  <Form.Control />
                </Form.Group>

                <Form.Group as={Col} controlId="formGridState">
                  <Form.Label>State</Form.Label>
                  <Form.Control as="select">
                    <option>Choose...</option>
                    <option>...</option>
                  </Form.Control>
                </Form.Group>

                <Form.Group as={Col} controlId="formGridZip">
                  <Form.Label>Zip</Form.Label>
                  <Form.Control />
                </Form.Group>
              </Form.Row>

              <Form.Group id="formGridCheckbox">
                <Form.Check type="checkbox" label="Check me out" />
              </Form.Group>

              <Button variant="primary" type="submit">
                Submit
              </Button>
            </Form>
          </Col>
        </Row>
      </Container>
    );
  }
}

Here is the result...

Notice how the form does not have columns and the form is not centralized.

I am using  "bootstrap": "^4.3.1"


问:
How to parse python b' before dict
How to access id or nickname value with python3:</p>

```<code>response._content = b'{"id":44564,"nickname":'Demo'}
</code>```

答:
It looks like you're trying to read in a Json string and convert it to a dict, e.g.:</p>

```<code>import json

# response._content = b'{"id":44564,"nickname":"Demo"}'

data = json.loads(response._content.decode('utf-8'))

# data = {'id': 44564, 'nickname': 'Demo'}
</code>```

Title: How to parse python b' before dict

Body:
How to access id or nickname value with python3:

response._content = b'{"id":44564,"nickname":'Demo'}

Body:
It looks like you're trying to read in a Json string and convert it to a dict, e.g.:

import json

# response._content = b'{"id":44564,"nickname":"Demo"}'

data = json.loads(response._content.decode('utf-8'))

# data = {'id': 44564, 'nickname': 'Demo'}