问:
write a program which turns a n-dimensional array or list with maximum n number of list nested to a single dimension or flat list
How to convert a list like this :

[[1,[2,["s",2],3]],[1,2,3,4,5,6],532, "Potato", [23, [[[1,[4,[2,[]],[0],[0],  [0]]], 234, 1222], "22More"]]]

to

[1, 2, 's', 2, 3, 1, 2, 3, 4, 5, 6, 532, 'Potato', 23, 1, 4, 2, 0, 0, 0, 234,    1222, '22More']

I have tried using a for loop and then unpacking them using that but it didn't work out. Now I thought I could make variables of the element in the master list and then try unpacking them but it is not happing the way I want

Please do help

Body:
you can use a recursive function to do that:

>>> list1 = [[1, [2, ['s', 2], 3]], [1, 2, 3, 4, 5, 6], 532, 'Potato', [23, [[[1, [4, [2, []], [0], [0], [0]]], 234, 1222], '22More']]]
>>> def listelements(mylist):
...     rslt = []
...     for value in mylist:
...             if isinstance(value,list):
...                     rslt.extend(_listconc(value))
...             else:
...                     rslt.append(value)
...     return rslt
...
>>> listelements(list1)
[1, 2, 's', 2, 3, 1, 2, 3, 4, 5, 6, 532, 'Potato', 23, 1, 4, 2, 0, 0, 0, 234, 1222, '22More']


来源: stackexchange

问:
is it possible to use a svg as a placeholder for image in next js?
I'm using next Js Image tag (next/image). Is it possible to import a svg and use it as a placeholder until the image finish loading?

I tried to create a use State and it to true on the "onLoad" of the tag as I would do in a img tag, but that doesn't work. The fallback image that should show before the image load never shows, it's like the images are always loaded, even thought they didn't appear on html yet

Here the code I tried:

```<code>const [hasImageLoaded, setHasImageLoaded] = useState(false);

  function handleImageLoaded(): void {
    setHasImageLoaded(true);
  }

const displayImgStyle = {
  display: hasImageLoaded ? undefined : 'none',
};

const loadingImgStyle = {
  display: hasImageLoaded ? 'none' : undefined,
};

return (
<>
  <div style={displayImgStyle}>
    <Image
      width={216}
      height={216}
      className={styles.pokemon}
      src={image}
      alt={name}
      title={name}
      onLoad={handleImageLoaded}
    />
  </div>

  <MySvg style={loadingImgStyle} />
</>
)

</code>```

答:
Maybe it can help you:</p>
```<code>const shimmer = (w: number, h: number) => `
  <svg width="${w}" height="${h}" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
    <defs>
      <linearGradient id="g">
        <stop stop-color="#333" offset="20%" />
        <stop stop-color="#222" offset="50%" />
        <stop stop-color="#333" offset="70%" />
      </linearGradient>
    </defs>
    <rect width="${w}" height="${h}" fill="#333" />
    <rect id="r" width="${w}" height="${h}" fill="url(#g)" />
    <animate xlink:href="#r" attributeName="x" from="-${w}" to="${w}" dur="1s" repeatCount="indefinite"  />
  </svg>`

const toBase64 = (str: string) =>
  typeof window === 'undefined'
    ? Buffer.from(str).toString('base64')
    : window.btoa(str)

<Image
   width={32}
   height={32}
   alt={Img2}
   placeholder="blur"
   blurDataURL={`data:image/svg+xml;base64,${toBase64(shimmer(32, 32))}`}
   src={`IMG_LINK`}
/>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm using next Js Image tag (next/image). Is it possible to import a svg and use it as a placeholder until the image finish loading?

I tried to create a use State and it to true on the "onLoad" of the tag as I would do in a img tag, but that doesn't work. The fallback image that should show before the image load never shows, it's like the images are always loaded, even thought they didn't appear on html yet

Here the code I tried:

const [hasImageLoaded, setHasImageLoaded] = useState(false);

  function handleImageLoaded(): void {
    setHasImageLoaded(true);
  }

const displayImgStyle = {
  display: hasImageLoaded ? undefined : 'none',
};

const loadingImgStyle = {
  display: hasImageLoaded ? 'none' : undefined,
};

return (
<>

    <Image
      width={216}
      height={216}
      className={styles.pokemon}
      src={image}
      alt={name}
      title={name}
      onLoad={handleImageLoaded}
    />

  <MySvg style={loadingImgStyle} />
</>
)

Body:
Maybe it can help you:

const shimmer = (w: number, h: number) => `
  <svg width="${w}" height="${h}" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
    <defs>
      <linearGradient id="g">
        <stop stop-color="#333" offset="20%" />
        <stop stop-color="#222" offset="50%" />
        <stop stop-color="#333" offset="70%" />
      </linearGradient>
    </defs>
    <rect width="${w}" height="${h}" fill="#333" />
    <rect id="r" width="${w}" height="${h}" fill="url(#g)" />
    <animate xlink:href="#r" attributeName="x" from="-${w}" to="${w}" dur="1s" repeatCount="indefinite"  />
  </svg>`

const toBase64 = (str: string) =>
  typeof window === 'undefined'
    ? Buffer.from(str).toString('base64')
    : window.btoa(str)

<Image
   width={32}
   height={32}
   alt={Img2}
   placeholder="blur"
   blurDataURL={`data:image/svg+xml;base64,${toBase64(shimmer(32, 32))}`}
   src={`IMG_LINK`}
/>


问:
The page div placed at the bottom with with fixed position hides other contents on smaller screen size?
I have a page where I would like to display a table and a panel that stays at the bottom of the page. I have looked up some answers but none of them works perfectly yet. not sure what is the issue. So the way my current code is to set the parent of the element to be placed at the bottom of the page to relative and set the child content to fixed position with bottom zero. this way it sets the div at the bottom of the page but the problem is that when sizing the page vertically on a smaller size the bottom div hides other page content. How to fix this I am using old bootstrap 3.7.

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

```

答:
A snippet with extra padding at the bottom:

.pt-4 {
  padding-top: 16px;
}

