答:
There's a typo in your CSS

Change the txt-field in your CSS to txt_field

This is your code:

.center {
  position: fixed;
  top: 40%;
  left: 70%;
  transform: translate(-50%, -50%);
  width: 720px;
  height: 350px;
  background: linear-gradient(180deg, white, silver);
  size: 100%;
  border-style: solid;
  border-color: black;
  border-width: 1px;
}

.center h1 {
  text-align: center;
  padding: 0 0 20px 0;
  border-bottom: 1px solid silver;
}

.center form {
  padding: 0 40px;
}

form .txt_field {
  position: relative;
  border-bottom: 2px solid #adadad;
  margin: 30px 0;
}

.txt_field input {
  width: 100%;
  padding: 0 5px;
  height: 40px;
  font-size: 16px;
  border: none;
  background: none;
  outline: none;
}

.no-outlin:focus {
  outline: none;
}

.txt_field label {
  position: absolute;
  top: 50%;
  left: 5px;
  color: #adadad;
  transform: translateY(-50%);
  font-size: 16px;
  pointer-events: none;
  transition: .7s;
  border: none;
}

.txt_field span::before {
  content: '';
  position: absolute;
  top: 40px;
  left: 0;
  width: 0%;
  height: 2px;
  background: #2691d9;
  transition: .7s;
}

.txt_field input:focus~label,
.txt_field input:valid~label {
  top: -5px;
  color: #2691d9;
}

.txt_field input:focus~span::before,
.txt_field input:valid~span::before {
  width: 100%;
}

.pass {
  margin: -5px 0 20px 5px;
  color: #a6a6a6;
  cursor: pointer;
}

.pass:hover {
  text-decoration: underline;
}

input[type="submit"] {
  width: 100%;
  height: 50px;
  border: 1px solid;
  background: #2691d9;
  border-radius: 25px;
  font-size: 18px;
  color: #e9f4fb;
  font-weight: 700;
  cursor: pointer;
  outline: none;
}

input[type="submit"]:hover {
  border-color: #2691d9;
  transition: .5s;
}

.signup_link {
  margin: 30px;
  text-align: center;
  font-size: 16px;
  color: #666666;
}

.signup_link a {
  color: #2691d9;
  text-decoration: none;
}

.signup_link a:hover {
  color: #2691d9;
  text-decoration: underline;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><head>

</head>

<body class="Body">

  <div class="center">
    <h1> Login </h1>
    <form method="post" class="Box">
      <div class="txt_field">
        <input type="text" required>
        <span></span>
        <label>Username</label>
      </div>
      <div class="txt_field">
        <input type="password" required>
        <span></span>
        <label>Password</label>
      </div>
      <div class="pass"> Forgotten Password? </div>
      <input type="submit" value="Login">
      <div class="signup_link">
        Not a Member? Create an Account!
      </div>

    </form>
  </div></code>```

Title: Login Form text boxes won't disappear

Body:
I've created this simple Login form for a uni project and for some reason the box around the text field is still showing, I want it to be invisible.
How the form works is; when a user clicks on either field, the placeholder lifts up and they type below it (refer to screenshot)
For some reason, however, the text box is still there.
Any help would be greatly appreciated.

.center {
      position:fixed;
      top: 40%;
      left: 70%;
      transform: translate(-50%, -50%);
      width: 720px;
      height: 350px;
      background: linear-gradient(180deg, white, silver );
      size: 100%;
      border-style: solid;
      border-color: black;
      border-width: 1px;

    }

    .center h1{
      text-align: center;
      padding: 0 0 20px 0;
      border-bottom: 1px solid silver;
    }

    .center form {
        padding: 0 40px;
    }

    form .txt_field {
    position: relative;
    border-bottom: 2px solid #adadad;
    margin: 30px 0;
    }

    .txt-field input {
     width: 100%;
     padding: 0 5px;
     height: 40px;
     font-size: 16px;
     border: none;
     background: none;
     outline: none;
    }

    .no-outlin:focus{
      outline: none;
    }

    .txt_field label{
      position: absolute;
      top: 50%;
      left: 5px;
      color: #adadad;
      transform: translateY(-50%);
      font-size: 16px;
      pointer-events: none;
      transition: .7s;
      border: none;
    }

    .txt_field span::before{
      content: '';
      position: absolute;
      top: 40px;
      left: 0;
      width: 0%;
      height: 2px;
      background: #2691d9;
      transition: .7s;
    }

    .txt_field input:focus ~ label,
    .txt_field input:valid ~ label {
      top: -5px;
      color: #2691d9;
    }

    .txt_field input:focus ~ span::before,
    .txt_field input:valid ~ span::before {
      width: 100%;
    }

    .pass {
      margin: -5px 0 20px 5px;
      color: #a6a6a6;
      cursor: pointer;
    }

    .pass:hover {
      text-decoration: underline;
    }

    input[type="submit"]{
      width: 100%;
      height: 50px;
      border: 1px solid;
      background: #2691d9;
      border-radius: 25px;
      font-size: 18px;
      color: #e9f4fb;
      font-weight: 700;
      cursor: pointer;
      outline: none;
    }

    input[type="submit"]:hover{
      border-color: #2691d9;
      transition: .5s;
    }

    .signup_link {
      margin: 30px;
      text-align: center;
      font-size: 16px;
      color: #666666;
    }

    .signup_link a{
      color: #2691d9;
      text-decoration: none;
    }

    .signup_link a:hover{
      color: #2691d9;
      text-decoration: underline;
    }

 Login

        <form method="post" class="Box">

           <input  type="text" required>

           Username

        <input type="password" required>

        Password

 Forgotten Password?

    <input type="submit" value="Login">

      Not a Member? Create an Account!

    </form>

Click here for sceenshot

Body:
There's a typo in your CSS

Change the txt-field in your CSS to txt_field

This is your code:

.center {
  position: fixed;
  top: 40%;
  left: 70%;
  transform: translate(-50%, -50%);
  width: 720px;
  height: 350px;
  background: linear-gradient(180deg, white, silver);
  size: 100%;
  border-style: solid;
  border-color: black;
  border-width: 1px;
}

.center h1 {
  text-align: center;
  padding: 0 0 20px 0;
  border-bottom: 1px solid silver;
}

.center form {
  padding: 0 40px;
}

form .txt_field {
  position: relative;
  border-bottom: 2px solid #adadad;
  margin: 30px 0;
}

.txt_field input {
  width: 100%;
  padding: 0 5px;
  height: 40px;
  font-size: 16px;
  border: none;
  background: none;
  outline: none;
}

.no-outlin:focus {
  outline: none;
}

.txt_field label {
  position: absolute;
  top: 50%;
  left: 5px;
  color: #adadad;
  transform: translateY(-50%);
  font-size: 16px;
  pointer-events: none;
  transition: .7s;
  border: none;
}

.txt_field span::before {
  content: '';
  position: absolute;
  top: 40px;
  left: 0;
  width: 0%;
  height: 2px;
  background: #2691d9;
  transition: .7s;
}

.txt_field input:focus~label,
.txt_field input:valid~label {
  top: -5px;
  color: #2691d9;
}

.txt_field input:focus~span::before,
.txt_field input:valid~span::before {
  width: 100%;
}

.pass {
  margin: -5px 0 20px 5px;
  color: #a6a6a6;
  cursor: pointer;
}

.pass:hover {
  text-decoration: underline;
}

input[type="submit"] {
  width: 100%;
  height: 50px;
  border: 1px solid;
  background: #2691d9;
  border-radius: 25px;
  font-size: 18px;
  color: #e9f4fb;
  font-weight: 700;
  cursor: pointer;
  outline: none;
}

input[type="submit"]:hover {
  border-color: #2691d9;
  transition: .5s;
}

.signup_link {
  margin: 30px;
  text-align: center;
  font-size: 16px;
  color: #666666;
}

.signup_link a {
  color: #2691d9;
  text-decoration: none;
}

.signup_link a:hover {
  color: #2691d9;
  text-decoration: underline;
}

<head>

</head>

<body class="Body">

  <div class="center">
    <h1> Login </h1>
    <form method="post" class="Box">
      <div class="txt_field">
        <input type="text" required>
        <span></span>
        <label>Username</label>
      </div>
      <div class="txt_field">
        <input type="password" required>
        <span></span>
        <label>Password</label>
      </div>
      <div class="pass"> Forgotten Password? </div>
      <input type="submit" value="Login">
      <div class="signup_link">
        Not a Member? <a class="nav-item-nav-link" routerLink="/register">Create an Account!</a>
      </div>

    </form>
  </div>


来源: stackexchange

问:
snapshot.data[0] throwing "The Method '[ ]' cannot be unconditionally invoked because the receiver can be 'null'
Also getting

```<code>Try making the call condtional (using ?.) or adding a null check to the target
</code>```

for the same line(s):

```<code>Text("${snapshot.data[index]}")
</code>```

If I do that I get only the error message from the title.

I have actually copy/pasted a FutureBuilder from another project of mine where it is working perfectly fine but in this one I get this error. The only difference is that in the not working project I see this:

```<code>AsyncSnapshot<Object?>
</code>```

and in the working project I see this:

```<code>AsyncSnapshot<dynamic>
</code>```

If I hover over snapshot

The entire section looks like this:

```<code>FutureBuilder(
          future: http_functions.myAsyncFunction(),
          builder: (context, snapshot) {
            return snapshot.hasData
                ? Scrollbar(
                    controller: _scrollController,
                    isAlwaysShown: true,
                    thickness: 4,
                    child: ListView.builder(
                      physics: const AlwaysScrollableScrollPhysics(),
                      shrinkWrap: true,
                      controller: _scrollController,
                      itemCount: 10,
                      itemBuilder: (context, index) {
                        return Card(
                          child: ListTile(
                            title: Text("${snapshot.data[index]}"),
                          ),
                        );
                      },
                    ),
                  )
                : const CircularProgressIndicator();
          },
        )
</code>```

While myAsyncFunction() returns a List<dynamic> using return json.decode(response.body);

答:
You need to define the type parameter of the FutureBuilder. And cast the snapshot.data to not null by using the ! operator

```<code>FutureBuilder<List<dynamic>>(
          future: http_functions.myAsyncFunction(),
          builder: (context, snapshot) {
            return snapshot.hasData
                ? Scrollbar(
                    controller: _scrollController,
                    isAlwaysShown: true,
                    thickness: 4,
                    child: ListView.builder(
                      physics: const AlwaysScrollableScrollPhysics(),
                      shrinkWrap: true,
                      controller: _scrollController,
                      itemCount: 10,
                      itemBuilder: (context, index) {
                        return Card(
                          child: ListTile(
                            title: Text("${snapshot.data![index]}"),
                          ),
                        );
                      },
                    ),
                  )
                : const CircularProgressIndicator();
          },
        )
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Also getting

Try making the call condtional (using ?.) or adding a null check to the target

for the same line(s):

Text("${snapshot.data[index]}")

If I do that I get only the error message from the title.

I have actually copy/pasted a FutureBuilder from another project of mine where it is working perfectly fine but in this one I get this error. The only difference is that in the not working project I see this:

AsyncSnapshot<Object?>

and in the working project I see this:

AsyncSnapshot<dynamic>

If I hover over snapshot

The entire section looks like this:

FutureBuilder(
          future: http_functions.myAsyncFunction(),
          builder: (context, snapshot) {
            return snapshot.hasData
                ? Scrollbar(
                    controller: _scrollController,
                    isAlwaysShown: true,
                    thickness: 4,
                    child: ListView.builder(
                      physics: const AlwaysScrollableScrollPhysics(),
                      shrinkWrap: true,
                      controller: _scrollController,
                      itemCount: 10,
                      itemBuilder: (context, index) {
                        return Card(
                          child: ListTile(
                            title: Text("${snapshot.data[index]}"),
                          ),
                        );
                      },
                    ),
                  )
                : const CircularProgressIndicator();
          },
        )

While myAsyncFunction() returns a List<dynamic> using return json.decode(response.body);

Body:
You need to define the type parameter of the FutureBuilder. And cast the snapshot.data to not null by using the ! operator

FutureBuilder<List<dynamic>>(
          future: http_functions.myAsyncFunction(),
          builder: (context, snapshot) {
            return snapshot.hasData
                ? Scrollbar(
                    controller: _scrollController,
                    isAlwaysShown: true,
                    thickness: 4,
                    child: ListView.builder(
                      physics: const AlwaysScrollableScrollPhysics(),
                      shrinkWrap: true,
                      controller: _scrollController,
                      itemCount: 10,
                      itemBuilder: (context, index) {
                        return Card(
                          child: ListTile(
                            title: Text("${snapshot.data![index]}"),
                          ),
                        );
                      },
                    ),
                  )
                : const CircularProgressIndicator();
          },
        )


问:
Customizing an Alert in SwiftUI
In an iOS app using SwiftUI, I have set an alert with this kind of code:

```<code>  Alert(title: Text("Nice Title"),
        message: Text("Some important message for the user."),
        dismissButton: .none)
</code>```

It works, but I would like to change one detail. The alert has a blue OK button. I want to customize it to have a grey OK button.

I have tried a couple of tweaks, one of them being this:

```<code>  Alert(title: Text("Nice Title"),
        message: Text("Some important message for the user."),
        dismissButton: .default(Text("OK").foregroundColor(.gray)))
</code>```

But none of my trials worked.

If anyone knows the way to go, please let me know.

答:
put this in the view that shows z alert</p>
```<code>    init() {
        UIView.appearance(whenContainedInInstancesOf: [UIAlertController.self]).tintColor = .purple1
    }
</code>```

Title: Customizing an Alert in SwiftUI

Body:
In an iOS app using SwiftUI, I have set an alert with this kind of code:

  Alert(title: Text("Nice Title"),
        message: Text("Some important message for the user."),
        dismissButton: .none)

It works, but I would like to change one detail. The alert has a blue OK button. I want to customize it to have a grey OK button.

I have tried a couple of tweaks, one of them being this:

  Alert(title: Text("Nice Title"),
        message: Text("Some important message for the user."),
        dismissButton: .default(Text("OK").foregroundColor(.gray)))

But none of my trials worked.

If anyone knows the way to go, please let me know.

Body:
put this in the view that shows z alert

    init() {
        UIView.appearance(whenContainedInInstancesOf: [UIAlertController.self]).tintColor = .purple1
    }


问:
phpmyadmin security
I have a production server with apache2, php, mysql.
I have just one site right now (mysite.com) as a virtual host.  I want to put phpmyadmin, webalizer, and maybe webmin on there.  So far, I installed phpmyadmin, and it works but the whole internet can go to mysite.com/phpmyadmin

How can I reduce the visibility to say 192.168.0.0/16 so it's just accessible to machines behind my firewall?

答: Use the <Location> directive (either in server configuration or if it is allowed, in .htaccess). In there, you can use Allow from to deny access to everyone else except some certain source.

OwnerDisplayName: Nick

ContentLicense: CC BY-SA 2.5

Title: phpmyadmin security

OwnerDisplayName: andri


问:
Check checkbox by index in another list
I have an unordered list with div and a hidden checkbox list, each with the same number of items.

How can I check an item in list 2 when I click a div in list 1 with the same index?

$(document).on('click', '.product-list li', function() {
  var index = $(this).index();
  if ($('.product-checkbox #checkbox index').prop('checked')) {
    $('.product-checkbox #checkbox index').prop('checked', false);
  } else {
    $('.product-checkbox #checkbox index').prop('checked', true);
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<ul class="product-list">
  <li>
    <div>Red</div>
  </li>
  <li>
    <div>White</div>
  </li>
  <li>
    <div>Blue</div>
  </li>
</ul>

<ul class="product-checkbox">
  <li>
    <input type="checkbox">Red
  </li>
  <li>
    <input type="checkbox">White
  </li>
  <li>
    <input type="checkbox">Blue
  </li>
</ul></code>```

So here if I click Red in the first UL, Red gets checked in the second UL.

I can get the index of the LI in the first but not apply that index to check the box.

答:
There's a couple of issues in your logic. Firstly, you can use eq() to select an element within a collection by its index. Secondly, #checkbox is looking for a single element with that id attribute. You should use the :checkbox selector instead to find any element of that type within the parent. Finally, you can make the prop() logic more succinct by providing a function which accepts the current state of the property as an argument and returns the inverted boolean value. Try this:

$(document).on('click', '.product-list li', e => {
  var index = $(e.currentTarget).index();
  $('.product-checkbox :checkbox').eq(index).prop('checked', (i, checked) => !checked);
});

/* anonymous function version for legacy support:

$(document).on('click', '.product-list li', function() {
  var index = $(this).index();
  $('.product-checkbox :checkbox').eq(index).prop('checked', function(i, checked) {
    return !checked;
  });
});
*/```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<ul class="product-list">
  <li><div>Red</div></li>
  <li><div>White</div></li>
  <li><div>Blue</div></li>
</ul>

<ul class="product-checkbox">
  <li><input type="checkbox">Red</li>
  <li><input type="checkbox">White</li>
  <li><input type="checkbox">Blue</li>
</ul></code>```

It's also worth noting that what you're doing here can be achieved in HTML alone with no need for JS or jQuery:

      Red
      <input type="checkbox" value="Red" />

      White
      <input type="checkbox" value="White" />

      Blue
      <input type="checkbox" value="Blue" />

```

Of course, I left the checkboxes visible in both examples so you can see the effect working, but they can still be easily hidden using CSS if necessary.

Title: Check checkbox by index in another list

Body:
I have an unordered list with div and a hidden checkbox list, each with the same number of items.

How can I check an item in list 2 when I click a div in list 1 with the same index?

$(document).on('click', '.product-list li', function() {
  var index = $(this).index();
  if ($('.product-checkbox #checkbox index').prop('checked')) {
    $('.product-checkbox #checkbox index').prop('checked', false);
  } else {
    $('.product-checkbox #checkbox index').prop('checked', true);
  }
});

Red

White

Blue

    <input type="checkbox">Red

    <input type="checkbox">White

    <input type="checkbox">Blue

So here if I click Red in the first UL, Red gets checked in the second UL.

I can get the index of the LI in the first but not apply that index to check the box.

Body:
There's a couple of issues in your logic. Firstly, you can use eq() to select an element within a collection by its index. Secondly, #checkbox is looking for a single element with that id attribute. You should use the :checkbox selector instead to find any element of that type within the parent. Finally, you can make the prop() logic more succinct by providing a function which accepts the current state of the property as an argument and returns the inverted boolean value. Try this:

$(document).on('click', '.product-list li', e => {
  var index = $(e.currentTarget).index();
  $('.product-checkbox :checkbox').eq(index).prop('checked', (i, checked) => !checked);
});

/* anonymous function version for legacy support:

$(document).on('click', '.product-list li', function() {
  var index = $(this).index();
  $('.product-checkbox :checkbox').eq(index).prop('checked', function(i, checked) {
    return !checked;
  });
});
*/

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<ul class="product-list">
  <li><div>Red</div></li>
  <li><div>White</div></li>
  <li><div>Blue</div></li>
</ul>

<ul class="product-checkbox">
  <li><input type="checkbox">Red</li>
  <li><input type="checkbox">White</li>
  <li><input type="checkbox">Blue</li>
</ul>

It's also worth noting that what you're doing here can be achieved in HTML alone with no need for JS or jQuery:

<ul class="product-list">
  <li>
    <label>
      Red
      <input type="checkbox" value="Red" />
    </label>
  </li>
  <li>
    <label>
      White
      <input type="checkbox" value="White" />
    </label>
  </li>
  <li>
    <label>
      Blue
      <input type="checkbox" value="Blue" />
    </label>
  </li>
</ul>

Of course, I left the checkboxes visible in both examples so you can see the effect working, but they can still be easily hidden using CSS if necessary.


问:
how to get a specific value of a column in pyspark?
I want all rows whose their value in column col1 is equal to yes. in pandas I can get like this

```<code>df[df['col1']=='yes']
</code>```

how is it in pyspark?

答:
You can use the filter method from the DataFrame.

df.filter(df["col1"] == "yes")
```
<p>or</p>
<pre class="lang-py prettyprint-override"><code>df.filter("col1 == 'yes'")
</code>```

Body:
I want all rows whose their value in column col1 is equal to yes. in pandas I can get like this

df[df['col1']=='yes']

how is it in pyspark?

Body:
You can use the filter method from the DataFrame.

df.filter(df["col1"] == "yes")

or

df.filter("col1 == 'yes'")


问:
UDF executing multiple times with Structured References
I am experiencing performance problems with a large (wide and long) table that uses a UDF that has variables passed as structured references.

It seems that when a structured reference for a specific cell, eg "[@A]" is passed to the UDF, it flags the whole column, ie "[A]" as dirty and every cell in the column the UDF references is recalculated (this is the source of the performance problem).

I have found that if I change the UDF within the table to use cell address, eg "A2", then the UDF only executes when that cell changes.

To test, create a simple function with debug.print to highlight when it is run:

```<code>Public Function zap(a As Double, b As Double) As Double
    Debug.Print "zap: " & a & "+" & b
    zap = a + b
End Function
</code>```

Create a 3 column table (A, B, C), with column C as "=zap([@A],[@B])".  if you enter or change a value in column A or B, the UDF will execute for each row regardless of whether the value in the row/column intersection has changed.

if you change column C to use cell addressing, eg  "=zap(A2,B2)", then the UDF only executes once for the row that has changed.

I can use cell addressing to overcome the performance problem, however using a table with structured references provide a lot of benefits for this application.

I would like to know if I have missed or misunderstood something about structured references, or whether there is an adjustment to the UDF that can accommodate.

答:
Thank you to Rory - placing an @ at the beginning of the formula worked:

```<code>=@zap([@A],[@B])
</code>```

Update:

In putting this into practice, I also found that should any of the dependent variables be based on formulas (eg, if [@A] contained a formula), then this will need an "@" at the front as well.

In my circumstance, there are so many dependencies it was easier to place an "@" at in front of every formula in the table (my new 'rule' when working with UDFs and Tables). Hope this helps someone.

Body:
I am experiencing performance problems with a large (wide and long) table that uses a UDF that has variables passed as structured references.

It seems that when a structured reference for a specific cell, eg "[@A]" is passed to the UDF, it flags the whole column, ie "[A]" as dirty and every cell in the column the UDF references is recalculated (this is the source of the performance problem).

I have found that if I change the UDF within the table to use cell address, eg "A2", then the UDF only executes when that cell changes.

To test, create a simple function with debug.print to highlight when it is run:

Public Function zap(a As Double, b As Double) As Double
    Debug.Print "zap: " & a & "+" & b
    zap = a + b
End Function

Create a 3 column table (A, B, C), with column C as "=zap([@A],[@B])".  if you enter or change a value in column A or B, the UDF will execute for each row regardless of whether the value in the row/column intersection has changed.

if you change column C to use cell addressing, eg  "=zap(A2,B2)", then the UDF only executes once for the row that has changed.

I can use cell addressing to overcome the performance problem, however using a table with structured references provide a lot of benefits for this application.

I would like to know if I have missed or misunderstood something about structured references, or whether there is an adjustment to the UDF that can accommodate.

Body:
Thank you to Rory - placing an @ at the beginning of the formula worked:

=@zap([@A],[@B])

Update:

In putting this into practice, I also found that should any of the dependent variables be based on formulas (eg, if [@A] contained a formula), then this will need an "@" at the front as well.

In my circumstance, there are so many dependencies it was easier to place an "@" at in front of every formula in the table (my new 'rule' when working with UDFs and Tables). Hope this helps someone.


问:
Overlapping 2 transparent Texture2Ds in OpenGL ES
I'm trying to make a 2D game for the iPad with OpenGL.  I'm new to OpenGL in general so this blending stuff is new.

My drawing code looks like this:

```<code>static CGFloat r=0;
r+=2.5;
r=remainder(r, 360);

glLoadIdentity();
//you can ignore the rotating and scaling
glRotatef(90, 0,0, -1);
glScalef(1, -1, 1);
glTranslatef(-1024, -768, 0);

glClearColor(0.3,0.8,1, 1.0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glEnable(GL_TEXTURE_2D);
glEnable (GL_BLEND);
glBlendFunc (GL_ONE,GL_ONE_MINUS_SRC_ALPHA);

[texture drawInRect:CGRectMake(512-54, abs(sin(((r+45)/180)*3.14)*500), 108, 108)];
[texture drawInRect:CGRectMake(512-54, abs(sin((r/180)*3.14)*500), 108, 108)];
</code>```

("texture" is a Texture2D that has a transparent background)
All I need to know how to do is make it so that a blue box around the texture doesnt cover up the other one.

答:
Sounds like you just need to open up the texture image in your favourite image editor and set the blue area to be 0% opaque (i.e. 0) in the alpha channel. The SRC_ALPHA part of GL_ONE_MINUS_SRC_ALPHA means the alpha value in the source texture.

Chances are you're using 32-bit colour, in which case you'll have four channels, 8 bits for Red, Green, Blue and Alpha.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to make a 2D game for the iPad with OpenGL.  I'm new to OpenGL in general so this blending stuff is new.

My drawing code looks like this:

static CGFloat r=0;
r+=2.5;
r=remainder(r, 360);

glLoadIdentity();
//you can ignore the rotating and scaling
glRotatef(90, 0,0, -1);
glScalef(1, -1, 1);
glTranslatef(-1024, -768, 0);

glClearColor(0.3,0.8,1, 1.0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glEnable(GL_TEXTURE_2D);
glEnable (GL_BLEND);
glBlendFunc (GL_ONE,GL_ONE_MINUS_SRC_ALPHA);

[texture drawInRect:CGRectMake(512-54, abs(sin(((r+45)/180)*3.14)*500), 108, 108)];
[texture drawInRect:CGRectMake(512-54, abs(sin((r/180)*3.14)*500), 108, 108)];

("texture" is a Texture2D that has a transparent background)
All I need to know how to do is make it so that a blue box around the texture doesnt cover up the other one.


问:
How do I get into a Docker container's shell?
I'm getting started working with Docker. I'm using the WordPress base image and docker-compose.

I'm trying to ssh into one of the containers to inspect the files/directories that were created during the initial build. I tried to run docker-compose run containername ls -la, but that didn't do anything. Even if it did, I'd rather have a console where I can traverse the directory structure, rather than run a single command. What is the right way to do this with Docker?

答:
There are two options we can connect to the docker terminal directly with these method shell and bash but usually bash is not supported and defualt sh is supported terminal
To sh into the running container, type this:

docker exec -it container_name/container_ID sh

To bash into a running container, type this:

docker exec -it container_name/container_ID bash

and you want to use only bash terminal than you can install the bash terminal in your Dockerfile like RUN apt install bash -y


问:
Selenium webriver do not working after update
15 and I need to upgrade to 4.1 but it is still not working.

my code:

from selenium import webdriver
import os.path
import requests

driver = webdriver.Firefox(executable_path="C:\\geckodriver.exe")

tag = "test"
driver.get("https://www.pexels.com/search/" + tag +"/?orientation=landscape&size=medium")

images = driver.find_elements_by_name('img')
l = 0
for image in images:
    src = image.get_attribute('src')

    l = +1

    try:
        if src[8] == "i":

            if src[26] == "p":
                src = src.replace('?auto=compress&cs=tinysrgb&dpr=1&w=500', '')

                if os.path.exists(tag+".txt"):
                    links = open(tag+".txt", "a")
                    link = src + "\n"
                    links.write(link)

                else:

                    links = open(tag+".txt", "w")
                    driver.quit()
```

I do not remember these images = driver.find_elements_by_name very well so I do not know how I had it but important is it is working I read on the Internet something like I need to use A Be but is not working.

答:
Try using the webdriver manager for selenium. It will download and cache the latest driver.</p>
```<code>pip install webdriver-manager
</code>```
```<code>from selenium import webdriver
from selenium.webdriver.firefox.service import Service
from webdriver_manager.firefox import GeckoDriverManager
from selenium.webdriver.common.by import By

s = Service(GeckoDriverManager().install())
driver = webdriver.Firefox(service=s)

tag = "test"
url = "https://www.pexels.com/search/" + tag +"/?orientation=landscape&size=medium"
driver.get(url)
images = driver.find_elements(By.TAG_NAME, 'img')
...
</code>```

Body:
15 and I need to upgrade to 4.1 but it is still not working.

my code:

from selenium import webdriver
import os.path
import requests

driver = webdriver.Firefox(executable_path="C:\\geckodriver.exe")

tag = "test"
driver.get("https://www.pexels.com/search/" + tag +"/?orientation=landscape&size=medium")

images = driver.find_elements_by_name('img')
l = 0
for image in images:
    src = image.get_attribute('src')

    l = +1

    try:
        if src[8] == "i":

            if src[26] == "p":
                src = src.replace('?auto=compress&cs=tinysrgb&dpr=1&w=500', '')

                if os.path.exists(tag+".txt"):
                    links = open(tag+".txt", "a")
                    link = src + "\n"
                    links.write(link)

                else:

                    links = open(tag+".txt", "w")
                    driver.quit()

I do not remember these images = driver.find_elements_by_name very well so I do not know how I had it but important is it is working I read on the Internet something like I need to use A Be but is not working.

Body:
Try using the webdriver manager for selenium. It will download and cache the latest driver.

pip install webdriver-manager

from selenium import webdriver
from selenium.webdriver.firefox.service import Service
from webdriver_manager.firefox import GeckoDriverManager
from selenium.webdriver.common.by import By

s = Service(GeckoDriverManager().install())
driver = webdriver.Firefox(service=s)

tag = "test"
url = "https://www.pexels.com/search/" + tag +"/?orientation=landscape&size=medium"
driver.get(url)
images = driver.find_elements(By.TAG_NAME, 'img')
...


问:
Vue3 reactive array from a get defined property?
I have an object set such as :

```<code>user = {
    name: 'Bill',
    addresses: [1, 2, 3]
}

addresses = {
    1: { zipcode: '91802', city: 'Los Angeles', country: 'US' },
    2: { zipcode: '06390', city: 'New York', country: 'US' },
    3: { zipcode: '94301', city: 'Palo Alto', country: 'US' }
}
</code>```

I modify the object such as :

```<code>user._addresses = user.addresses
Object.defineProperties(document, {
    addresses: {
        get () {
            return user._addresses.map(id => addresses[id])
        }
    }
})
</code>```

The issue is that if I now update _addresses, the addresses object is not automatically updated.

Such as:

```<code>user._addresses = [1, 2]
</code>```

The interface does not update to reflect the changes.

I tried to play with ref, toRef, reactive from Vue3 but I honestly don't know where to place them in order to have a reactivity on addresses whenever I change _addresses.

答:
Found it!

The issue is that a Proxy works on an array as long as it is not overriden.

So doing

```<code>proxy_array = []
</code>```

Will erase the proxy and replace it with a basic array!

So far, the best way I found to keep the Proxy (and thus, the reactivity) is to clear the array then add the items back, one by one:

```<code>proxy_array.splice(0, proxy_array.length)
new_array.forEach(item => proxy_array.push(item))
</code>```

If there's a better solution for that, I'm interested!

Body:
I have an object set such as :

user = {
    name: 'Bill',
    addresses: [1, 2, 3]
}

addresses = {
    1: { zipcode: '91802', city: 'Los Angeles', country: 'US' },
    2: { zipcode: '06390', city: 'New York', country: 'US' },
    3: { zipcode: '94301', city: 'Palo Alto', country: 'US' }
}

I modify the object such as :

user._addresses = user.addresses
Object.defineProperties(document, {
    addresses: {
        get () {
            return user._addresses.map(id => addresses[id])
        }
    }
})

The issue is that if I now update _addresses, the addresses object is not automatically updated.

Such as:

user._addresses = [1, 2]

The interface does not update to reflect the changes.

I tried to play with ref, toRef, reactive from Vue3 but I honestly don't know where to place them in order to have a reactivity on addresses whenever I change _addresses.

Body:
Found it!

The issue is that a Proxy works on an array as long as it is not overriden.

So doing

proxy_array = []

Will erase the proxy and replace it with a basic array!

So far, the best way I found to keep the Proxy (and thus, the reactivity) is to clear the array then add the items back, one by one:

proxy_array.splice(0, proxy_array.length)
new_array.forEach(item => proxy_array.push(item))

If there's a better solution for that, I'm interested!


问:
Strange exception suddenly appears when trying to install a setup project, need help big time
Using Visual Studio 2010 to build a setup project that installs a Windows Forms application .Net 4.0 C#. It has worked fine for ages but now when I'm trying to install the finished setup file, I'm getting this error message:

Error 1001. Unable to get installed types in the "Path" assembly. -->
  Unable to load one or more of the requested types. Retrieve the
  LoaderExceptions property for more information.

I have been searching for answers for over 4 hours now without finding anything. This problem just came without me doing anything. Last time I build the install file was like 2 weeks ago and there was NO problem at all. I haven't deleted any reference or any code that have anything to do with the setup project.

How could this problem appear from nothing and more important, how do I fix it?

答:
Have the same error today. For me it was the project type of the class library.

I noticed that the pucture on the guide I was following had selected Class Library (.NET Framework) instead of just Class Library.

Creating the correct project type fixed the error.

https://nhvu1988.com/posts/how-to-create-msi-installer-using-vs-installer/


问:
Adding users via flyway DB migration
I've read in some articles that it's best practice NOT to add DB users via flyway db migration. It's not very clear to me as to why it's not a good practice. One thing we thought about is that it might be good to have the user configuration automatically documented in the code.

One article mentioned that you might want different user configuration for different environments. But you could also control that in flyway.

When/why would you not want to add DB users using flyway DB migration?

答:
If I'm deploying a new user for the database that will be common across all environments, I would absolutely make the creation of that user a part of the Flyway deployment scripts. It fundamentally makes sense. "Version 43.43 is where we added the login snarglegrass to the app."

On the other hand, if you are working on setting up different environments with varying permissions, I probably will make that part of the flow control commands in pre/post deployment scripts instead of using Flyway. The reason for this is because it can be challenging to write the scripts in such a way as they're repeatable and safe. You could still do it that way though.

Title: Adding users via flyway DB migration


问:
Error: "Cannot send session cache limiter" related to encoding
I'm started having problems with the encoding, it seems that somehow Notepad++ changed the encoding or something. Anyway all files where encoded in UTF-8, but I checked and some changed to UTF-8 without BOM. Changing one to UTF-8 fixed the special characters issue.

"TageÃƒÂ¡" changed to "Tageá" but I started getting an error:

```<code>Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at /home/content/02/6945202/html/usuario/index.php:1) in /home/content/02/6945202/html/usuario/index.php on line 1
</code>```

This is line 1:

```<code><? session_start(); ?>
</code>```

I don't understand why I'm having this issue, since using ANSI or UTF-8 without BOM the page shows with no errors.

What can be the problem? Thanks

答:
This is generally caused by having some output before you make the above call.  This happens because output must come after headers, so if there is output the headers are sent.  Whitespace will cause this to happen, which can even be caused by spaces or newlines before or after the PHP tags.

To fix this problem you can eliminate all output before this call, though this is often not feasible.

A better solution is to enable output_buffering in your php.ini.

Body:
I'm started having problems with the encoding, it seems that somehow Notepad++ changed the encoding or something. Anyway all files where encoded in UTF-8, but I checked and some changed to UTF-8 without BOM. Changing one to UTF-8 fixed the special characters issue.

"TageÃƒÂ¡" changed to "Tageá" but I started getting an error:

Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at /home/content/02/6945202/html/usuario/index.php:1) in /home/content/02/6945202/html/usuario/index.php on line 1

This is line 1:

<? session_start(); ?>

I don't understand why I'm having this issue, since using ANSI or UTF-8 without BOM the page shows with no errors.

What can be the problem? Thanks


问:
How to detect swiping or selecting event in XLPagerTabStrip swift
I am going to detect the swiping or selecting tab event in XLPagerTabStrip library in Swift 4.
I only need to get the tab index whenever selected tab is changed.
So I have checked library in Github but not found any good solutions.

thanks.

答:
You can simply override updateContent</p>
```<code>override func updateContent() {
    super.updateContent()
    // your code ....
}

</code>```

Body:
You can simply override updateContent

override func updateContent() {
    super.updateContent()
    // your code ....
}


问:
Styling BottomNavigation in React.js Material-UI
How do I change the color of the icon and text of the selected link (Home in this example) to red and the color of the icon and text of the inactive links (Course and Authors in this example) to green? The docs are very thin.

```<code>class MyBottomNavigation extends Component {

  render() {
    return (
      <Paper zDepth={1}>
        <BottomNavigation selectedIndex={this.state.selectedIndex}>

          <BottomNavigationItem
            label="Home"
            icon={recentsIcon}
          />

          <BottomNavigationItem
            label="Course"
            icon={favoritesIcon}
          />

          <BottomNavigationItem
            label="Authors"
            icon={nearbyIcon}
          />
        </BottomNavigation>
      </Paper>
    )
  }
}

export default MyBottomNavigation
</code>```

答:
Since 5.* version is posible who your use sx props

Component BottomNavigation

<BottomNavigation
  sx={{
    bgcolor: 'purple',
    '& .Mui-selected': {
      '& .MuiBottomNavigationAction-label': {
        fontSize: theme => theme.typography.caption,
        transition: 'none',
        fontWeight: 'bold',
        lineHeight: '20px'
      },
      '& .MuiSvgIcon-root, & .MuiBottomNavigationAction-label': {
        color: theme => theme.palette.secondary.main
      }
    }
  }}
>
...
</BottomNavigation>

```

Body:
How do I change the color of the icon and text of the selected link (Home in this example) to red and the color of the icon and text of the inactive links (Course and Authors in this example) to green? The docs are very thin.

class MyBottomNavigation extends Component {

  render() {
    return (
      <Paper zDepth={1}>
        <BottomNavigation selectedIndex={this.state.selectedIndex}>

          <BottomNavigationItem
            label="Home"
            icon={recentsIcon}
          />

          <BottomNavigationItem
            label="Course"
            icon={favoritesIcon}
          />

          <BottomNavigationItem
            label="Authors"
            icon={nearbyIcon}
          />
        </BottomNavigation>
      </Paper>
    )
  }
}

export default MyBottomNavigation


问:
Zip archive with nested folder inside does not unzip with yauzl
I am writing software which, among other things, downloads a zip archive using the Dropbox API and then unzips that archive using yauzl.

The way the files are stored and downloaded from DB often ends up with nested folders, and I need to keep it that way.

However my implementation of yauzl is not capable of unzipping while keeping that nested folder structure, if there is a nested folder in the archive it does not unzip at all.

Here is my unzip function, which is the default yauzl example with the addition of local file write at the end.

```<code>const unzip = () => {
    let zipPath = "pathToFile.zip"
    let extractPath = "pathToExtractLocation"

        yauzl.open(zipPath, {lazyEntries: true}, function(err, zipfile) {
            if (err) throw err;
            zipfile.readEntry();
            zipfile.on("entry", function(entry) {
            if (/\/$/.test(entry.fileName)) {
                // Directory file names end with '/'.
                // Note that entries for directories themselves are optional.
                // An entry's fileName implicitly requires its parent directories to exist.
                zipfile.readEntry();
            } else {
                // file entry
                zipfile.openReadStream(entry, function(err, readStream) {
                if (err) throw err;
                readStream.on("end", function() {
                    zipfile.readEntry();
                });
                const writer = fs.createWriteStream(path.join(extractPath, entry.fileName));
                readStream.pipe(writer);
                });
            }
            });
        });
}
</code>```

Removing the if (/\/$/.test(entry.fileName)) check treats the top level folder as a file, extracting it with no file extension and 0kb size. What I want it to do is extract the archive including subfolders (to at least a depth of 2, being aware of the risk of zip bombing).

Is that possible using yauzl?

答:
The code needs to create the directory tree at the extract path. You may use fs.mkdir with the recursive option to ensure that a directory exists before extract to it.

if (/\/$/.test(entry.fileName)) {
  // Directory file names end with '/'.
  // Note that entries for directories themselves are optional.
  // An entry's fileName implicitly requires its parent directories to exist.
  zipfile.readEntry();
} else {
  // file entry
  fs.mkdir(
    path.join(extractPath, path.dirname(entry.fileName)),
    { recursive: true },
    (err) => {
      if (err) throw err;
      zipfile.openReadStream(entry, function (err, readStream) {
        if (err) throw err;
        readStream.on("end", function () {
          zipfile.readEntry();
        });
        const writer = fs.createWriteStream(
          path.join(extractPath, entry.fileName)
        );
        readStream.pipe(writer);
      });
    }
  );
}
```

Body:
I am writing software which, among other things, downloads a zip archive using the Dropbox API and then unzips that archive using yauzl.

The way the files are stored and downloaded from DB often ends up with nested folders, and I need to keep it that way.

However my implementation of yauzl is not capable of unzipping while keeping that nested folder structure, if there is a nested folder in the archive it does not unzip at all.

Here is my unzip function, which is the default yauzl example with the addition of local file write at the end.

const unzip = () => {
    let zipPath = "pathToFile.zip"
    let extractPath = "pathToExtractLocation"

        yauzl.open(zipPath, {lazyEntries: true}, function(err, zipfile) {
            if (err) throw err;
            zipfile.readEntry();
            zipfile.on("entry", function(entry) {
            if (/\/$/.test(entry.fileName)) {
                // Directory file names end with '/'.
                // Note that entries for directories themselves are optional.
                // An entry's fileName implicitly requires its parent directories to exist.
                zipfile.readEntry();
            } else {
                // file entry
                zipfile.openReadStream(entry, function(err, readStream) {
                if (err) throw err;
                readStream.on("end", function() {
                    zipfile.readEntry();
                });
                const writer = fs.createWriteStream(path.join(extractPath, entry.fileName));
                readStream.pipe(writer);
                });
            }
            });
        });
}

Removing the if (/\/$/.test(entry.fileName)) check treats the top level folder as a file, extracting it with no file extension and 0kb size. What I want it to do is extract the archive including subfolders (to at least a depth of 2, being aware of the risk of zip bombing).

Is that possible using yauzl?


问:
Reading values from test fixture Cypress
I'm new to Cypress and started playing around with fixtures.I'm trying to read values from a JSON file and then assert the values in a test.

Here is my code

```<code>it('Fixture test' ,() => {
    cy.fixture('AllNotificationStates').then(notifications => {
        for(let n in notifications) {
            cy.intercept('GET', '**/api', { fixture: 'AllNotificationStates.json' });

            cy.wrap(notifications[n])
            .should('be.an', 'object')
            .and('contain', {
                rowId: 1,
                streamId: "33e24004-04ff-4c44-8d59-c8752b0f43d7",
                notificationStatus: "Sent",
              });
        }
    });
})
</code>```

What this does is assert that the properties within the JSON file match the values I expect. What I'm trying to do is read the values from the fixture file save them to an object and then assert them in my test. So for example the property rowId in the contain should not be hard coded but read from the fixture file.

Edit here is my JSON file:

```<code>[
    {
      "rowId": 1,
      "streamId": "33e24004-04ff-4c44-8d59-c8752b0f43d7",
      "notificationStatus": "Sent",
      "details": {
        "name": "Notification",
        "createdTime": "2022-02-07T11:59:15.423Z",
        "createdBy": "test@test.com",
      }
]
</code>```

答:
You can directly replace the hardcoded values with the values from the json file like this:

it('Fixture test', () => {
  cy.fixture('AllNotificationStates').then((notifications) => {
    for (let n in notifications) {

      cy.intercept('GET', '**/api', {fixture: 'AllNotificationStates.json'})

      cy.wrap(notifications[n]).should('be.an', 'object').and('contain', {
        rowId: notifications[n].rowId,
        streamId: notifications[n].streamId,
        notificationStatus: notifications[n].notificationStatus,
      })
    }
  })
})
```

Body:
I'm new to Cypress and started playing around with fixtures.I'm trying to read values from a JSON file and then assert the values in a test.

Here is my code

it('Fixture test' ,() => {
    cy.fixture('AllNotificationStates').then(notifications => {
        for(let n in notifications) {
            cy.intercept('GET', '**/api', { fixture: 'AllNotificationStates.json' });

            cy.wrap(notifications[n])
            .should('be.an', 'object')
            .and('contain', {
                rowId: 1,
                streamId: "33e24004-04ff-4c44-8d59-c8752b0f43d7",
                notificationStatus: "Sent",
              });
        }
    });
})

What this does is assert that the properties within the JSON file match the values I expect. What I'm trying to do is read the values from the fixture file save them to an object and then assert them in my test. So for example the property rowId in the contain should not be hard coded but read from the fixture file.

Edit here is my JSON file:

[
    {
      "rowId": 1,
      "streamId": "33e24004-04ff-4c44-8d59-c8752b0f43d7",
      "notificationStatus": "Sent",
      "details": {
        "name": "Notification",
        "createdTime": "2022-02-07T11:59:15.423Z",
        "createdBy": "test@test.com",
      }
]


问:
Nest can't resolve dependencies of the GraphQLModule
Im trying to add a graphql server to nestjs based on documentation, but im getting this error:

```<code>Nest can't resolve dependencies of the GraphQLModule (HttpAdapterHost, GqlModuleOptions, GraphQLFactory, GraphQLTypesLoader, ?). Please make sure that the argument at index [4] is available in the GraphQLModule context. +19ms
</code>```

Error: Nest can't resolve dependencies of the GraphQLModule (HttpAdapterHost, GqlModuleOptions, GraphQLFactory, GraphQLTypesLoader, ?). Please make sure that the argument at index [4] is available in the GraphQLModule context.

答:
Your Versions does not compatible.

From the docs itself: https://docs.nestjs.com/graphql/quick-start

```<code>WARNING
@nestjs/graphql@^9 is compatible with Apollo v3 (check out Apollo Server 3 migration guide for more details), while @nestjs/graphql@^8 only supports Apollo v2 (e.g., apollo-server-express@2.x.x package). Both versions (v9 and v8) are fully compatible with Nest v8 (@nestjs/common@^8, @nestjs/core@^8, etc.).
</code>```

Body:
Im trying to add a graphql server to nestjs based on documentation, but im getting this error:

Nest can't resolve dependencies of the GraphQLModule (HttpAdapterHost, GqlModuleOptions, GraphQLFactory, GraphQLTypesLoader, ?). Please make sure that the argument at index [4] is available in the GraphQLModule context. +19ms

Error: Nest can't resolve dependencies of the GraphQLModule (HttpAdapterHost, GqlModuleOptions, GraphQLFactory, GraphQLTypesLoader, ?). Please make sure that the argument at index [4] is available in the GraphQLModule context.

Body:
Your Versions does not compatible.

From the docs itself: https://docs.nestjs.com/graphql/quick-start

WARNING
@nestjs/graphql@^9 is compatible with Apollo v3 (check out Apollo Server 3 migration guide for more details), while @nestjs/graphql@^8 only supports Apollo v2 (e.g., apollo-server-express@2.x.x package). Both versions (v9 and v8) are fully compatible with Nest v8 (@nestjs/common@^8, @nestjs/core@^8, etc.).


问:
How to copy directory from remote server with scp, excluding a specific subdirectory
I have a directory that I want to copy from a remote server to my desktop. In this directory there is a 40Gb subdirectory that I want to exclude from copying. Until now I used the scp command but there is no -exclude option or anything similar in the man page. By looking online I found a bunch of different ways to copy directory from remote host or exclude a subdirectory when copying locally but no way of how to combine those two. Any help is appreciated. Thanks.

答:
Another option if you can't use rsync (on a readonly system for exemple) is to tar over ssh.

tar \
  --exclude='temp' \
  --exclude='work' \
  --exclude='logs' \
  -cpf \. # c: create p: preserve owner f: dest file... is output stream
  - \
  apache-tomcat-9.0.17 \. # file or folder to compress/send through ssh
     | ssh foo@bar.com '(cd ~/my/save/directory; tar xfp - )'
```


问:
How to avoid authentication when connecting to standalone chrome debug container?
I am using selenium/standalone-chrome-debug.

By default connecting to the container via VNC will trigger an authentication prompt which can be avoided by setting an environment variable as per the documentation:

If you want to run VNC without password authentication you can set the environment variable VNC_NO_PASSWORD=1.

When I start the container with the following command, I'm still prompted for the password:

docker run -d -p 4444:4444 -p 0:5900 -v /dev/shm:/dev/shm -e VNC_NO_PASSWORD=1 selenium/standalone-chrome-debug
```

As you can see in the following screencast:

I'm still asked for a password

Trying to authenticate without password fails

When I use the default password (secret), it passes

Question: how do I avoid authentication completely?

答:
Adding

```<code>  VNC_NO_PASSWORD: 1
</code>```

to the environment of the relevant service in docker-compose.yml worked for me.

Body:
I am using selenium/standalone-chrome-debug.

By default connecting to the container via VNC will trigger an authentication prompt which can be avoided by setting an environment variable as per the documentation:

If you want to run VNC without password authentication you can set the environment variable VNC_NO_PASSWORD=1.

When I start the container with the following command, I'm still prompted for the password:

docker run -d -p 4444:4444 -p 0:5900 -v /dev/shm:/dev/shm -e VNC_NO_PASSWORD=1 selenium/standalone-chrome-debug

As you can see in the following screencast:

I'm still asked for a password

Trying to authenticate without password fails

When I use the default password (secret), it passes

Question: how do I avoid authentication completely?

Body:
Adding

  VNC_NO_PASSWORD: 1

to the environment of the relevant service in docker-compose.yml worked for me.


问:
Why is the SOAP XML attribute not being set?
When creating SOAP with SOAP::Lite

```<code>#!/usr/bin/perl
use 5.006;
use strict;
use warnings;
use SOAP::Lite +trace => [ 'debug' ];

my $req1 = SOAP::Lite->new(
    readable => 1,
    autotype => 0,
    proxy    => 'https://ics2wstest.ic3.com/commerce/1.x/transactionProcessor',
);

# req1 does not generate the XML attribute <item id="0"> it just generates
# <item>
$req1->requestMessage(
    \SOAP::Data->new(
        name => 'item',
        attr => { id => '0' },
        value => \SOAP::Data->new(
            name => 'foo',
            value => 1,
        ),
     ),
);
</code>```

I get this XML (note: well this is the important part)

```<code><item>
  <foo>1</foo>
</item>
</code>```

I do not understand why I am not getting this XML

```<code><item id="0">
   <foo>1</foo>
</item>
</code>```

can anyone tell me how to get the attribute to be generated?

note: this near identical (instead of naming the attribute id it's named foo)  code works. so I think this may be a bug

```<code>$req->requestMessage(
    \SOAP::Data->new(
        name => 'item',
        attr => { foo => '0' },
        value => \SOAP::Data->new(
            name => 'foo',
            value => 1,
        ),
     ),
);
</code>```

答:
update: Fixed in 0.714

It's conflicting with something SOAP::Lite or SOAP uses

```<code>sub xmlize {
    my $self = shift;
    my($name, $attrs, $values, $id) = @{+shift};
    $attrs ||= {};

    local $self->{_level} = $self->{_level} + 1;
    return $self->tag($name, $attrs)
        unless defined $values;
    return $self->tag($name, $attrs, $values)
        unless UNIVERSAL::isa($values => 'ARRAY');
    return $self->tag($name, {%$attrs, href => '#'.$self->multiref_anchor($id)})
        if $self->is_href($id, delete($attrs->{_id}));
    return $self->tag($name,
        {
            %$attrs, id => $self->multiref_anchor($id)      <-------- Clobbers your id
        },
        map {$self->xmlize($_)} @$values
    );
}
</code>```

I think that's where your id gets lost. And was the section of code changed in 0.714

Body:
When creating SOAP with SOAP::Lite

#!/usr/bin/perl
use 5.006;
use strict;
use warnings;
use SOAP::Lite +trace => [ 'debug' ];

my $req1 = SOAP::Lite->new(
    readable => 1,
    autotype => 0,
    proxy    => 'https://ics2wstest.ic3.com/commerce/1.x/transactionProcessor',
);

# req1 does not generate the XML attribute <item id="0"> it just generates
# <item>
$req1->requestMessage(
    \SOAP::Data->new(
        name => 'item',
        attr => { id => '0' },
        value => \SOAP::Data->new(
            name => 'foo',
            value => 1,
        ),
     ),
);

I get this XML (note: well this is the important part)

<item>
  <foo>1</foo>
</item>

I do not understand why I am not getting this XML

<item id="0">
   <foo>1</foo>
</item>

can anyone tell me how to get the attribute to be generated?

note: this near identical (instead of naming the attribute id it's named foo)  code works. so I think this may be a bug

$req->requestMessage(
    \SOAP::Data->new(
        name => 'item',
        attr => { foo => '0' },
        value => \SOAP::Data->new(
            name => 'foo',
            value => 1,
        ),
     ),
);

Body:
update: Fixed in 0.714

It's conflicting with something SOAP::Lite or SOAP uses

sub xmlize {
    my $self = shift;
    my($name, $attrs, $values, $id) = @{+shift};
    $attrs ||= {};

    local $self->{_level} = $self->{_level} + 1;
    return $self->tag($name, $attrs)
        unless defined $values;
    return $self->tag($name, $attrs, $values)
        unless UNIVERSAL::isa($values => 'ARRAY');
    return $self->tag($name, {%$attrs, href => '#'.$self->multiref_anchor($id)})
        if $self->is_href($id, delete($attrs->{_id}));
    return $self->tag($name,
        {
            %$attrs, id => $self->multiref_anchor($id)      <-------- Clobbers your id
        },
        map {$self->xmlize($_)} @$values
    );
}

I think that's where your id gets lost. And was the section of code changed in 0.714


问:
snapshot.data[0] throwing "The Method '[ ]' cannot be unconditionally invoked because the receiver can be 'null'
Also getting

```<code>Try making the call condtional (using ?.) or adding a null check to the target
</code>```

for the same line(s):

```<code>Text("${snapshot.data[index]}")
</code>```

If I do that I get only the error message from the title.

I have actually copy/pasted a FutureBuilder from another project of mine where it is working perfectly fine but in this one I get this error. The only difference is that in the not working project I see this:

```<code>AsyncSnapshot<Object?>
</code>```

and in the working project I see this:

```<code>AsyncSnapshot<dynamic>
</code>```

If I hover over snapshot

The entire section looks like this:

```<code>FutureBuilder(
          future: http_functions.myAsyncFunction(),
          builder: (context, snapshot) {
            return snapshot.hasData
                ? Scrollbar(
                    controller: _scrollController,
                    isAlwaysShown: true,
                    thickness: 4,
                    child: ListView.builder(
                      physics: const AlwaysScrollableScrollPhysics(),
                      shrinkWrap: true,
                      controller: _scrollController,
                      itemCount: 10,
                      itemBuilder: (context, index) {
                        return Card(
                          child: ListTile(
                            title: Text("${snapshot.data[index]}"),
                          ),
                        );
                      },
                    ),
                  )
                : const CircularProgressIndicator();
          },
        )
</code>```

While myAsyncFunction() returns a List<dynamic> using return json.decode(response.body);

答: Use snapshot.data![index] to force that it's not null at this point.

Body:
Also getting

Try making the call condtional (using ?.) or adding a null check to the target

for the same line(s):

Text("${snapshot.data[index]}")

If I do that I get only the error message from the title.

I have actually copy/pasted a FutureBuilder from another project of mine where it is working perfectly fine but in this one I get this error. The only difference is that in the not working project I see this:

AsyncSnapshot<Object?>

and in the working project I see this:

AsyncSnapshot<dynamic>

If I hover over snapshot

The entire section looks like this:

FutureBuilder(
          future: http_functions.myAsyncFunction(),
          builder: (context, snapshot) {
            return snapshot.hasData
                ? Scrollbar(
                    controller: _scrollController,
                    isAlwaysShown: true,
                    thickness: 4,
                    child: ListView.builder(
                      physics: const AlwaysScrollableScrollPhysics(),
                      shrinkWrap: true,
                      controller: _scrollController,
                      itemCount: 10,
                      itemBuilder: (context, index) {
                        return Card(
                          child: ListTile(
                            title: Text("${snapshot.data[index]}"),
                          ),
                        );
                      },
                    ),
                  )
                : const CircularProgressIndicator();
          },
        )

While myAsyncFunction() returns a List<dynamic> using return json.decode(response.body);


问:
Group BY and take into account changing values
I have data in a table like this:

id
name
timestamp
location

1
John
2022-02-07 12:00:01
Area a

2
John
2022-02-07 11:44:23
Area a

3
John
2022-02-07 12:55:25
Area a

4
John
2022-02-07 13:00:06
Area b

5
John
2022-02-07 14:05:41
Area b

6
John
2022-02-07 15:05:41
Area b

7
sam
2021-12-27 10:20:35
Area a

8
sam
2021-12-27 11:35:24
Area a

9
sam
2022-02-07 12:00:01
Area b

10
sam
2022-02-07 12:10:38
Area b

11
sam
2022-02-07 12:17:01
Area b

12
sam
2022-02-07 12:29:01
Area a

Is it possible to create a view that tells me how long each user staid in an area ?

If i try a query like this, it doesnt work if a user comes back to an old area

```<code>Select name, location, MIN(timestamp) AS timeOfArrival, MAX(timestamp) AS timeOfDeparture
FROM MyTable
GROUP BY name, location
</code>```

Here it shows Sam staying more than a month at the same location:

```<code> name  | location |    timeOfArrival     |   timeOfDeparture
---------------------------------------------------------------
 John  |  Area a  | 2022-02-07 12:00:01  | 2022-02-07 12:55:25
 John  |  Area b  | 2022-02-07 13:05:41  | 2022-02-07 15:05:41
 sam   |  Area a  | 2021-12-27 10:20:35  | 2022-02-07 12:29:01
 sam   |  Area b  | 2022-02-07 12:00:01  | 2022-02-07 12:17:01
</code>```

答:
If I understood correctly, for a single user and an area, timestamps are alternatively associated with either arrival or departure.

Therefore, you can identify an event as a combination of an arrival and subsequent departure, or a single arrival. I computed an event identifier eid as a simple function of the row number of the table partitioned by name and location and sorted by timestamp.

Then added eid to the grouping variables and obtained a table with details of events per user and area:

select  name,
        location,
        min(timestamp) as arrivalTime,
        max(timestamp) as departureTime
    from (
      SELECT *,
             floor((pid - 1)/2) as eid
        from (
          SELECT *,
                 Row_Number() OVER(PARTITION BY name,location ORDER BY timestamp) as pid
            from MyTable
        ) q1
    ) q2
group by name, location, eid;
```
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>name</th>
<th>location</th>
<th>arrivalTime</th>
<th>departureTime</th>
</tr>
</thead>
<tbody>
<tr>
<td>John</td>
<td>Area a</td>
<td>2022-02-07 11:44:23</td>
<td>2022-02-07 12:00:01</td>
</tr>
<tr>
<td>John</td>
<td>Area a</td>
<td>2022-02-07 12:55:25</td>
<td>2022-02-07 12:55:25</td>
</tr>
<tr>
<td>John</td>
<td>Area b</td>
<td>2022-02-07 13:00:06</td>
<td>2022-02-07 14:05:41</td>
</tr>
<tr>
<td>John</td>
<td>Area b</td>
<td>2022-02-07 15:05:41</td>
<td>2022-02-07 15:05:41</td>
</tr>
<tr>
<td>sam</td>
<td>Area a</td>
<td>2021-12-27 10:20:35</td>
<td>2021-12-27 11:35:24</td>
</tr>
<tr>
<td>sam</td>
<td>Area a</td>
<td>2022-02-07 12:29:01</td>
<td>2022-02-07 12:29:01</td>
</tr>
<tr>
<td>sam</td>
<td>Area b</td>
<td>2022-02-07 12:00:01</td>
<td>2022-02-07 12:10:38</td>
</tr>
<tr>
<td>sam</td>
<td>Area b</td>
<td>2022-02-07 12:17:01</td>
<td>2022-02-07 12:17:01</td>
</tr>
</tbody>
</table>
</div>
<p>However, if you're only interested in total stay time you can simplify the query and calculate difference of timestamps only between an even row number and the row immediately preceding (with rows ordered by timestamp and properly partitioned). The following example works on sqlite:</p>
<pre class="lang-sql prettyprint-override"><code>  select name,
          location,
          sum(stayTimeHours)
    from (
      SELECT *,
             case Row_Number() OVER(PARTITION BY name,location ORDER BY timestamp) % 2
             when 1               -- odd number, arrival
               then 0             -- only accumulate hours, after departure
             when 0               -- even number, departure
             then CAST((julianday(timestamp) -
                        julianday(LAG(timestamp) OVER(PARTITION BY name,location ORDER BY timestamp))) *
                        24
                        AS REAL)
             end
              as stayTimeHours
        from MyTable
    ) q1
   group by name,
            location;
</code>```

name
location
stayTimeHours

John
Area a
0.260555550456047

John
Area b
1.09305556118488

sam
Area a
1.2469444423914

sam
Area b
0.176944445818663

Body:
I have data in a table like this:

id
name
timestamp
location

1
John
2022-02-07 12:00:01
Area a

2
John
2022-02-07 11:44:23
Area a

3
John
2022-02-07 12:55:25
Area a

4
John
2022-02-07 13:00:06
Area b

5
John
2022-02-07 14:05:41
Area b

6
John
2022-02-07 15:05:41
Area b

7
sam
2021-12-27 10:20:35
Area a

8
sam
2021-12-27 11:35:24
Area a

9
sam
2022-02-07 12:00:01
Area b

10
sam
2022-02-07 12:10:38
Area b

11
sam
2022-02-07 12:17:01
Area b

12
sam
2022-02-07 12:29:01
Area a

Is it possible to create a view that tells me how long each user staid in an area ?

If i try a query like this, it doesnt work if a user comes back to an old area

Select name, location, MIN(timestamp) AS timeOfArrival, MAX(timestamp) AS timeOfDeparture
FROM MyTable
GROUP BY name, location

Here it shows Sam staying more than a month at the same location:

 name  | location |    timeOfArrival     |   timeOfDeparture
---------------------------------------------------------------
 John  |  Area a  | 2022-02-07 12:00:01  | 2022-02-07 12:55:25
 John  |  Area b  | 2022-02-07 13:05:41  | 2022-02-07 15:05:41
 sam   |  Area a  | 2021-12-27 10:20:35  | 2022-02-07 12:29:01
 sam   |  Area b  | 2022-02-07 12:00:01  | 2022-02-07 12:17:01

Body:
If I understood correctly, for a single user and an area, timestamps are alternatively associated with either arrival or departure.

Therefore, you can identify an event as a combination of an arrival and subsequent departure, or a single arrival. I computed an event identifier eid as a simple function of the row number of the table partitioned by name and location and sorted by timestamp.

Then added eid to the grouping variables and obtained a table with details of events per user and area:

select  name,
        location,
        min(timestamp) as arrivalTime,
        max(timestamp) as departureTime
    from (
      SELECT *,
             floor((pid - 1)/2) as eid
        from (
          SELECT *,
                 Row_Number() OVER(PARTITION BY name,location ORDER BY timestamp) as pid
            from MyTable
        ) q1
    ) q2
group by name, location, eid;

name
location
arrivalTime
departureTime

John
Area a
2022-02-07 11:44:23
2022-02-07 12:00:01

John
Area a
2022-02-07 12:55:25
2022-02-07 12:55:25

John
Area b
2022-02-07 13:00:06
2022-02-07 14:05:41

John
Area b
2022-02-07 15:05:41
2022-02-07 15:05:41

sam
Area a
2021-12-27 10:20:35
2021-12-27 11:35:24

sam
Area a
2022-02-07 12:29:01
2022-02-07 12:29:01

sam
Area b
2022-02-07 12:00:01
2022-02-07 12:10:38

sam
Area b
2022-02-07 12:17:01
2022-02-07 12:17:01

However, if you're only interested in total stay time you can simplify the query and calculate difference of timestamps only between an even row number and the row immediately preceding (with rows ordered by timestamp and properly partitioned). The following example works on sqlite:

  select name,
          location,
          sum(stayTimeHours)
    from (
      SELECT *,
             case Row_Number() OVER(PARTITION BY name,location ORDER BY timestamp) % 2
             when 1               -- odd number, arrival
               then 0             -- only accumulate hours, after departure
             when 0               -- even number, departure
             then CAST((julianday(timestamp) -
                        julianday(LAG(timestamp) OVER(PARTITION BY name,location ORDER BY timestamp))) *
                        24
                        AS REAL)
             end
              as stayTimeHours
        from MyTable
    ) q1
   group by name,
            location;

name
location
stayTimeHours

John
Area a
0.260555550456047

John
Area b
1.09305556118488

sam
Area a
1.2469444423914

sam
Area b
0.176944445818663


问:
Displaying custom HTML or XML reports with Jenkins
I have generated custom XML reports through testing. is it possible to display these XML with Jenkins? If possible, then how to display it with Jenkins?</p>

答:
Badge plugin

Usage in a pipeline:

```<code>def icon = "info.gif"
createSummary(
  icon: icon,
  text: """<h1>My Custom Summary</h1>"""
)
</code>```

Body:
Badge plugin

Usage in a pipeline:

def icon = "info.gif"
createSummary(
  icon: icon,
  text: """<h1>My Custom Summary</h1>"""
)


问:
Setting width and height using jQuery isotope plugin
I'm using the jQuery Isotope plugin, and although I have it working, I can't seem to get it to recognise any margins.

I can see in Firebug that the margins are being applied, but the items are just overlapping the margin (I think becasuse isotope uses absolute positioning).

I had the width working briefly by using the following:

```<code>masonry : {
columnWidth : 172
          }
</code>```

but I couldn't figure out how to get the height working (I tried rowHeight with masonry, and masonryHorizontal).

How do I tell isotope what widths, and heights to use?

Thanks

答:
I was having a similar (if not the same) problem; I had no vertical spacing between my items. Make sure you're including the following CSS properties on your tiled elements:

```<code>.element {
  width: 110px; /*your columnWidth minus 10px */
  height: 110px; /*same as width, for a square grid system*/
  margin: 5px; /*5px here will result in 10px of vertical spacing between tiles*/
  float: left;
  overflow: hidden;
  position: relative;
}
</code>```

Hope this helps.

Body:
I'm using the jQuery Isotope plugin, and although I have it working, I can't seem to get it to recognise any margins.

I can see in Firebug that the margins are being applied, but the items are just overlapping the margin (I think becasuse isotope uses absolute positioning).

I had the width working briefly by using the following:

masonry : {
columnWidth : 172
          }

but I couldn't figure out how to get the height working (I tried rowHeight with masonry, and masonryHorizontal).

How do I tell isotope what widths, and heights to use?

Thanks

Body:
I was having a similar (if not the same) problem; I had no vertical spacing between my items. Make sure you're including the following CSS properties on your tiled elements:

.element {
  width: 110px; /*your columnWidth minus 10px */
  height: 110px; /*same as width, for a square grid system*/
  margin: 5px; /*5px here will result in 10px of vertical spacing between tiles*/
  float: left;
  overflow: hidden;
  position: relative;
}

Hope this helps.


问:
Change the stroke/fill color of SF Symbol icon in SwiftUI?
I am looking for a way to change the stroke / fill color of an SF Symbol icon in SwiftUI.

I have tried .background(Color.red) but that just changes the background of the whole icon (no change is applied to the actual icon itself) as implied. I also tried .foregroundColor(Color.red)which does nothing to the icon.

contents of content view are as follows:

```<code>var body: some View {
    Image(systemName: "person.circle").foregroundColor(.red)
}
</code>```

答:
One trick I figured out that works nicely for iOS 14 is to use the fill and non fill versions together to get two colors regardless of whether 14 or 15:</p>
```<code>ZStack {
    Image(systemName: "person.circle")
        .foregroundColor(.white)
    Image(systemName: "person.circle.fill")
        .foregroundColor(.yellow)
}
</code>```

Body:
I am looking for a way to change the stroke / fill color of an SF Symbol icon in SwiftUI.

I have tried .background(Color.red) but that just changes the background of the whole icon (no change is applied to the actual icon itself) as implied. I also tried .foregroundColor(Color.red)which does nothing to the icon.

contents of content view are as follows:

var body: some View {
    Image(systemName: "person.circle").foregroundColor(.red)
}

Body:
One trick I figured out that works nicely for iOS 14 is to use the fill and non fill versions together to get two colors regardless of whether 14 or 15:

ZStack {
    Image(systemName: "person.circle")
        .foregroundColor(.white)
    Image(systemName: "person.circle.fill")
        .foregroundColor(.yellow)
}


问:
Java 8 Mvn Project doesn't work on Java 17
I have a Maven Project which was written using Java 8. If I try to run it in Intelliji using SDK 17 everything is red and it doesn't work at all. If I use Java 8 however it works. Why doesn't it work with SDK 17? It should be compatible.
Errors in my Code</p>

答:
Those errors are JavaFX related, not Java in general. JavaFX has never been a standard part of Java SE.

You need to either:

Add an implementation of JavaFX to your project. Add dependencies to your project for the OpenJFX library. That code base for that implementation is housed as a subproject on the OpenJDK site, and is co-led by Gluon and Oracle.

Use a Java implementation that includes the OpenJFX library. At least two vendors offer an edition of their JDK product with OpenJFX: ZuluFX by Azul Systems, and LibericaFX by BellSoft.


问:
Replace Numeric Columns of dataset from other columns
I have a dataset that has many columns, I want to extract the numeric columns and replace with the mean of the columns and then these modified columns replacing the ones in the original dataframe.

```<code>df1 = df.select_dtypes(include = ["number"]).apply(lambda x: x.fillna(x.mean()),axis=0)
df.loc[df.select_dtypes(include = ["number"])] = df1
</code>```

I managed to extract the numeric columns but I couldn't replace them, the idea is not to manually indicate which are those numeric columns.

答:
It's probably easier to assign a new/changed DataFrame. This will only change the columns you altered.

```<code>new_df = df.assign(**df.select_dtypes('number').apply(lambda x: x.fillna(x.mean())))
</code>```

If you want to preserve the original DataFrame, you can do it in steps:

```<code>cols = df.select_dtypes('number').columns
df[cols] = df[cols].apply(lambda x: x.fillna(x.mean()))
</code>```

Body:
I have a dataset that has many columns, I want to extract the numeric columns and replace with the mean of the columns and then these modified columns replacing the ones in the original dataframe.

df1 = df.select_dtypes(include = ["number"]).apply(lambda x: x.fillna(x.mean()),axis=0)
df.loc[df.select_dtypes(include = ["number"])] = df1

I managed to extract the numeric columns but I couldn't replace them, the idea is not to manually indicate which are those numeric columns.

Body:
It's probably easier to assign a new/changed DataFrame. This will only change the columns you altered.

new_df = df.assign(**df.select_dtypes('number').apply(lambda x: x.fillna(x.mean())))

If you want to preserve the original DataFrame, you can do it in steps:

cols = df.select_dtypes('number').columns
df[cols] = df[cols].apply(lambda x: x.fillna(x.mean()))


问:
in Bigquery: Classify the weather for a day when two (or more) weather types (fx sun and rain) occurres on the same day
I have a table with weather data as below. I wish to classify days as being either:

"sunny" if the value is >0 (hours of sun),

"rainy" if the value is >0 (mm precipitation)

or both ("sun and rain") if there is >0 hours and 0> mm rain on the same day

date
element
value
unit

29.11.2021
precipitation
2,4
mm

29.11.2021
sun
0,2
hours

30.11.2021
precipitation
3,7
mm

30.11.2021
sun
4
hours

31.11.2021
sun
2
hours

31.11.2021
precipitation
0
mm

I've used CASE for classifying a day witn ONLY sun or ONLY rain like this:

```<code>case when element= 'sun' and value>0 then "sun"
     when element= 'precipitation' and value>0 then "rain"
</code>```

However, if a day has BOTH rain and sun I am not sure how to achieve this. I tried:

```<code> case when element= 'precipitation' and value>0
       and element= 'sun' and value>0
 then "rain/sun" end as weather
</code>```

but this will not give me any result, probably because i need to somehow partition by date (?). The outcome Im looking for is something like a classic weather report:

date
element

29.11.2021
sun and rain

30.11.2021
sun and rain

31.11.2021
sun

答:
You may change precipitation to say rain as you please, but here is the general idea of a solution using string_agg

```<code>with cte as

(select date, element
 from t
 group by date, element
 having sum(value) > 0)

select date, string_agg(element,' and ' order by element) as element
from cte
group by date;
</code>```

Body:
I have a table with weather data as below. I wish to classify days as being either:

"sunny" if the value is >0 (hours of sun),

"rainy" if the value is >0 (mm precipitation)

or both ("sun and rain") if there is >0 hours and 0> mm rain on the same day

date
element
value
unit

29.11.2021
precipitation
2,4
mm

29.11.2021
sun
0,2
hours

30.11.2021
precipitation
3,7
mm

30.11.2021
sun
4
hours

31.11.2021
sun
2
hours

31.11.2021
precipitation
0
mm

I've used CASE for classifying a day witn ONLY sun or ONLY rain like this:

case when element= 'sun' and value>0 then "sun"
     when element= 'precipitation' and value>0 then "rain"

However, if a day has BOTH rain and sun I am not sure how to achieve this. I tried:

 case when element= 'precipitation' and value>0
       and element= 'sun' and value>0
 then "rain/sun" end as weather

but this will not give me any result, probably because i need to somehow partition by date (?). The outcome Im looking for is something like a classic weather report:

date
element

29.11.2021
sun and rain

30.11.2021
sun and rain

31.11.2021
sun

Body:
You may change precipitation to say rain as you please, but here is the general idea of a solution using string_agg

with cte as

(select date, element
 from t
 group by date, element
 having sum(value) > 0)

select date, string_agg(element,' and ' order by element) as element
from cte
group by date;


问:
Inno Setup throws exception "The process cannot access the file because it is being used by another process." on repeated use of ExtractTemporaryFile
I have an Inno Setup script with silent install options that have procedure that uses ExtractTemporaryFile:

procedure SetAccessPermission(folderName : string; groupName : string );
Var
  output : string;
  ErrorCode : integer;
begin
  ExtractTemporaryFile('EnvironmentAdjustment.exe');
  ExtractTemporaryFile('EnvironmentAdjustment.exe.config');
  ExtractTemporaryFile('Win32Security.dll');
  ShellExec('', ExpandConstant('{tmp}\EnvironmentAdjustment.exe'),
    ExpandConstant('"' + folderName + '" "' + groupName + '" '),
    ExpandConstant('{tmp}'), SW_HIDE, ewWaitUntilTerminated, ErrorCode);
  LoadStringFromFile(ExpandConstant(resultPath + '\folderaccess.txt'), output);
  Log('Result: ' + SysErrorMessage(ErrorCode) + ')');
end;
```
<p>That procedure is used several times in the code:</p>
<pre class="lang-pascal prettyprint-override"><code>SetAccessPermission('{app}\WebSite\imagescache', groupForSettingReadWritePermisions);
SetAccessPermission('{app}\WebSite\formscache', groupForSettingReadWritePermisions);
</code>```

But on the second use exception is thrown:

The process cannot access the file because it is being used by another process.

I've added some logs and found that it definitely fails on the first ExtractTemporaryFile executing. No any existing processes don't use that file, so I think that's something inside in Inno Setup. I wasted too much time to understand what goes wrong, but I have not idea still. Also, this issue occurs only on single machine with Windows Server 2012 R2 (and even there such problem started only some time ago), script is executed properly on all others, so that adds more questions.

答:
As @Andrew commented, the file is most likely locked by some antivirus or something similar. Use Process Explorer/Process Monitor to check, what process is using the file.

Anyway, it's waste to extract the files multiple times. Extract them on the first use only:

if not FileExists(ExpandConstant('{tmp}\EnvironmentAdjustment.exe')) then
begin
  ExtractTemporaryFile('EnvironmentAdjustment.exe');
  ExtractTemporaryFile('EnvironmentAdjustment.exe.config');
  ExtractTemporaryFile('Win32Security.dll');
end;
```

Or do what Inno Setup does: Retry the extraction after small pause, when it fails.

Body:
I have an Inno Setup script with silent install options that have procedure that uses ExtractTemporaryFile:

procedure SetAccessPermission(folderName : string; groupName : string );
Var
  output : string;
  ErrorCode : integer;
begin
  ExtractTemporaryFile('EnvironmentAdjustment.exe');
  ExtractTemporaryFile('EnvironmentAdjustment.exe.config');
  ExtractTemporaryFile('Win32Security.dll');
  ShellExec('', ExpandConstant('{tmp}\EnvironmentAdjustment.exe'),
    ExpandConstant('"' + folderName + '" "' + groupName + '" '),
    ExpandConstant('{tmp}'), SW_HIDE, ewWaitUntilTerminated, ErrorCode);
  LoadStringFromFile(ExpandConstant(resultPath + '\folderaccess.txt'), output);
  Log('Result: ' + SysErrorMessage(ErrorCode) + ')');
end;

That procedure is used several times in the code:

SetAccessPermission('{app}\WebSite\imagescache', groupForSettingReadWritePermisions);
SetAccessPermission('{app}\WebSite\formscache', groupForSettingReadWritePermisions);

But on the second use exception is thrown:

The process cannot access the file because it is being used by another process.

I've added some logs and found that it definitely fails on the first ExtractTemporaryFile executing. No any existing processes don't use that file, so I think that's something inside in Inno Setup. I wasted too much time to understand what goes wrong, but I have not idea still. Also, this issue occurs only on single machine with Windows Server 2012 R2 (and even there such problem started only some time ago), script is executed properly on all others, so that adds more questions.

Body:
As @Andrew commented, the file is most likely locked by some antivirus or something similar. Use Process Explorer/Process Monitor to check, what process is using the file.

Anyway, it's waste to extract the files multiple times. Extract them on the first use only:

if not FileExists(ExpandConstant('{tmp}\EnvironmentAdjustment.exe')) then
begin
  ExtractTemporaryFile('EnvironmentAdjustment.exe');
  ExtractTemporaryFile('EnvironmentAdjustment.exe.config');
  ExtractTemporaryFile('Win32Security.dll');
end;

Or do what Inno Setup does: Retry the extraction after small pause, when it fails.


问:
Is there a way to rename the categories of the legend?
I'm looking for a way to change the name of the legend of the graph without changing the data?

答:
Unfortunately, you can't do this directly in the format page. You'll either have to create another column that contains a user-friendly name for your data. Then use that as the legend.

Ex.

```<code>Legend = SWITCH(
    TRUE,
    Table[Lag Days] <= 3, "Low",
    Table[Lag Days] <= 7, "Medium",
    Table[Lag Days] <= 30, "High",
    "Extreme"
)
</code>```

Or maybe use grouping to create the legend names that you would like.

Body:
Unfortunately, you can't do this directly in the format page. You'll either have to create another column that contains a user-friendly name for your data. Then use that as the legend.

Ex.

Legend = SWITCH(
    TRUE,
    Table[Lag Days] <= 3, "Low",
    Table[Lag Days] <= 7, "Medium",
    Table[Lag Days] <= 30, "High",
    "Extreme"
)

Or maybe use grouping to create the legend names that you would like.


问:
Multiprocessing of for nested loops
I am trying to excute the following code, to save the list data_set_N at the end.

```<code>import re
data_set_N=[]
for i_1 in list(range(10))+list("+-"):
    for i_2 in list(range(10))+list("+-*/")+["=="]:
        for i_3 in list(range(10))+list("+-*/")+["=="]:
            for i_4 in list(range(10))+list("+-*/")+["=="]:
                for i_5 in list(range(10))+list("+-*/")+["=="]:
                    for i_6 in list(range(10))+list("+-*/")+["=="]:
                        for i_7 in list(range(10))+list("+-*/")+["=="]:
                            for i_8 in list(range(10)):
                                try :
                                    value= str(i_1)+str(i_2)+str(i_3)+str(i_4)+str(i_5)+str(i_6)+str(i_7)+str(i_8)
                                    valuev=re.sub(r'\b0+(?!\b)', '', value)
                                    evaluation = eval(valuev)
                                    if type(evaluation) == type(True) and evaluation and "//" not in value:
                                        data_set_N.append(value)

                                except:
                                    continue
print(len(data_set_N))
</code>```

The problem is that it will take more than 50 hours, for the the first i_1 it took 4.5 hours.
To get data_set_N faster I wanted to use multiprocessing. The idea was to use something like this :

```<code>from multiprocessing import Process, Manager
import itertools
import re

def add_value(data_set_N,paramlist):
    #I am not sure if this function is well defined
    try
        i_1,i_2,i_3,i_4 = paramlist[0],paramlist[1],paramlist[2],paramlist[3]
        i_5,i_6,i_7,i_8 = paramlist[4],paramlist[5],paramlist[6],paramlist[7]
        value = str(i_1)+str(i_2)+str(i_3)+str(i_4)+str(i_5)+str(i_6)+str(i_7)+str(i_8)
        valuev =re.sub(r'\b0+(?!\b)', '', value)
        evaluation = eval(valuev)
        if type(evaluation) == type(True) and evaluation and "//" not in value:
            data_set_N.append(value)

    except:
        return

data_set_N = []
#Generate values for each parameter
I_1 = list(range(10))+list("+-")
I_2 = list(range(10))+list("+-*/")+["=="]
I_3 = list(range(10))+list("+-*/")+["=="]
I_4 = list(range(10))+list("+-*/")+["=="]
I_5 = list(range(10))+list("+-*/")+["=="]
I_6 = list(range(10))+list("+-*/")+["=="]
I_7 = list(range(10))+list("+-*/")+["=="]
I_8 = list(range(10))
paramlist = list(itertools.product(I_1,I_2,I_3,I_4,I_5,I_6,I_7,I_8))

if __name__ == "__main__":
    with Manager() as manager:
        data_set_N = manager.list()  # <-- can be shared between processes.
        processes = []

        for i in range(10): #os.cpu_count() - 2 =10 , this range can be changed
            p = Process(target=add_value, args=(data_set_N,paramlist))  # Passing the list
            p.start()
            processes.append(p)

        for p in processes:
            pool.close()
            pool.join()

        data_set_N = list(data_set_N) #the final list

</code>```

The problem here is with paramlist that causes a MemoryError (because its size is 12x15^6x10).

Is there a way to use multiprocessing to execute the code faster (around 10 hours), while avoiding memory problems?

答:
What I would do is:

Use a multiprocessing pool.

Keep your basic code as is except with 7 nested loops (the seven inner loops) and each submitted task is processing a value from the i_1 list.

Move the inexpensive '//' in value check immediately after value is evaluated and possibly avoid doing a needless regular expression substitution and call to the eval function.

This will use up to 12 cores (the length of the i_1 list) if your computer has them. If your computer has 12 cores and they are all physical cores and nothing else is running, I would expect the execution time to be reduced by a factor of 12. If you have 6 physical and 6 logical cores and other processes are running, then the execution time will clearly not be reduced by a factor of 12 (I cannot predict by how much). But this is the simplest way of solving your memory issues.

If you had many more cores than 12, then you could define process_value to have the 6 inner most loops and use method starmap (each element of the iterable will be a tuple and process_value will now have two arguments in addition to the managed list, i_1 and i_2) with the iterable argument being the product of i_1 list and i_2 list.

from multiprocessing import Pool, Manager, cpu_count
from functools import partial
import re

def process_value(data_set_N, i_1):
    for i_2 in list(range(10))+list("+-*/")+["=="]:
        for i_3 in list(range(10))+list("+-*/")+["=="]:
            for i_4 in list(range(10))+list("+-*/")+["=="]:
                for i_5 in list(range(10))+list("+-*/")+["=="]:
                    for i_6 in list(range(10))+list("+-*/")+["=="]:
                        for i_7 in list(range(10))+list("+-*/")+["=="]:
                            for i_8 in list(range(10)):
                                try:
                                    value = str(i_1)+str(i_2)+str(i_3)+str(i_4)+str(i_5)+str(i_6)+str(i_7)+str(i_8)
                                    if '//' in value:
                                        continue
                                    valuev = re.sub(r'\b0+(?!\b)', '', value)
                                    evaluation = eval(valuev)
                                    if type(evaluation) == type(True) and evaluation:
                                        data_set_N.append(value)
                                except:
                                    continue

if __name__ == '__main__':
    with Manager() as manager:
        data_set_N = manager.list()
        # The iterable is the i_1 list:
        i_1_list = list(range(10))+list("+-")
        POOL_SIZE = min(cpu_count(), len(i_1_list))
        pool = Pool(POOL_SIZE)
        pool.map(partial(process_value, data_set_N), i_1_list)
        pool.close()
        pool.join()
        print(len(data_set_N))
```

Title: Multiprocessing of for nested loops

Body:
I am trying to excute the following code, to save the list data_set_N at the end.

import re
data_set_N=[]
for i_1 in list(range(10))+list("+-"):
    for i_2 in list(range(10))+list("+-*/")+["=="]:
        for i_3 in list(range(10))+list("+-*/")+["=="]:
            for i_4 in list(range(10))+list("+-*/")+["=="]:
                for i_5 in list(range(10))+list("+-*/")+["=="]:
                    for i_6 in list(range(10))+list("+-*/")+["=="]:
                        for i_7 in list(range(10))+list("+-*/")+["=="]:
                            for i_8 in list(range(10)):
                                try :
                                    value= str(i_1)+str(i_2)+str(i_3)+str(i_4)+str(i_5)+str(i_6)+str(i_7)+str(i_8)
                                    valuev=re.sub(r'\b0+(?!\b)', '', value)
                                    evaluation = eval(valuev)
                                    if type(evaluation) == type(True) and evaluation and "//" not in value:
                                        data_set_N.append(value)

                                except:
                                    continue
print(len(data_set_N))

The problem is that it will take more than 50 hours, for the the first i_1 it took 4.5 hours.
To get data_set_N faster I wanted to use multiprocessing. The idea was to use something like this :

from multiprocessing import Process, Manager
import itertools
import re

def add_value(data_set_N,paramlist):
    #I am not sure if this function is well defined
    try
        i_1,i_2,i_3,i_4 = paramlist[0],paramlist[1],paramlist[2],paramlist[3]
        i_5,i_6,i_7,i_8 = paramlist[4],paramlist[5],paramlist[6],paramlist[7]
        value = str(i_1)+str(i_2)+str(i_3)+str(i_4)+str(i_5)+str(i_6)+str(i_7)+str(i_8)
        valuev =re.sub(r'\b0+(?!\b)', '', value)
        evaluation = eval(valuev)
        if type(evaluation) == type(True) and evaluation and "//" not in value:
            data_set_N.append(value)

    except:
        return

data_set_N = []
#Generate values for each parameter
I_1 = list(range(10))+list("+-")
I_2 = list(range(10))+list("+-*/")+["=="]
I_3 = list(range(10))+list("+-*/")+["=="]
I_4 = list(range(10))+list("+-*/")+["=="]
I_5 = list(range(10))+list("+-*/")+["=="]
I_6 = list(range(10))+list("+-*/")+["=="]
I_7 = list(range(10))+list("+-*/")+["=="]
I_8 = list(range(10))
paramlist = list(itertools.product(I_1,I_2,I_3,I_4,I_5,I_6,I_7,I_8))

if __name__ == "__main__":
    with Manager() as manager:
        data_set_N = manager.list()  # <-- can be shared between processes.
        processes = []

        for i in range(10): #os.cpu_count() - 2 =10 , this range can be changed
            p = Process(target=add_value, args=(data_set_N,paramlist))  # Passing the list
            p.start()
            processes.append(p)

        for p in processes:
            pool.close()
            pool.join()

        data_set_N = list(data_set_N) #the final list

The problem here is with paramlist that causes a MemoryError (because its size is 12x15^6x10).

Is there a way to use multiprocessing to execute the code faster (around 10 hours), while avoiding memory problems?