.pb-20 {
  padding-bottom: 80px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

<div class="container-fluid pt-4 pb-20">
  <div class="row">
    <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12">
      <div class="table-responsive">
        <table id="" class="table table-striped table-hover table-bordered">
          <thead>
            <tr>
              <th></th>
              <th></th>
              <th></th>
              <th></th>
              <th></th>
              <th></th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
            </tr>
            <tr>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
            </tr>
            <tr>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
            </tr>
            <tr>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
            </tr>
            <tr>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
            </tr>
            <tr>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
            </tr>
            <tr>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
            </tr>
            <tr>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
            </tr>
            <tr>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
            </tr>
            <tr>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
            </tr>
            <tr>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
            </tr>
            <tr>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
            </tr>
            <tr>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
            </tr>
            <tr>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
            </tr>
            <tr>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
            </tr>
            <tr>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
            </tr>
            <tr>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
            </tr>
            <tr>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
            </tr>
            <tr>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
            </tr>
            <tr>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
            </tr>
            <tr>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
    <div class="" style="position:relative;">
      <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12" style="position:fixed; bottom:0;">
        <div class="panel panel-primary">
          <div class="panel-heading">
            <h3 class="panel-title">
            </h3>
          </div>
          <div class="panel-body">
            <div class="row">
              <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12">
                <p></p>
                <p></p>
                <p></p>
                <p></p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div></code>```

Body:
A snippet with extra padding at the bottom:

.pt-4 {
  padding-top: 16px;
}

.pb-20 {
  padding-bottom: 80px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

<div class="container-fluid pt-4 pb-20">
  <div class="row">
    <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12">
      <div class="table-responsive">
        <table id="" class="table table-striped table-hover table-bordered">
          <thead>
            <tr>
              <th></th>
              <th></th>
              <th></th>
              <th></th>
              <th></th>
              <th></th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
            </tr>
            <tr>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
            </tr>
            <tr>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
            </tr>
            <tr>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
            </tr>
            <tr>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
            </tr>
            <tr>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
            </tr>
            <tr>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
            </tr>
            <tr>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
            </tr>
            <tr>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
            </tr>
            <tr>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
            </tr>
            <tr>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
            </tr>
            <tr>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
            </tr>
            <tr>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
            </tr>
            <tr>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
            </tr>
            <tr>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
            </tr>
            <tr>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
            </tr>
            <tr>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
            </tr>
            <tr>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
            </tr>
            <tr>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
            </tr>
            <tr>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
            </tr>
            <tr>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
    <div class="" style="position:relative;">
      <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12" style="position:fixed; bottom:0;">
        <div class="panel panel-primary">
          <div class="panel-heading">
            <h3 class="panel-title">
            </h3>
          </div>
          <div class="panel-body">
            <div class="row">
              <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12">
                <p></p>
                <p></p>
                <p></p>
                <p></p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>


问:
Adding image to the SectionHeaderItem in Google Forms Apps script
I've been using Google Apps Scripts to generate Google Forms and sent be email.
However, i've been trying to add a logo to the header section however there is no function or a possible way that I can find online of adding it.

I can add images using ImageItem(), however, this does not add to the header section and stays as a single item at the start of the form.

Is there anyway of adding images to the header section using google apps script or thats only possible using the customizable UI made for designing google forms?

答:
Assuming that for "header section" you mean the form header, the Forms Service doesn't include any class for the form header, so the only way to customize it is by using the Google Forms editor. By the other hand SectionHeaderItem, doesn't allow to insert images, only a title and a description.

Reference

https://developers.google.com/apps-script/reference/forms


问:
Pandas: How to merge all rows into a single row?
I have the following dataframe:

```<code>  text
1 "abc"
2 "def"
3 "ghi"
4 "jkl"
</code>```

How can I merge these rows into a dataframe with a single row like the following one?

```<code>  text
1 "abc, def, ghi, jkl"
</code>```

Comma separation is not a must but all the values should be in a single row. The values can also be stored in a comma separated list of strings.

答:
Try this:

```<code>df = pd.DataFrame({'text': [', '.join(df['text'].str.strip('"').tolist())]})
</code>```

Output:

```<code>>>> df
                 text
0  abc, def, ghi, jkl
</code>```

Body:
I have the following dataframe:

  text
1 "abc"
2 "def"
3 "ghi"
4 "jkl"

How can I merge these rows into a dataframe with a single row like the following one?

  text
1 "abc, def, ghi, jkl"

Comma separation is not a must but all the values should be in a single row. The values can also be stored in a comma separated list of strings.

Body:
Try this:

df = pd.DataFrame({'text': [', '.join(df['text'].str.strip('"').tolist())]})

Output:

>>> df
                 text
0  abc, def, ghi, jkl


问:
What is the best method for Backend and Frontend communication (incl. SessionID)?
I have a small project running and I question myself, how to do it. I host on two server. One is for Backend and one for Frontend. The Backend-Server is running on NodeJS and as DB MongoDB and I already have my own small API to communicate with it. On the Frontend-Server I am using React. My Question now: What is the best way to make a SessionID on the Frontend and Send it to the Backend-Server over the Frontend-Server?

For example SessionID3 should get displayed a bike on his site and SessionID2 a car (both informations are stored on the Backend-Server on the DB).

I look forward to any replies, thanks!

答:
Most Jamstack setups have an API server that serves content in the form of json/raw (like Github's developer API)in which Nodejs and JavaScript has a built in feature which allows the quick conversion to a JSON object with references in which you can read about that on MDN.

Diagram of Jamstacking with React & Vue

^ since it is actually the client sending the request and doing most of the work and not the front-end server, you can use universal-cookie to set or get a session ID permanently, parse it into JSON and send with the POST request to the Back-end API. You could also do this with Math.random(min, max) as well of you just want a random string of numbers to be sent.

Axios is asynchronous so you want to use async/await or .then() with it so that it works correctly. You can view the official docs at https://axios-http.com/docs/intro. The value returned by Axios is the response in which you will want to parse the "body" the header returned so it can be used.

Another alternative to get the browser session id (which is erased after the browser is closed) is a module called react-session-hook

In my opinion, for what you are trying to do, adding another server that relays the message is not optimal as that adds another sequential connection that makes things take twice as long as it would otherwise. In other-words, this is not necessary. The only time you do this is if the keys to access the API are sensitive meaning they contain important information and musts be hidden.


问:
Grails 4 how to test if domain class PersistentProperty is an assocation?
In earlier versions of Grails 3 there was a property "GrailsDomainClassProperty.association". I could use this to test whether a property was part of an association.  In Grails 4 how do I use PersistentProperty to find this out?  Is a property a simple type or an association - one-to-one, one-to-many, etc?</p>

答: It looks like the answer is to get the PersistentEntity.associations list and check there as to whether an arbitrary property is in fact an assocation.  There may be a better answer but that is what I'm going with.</p>


问:
notify user when wifi, or 3g 4g network get lost jquery or javascript
we have web site which is optimized for mobile phone. we do qute frequent ajax requestes and some time an event get rigered from a back end.

now the problem is how to properly manage when network connection get lost.

can we create a custom event where it will be triggered when a connection get lost using jquery?

答:
Try this:</p>

```<code>function doIhaveInterWebs(){
  $.ajax({
    url: "test.txt",
    success: function() {return true}
    error: function(){return false}
   });
 }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Try this:

function doIhaveInterWebs(){
  $.ajax({
    url: "test.txt",
    success: function() {return true}
    error: function(){return false}
   });
 }


问:
Using "void" type as a parameterized type in Go generics (version 1.18) or above
Go introduced generics in version 1.18. I just downloaded the latest beta version to test this major new feature.

Consider the code below:

package main

import "fmt"

func Demo1(n int) int {
    return n
}

func Demo2(n int) {
    fmt.Println(n)
}

func Call[T1, T2 any](fn func(T1) T2, param T1) {
    fn(param)
}

func main() {
    // Okay
    Call(Demo1, 1)
    // type func(n int) of Demo2 does not match
    // inferred type func(int) T2 for func(T1) T2
    Call(Demo2, 2)
}

```
<p>The function <code>Call</code> accepts a function <code>fn</code> as a parameter, and calls it with the parameter <code>param</code>. The first call to <code>Call</code> is fine, the inferred type is <code>int</code> for both <code>T1</code> and <code>T2</code>. However, the second call failed to compile.</p>
<p>I know I can always write an adapter to wrap <code>Demo2</code>:</p>
<pre class="lang-golang prettyprint-override"><code>wrapped := func(n int) int {
    Demo2(n)
    return -1
}
Call(wrapped, 2)
</code>```

But that hurts performance and defeat the purpose of my current project.

Do you have any ideas to solve the problem? Or shall I fire a bug report?

Thanks!

Edit 1 (Background):

I am updating a benchmarking library I wrote 6 years ago to use generics. It targets to provide carefully written benchmark functions so that the benchmark results are more consistent than writing custom benchmarks independently.

For example, if a user wants to benchmark his function Sum of signature func(int) int, with the parameter values between 0 and 10, he can write this:

func BenchmarkSum(b *testing.B) {
    butils.BenchmarkFnIntRetInt(b, Sum, butils.UniformDistribution(0, 10))
}
```
<p><code>BenchmarkFnIntRetInt</code> could be used to benchmark other <code>func(int) int</code> functions. The benchmark results would be more consistent than writing a separate routine, say <code>BenchmarkProduct</code> to benchmark the <code>Product</code> function. Since the grounds are the same, the benchmark results would be more consistent when comparing implementations by different authors.</p>
<p>In my library, the function signatures look like this:</p>
<pre class="lang-golang prettyprint-override"><code>func UniformDistribution(min, max int) func() int {
    // ...
}

func BenchmarkFnIntRetInt(
    b *testing.B,
    target func(int) int,
    paramGen func() int,
) {
    // ...
}
</code>```

Since Go has generics now, I could get rid of most of the redundant combinations (a.k.a. overloads, like one for func(int) int, and another for func(int) string, and yet another for func(int) bool), and replace them by generics instead. I hope the users can get rid of the overloads and just write:

func BenchmarkSum(b *testing.B) {
    butils.BenchmarkGeneric(b, Sum, butils.UniformDistribution(0, 10))
}
```

The problem of icza's solution of writing one version for "non-void", and another for "void" is that there are a lot of higher order functions in my library. The number of versions I need to write grows exponentially as the number of function parameters grows.

For example, if I have fn1 and fn2, then 4 versions are needed; If I have fn1, fn2 and fn3, then 8 versions are needed; and so on.

答:
This is not a bug. There is no void type in Go.

Your Call() function requires an argument of function type that must have a result parameter. Demo2() does not have any. It does not qualify for the first argument to Call() no matter what types are used to instantiate the parameterized Call() function.

You can't describe functions with and without result types with a single type, not even with type parameters.

You must use 2 Call() functions, e.g.:

```<code>func Call[T1, T2 any](fn func(T1) T2, param T1) {
    fn(param)
}

func CallNoResult[T any](fn func(T), param T) {
    fn(param)
}
</code>```

And using them (try it on the Go Playground):

```<code>Call(Demo1, 1)
CallNoResult(Demo2, 2)
</code>```

If you need to handle all function types, you should use reflection. Here's the essence of it (type and parameter checks omitted):

```<code>func Call(f interface{}, params ...interface{}) {
    v := reflect.ValueOf(f)

    vparams := make([]reflect.Value, len(params))
    for i, p := range params {
        vparams[i] = reflect.ValueOf(p)
    }
    v.Call(vparams)
}
</code>```

Testing it:

```<code>func Demo1(n int) int {
    fmt.Println("Demo1", n)
    return n
}

func Demo2(n int) {
    fmt.Println("Demo2", n)
}

func main() {
    Call(Demo1, 1)
    Call(Demo2, 2)
}
</code>```

This will output (try it on the Go Playground):

```<code>Demo1 1
Demo2 2
</code>```

Body:
Go introduced generics in version 1.18. I just downloaded the latest beta version to test this major new feature.

Consider the code below:

package main

import "fmt"

func Demo1(n int) int {
    return n
}

func Demo2(n int) {
    fmt.Println(n)
}

func Call[T1, T2 any](fn func(T1) T2, param T1) {
    fn(param)
}

func main() {
    // Okay
    Call(Demo1, 1)
    // type func(n int) of Demo2 does not match
    // inferred type func(int) T2 for func(T1) T2
    Call(Demo2, 2)
}

The function Call accepts a function fn as a parameter, and calls it with the parameter param. The first call to Call is fine, the inferred type is int for both T1 and T2. However, the second call failed to compile.

I know I can always write an adapter to wrap Demo2:

wrapped := func(n int) int {
    Demo2(n)
    return -1
}
Call(wrapped, 2)

But that hurts performance and defeat the purpose of my current project.

Do you have any ideas to solve the problem? Or shall I fire a bug report?

Thanks!

Edit 1 (Background):

I am updating a benchmarking library I wrote 6 years ago to use generics. It targets to provide carefully written benchmark functions so that the benchmark results are more consistent than writing custom benchmarks independently.

For example, if a user wants to benchmark his function Sum of signature func(int) int, with the parameter values between 0 and 10, he can write this:

func BenchmarkSum(b *testing.B) {
    butils.BenchmarkFnIntRetInt(b, Sum, butils.UniformDistribution(0, 10))
}

BenchmarkFnIntRetInt could be used to benchmark other func(int) int functions. The benchmark results would be more consistent than writing a separate routine, say BenchmarkProduct to benchmark the Product function. Since the grounds are the same, the benchmark results would be more consistent when comparing implementations by different authors.

In my library, the function signatures look like this:

func UniformDistribution(min, max int) func() int {
    // ...
}

func BenchmarkFnIntRetInt(
    b *testing.B,
    target func(int) int,
    paramGen func() int,
) {
    // ...
}

Since Go has generics now, I could get rid of most of the redundant combinations (a.k.a. overloads, like one for func(int) int, and another for func(int) string, and yet another for func(int) bool), and replace them by generics instead. I hope the users can get rid of the overloads and just write:

func BenchmarkSum(b *testing.B) {
    butils.BenchmarkGeneric(b, Sum, butils.UniformDistribution(0, 10))
}

The problem of icza's solution of writing one version for "non-void", and another for "void" is that there are a lot of higher order functions in my library. The number of versions I need to write grows exponentially as the number of function parameters grows.

For example, if I have fn1 and fn2, then 4 versions are needed; If I have fn1, fn2 and fn3, then 8 versions are needed; and so on.

Body:
This is not a bug. There is no void type in Go.

Your Call() function requires an argument of function type that must have a result parameter. Demo2() does not have any. It does not qualify for the first argument to Call() no matter what types are used to instantiate the parameterized Call() function.

You can't describe functions with and without result types with a single type, not even with type parameters.

You must use 2 Call() functions, e.g.:

func Call[T1, T2 any](fn func(T1) T2, param T1) {
    fn(param)
}

func CallNoResult[T any](fn func(T), param T) {
    fn(param)
}

And using them (try it on the Go Playground):

Call(Demo1, 1)
CallNoResult(Demo2, 2)

If you need to handle all function types, you should use reflection. Here's the essence of it (type and parameter checks omitted):

func Call(f interface{}, params ...interface{}) {
    v := reflect.ValueOf(f)

    vparams := make([]reflect.Value, len(params))
    for i, p := range params {
        vparams[i] = reflect.ValueOf(p)
    }
    v.Call(vparams)
}

Testing it:

func Demo1(n int) int {
    fmt.Println("Demo1", n)
    return n
}

func Demo2(n int) {
    fmt.Println("Demo2", n)
}

func main() {
    Call(Demo1, 1)
    Call(Demo2, 2)
}

This will output (try it on the Go Playground):

Demo1 1
Demo2 2


问:
How label to the data (not the axes) of the plot of a confusion matrix that displays True Positive, False Positive, False Negative and True Negative
I am trying to label the plot of my confusion matrix. The first image below is what my plot currently shows. The subsequent image is what I want to emulate. Here are the features I want to add in order of importance.

Need to have the data labeled like TP = 374  etc.

Can I set background color of xlabels and ylabels?

Can I specify the face colors since there are only 4 quadrants?

答:
You can use seaborn's heatmap with explicit annotations. The colors are defined by the data values in combination with the colormap.

import matplotlib.pyplot as plt
import seaborn as sns

cm = [[327, 237], [289, 200]]
sns.set(font_scale=3)
plt.figure(figsize=(7, 7))
ax = sns.heatmap(data=[[1, 0], [0, 1]], cmap=sns.color_palette(['tomato', 'lightgreen'], as_cmap=True),
                 annot=[[f"TP={cm[0][0]:.0f}", f"FP={cm[0][1]:.0f}"], [f"FN={cm[1][0]:.0f}", f"TN={cm[1][1]:.0f}"]],
                 fmt='', annot_kws={'fontsize': 30}, cbar=False, square=True)

ax.set_xlabel('Actual Values')
ax.set_ylabel('Predicted')
ax.tick_params(length=0, labeltop=True, labelbottom=False)
ax.xaxis.set_label_position('top')
ax.set_xticklabels(['Positive', 'Negative'])
ax.set_yticklabels(['Positive', 'Negative'], rotation=90, va='center')
ax.add_patch(plt.Rectangle((0, 1), 1, 0.1, color='yellow', clip_on=False, zorder=0, transform=ax.transAxes))
ax.add_patch(plt.Rectangle((0, 0), -0.1, 1, color='yellow', clip_on=False, zorder=0, transform=ax.transAxes))
plt.tight_layout()
plt.show()
```


问:
How to prevent Keycloak from displaying the password in body?
I have an Angular app that is redirected to Keycloak login page. After the user login I check the requests that have been done, and there is one similar to:

```<code>https://localhost:8443/auth/realms/XXX/login-actions/authenticate?session_code=XXX&execution=XXX&client_id=XXX&tab_id=XXX
</code>```

In this request I can see in the body the username and the password the user sent:

```<code>username=my_user
password=my_password
credentialId=""
</code>```

This is not encrypted and I can see it easily on the browser. Of course this is unsafe, so I would like to know. How can I prevent this behavior?

答:
It's safe to send password in your body.

You can test it on stackOverflow himself which send you login/password in clear and use SSL certificate.

You send your password one time and use token after that.

SSL certificate is a solution if you want to prevent MIM.

Body:
I have an Angular app that is redirected to Keycloak login page. After the user login I check the requests that have been done, and there is one similar to:

https://localhost:8443/auth/realms/XXX/login-actions/authenticate?session_code=XXX&execution=XXX&client_id=XXX&tab_id=XXX

In this request I can see in the body the username and the password the user sent:

username=my_user
password=my_password
credentialId=""

This is not encrypted and I can see it easily on the browser. Of course this is unsafe, so I would like to know. How can I prevent this behavior?


问:
bash execute functions based on certain word in arguments
i have the following bash script contains multiple functions

```<code>#!/usr/bin/bash

#checks if the arguments is directory and extract the domain name from it
if [[ -d "$1" ]]; then
    domain=$(echo "$1" | grep -iEo '[[:alnum:]-]+\.[a-z]+')
    WORKING_DIR="$1"
else
    domain="$1"
    echo "it is domain name"
fi

example_fun1(){
    ping -c 4 $domain
}

example_fun2(){
    nslookup $domain
}

for x in "$@" ;do
    example_fun1 $x
    example_fun2 $x
done
</code>```

and run as following

```<code>./script.sh ./pathtofolder/example.com/ ./pathtofolder/test.com/
</code>```

Or

```<code>./script.sh example.com test.com
</code>```

and working probably BUT i need to add more feature which is check if certain word based in arguments like fun1 it will execute function example_fun1 only

desired execution

```<code>./script.sh fun1 ./pathtofolder/example.com/ ./pathtofolder/test.com/
</code>```

OR

```<code>./script.sh fun1 example.com test.com
</code>```

Thanks

答:
Try the following

```<code>#!/usr/bin/bash

function=""
if [[ $( echo $1 | grep fun1 ) ]]
then
     function="example_fun1"
     shift
elif [[ $( echo $1 | grep fun2 ) ]]
then
     function="example_fun2"
     shift
fi

#checks if the arguments is directory and extract the domain name from it

example_fun1(){
    ping -c 4 $domain
}

example_fun2(){
    nslookup $domain
}

if [[ "$function" != "" ]]
then
        for input in "$@"; do
            if [[ -d "$1" ]]; then
                domain=$(echo "$1" | grep -iEo '[[:alnum:]-]+\.[a-z]+')
                WORKING_DIR="$1"
            else
                domain="$1"
                echo "it is domain name"
            fi
            "$function"
            shift
        done
else
        for input in "$@"; do
            if [[ -d "$1" ]]; then
                domain=$(echo "$1" | grep -iEo '[[:alnum:]-]+\.[a-z]+')
                WORKING_DIR="$1"
            else
                domain="$1"
                echo "it is domain name"
            fi
             example_fun1
             example_fun2
             shift
        done
fi
</code>```

This way you can pass fun1 and execute only  fun1
Or if you don't pass any of these for example both of them will be executed

Body:
i have the following bash script contains multiple functions

#!/usr/bin/bash

#checks if the arguments is directory and extract the domain name from it
if [[ -d "$1" ]]; then
    domain=$(echo "$1" | grep -iEo '[[:alnum:]-]+\.[a-z]+')
    WORKING_DIR="$1"
else
    domain="$1"
    echo "it is domain name"
fi

example_fun1(){
    ping -c 4 $domain
}

example_fun2(){
    nslookup $domain
}

for x in "$@" ;do
    example_fun1 $x
    example_fun2 $x
done

and run as following

./script.sh ./pathtofolder/example.com/ ./pathtofolder/test.com/

Or

./script.sh example.com test.com

and working probably BUT i need to add more feature which is check if certain word based in arguments like fun1 it will execute function example_fun1 only

desired execution

./script.sh fun1 ./pathtofolder/example.com/ ./pathtofolder/test.com/

OR

./script.sh fun1 example.com test.com

Thanks

Body:
Try the following

#!/usr/bin/bash

function=""
if [[ $( echo $1 | grep fun1 ) ]]
then
     function="example_fun1"
     shift
elif [[ $( echo $1 | grep fun2 ) ]]
then
     function="example_fun2"
     shift
fi

#checks if the arguments is directory and extract the domain name from it

example_fun1(){
    ping -c 4 $domain
}

example_fun2(){
    nslookup $domain
}

if [[ "$function" != "" ]]
then
        for input in "$@"; do
            if [[ -d "$1" ]]; then
                domain=$(echo "$1" | grep -iEo '[[:alnum:]-]+\.[a-z]+')
                WORKING_DIR="$1"
            else
                domain="$1"
                echo "it is domain name"
            fi
            "$function"
            shift
        done
else
        for input in "$@"; do
            if [[ -d "$1" ]]; then
                domain=$(echo "$1" | grep -iEo '[[:alnum:]-]+\.[a-z]+')
                WORKING_DIR="$1"
            else
                domain="$1"
                echo "it is domain name"
            fi
             example_fun1
             example_fun2
             shift
        done
fi

This way you can pass fun1 and execute only  fun1
Or if you don't pass any of these for example both of them will be executed


问:
When to use the 'sanitize' method in view files?
I am using Ruby on Rails 3.0.9 and I would like to know when I MAY, SHOULD and MUST use the sanitize(...) method for security reasons.

An usage example can be:

```<code>sanitize(flash[:notice])
</code>```

答:
You should use it whenever you are displaying data which as been input by the user, i.e. it cannot be trusted.

For example in a chat application a user can write posts which are then displayed on the page. In this case it is important to sanitize the input.

If you don't sanitize the input, the user can inject HTML and Javascript code into your page, which affects all other users viewing the same page. This way the attacker can gain complete control over the page.

On the other hand it is not necessary to sanitize data your application created, i.e. in your example (sanitize(flash[:notice])) is not necessary. (Assuming you are using flash to display status messages created by your application)

Body:
I am using Ruby on Rails 3.0.9 and I would like to know when I MAY, SHOULD and MUST use the sanitize(...) method for security reasons.

An usage example can be:

sanitize(flash[:notice])


问:
Using slug as a filter with Graphql and Strapi V4
Trying to use slug as an uuid to fetch single pages from a strapi backend v4.
my query to get pages works well. It's just I can't filter using slug:

my pages query:

  query {
   pages {
    data {
      attributes {
            Name
            slug
      }
    }
 }
}
```

how to get single page using slug uuid within this schema ? every trails to implement ($slug: String!) fails as where to locate slug.

答:
You can use filters. Just pass slug as argument and use the 'eq' keyword for comparison which stands for equals.</p>
```<code>query pages($slug:String) {
    pages(filters:{slug:{eq:$slug}}) {
        data {
            attributes {
                Name
                slug
            }
        }
    }
}
</code>```

Body:
Trying to use slug as an uuid to fetch single pages from a strapi backend v4.
my query to get pages works well. It's just I can't filter using slug:

my pages query:

  query {
   pages {
    data {
      attributes {
            Name
            slug
      }
    }
 }
}

how to get single page using slug uuid within this schema ? every trails to implement ($slug: String!) fails as where to locate slug.

Body:
You can use filters. Just pass slug as argument and use the 'eq' keyword for comparison which stands for equals.

query pages($slug:String) {
    pages(filters:{slug:{eq:$slug}}) {
        data {
            attributes {
                Name
                slug
            }
        }
    }
}


问:
WinForm C# wait 5 second
For my Win Form program, I need to wait 5 second but the normal c# Thread.Sleep(5000); doesn’t work in the Win Form so I tried Task.Delay(5000); but it still doesn’t work. Help

```<code>public void waitThen();
{
    Task.Delay(5000);
    checkForDone();
}
</code>```

答:
There's a long comment thread above, but hopefully an answer can simplify for future visitors...

Task.Delay is an asynchronous operation.  (Whether or not it's internally marked as async I can't say for sure, but it's "awaitable".)  You just need to await it:

```<code>public async Task waitThen()
{
    await Task.Delay(5000);
    checkForDone();
}
</code>```

Note also that the method now returns a Task, not void.  This makes your waitThen method also awaitable, so consuming code will need to await it if that code also wants to wait until the operation is complete before continuing.

but the normal c# Thread.Sleep(5000); doesn’t work in the Win Form

Sure it does, it always has.  However, unless it's done on a separate thread explicitly then it will also freeze the UI for 5 seconds.  Which "works" but is certainly not ideal.  Relying on Task is generally the preferred approach.

Asides related to the comment thread above:

In order to use Task, you need using System.Threading.Tasks;

In order to use Thread, you need using System.Threading;

Method names in C# are traditionally capitalized: WaitThen

Title: WinForm C# wait 5 second

Body:
For my Win Form program, I need to wait 5 second but the normal c# Thread.Sleep(5000); doesn’t work in the Win Form so I tried Task.Delay(5000); but it still doesn’t work. Help

public void waitThen();
{
    Task.Delay(5000);
    checkForDone();
}

Body:
There's a long comment thread above, but hopefully an answer can simplify for future visitors...

Task.Delay is an asynchronous operation.  (Whether or not it's internally marked as async I can't say for sure, but it's "awaitable".)  You just need to await it:

public async Task waitThen()
{
    await Task.Delay(5000);
    checkForDone();
}

Note also that the method now returns a Task, not void.  This makes your waitThen method also awaitable, so consuming code will need to await it if that code also wants to wait until the operation is complete before continuing.

but the normal c# Thread.Sleep(5000); doesn’t work in the Win Form

Sure it does, it always has.  However, unless it's done on a separate thread explicitly then it will also freeze the UI for 5 seconds.  Which "works" but is certainly not ideal.  Relying on Task is generally the preferred approach.

Asides related to the comment thread above:

In order to use Task, you need using System.Threading.Tasks;

In order to use Thread, you need using System.Threading;

Method names in C# are traditionally capitalized: WaitThen


问:
How to use ELK with SCDF stream applications?
In our company, we use ELK stack for logging through Spring Cloud Config and logback.

I would like to use ELK with SCDF too.

For our own applications, we can add the logstash-logback-encoder dependency to make it work.

But with standard stream applications which do not include this dependency, I have an exception because LogstashTcpSocketAppender is not defined ?

Is there a way to use ELK with stream applications like time-source or log-sink in ticktock stream for example ?

答: I think the best option is to clone the repository, add the dependency and generate the applications on your own since it is considered as customization. Please let us know if you need help with generating the apps.</p>


问:
How to turn these C# foreach loops into LINQ to Objects and return a bool?
I'm writing a .Net 3.5 C# script for Sony Vegas Pro. I've created this method which returns true if it finds a video event with the same timecode as a given audio event.

This works but I'm wondering if I could get rid of the foreach loops using LINQ. I'm just learning LINQ and I'm finding it quite hard so if you could explain your thought steps in getting to the solution, that'd be great.

```<code>private bool videoExistsWithSameStart(TrackEvent currentEvent)
    {
        //Look through each video track - we don't want audio tracks.
        var videoTracks = from t in myVegas.Project.Tracks
                          where t.IsVideo()
                          select t;

        foreach (Track t in videoTracks)
        {
            foreach (TrackEvent te in t.Events)
            {
                if (te.Start == currentEvent.Start)
                    return true;
            }
        }
        return false;
    }
</code>```

答:
Another alternative:</p>

```<code>return myVegas.Project.Tracks
    .Where(track => track.IsVideo())
    .SelectMany(track => track.Events)
    .Any(trackEvent => trackEvent.Start == currentEvent.Start);
</code>```

Body:
I'm writing a .Net 3.5 C# script for Sony Vegas Pro. I've created this method which returns true if it finds a video event with the same timecode as a given audio event.

This works but I'm wondering if I could get rid of the foreach loops using LINQ. I'm just learning LINQ and I'm finding it quite hard so if you could explain your thought steps in getting to the solution, that'd be great.

private bool videoExistsWithSameStart(TrackEvent currentEvent)
    {
        //Look through each video track - we don't want audio tracks.
        var videoTracks = from t in myVegas.Project.Tracks
                          where t.IsVideo()
                          select t;

        foreach (Track t in videoTracks)
        {
            foreach (TrackEvent te in t.Events)
            {
                if (te.Start == currentEvent.Start)
                    return true;
            }
        }
        return false;
    }

Body:
Another alternative:

return myVegas.Project.Tracks
    .Where(track => track.IsVideo())
    .SelectMany(track => track.Events)
    .Any(trackEvent => trackEvent.Start == currentEvent.Start);


问:
Typing a closure that returns an anonymous type borrowing from one of its inputs without heap allocation or trait objects
Let's say that I have the following working code:

use std::collections::VecDeque;

fn modify<S, F>(state: &mut S, func: F)
where
    F: for<'a> Fn(&'a mut S) -> Box<dyn Iterator<Item = &mut u64> + 'a>
{
    let mut prev = 1;
    for _ in 0..3 {
        for item in func(state) {
            let val = *item;
            *item = val * prev;
            prev = val;
        }
    }
}

fn main() {
    let mut state: VecDeque<u64> = vec![1,2,3,4].into();

    modify(&mut state, |s| Box::new(s.iter_mut()));
    assert_eq!(state, [48, 8, 24, 864]);

    modify(&mut state, |s| Box::new(s.iter_mut().take(2)));
    assert_eq!(state, [147456, 7077888, 24, 864]);

    modify(&mut state, |s| Box::new(s.iter_mut().skip(2)));
    assert_eq!(state, [147456, 7077888, 429981696, 10319560704]);
}
```
<p><code>modify</code> takes a function that generates an iterator multiple times from a given <code>state</code> variable (in this case, a <code>VecDeque</code>). This function works, but contains an unnecessary heap allocation as well as unneeded polymorphism in the form of a trait object. I'd very much like to do something like this:</p>
<pre class="lang-rust prettyprint-override"><code>use std::collections::VecDeque;

fn modify<'a, S, F, I>(state: &'a mut S, func: F)
where
    F: Fn(&'a mut S) -> I,
    I: Iterator<Item = &'a mut u64>
{
    let mut prev = 1;
    for _ in 0..3 {
        for item in func(state) {
            let val = *item;
            *item = val * prev;
            prev = val;
        }
    }
}

fn main() {
    let mut state: VecDeque<u64> = vec![1,2,3,4].into();

    modify(&mut state, |s| s.iter_mut());
    assert_eq!(state, [48, 8, 24, 864]);

    modify(&mut state, |s| s.iter_mut().take(2));
    assert_eq!(state, [147456, 7077888, 24, 864]);

    modify(&mut state, |s| s.iter_mut().skip(2));
    assert_eq!(state, [147456, 7077888, 429981696, 10319560704]);
}
</code>```

But I now get this error:

```<code>error[E0499]: cannot borrow `*state` as mutable more than once at a time
  --> src/main.rs:10:26
   |
3  | fn modify<'a, S, F, I>(state: &'a mut S, func: F)
   |           -- lifetime `'a` defined here
...
10 |         for item in func(state) {
   |                     -----^^^^^-
   |                     |    |
   |                     |    `*state` was mutably borrowed here in the previous iteration of the loop
   |                     argument requires that `*state` is borrowed for `'a`

For more information about this error, try `rustc --explain E0499`.
</code>```

And I can't figure out how to wrangle the borrow checker to do what I want. Any clues would be appreciated. Thanks!

答:
TL;DR

No, not until closure HRTB inference is fixed. Current workarounds include using function pointers instead or implementing a helper trait on custom structs -- the helper trait is needed regardless of approach until higher-kinded types are introduced in Rust.

Playground

Details

To avoid returning a Box, you would need the type parameter I to be generic over the lifetime 'a, so that you can use it with any lifetime (in a for<'a> bound, for example). Unfortunately, as discussed in a similar question, Rust does not yet support higher-kinded types (type parameters that are themselves generic over other type parameters), so we must use a helper trait:

```<code>trait GenerateIterator<'a, S: 'a> {
    type Output: Iterator<Item = &'a mut u64>;
    fn generate(self, s: &'a mut S) -> Self::Output;
}

impl<'a, S: 'a, I, F> GenerateIterator<'a, S> for F
where
    F: Fn(&'a mut S) -> I,
    I: Iterator<Item = &'a mut u64>,
{
    type Output = I;
    fn generate(self, s: &'a mut S) -> Self::Output {
        self(s)
    }
}

fn modify<S>(state: &mut S, func: impl for<'a> GenerateIterator<'a, S>) {
    let mut prev = 1;
    for _ in 0..3 {
        for item in func.generate(state) {
            let val = *item;
            *item = val * prev;
            prev = val;
        }
    }
}
</code>```

This is great in helping us work around the use of higher-kinded types in this situation, but due to another compiler limitation in closure HRTB (higher-ranked trait bound) inference, the compiler is unable to infer that the closures we pass to modify are general over any lifetime. The alternative is to use function pointers like VecDeque::iter_mut, or create your own structs that implement GenerateIterator to generate the Iterator as you want:

```<code>fn main() {
    fn take2(s: &mut VecDeque<u64>) -> impl Iterator<Item = &mut u64> {
        s.iter_mut().take(2)
    }

    fn skip2(s: &mut VecDeque<u64>) -> impl Iterator<Item = &mut u64> {
        s.iter_mut().skip(2)
    }

    let mut state: VecDeque<u64> = vec![1, 2, 3, 4].into();

    modify(&mut state, VecDeque::iter_mut);
    assert_eq!(state, [48, 8, 24, 864]);

    modify(&mut state, take2);
    assert_eq!(state, [147456, 7077888, 24, 864]);

    modify(&mut state, skip2);
    assert_eq!(state, [147456, 7077888, 429981696, 10319560704]);
}
</code>```

Body:
Let's say that I have the following working code:

use std::collections::VecDeque;

fn modify<S, F>(state: &mut S, func: F)
where
    F: for<'a> Fn(&'a mut S) -> Box<dyn Iterator<Item = &mut u64> + 'a>
{
    let mut prev = 1;
    for _ in 0..3 {
        for item in func(state) {
            let val = *item;
            *item = val * prev;
            prev = val;
        }
    }
}

fn main() {
    let mut state: VecDeque<u64> = vec![1,2,3,4].into();

    modify(&mut state, |s| Box::new(s.iter_mut()));
    assert_eq!(state, [48, 8, 24, 864]);

    modify(&mut state, |s| Box::new(s.iter_mut().take(2)));
    assert_eq!(state, [147456, 7077888, 24, 864]);

    modify(&mut state, |s| Box::new(s.iter_mut().skip(2)));
    assert_eq!(state, [147456, 7077888, 429981696, 10319560704]);
}

modify takes a function that generates an iterator multiple times from a given state variable (in this case, a VecDeque). This function works, but contains an unnecessary heap allocation as well as unneeded polymorphism in the form of a trait object. I'd very much like to do something like this:

use std::collections::VecDeque;

fn modify<'a, S, F, I>(state: &'a mut S, func: F)
where
    F: Fn(&'a mut S) -> I,
    I: Iterator<Item = &'a mut u64>
{
    let mut prev = 1;
    for _ in 0..3 {
        for item in func(state) {
            let val = *item;
            *item = val * prev;
            prev = val;
        }
    }
}

fn main() {
    let mut state: VecDeque<u64> = vec![1,2,3,4].into();

    modify(&mut state, |s| s.iter_mut());
    assert_eq!(state, [48, 8, 24, 864]);

    modify(&mut state, |s| s.iter_mut().take(2));
    assert_eq!(state, [147456, 7077888, 24, 864]);

    modify(&mut state, |s| s.iter_mut().skip(2));
    assert_eq!(state, [147456, 7077888, 429981696, 10319560704]);
}

But I now get this error:

error[E0499]: cannot borrow `*state` as mutable more than once at a time
  --> src/main.rs:10:26
   |
3  | fn modify<'a, S, F, I>(state: &'a mut S, func: F)
   |           -- lifetime `'a` defined here
...
10 |         for item in func(state) {
   |                     -----^^^^^-
   |                     |    |
   |                     |    `*state` was mutably borrowed here in the previous iteration of the loop
   |                     argument requires that `*state` is borrowed for `'a`

For more information about this error, try `rustc --explain E0499`.

And I can't figure out how to wrangle the borrow checker to do what I want. Any clues would be appreciated. Thanks!

Body:
TL;DR

No, not until closure HRTB inference is fixed. Current workarounds include using function pointers instead or implementing a helper trait on custom structs -- the helper trait is needed regardless of approach until higher-kinded types are introduced in Rust.

Playground

Details

To avoid returning a Box, you would need the type parameter I to be generic over the lifetime 'a, so that you can use it with any lifetime (in a for<'a> bound, for example). Unfortunately, as discussed in a similar question, Rust does not yet support higher-kinded types (type parameters that are themselves generic over other type parameters), so we must use a helper trait:

trait GenerateIterator<'a, S: 'a> {
    type Output: Iterator<Item = &'a mut u64>;
    fn generate(self, s: &'a mut S) -> Self::Output;
}

impl<'a, S: 'a, I, F> GenerateIterator<'a, S> for F
where
    F: Fn(&'a mut S) -> I,
    I: Iterator<Item = &'a mut u64>,
{
    type Output = I;
    fn generate(self, s: &'a mut S) -> Self::Output {
        self(s)
    }
}

fn modify<S>(state: &mut S, func: impl for<'a> GenerateIterator<'a, S>) {
    let mut prev = 1;
    for _ in 0..3 {
        for item in func.generate(state) {
            let val = *item;
            *item = val * prev;
            prev = val;
        }
    }
}

This is great in helping us work around the use of higher-kinded types in this situation, but due to another compiler limitation in closure HRTB (higher-ranked trait bound) inference, the compiler is unable to infer that the closures we pass to modify are general over any lifetime. The alternative is to use function pointers like VecDeque::iter_mut, or create your own structs that implement GenerateIterator to generate the Iterator as you want:

fn main() {
    fn take2(s: &mut VecDeque<u64>) -> impl Iterator<Item = &mut u64> {
        s.iter_mut().take(2)
    }

    fn skip2(s: &mut VecDeque<u64>) -> impl Iterator<Item = &mut u64> {
        s.iter_mut().skip(2)
    }

    let mut state: VecDeque<u64> = vec![1, 2, 3, 4].into();

    modify(&mut state, VecDeque::iter_mut);
    assert_eq!(state, [48, 8, 24, 864]);

    modify(&mut state, take2);
    assert_eq!(state, [147456, 7077888, 24, 864]);

    modify(&mut state, skip2);
    assert_eq!(state, [147456, 7077888, 429981696, 10319560704]);
}


问:
ERROR StatusLogger Log4j2 could not find a logging implementation
I am trying to implement log4j 2 but it keeps throwing the following error.

```<code>> ERROR StatusLogger Log4j2 could not find a logging implementation.
> Please add log4j-core to the classpath. Using SimpleLogger to log to
> the console...
> ERROR LogExample This Will Be Printed On Error
> FATAL LogExample This Will Be Printed On Fatal
</code>```

I have tried the solution given on the net. But the don't seem to be working for me.

This is the code that I am trying to run.

```<code>package demo;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class LogExample {

    private static final Logger LOG = LogManager.getLogger(LogExample.class);

    public static void main(String[] args) {

        LOG.debug("This Will Be Printed On Debug");
        LOG.info("This Will Be Printed On Info");
        LOG.warn("This Will Be Printed On Warn");
        LOG.error("This Will Be Printed On Error");
        LOG.fatal("This Will Be Printed On Fatal");
        LOG.info("Appending string: {}.", "Hello, World");
    }

}
</code>```

Project and dependency added in the pom.xml:

Any help is appreciated.

答:
I was facing the same issue for upgrading log4j from 1.x to Log4j-2.17.1. Was getting this error while deploying to GlassFish server.

I took the following steps to correct this:

Disbled the autoInitialization of Log4j2. Added to web.xml

<context-param> <param-name>isLog4jAutoInitializationDisabled</param-name> <param-value>true</param-value> </context-param>

Initialized Log4j2 programmatically:

InputStream inputStream = new  FileInputStream("path of Log4j2.xml"); ConfigurationSource source = new ConfigurationSource(inputStream); Configurator.initialize(null, source);

Body:
I am trying to implement log4j 2 but it keeps throwing the following error.

> ERROR StatusLogger Log4j2 could not find a logging implementation.
> Please add log4j-core to the classpath. Using SimpleLogger to log to
> the console...
> ERROR LogExample This Will Be Printed On Error
> FATAL LogExample This Will Be Printed On Fatal

I have tried the solution given on the net. But the don't seem to be working for me.

This is the code that I am trying to run.

package demo;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class LogExample {

    private static final Logger LOG = LogManager.getLogger(LogExample.class);

    public static void main(String[] args) {

        LOG.debug("This Will Be Printed On Debug");
        LOG.info("This Will Be Printed On Info");
        LOG.warn("This Will Be Printed On Warn");
        LOG.error("This Will Be Printed On Error");
        LOG.fatal("This Will Be Printed On Fatal");
        LOG.info("Appending string: {}.", "Hello, World");
    }

}

Project and dependency added in the pom.xml:

Any help is appreciated.


问:
How to configure in cmake
I am currently working on a project which is using cmake. The project has alsa as an optional dependency. Thus the projects CMakeLists.txt contains.

```<code>find_package(ALSA)
</code>```

However I want the build to never build against alsa, even if if is on my system. (Kind of like the --without-ALSA that would have been in a configure)

I want to do this in a commandline-parameter when running cmake, not by modifying the  CMakeLists.txt

Is this possible with cmake?

EDIT:

OR would it be better to have the project implement something like this:

```<code> if(WITH_ALSA)
    find_package(ALSA REQUIRED)
 elseif(NOT WITHOUT_ALSA)
    find_package(ALSA)
 endif()
</code>```

EDIT2:

In the end I used the with & without option I described above (edit1). To have a little readability I defined a macro that acually does everything for me.

See the FindOptionalPackage.cmake in the FreeRDP project

答:
First run CMake and open the generated CMakeCache.txt file. You will find something like:

ALSA_INCLUDE_DIR=/usr/include/alsa

(you basically just need to know how the variable is called). Then you should be able to call cmake with a parameter

```<code>-DALSA_INCLUDE_DIR=ALSA_INCLUDE_DIR_NOTFOUND
</code>```

This tells cmake, that alsa is not on your system. If this does not work, try to look at other variables containing alsa and set them to some values indicating the library could not been found. If the FindALSA.cmake script is implemented correctly (i.e. does correct caching), this should work.

Title: How to configure in cmake

Body:
I am currently working on a project which is using cmake. The project has alsa as an optional dependency. Thus the projects CMakeLists.txt contains.

find_package(ALSA)

However I want the build to never build against alsa, even if if is on my system. (Kind of like the --without-ALSA that would have been in a configure)

I want to do this in a commandline-parameter when running cmake, not by modifying the  CMakeLists.txt

Is this possible with cmake?

EDIT:

OR would it be better to have the project implement something like this:

 if(WITH_ALSA)
    find_package(ALSA REQUIRED)
 elseif(NOT WITHOUT_ALSA)
    find_package(ALSA)
 endif()

EDIT2:

In the end I used the with & without option I described above (edit1). To have a little readability I defined a macro that acually does everything for me.

See the FindOptionalPackage.cmake in the FreeRDP project

Body:
First run CMake and open the generated CMakeCache.txt file. You will find something like:

ALSA_INCLUDE_DIR=/usr/include/alsa

(you basically just need to know how the variable is called). Then you should be able to call cmake with a parameter

-DALSA_INCLUDE_DIR=ALSA_INCLUDE_DIR_NOTFOUND

This tells cmake, that alsa is not on your system. If this does not work, try to look at other variables containing alsa and set them to some values indicating the library could not been found. If the FindALSA.cmake script is implemented correctly (i.e. does correct caching), this should work.


问:
How to get response body from Express.js server using Supertest?
I started to write some tests for my application and I have issues to read/get response from the server. I tried many things but nothing really worked, can someone help me please ?

```<code>// /api/checkCreds
exports.checkCreds = async function(req, res){
//validation
if(!await User.checkCreds(req.body.username, req.body.password)){
    var result = {error: true, data: "Incorrect"}
    res.sendStatus = 401;
    return res.send(JSON.stringify(result));
}
</code>```

If credentials sent to the server aren't matching, return a response with "Incorrect" message back to the user.
In the test I'm trying to get data from the server to check if properties are matching the expected output.

```<code>    //test.js
    it("We should fail with HTTP code 401 because incorrect data is passed (username='incorrect' password='incorrect')", function(done){
       supertest(app)
       .post('/api/checkCreds')
       .send({username: 'incorrect', password: 'incorrect'})
       .expect({error: true, data: "Incorrect"})
       .expect(401, done);
   });
</code>```

When ran, test fails because expected properties are different from the response sent by the server, which is an empty object {}.

Any help is appreciated.

答:
You may try changing your first expect to see if you can coax supertest into showing you the actual body that it's comparing to. For example, expect('')

If that doesn't work, there's a version of expect that accepts a function. In that function, you should be able to print out what you are getting in the response body, ie. console.log(res).

It may be that there's some confusion with the JSON return type-- I haven't used that directly. You could try expecting JSON.

Finally, there's a strange paragraph in the documentation that I don't think applies, but I thought I'd mention:

One thing to note with the above statement is that superagent now sends any HTTP error (anything other than a 2XX response code) to the callback as the first argument if you do not add a status code expect (i.e. .expect(302)).

Body:
I started to write some tests for my application and I have issues to read/get response from the server. I tried many things but nothing really worked, can someone help me please ?

// /api/checkCreds
exports.checkCreds = async function(req, res){
//validation
if(!await User.checkCreds(req.body.username, req.body.password)){
    var result = {error: true, data: "Incorrect"}
    res.sendStatus = 401;
    return res.send(JSON.stringify(result));
}

If credentials sent to the server aren't matching, return a response with "Incorrect" message back to the user.
In the test I'm trying to get data from the server to check if properties are matching the expected output.

    //test.js
    it("We should fail with HTTP code 401 because incorrect data is passed (username='incorrect' password='incorrect')", function(done){
       supertest(app)
       .post('/api/checkCreds')
       .send({username: 'incorrect', password: 'incorrect'})
       .expect({error: true, data: "Incorrect"})
       .expect(401, done);
   });

When ran, test fails because expected properties are different from the response sent by the server, which is an empty object {}.

Any help is appreciated.


问:
Making prediction in Keras using a custom generator
I have an image-classifier model in TensorFlow which I wanna make predictions with. I have created a custom generator to avoid loading it all in the RAM at the same time.

```<code>def load_and_preprocess_image(url_path_x):
        with requests.Session() as s:
            request_x=s.get(url_path_x).content
        img = Image.open(BytesIO(request_x))
        img = img.convert('RGB')
        img = img.resize((224,224), Image.NEAREST)
        img = tensorflow.keras.preprocessing.image.img_to_array(img)
        return(img)

def prediction_generator(urls_x):
    for url_x in urls_x:
        try:
            yield load_and_preprocess_image(path_x=url_x, is_url=True).reshape(1,224,224,3)
        except:
            yield load_and_preprocess_image(path_x=dummy_image_path, is_url=True).reshape(1,224,224,3)

my_path_gen = prediction_generator(df['url_path_column'])
preds_probas = model_i.predict(my_path_gen, batch_size=1, verbose=0, steps=None, callbacks=None, max_queue_size=10, workers=1, use_multiprocessing=False)
</code>```

However, it seems that my code is consuming extensive RAM as if the code is loading all the images into the RAM at the same time. Is there anything wrong with my custom generator?

答:
The generators are fine guys and they aren't using excessive RAM. The issue was somewhere else.

Anyways, I'm leaving the question here so that maybe the code be useful to someone.

Body:
I have an image-classifier model in TensorFlow which I wanna make predictions with. I have created a custom generator to avoid loading it all in the RAM at the same time.

def load_and_preprocess_image(url_path_x):
        with requests.Session() as s:
            request_x=s.get(url_path_x).content
        img = Image.open(BytesIO(request_x))
        img = img.convert('RGB')
        img = img.resize((224,224), Image.NEAREST)
        img = tensorflow.keras.preprocessing.image.img_to_array(img)
        return(img)

def prediction_generator(urls_x):
    for url_x in urls_x:
        try:
            yield load_and_preprocess_image(path_x=url_x, is_url=True).reshape(1,224,224,3)
        except:
            yield load_and_preprocess_image(path_x=dummy_image_path, is_url=True).reshape(1,224,224,3)

my_path_gen = prediction_generator(df['url_path_column'])
preds_probas = model_i.predict(my_path_gen, batch_size=1, verbose=0, steps=None, callbacks=None, max_queue_size=10, workers=1, use_multiprocessing=False)

However, it seems that my code is consuming extensive RAM as if the code is loading all the images into the RAM at the same time. Is there anything wrong with my custom generator?


问:
Java: Rationale of the Object class not being declared abstract
Why wasn't the java.lang.Object class declared to be abstract ?

Surely for an Object to be useful it needs added state or behaviour, an Object class is an abstraction, and as such it should have been declared abstract ...  why did they choose not to ?

答:
Does Object specify methods that classes extending it must implement in order to be useful? No, and therefor it needn't be abstract.

The concept of a class being abstract has a well defined meaning that does not apply to Object.

OwnerDisplayName: Ande Turner

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Ande

OwnerDisplayName: Kris


问:
Problem running pdf2text jar. File not found exception
I have been trying to run the pdf2text tool provided by apache. I initially got the 'failed to load main-class manifest attribute' error. So I modified the manifest file in the jar to include the Main-Class attribute. Wrote it as -

```<code>Main-Class: org.apache.pdfbox.ExtractText
</code>```

But after this, I am getting the exception -

```<code>Exception in thread "main" java.io.FileNotFoundException:
        org.apache.pdfbox.ExtractText (No such file or directory)
        at java.io.FileInputStream.open(Native Method)
        at java.io.FileInputStream.<init>(FileInputStream.java:106)
        at java.io.FileInputStream.<init>(FileInputStream.java:66)
        at org.apache.pdfbox.pdmodel.PDDocument.load(PDDocument.java:978)
        at org.apache.pdfbox.ExtractText.startExtraction(ExtractText.java:196)
        at org.apache.pdfbox.ExtractText.main(ExtractText.java:76)
</code>```

What can possibly be the mistake here?

答:
try to switch to this entry point (Main-class):

```<code>org.apache.pdfbox.PDFBox
</code>```

edit: this setup should also work (if you want to extract text)

```<code>java -cp ./pdfbox-1.6.0.jar org.apache.pdfbox.PDFBox ExtractText some.pdf
</code>```

note that you need to add Apache's logging package and so on to your CLASSPATH variable, unless you set that at the command line as well..

Body:
I have been trying to run the pdf2text tool provided by apache. I initially got the 'failed to load main-class manifest attribute' error. So I modified the manifest file in the jar to include the Main-Class attribute. Wrote it as -

Main-Class: org.apache.pdfbox.ExtractText

But after this, I am getting the exception -

Exception in thread "main" java.io.FileNotFoundException:
        org.apache.pdfbox.ExtractText (No such file or directory)
        at java.io.FileInputStream.open(Native Method)
        at java.io.FileInputStream.<init>(FileInputStream.java:106)
        at java.io.FileInputStream.<init>(FileInputStream.java:66)
        at org.apache.pdfbox.pdmodel.PDDocument.load(PDDocument.java:978)
        at org.apache.pdfbox.ExtractText.startExtraction(ExtractText.java:196)
        at org.apache.pdfbox.ExtractText.main(ExtractText.java:76)

What can possibly be the mistake here?

Body:
try to switch to this entry point (Main-class):

org.apache.pdfbox.PDFBox

edit: this setup should also work (if you want to extract text)

java -cp ./pdfbox-1.6.0.jar org.apache.pdfbox.PDFBox ExtractText some.pdf

note that you need to add Apache's logging package and so on to your CLASSPATH variable, unless you set that at the command line as well..


问:
DiffableDataSource does not update properly after applying changes in snapshot
I'm trying to filter a list of users in a TableViewDiffableDataSource. The filtered array of  users is passed to the following function:

```<code>private func updateUserCell(_ users: Users? = nil) {

        guard let newUsers = users else {

            print("No users to show")

            return

        }

        snapShot.deleteItems(viewModel.userList)

        dataSource!.apply(snapShot, animatingDifferences: false)

        if newUsers == [] { return }

        var snapShot = dataSource?.snapshot()

        snapShot?.appendItems(newUsers, toSection: .main)

        dataSource!.apply(snapShot!, animatingDifferences: true)

    }
</code>```

Debugging shows that the users get appended correctly in the snapshot. But applying shows correct number of filtered users but only the users from the top of the complete list.

i.e. if I have a full list of users [Chloe, Max, John, Martin]. Searching for "jo" only shows Chloe.
Searching for "ma" shows Chloe and Max instead of Max and Martin.

答:
I'm not sure I fully understand the logic behind your approach above but unless I'm missing something that the snippet isn't making clear, a far simpler approach would appear to be just to create a new snapshot with the required users and apply that, rather than modifying the existing one.

```<code>private func updateUserCell(_ users: Users? = nil) {
  guard let newUsers = users, !newUsers.isEmpty else {return}

  var snapshot = NSDiffableDataSourceSnapshot<Section, User>()
  snapshot.appendSections([.main])
  snapshot.appendItems(newUsers, toSection: .main)
  dataSource.apply(snapshot, animatingDifferences: true)
}
</code>```

nb. having an update users method that default to nil and therefore bailing out seems a strange design choice.  It suggests the logic behind calling it is a bit skewed.

Body:
I'm trying to filter a list of users in a TableViewDiffableDataSource. The filtered array of  users is passed to the following function:

private func updateUserCell(_ users: Users? = nil) {

        guard let newUsers = users else {

            print("No users to show")

            return

        }

        snapShot.deleteItems(viewModel.userList)

        dataSource!.apply(snapShot, animatingDifferences: false)

        if newUsers == [] { return }

        var snapShot = dataSource?.snapshot()

        snapShot?.appendItems(newUsers, toSection: .main)

        dataSource!.apply(snapShot!, animatingDifferences: true)

    }

Debugging shows that the users get appended correctly in the snapshot. But applying shows correct number of filtered users but only the users from the top of the complete list.

i.e. if I have a full list of users [Chloe, Max, John, Martin]. Searching for "jo" only shows Chloe.
Searching for "ma" shows Chloe and Max instead of Max and Martin.

Body:
I'm not sure I fully understand the logic behind your approach above but unless I'm missing something that the snippet isn't making clear, a far simpler approach would appear to be just to create a new snapshot with the required users and apply that, rather than modifying the existing one.

private func updateUserCell(_ users: Users? = nil) {
  guard let newUsers = users, !newUsers.isEmpty else {return}

  var snapshot = NSDiffableDataSourceSnapshot<Section, User>()
  snapshot.appendSections([.main])
  snapshot.appendItems(newUsers, toSection: .main)
  dataSource.apply(snapshot, animatingDifferences: true)
}

nb. having an update users method that default to nil and therefore bailing out seems a strange design choice.  It suggests the logic behind calling it is a bit skewed.


问:
Is there anything in Python that can persistently check to see if an Outlook email with a certain subject title came in?
I want to know if there's anything in Python that can constantly read my Outlook messages every five minutes. I want it to just check my email every 5 minutes (3:05PM, 3:10PM, 3:15PM, etc.) and as soon as an email comes in my inbox saying with a subject line like "Hello what's up" I want Python to automatically trigger a piece of .py code.

What I know so far

I already know how to access Outlook -

```<code>import win32com.client
win32com.client.Dispatch('outlook.application')
mapi = outlook.GetNamespace("MAPI")
inbox = mapi.GetDefaultFolder(1)
...
...
</code>```

Some possibilities

I am currently looking at a couple links such as persistently running Python in the background, listening for oncoming emails with Python, how to trigger a script upon email receipt as well as a Youtube video that talks about how to run a python script upon sending an email.

Hopefully I'll be able to figure out exactly how to run my Python script upon receipt of email, but in the meantime this question stays open. Thanks in advance.

答:
thanks for your help. It's been a month, but I revisited this problem and was able to find a solution. While I couldn't find a python program that would listen for an Outlook email, VBA in Outlook could listen for an email and then kick off a python script.

My python code was originally geared to edit an Excel spreadsheet directly. So, when I received an email with a certain subject line blah for example,  python file main.py would automatically execute and edit an excel file main.xlsx accordingly.

Something to note is that main.xlsx cannot be open at the time the email arrives. If anyone has any guidance on how to have main.xlsx be modified on the chance that the email arrives while it is open, I'd greatly appreciate it.

The below code solved my issue exactly:

```<code>Private Sub inboxItems_ItemAdd(ByVal Item As Object)
On Error GoTo ErrorHandler
Dim Msg As Outlook.MailItem
Dim MessageInfo
Dim Result
If TypeName(Item) = "MailItem" Then
    Debug.Print "Arrived"
    If Item.Subject = "Blah" Then
        Const PyExe = """C:\...\...\...\...\...\python3.9\latest\python.exe"""
        Const PyScript = "R:\...\...\Anders\Python\main.py"

        Dim objShell As Object, cmd As String
        Set objShell = CreateObject("Wscript.Shell")

        cmd = PyExe & " " & PyScript
        Debug.Print cmd

        objShell.Run cmd
        objShell.exec cmd

        MsgBox objShell.exec(cmd).StdOut.ReadAll
    End If
End If
ExitNewItem:
    Exit Sub
ErrorHandler:
    MsgBox Err.Number & " - " & Err.Description
    Resume ExitNewItem
End Sub
</code>```

Body:
I want to know if there's anything in Python that can constantly read my Outlook messages every five minutes. I want it to just check my email every 5 minutes (3:05PM, 3:10PM, 3:15PM, etc.) and as soon as an email comes in my inbox saying with a subject line like "Hello what's up" I want Python to automatically trigger a piece of .py code.

What I know so far

I already know how to access Outlook -

import win32com.client
win32com.client.Dispatch('outlook.application')
mapi = outlook.GetNamespace("MAPI")
inbox = mapi.GetDefaultFolder(1)
...
...

Some possibilities

I am currently looking at a couple links such as persistently running Python in the background, listening for oncoming emails with Python, how to trigger a script upon email receipt as well as a Youtube video that talks about how to run a python script upon sending an email.

Hopefully I'll be able to figure out exactly how to run my Python script upon receipt of email, but in the meantime this question stays open. Thanks in advance.

Body:
thanks for your help. It's been a month, but I revisited this problem and was able to find a solution. While I couldn't find a python program that would listen for an Outlook email, VBA in Outlook could listen for an email and then kick off a python script.

My python code was originally geared to edit an Excel spreadsheet directly. So, when I received an email with a certain subject line blah for example,  python file main.py would automatically execute and edit an excel file main.xlsx accordingly.

Something to note is that main.xlsx cannot be open at the time the email arrives. If anyone has any guidance on how to have main.xlsx be modified on the chance that the email arrives while it is open, I'd greatly appreciate it.

The below code solved my issue exactly:

Private Sub inboxItems_ItemAdd(ByVal Item As Object)
On Error GoTo ErrorHandler
Dim Msg As Outlook.MailItem
Dim MessageInfo
Dim Result
If TypeName(Item) = "MailItem" Then
    Debug.Print "Arrived"
    If Item.Subject = "Blah" Then
        Const PyExe = """C:\...\...\...\...\...\python3.9\latest\python.exe"""
        Const PyScript = "R:\...\...\Anders\Python\main.py"

        Dim objShell As Object, cmd As String
        Set objShell = CreateObject("Wscript.Shell")

        cmd = PyExe & " " & PyScript
        Debug.Print cmd

        objShell.Run cmd
        objShell.exec cmd

        MsgBox objShell.exec(cmd).StdOut.ReadAll
    End If
End If
ExitNewItem:
    Exit Sub
ErrorHandler:
    MsgBox Err.Number & " - " & Err.Description
    Resume ExitNewItem
End Sub


问:
Cannot find symbol class ActivityEngageBindingImpl
I'm using rxjava2 + mvvvmhabit library. How to fix this issue?

```<code>Cannot find symbol class ActivityEngageBindingImpl
[databinding] {"msg":"Cannot resolve type \u0027LayoutManagers\u0027",
"file":"app/src/main/res/layout/activity_engage.xml",
"pos":[{"line0":34,"col0":37,"line1":34,"col1":50}]}
</code>```

My activity_engage.xml file

```<code><layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:aapt="http://schemas.android.com/aapt"
    xmlns:binding="http://schemas.android.com/apk/res-auto"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <data>
        <import type="me.tatarka.bindingcollectionadapter2.LayoutManagers" />
        <import type="me.goldze.mvvmhabit.binding.viewadapter.recyclerview.LineManagers" />
        <variable
            name="viewModel"
            type="com.founicy.analy.ui.activity.engage.EngageViewModel" />

    </data>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <androidx.appcompat.widget.Toolbar
            android:id="@+id/tb_engage"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="@color/colorBackground"
            android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
            app:titleTextAppearance="@style/CustomToolbar" />

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/rv_engage_view"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_below="@+id/tb_engage"
            binding:itemBinding="@{viewModel.itemBinding}"
            binding:items="@{viewModel.observableList}"
            binding:layoutManager="@{LayoutManagers.linear()}"
            binding:lineManager="@{LineManagers.horizontal()}"
            android:scrollbarSize="3dp"
            android:scrollbarThumbVertical="@drawable/scroll_bar_color"
            android:scrollbars="vertical" />

        <LinearLayout
            android:id="@+id/ll_empty_engage"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:gravity="center"
            android:orientation="vertical"
            android:visibility="@{viewModel.llEmptyEngageVisible}">

            <ImageView
                android:layout_width="56dp"
                android:layout_height="56dp"
                android:src="@drawable/ic_data_empty" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:text="@string/date_empty"
                android:textColor="@color/textGrey"
                android:textSize="@dimen/engage_card_text" />
        </LinearLayout>

        <ProgressBar
            android:id="@+id/pb_engage"
            style="@style/Widget.AppCompat.ProgressBar.Horizontal"
            android:layout_width="match_parent"
            android:layout_height="3dp"
            android:layout_alignParentTop="true"
            android:visibility="gone" />
    </RelativeLayout>
</layout>
</code>```

答:
Please use the previous version of library. You should remove 4.0.0 and use 2.2.0

```<code>implementation 'me.tatarka.bindingcollectionadapter2:bindingcollectionadapter:4.0.0'
implementation 'me.tatarka.bindingcollectionadapter2:bindingcollectionadapter-recyclerview:4.0.0'
implementation 'me.tatarka.bindingcollectionadapter2:bindingcollectionadapter-viewpager2:4.0.0'
</code>```

Use 2.2.0 version

```<code>implementation 'me.tatarka.bindingcollectionadapter2:bindingcollectionadapter:2.2.0'
implementation 'me.tatarka.bindingcollectionadapter2:bindingcollectionadapter-recyclerview:2.2.0'
</code>```

Body:
I'm using rxjava2 + mvvvmhabit library. How to fix this issue?

Cannot find symbol class ActivityEngageBindingImpl
[databinding] {"msg":"Cannot resolve type \u0027LayoutManagers\u0027",
"file":"app/src/main/res/layout/activity_engage.xml",
"pos":[{"line0":34,"col0":37,"line1":34,"col1":50}]}

My activity_engage.xml file

<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:aapt="http://schemas.android.com/aapt"
    xmlns:binding="http://schemas.android.com/apk/res-auto"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <data>
        <import type="me.tatarka.bindingcollectionadapter2.LayoutManagers" />
        <import type="me.goldze.mvvmhabit.binding.viewadapter.recyclerview.LineManagers" />
        <variable
            name="viewModel"
            type="com.founicy.analy.ui.activity.engage.EngageViewModel" />

    </data>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <androidx.appcompat.widget.Toolbar
            android:id="@+id/tb_engage"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="@color/colorBackground"
            android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
            app:titleTextAppearance="@style/CustomToolbar" />

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/rv_engage_view"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_below="@+id/tb_engage"
            binding:itemBinding="@{viewModel.itemBinding}"
            binding:items="@{viewModel.observableList}"
            binding:layoutManager="@{LayoutManagers.linear()}"
            binding:lineManager="@{LineManagers.horizontal()}"
            android:scrollbarSize="3dp"
            android:scrollbarThumbVertical="@drawable/scroll_bar_color"
            android:scrollbars="vertical" />

        <LinearLayout
            android:id="@+id/ll_empty_engage"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:gravity="center"
            android:orientation="vertical"
            android:visibility="@{viewModel.llEmptyEngageVisible}">

            <ImageView
                android:layout_width="56dp"
                android:layout_height="56dp"
                android:src="@drawable/ic_data_empty" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:text="@string/date_empty"
                android:textColor="@color/textGrey"
                android:textSize="@dimen/engage_card_text" />
        </LinearLayout>

        <ProgressBar
            android:id="@+id/pb_engage"
            style="@style/Widget.AppCompat.ProgressBar.Horizontal"
            android:layout_width="match_parent"
            android:layout_height="3dp"
            android:layout_alignParentTop="true"
            android:visibility="gone" />
    </RelativeLayout>
</layout>

Body:
Please use the previous version of library. You should remove 4.0.0 and use 2.2.0

implementation 'me.tatarka.bindingcollectionadapter2:bindingcollectionadapter:4.0.0'
implementation 'me.tatarka.bindingcollectionadapter2:bindingcollectionadapter-recyclerview:4.0.0'
implementation 'me.tatarka.bindingcollectionadapter2:bindingcollectionadapter-viewpager2:4.0.0'

Use 2.2.0 version

implementation 'me.tatarka.bindingcollectionadapter2:bindingcollectionadapter:2.2.0'
implementation 'me.tatarka.bindingcollectionadapter2:bindingcollectionadapter-recyclerview:2.2.0'


问:
How can I add a counter column that records the number of occurrences of a value in a data frame in R?
I have the following data frame:

df <- data.frame(catergory=c("a","b","b","b","b","a","c"), value=c(1,5,3,6,7,4,6))

and I want to record the number of occurrences of each category so the output would be:

```<code>df <- data.frame(catergory=c("a","b","b","b","b","a","c"), value=c(1,5,3,6,7,4,6),
category_count=c(2,4,4,4,4,2,1))
</code>```

Is there a simple way to do this?

答:
With dplyr:</p>
```<code>library(dplyr)

df %>%
        group_by(category) %>%
        mutate(category_count = n()) %>%
        ungroup

# A tibble: 7 × 3
  category value category_count
  <chr>    <dbl>          <int>
1 a            1              2
2 b            5              4
3 b            3              4
4 b            6              4
5 b            7              4
6 a            4              2
7 c            6              1
</code>```

Body:
I have the following data frame:

df <- data.frame(catergory=c("a","b","b","b","b","a","c"), value=c(1,5,3,6,7,4,6))

and I want to record the number of occurrences of each category so the output would be:

df <- data.frame(catergory=c("a","b","b","b","b","a","c"), value=c(1,5,3,6,7,4,6),
category_count=c(2,4,4,4,4,2,1))

Is there a simple way to do this?

Body:
With dplyr:

library(dplyr)

df %>%
        group_by(category) %>%
        mutate(category_count = n()) %>%
        ungroup

# A tibble: 7 × 3
  category value category_count
  <chr>    <dbl>          <int>
1 a            1              2
2 b            5              4
3 b            3              4
4 b            6              4
5 b            7              4
6 a            4              2
7 c            6              1


问:
How to make text/bg/etc. change colors on loop?
Let's say i want to make the background go between black and blue. I am using the code

```<code>    <head>
      <style>
        body {background:skyblue;}
      </style>
    </head>
    <body>
      code
    </body>
   </html>
</code>```

and i want for it to change to {background:black;} every 2 seconds, then switch back to blue. How do I do that?

答:
      code

```

Here is a way to do it, but it is considered bad practice to have extremely graphical effects like this since it might give people headaches and such if they have to look at screens like this for extended periods of time. Use animations sparingly.

Body:
Let's say i want to make the background go between black and blue. I am using the code

      code

and i want for it to change to {background:black;} every 2 seconds, then switch back to blue. How do I do that?

Body:
<head>
      <style>
        body {
          animation: switch 2s linear 0s infinite alternate forwards;
        }
        @keyframes switch {
          from {
            background:skyblue;
          }
          49.9% {
            background:skyblue;
          }
          50.1% {
            background:black;
          }
          to {
            background:black;
          }
        }
      </style>
    </head>
    <body>
      code
    </body>
</html>

Here is a way to do it, but it is considered bad practice to have extremely graphical effects like this since it might give people headaches and such if they have to look at screens like this for extended periods of time. Use animations sparingly.


问:
Nuxt: Hydration of static page fails (asyncData missing)
Once again I have a nuxt question:

I have some static pages which make use of asyncData.
In my asyncData I load data from a JSON file. On the server I do that via filesystem and on the client with axios.

This looks more or less like this:

```<code>async asyncData({ app, route, store, error, $axios }) {
  try {
    let json
    const slug = 'mypage'

    if (process.server) {
      json = JSON.parse(
        require('fs').readFileSync(
          `static/pages/pages.de.${slug}.json`,
          'utf8'
        )
      )
    } else {
      json = await $axios.$get(`/pages/pages.de.${slug}.json`).then((res) => {
        return res
      })
    }

    return {
      page: json.items[0],
    }
  } catch (e) {
    console.error('e: ', e)
    error({ statusCode: 404, message: 'Post not found', e })
  }
}
</code>```

This works like expected and I get my page data like expected.
One weird thing is happening though.
When I run nuxt generate to serve my pages in full static mode my pages are pregenerated. Therefore the server request is made and page is filled with the JSON data. The data is then rendered into a static HTML. All good...

But when I load up that static HTML (initial entry point, not after route change!) the hydration is not being done!

In my network tab I can see a payload.js and a state.js (vuex stuff) being loaded. But  this.page remains undefined forever...

In my understanding this.page should be filled with data from the payload.js right after loading it.

Because my template includes a v-if

```<code><template>
  <div v-if="page" class="Page">
    // page content
  </div>
</template>
</code>```

Everything inside that v-if breaks.
Click handlers etc.

This problem exists only on the initial entry points. If I go to another route and come back it works perfectly fine...

I use the newest stable nuxt v2.15.8.
Also I have pages with a very similar setup where things work like expected.
So if anyone has a clue where I could look for errors or give me a hint if I misunderstand some concepts, I would be very glad to hear.

Cheers

答:
Ok. I finally found the solution.
Just to state things clearly:

the page should be hydrated with the payload.js

things should work just normally!

In my case I had a function in my nuxt.config that told the app which routes to generate. Some routes seemed to have missed a leading slash, which broke the whole thing...

Although the route generation process worked just fine, I believe that the payload.js was then not "fitting" the current route...

I don't have the details, but missing leading slashes in my routes was the problem.
So if anyone experiences the same, you could just make sure your routes are correct...

♀

Body:
Once again I have a nuxt question:

I have some static pages which make use of asyncData.
In my asyncData I load data from a JSON file. On the server I do that via filesystem and on the client with axios.

This looks more or less like this:

async asyncData({ app, route, store, error, $axios }) {
  try {
    let json
    const slug = 'mypage'

    if (process.server) {
      json = JSON.parse(
        require('fs').readFileSync(
          `static/pages/pages.de.${slug}.json`,
          'utf8'
        )
      )
    } else {
      json = await $axios.$get(`/pages/pages.de.${slug}.json`).then((res) => {
        return res
      })
    }

    return {
      page: json.items[0],
    }
  } catch (e) {
    console.error('e: ', e)
    error({ statusCode: 404, message: 'Post not found', e })
  }
}

This works like expected and I get my page data like expected.
One weird thing is happening though.
When I run nuxt generate to serve my pages in full static mode my pages are pregenerated. Therefore the server request is made and page is filled with the JSON data. The data is then rendered into a static HTML. All good...

But when I load up that static HTML (initial entry point, not after route change!) the hydration is not being done!

In my network tab I can see a payload.js and a state.js (vuex stuff) being loaded. But  this.page remains undefined forever...

In my understanding this.page should be filled with data from the payload.js right after loading it.

Because my template includes a v-if

<template>

    // page content

</template>

Everything inside that v-if breaks.
Click handlers etc.

This problem exists only on the initial entry points. If I go to another route and come back it works perfectly fine...

I use the newest stable nuxt v2.15.8.
Also I have pages with a very similar setup where things work like expected.
So if anyone has a clue where I could look for errors or give me a hint if I misunderstand some concepts, I would be very glad to hear.

Cheers


问:
How to recover grants for root user in mysql
I accidentally removed all privileges for root user. How can I recover it ?</p>

答:
First, start MySQL with --skip-grant-tables
Next, run the following query:
UPDATE mysql.user SET
Select_priv = 'Y',

          Insert_priv = 'Y',
          Update_priv = 'Y',
          Delete_priv = 'Y',
          Create_priv = 'Y',
            Drop_priv = 'Y',
          Reload_priv = 'Y',
        Shutdown_priv = 'Y',
         Process_priv = 'Y',
            File_priv = 'Y',
           Grant_priv = 'Y',
      References_priv = 'Y',
           Index_priv = 'Y',
           Alter_priv = 'Y',
         Show_db_priv = 'Y',
           Super_priv = 'Y',
Create_tmp_table_priv = 'Y',
     Lock_tables_priv = 'Y',
         Execute_priv = 'Y',
      Repl_slave_priv = 'Y',
     Repl_client_priv = 'Y',
     Create_view_priv = 'Y',
       Show_view_priv = 'Y',
  Create_routine_priv = 'Y',
   Alter_routine_priv = 'Y',
     Create_user_priv = 'Y',
           Event_priv = 'Y',
         Trigger_priv = 'Y',
max_questions = 0,
          max_updates = 0,
      max_connections = 0,
 max_user_connections = 0
WHERE user = 'root'

Finally, run FLUSH PRIVILEGES; and restart MySQL

If you need to reset the password as well, follow the instructions in the link above.