问:
CSS media multiple queries doesn't work when the statements are overarching
I want to make a website with Html, CSS and javascript.
Currently, I am facing the issue, that multiple media queries (in CSS) don't work at the same time.

I already looked at similar questions asked about this topic, in which they said you can nest multiple queries but then more than two media queries still don't seem to work (the code below isn't nested though).

My goal is it that the fade in / fade out of the navigation bar is fluent at every height and width (which would work, but now won't because too many queries). Between (min-width: 961px) and (max-width: 1101px) that max-width should be bigger (80%) than else (60%), so that the element Über uns is still on one line shown. The vh when the dropdown menu is showing should be on 75vh when the screen size is between (max-width: 961px) and (max-height: 501px). Last but not least if screen size is smaller than 961px it should just show the menu button.

<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width" />
    <title>Avisch</title>
    <link rel="stylesheet" href="Startseite.css" />

        AVISCH

            Startseite

            Über uns

            Blog

            Kontakt

```
<pre class="lang-css prettyprint-override"><code>* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
  font-family: "Kumbh Sans", sans-serif;
}

.navbar {
  background: #d4d4cc;
  height: 80px;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 1.2rem;
  position: sticky;
  top: 0;
  z-index: 999; /*Damit Navbar immer sichtbar ist*/
  box-shadow: inset -26.0416vw 0px 26.0416vw -18.22916vw #131313,
    inset 26.0416vw 0px 26.0416vw -18.22916vw #131313;
}

.navbar__container {
  background: #131313;
  display: flex;
  justify-content: space-between;
  height: 80px;
  z-index: 1;
  width: 100%;
  max-width: 67.708333333333333333333333333333%;
  margin: 0 auto;
  padding: 0 50px;
  box-shadow: inset 26.0416vw 0px 26.0416vw -17.447916666666666666666666666667vw
      #d4d4cc,
    inset -26.0416vw 0px 26.0416vw -17.447916666666666666666666666667vw #d4d4cc;
}

#navbar__logo {
  background-color: #ff8177;
  background-image: linear-gradient(to right, #131313 45%, #ee1d23 100%);
  background-size: 100%;
  -webkit-background-clip: text;
  -moz-background-clip: text;
  -webkit-text-fill-color: transparent;
  -moz-text-fill-color: transparent;
  display: flex;
  align-items: center;
  cursor: pointer;
  text-decoration: none;
  font-size: 2.5rem;
  font-weight: bold;
}

.navbar__menu {
  display: flex;
  align-items: center;
  list-style: none;
  text-align: center;
}

.navbar__item {
  height: 50px;
  margin: 5px;
}

.navbar__links {
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  text-decoration: none;
  padding: 0 1rem;
  height: 100%;
}
.navbar__links:hover {
  background: #b8151b;
  border: none;
  outline: none;
  border-radius: 4px;
  width: 100%;
  height: 100%;
  transition: all 0.3s ease;
}

@media screen and (max-width: 961px) {
  .navbar__container {
    display: flex;
    justify-content: space-between;
    height: 80px;
    z-index: 1;
    width: 100%;
    max-width: 1300px;
    padding: 0;
  }

  .navbar__menu {
    display: grid;
    grid-template-columns: auto;
    margin: 0;
    width: 100%;
    position: absolute;
    top: 100%;
    top: -1000px;
    opacity: 0;
    transition: all 0.5s ease;
    height: 60vh;
    z-index: -1;
    background: #131313;
  }

  .navbar__menu.active {
    background: #131313;
    box-shadow: inset 500px 0px 500px -450px #d4d4cc,
      inset -500px 0px 500px -450px #d4d4cc;
    top: 100%;
    opacity: 1;
    transition: all 0.5s ease;
    z-index: 99;
    height: 60vh;
    font-size: 1.6rem;
  }

  #navbar__logo {
    padding-left: 25px;
  }

  .navbar__toggle .bar {
    width: 25px;
    height: 3px;
    margin: 5px auto;
    transition: all 0.3s ease-in-out;
    background: #000;
    display: block;
    cursor: pointer;
  }

  .navbar__item {
    width: 100%;
    margin: 0;
  }

  .navbar__links {
    text-align: center;
    padding-top: 1rem;
    padding-bottom: 1rem;
    width: 100%;
    display: table;
  }

  .navbar__links:hover {
    width: 100%;
    height: 100%;
    transition: all 0.3s ease;
  }

  #mobile-menu {
    position: absolute;
    top: 20%;
    right: 5%;
    transform: translate(5%, 20%);
  }

  #mobile-menu.is-active .bar:nth-child(2) {
    opacity: 0;
  }

  #mobile-menu.is-active .bar:nth-child(1) {
    transform: translateY(8px) rotate(45deg);
  }
  #mobile-menu.is-active .bar:nth-child(3) {
    transform: translateY(-8px) rotate(-45deg);
  }
}

@media screen and (min-width: 1101px) {
  .navbar__container {
    max-width: 67.708333333333333333333333333333%;
  }
}

@media screen and (min-width: 961px), screen and (max-width: 1101px) {
  .navbar__container {
    max-width: 80%;
  }

@media screen and (max-width: 961px) and (max-height: 501px) {
  .navbar__menu.active {
    height: 75vh;
  }
}
</code>```

答:
Regarding the problem with the width, your basic problem is this line:

```<code>@media screen and (min-width: 961px), screen and (max-width: 1101px)
</code>```

When you use a comma in a media rule, it operates as a logical OR. So this rule will be applied if the width is greater than 961 OR if it is less than 1101 -- which is true for all widths. Instead, you need a logical AND between these conditions, so that the rule only applies between these two widths:

```<code>@media screen and (min-width: 961px) and (max-width: 1101px)
</code>```

My preferred way to arrange media queries is to follow the principle of mobile-first design, listing narrow viewport rules first, then add media queries for wider viewports in increasing order of width. That way, each media query just overrides whatever styles it needs to, at whatever width it needs to, and you don’t get tangled up with ANDs and ORs.

```<code>.navbar__container {
  width: 100%;                    /* narrow viewports */
}

@media (min-width: 961px) {
  .navbar__container {
    max-width: 80%;               /* medium viewports */
  }
}

@media (min-width: 1101px) {
  .navbar__container {
    max-width: 68%;               /* wide viewports */
  }
}
</code>```

Body:
I want to make a website with Html, CSS and javascript.
Currently, I am facing the issue, that multiple media queries (in CSS) don't work at the same time.

I already looked at similar questions asked about this topic, in which they said you can nest multiple queries but then more than two media queries still don't seem to work (the code below isn't nested though).

My goal is it that the fade in / fade out of the navigation bar is fluent at every height and width (which would work, but now won't because too many queries). Between (min-width: 961px) and (max-width: 1101px) that max-width should be bigger (80%) than else (60%), so that the element Über uns is still on one line shown. The vh when the dropdown menu is showing should be on 75vh when the screen size is between (max-width: 961px) and (max-height: 501px). Last but not least if screen size is smaller than 961px it should just show the menu button.

<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width" />
    <title>Avisch</title>
    <link rel="stylesheet" href="Startseite.css" />

        AVISCH

            Startseite

            Über uns

            Blog

            Kontakt

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
  font-family: "Kumbh Sans", sans-serif;
}

.navbar {
  background: #d4d4cc;
  height: 80px;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 1.2rem;
  position: sticky;
  top: 0;
  z-index: 999; /*Damit Navbar immer sichtbar ist*/
  box-shadow: inset -26.0416vw 0px 26.0416vw -18.22916vw #131313,
    inset 26.0416vw 0px 26.0416vw -18.22916vw #131313;
}

.navbar__container {
  background: #131313;
  display: flex;
  justify-content: space-between;
  height: 80px;
  z-index: 1;
  width: 100%;
  max-width: 67.708333333333333333333333333333%;
  margin: 0 auto;
  padding: 0 50px;
  box-shadow: inset 26.0416vw 0px 26.0416vw -17.447916666666666666666666666667vw
      #d4d4cc,
    inset -26.0416vw 0px 26.0416vw -17.447916666666666666666666666667vw #d4d4cc;
}

#navbar__logo {
  background-color: #ff8177;
  background-image: linear-gradient(to right, #131313 45%, #ee1d23 100%);
  background-size: 100%;
  -webkit-background-clip: text;
  -moz-background-clip: text;
  -webkit-text-fill-color: transparent;
  -moz-text-fill-color: transparent;
  display: flex;
  align-items: center;
  cursor: pointer;
  text-decoration: none;
  font-size: 2.5rem;
  font-weight: bold;
}

.navbar__menu {
  display: flex;
  align-items: center;
  list-style: none;
  text-align: center;
}

.navbar__item {
  height: 50px;
  margin: 5px;
}

.navbar__links {
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  text-decoration: none;
  padding: 0 1rem;
  height: 100%;
}
.navbar__links:hover {
  background: #b8151b;
  border: none;
  outline: none;
  border-radius: 4px;
  width: 100%;
  height: 100%;
  transition: all 0.3s ease;
}

@media screen and (max-width: 961px) {
  .navbar__container {
    display: flex;
    justify-content: space-between;
    height: 80px;
    z-index: 1;
    width: 100%;
    max-width: 1300px;
    padding: 0;
  }

  .navbar__menu {
    display: grid;
    grid-template-columns: auto;
    margin: 0;
    width: 100%;
    position: absolute;
    top: 100%;
    top: -1000px;
    opacity: 0;
    transition: all 0.5s ease;
    height: 60vh;
    z-index: -1;
    background: #131313;
  }

  .navbar__menu.active {
    background: #131313;
    box-shadow: inset 500px 0px 500px -450px #d4d4cc,
      inset -500px 0px 500px -450px #d4d4cc;
    top: 100%;
    opacity: 1;
    transition: all 0.5s ease;
    z-index: 99;
    height: 60vh;
    font-size: 1.6rem;
  }

  #navbar__logo {
    padding-left: 25px;
  }

  .navbar__toggle .bar {
    width: 25px;
    height: 3px;
    margin: 5px auto;
    transition: all 0.3s ease-in-out;
    background: #000;
    display: block;
    cursor: pointer;
  }

  .navbar__item {
    width: 100%;
    margin: 0;
  }

  .navbar__links {
    text-align: center;
    padding-top: 1rem;
    padding-bottom: 1rem;
    width: 100%;
    display: table;
  }

  .navbar__links:hover {
    width: 100%;
    height: 100%;
    transition: all 0.3s ease;
  }

  #mobile-menu {
    position: absolute;
    top: 20%;
    right: 5%;
    transform: translate(5%, 20%);
  }

  #mobile-menu.is-active .bar:nth-child(2) {
    opacity: 0;
  }

  #mobile-menu.is-active .bar:nth-child(1) {
    transform: translateY(8px) rotate(45deg);
  }
  #mobile-menu.is-active .bar:nth-child(3) {
    transform: translateY(-8px) rotate(-45deg);
  }
}

@media screen and (min-width: 1101px) {
  .navbar__container {
    max-width: 67.708333333333333333333333333333%;
  }
}

@media screen and (min-width: 961px), screen and (max-width: 1101px) {
  .navbar__container {
    max-width: 80%;
  }

@media screen and (max-width: 961px) and (max-height: 501px) {
  .navbar__menu.active {
    height: 75vh;
  }
}

Body:
Regarding the problem with the width, your basic problem is this line:

@media screen and (min-width: 961px), screen and (max-width: 1101px)

When you use a comma in a media rule, it operates as a logical OR. So this rule will be applied if the width is greater than 961 OR if it is less than 1101 -- which is true for all widths. Instead, you need a logical AND between these conditions, so that the rule only applies between these two widths:

@media screen and (min-width: 961px) and (max-width: 1101px)

My preferred way to arrange media queries is to follow the principle of mobile-first design, listing narrow viewport rules first, then add media queries for wider viewports in increasing order of width. That way, each media query just overrides whatever styles it needs to, at whatever width it needs to, and you don’t get tangled up with ANDs and ORs.

.navbar__container {
  width: 100%;                    /* narrow viewports */
}

@media (min-width: 961px) {
  .navbar__container {
    max-width: 80%;               /* medium viewports */
  }
}

@media (min-width: 1101px) {
  .navbar__container {
    max-width: 68%;               /* wide viewports */
  }
}


来源: stackexchange

问:
How can I change the volume of a stream playing in pyaudio
I have a normal stream in Pyaudio that plays a wav file but I can not find any way to change the volume of the stream. I tried multiplying the data by some number but that did not work.</p>
```<code>import pyaudio
import wave

audio = pyaudio.PyAudio()
chunk = 1024
af = wave.open("filename.wav", 'rb')
pa = pyaudio.PyAudio()

stream = pa.open(format =
pa.get_format_from_width(af.getsampwidth()),
            channels = af.getnchannels(),
            rate = af.getframerate(),
            output_device_index=9,
            output = True)

rd_data = af.readframes(chunk)

while rd_data != '':
    #do some majic to change the volume
    stream.write(rd_data)
    rd_data = af.readframes(chunk)
</code>```

答:
You can use numpy for this:

```<code>import numpy

def audio_datalist_set_volume(datalist, volume):
    """ Change value of list of audio chunks """
    sound_level = (volume / 100.)

    for i in range(len(datalist)):
        chunk = numpy.fromstring(datalist[i], numpy.int16)

        chunk = chunk * sound_level

        datalist[i] = chunk.astype(numpy.int16)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a normal stream in Pyaudio that plays a wav file but I can not find any way to change the volume of the stream. I tried multiplying the data by some number but that did not work.

import pyaudio
import wave

audio = pyaudio.PyAudio()
chunk = 1024
af = wave.open("filename.wav", 'rb')
pa = pyaudio.PyAudio()

stream = pa.open(format =
pa.get_format_from_width(af.getsampwidth()),
            channels = af.getnchannels(),
            rate = af.getframerate(),
            output_device_index=9,
            output = True)

rd_data = af.readframes(chunk)

while rd_data != '':
    #do some majic to change the volume
    stream.write(rd_data)
    rd_data = af.readframes(chunk)

Body:
You can use numpy for this:

import numpy

def audio_datalist_set_volume(datalist, volume):
    """ Change value of list of audio chunks """
    sound_level = (volume / 100.)

    for i in range(len(datalist)):
        chunk = numpy.fromstring(datalist[i], numpy.int16)

        chunk = chunk * sound_level

        datalist[i] = chunk.astype(numpy.int16)


问:
Same JMX Mbean class for many application at same server
I have more than 5 spring web application and all of them are utilizing another common library. This common library has its own MBeans. Because of mandatory unique objectName constraint, my applications could not be deployed on same server.

The way I am using MBeans are like this:

```<code>@ManagedResource(objectName = "com.org.city:name=City", description = "City related operations")
</code>```

I would like to use same MBean class with different objectNames for all applications. What is the correct way to utilize it without duplicating my MBeans.

Thanks

答:
I have implemented ObjectNamingStrategy for custom behaviour. </p>

```<code>   @Override
  public ObjectName getObjectName(Object managedBean, String beanKey) throws MalformedObjectNameException {
     Class managedClass = AopUtils.getTargetClass(managedBean);
     Hashtable<String, String> properties = new Hashtable<String, String>();
     properties.put("type",ClassUtils.getPackageName(managedClass).concat(".").concat(ClassUtils.getShortName(managedClass)));
     properties.put("name", beanKey);
     return ObjectNameManager.getInstance(domain, properties);
  }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have more than 5 spring web application and all of them are utilizing another common library. This common library has its own MBeans. Because of mandatory unique objectName constraint, my applications could not be deployed on same server.

The way I am using MBeans are like this:

@ManagedResource(objectName = "com.org.city:name=City", description = "City related operations")

I would like to use same MBean class with different objectNames for all applications. What is the correct way to utilize it without duplicating my MBeans.

Thanks

Body:
I have implemented ObjectNamingStrategy for custom behaviour.

   @Override
  public ObjectName getObjectName(Object managedBean, String beanKey) throws MalformedObjectNameException {
     Class managedClass = AopUtils.getTargetClass(managedBean);
     Hashtable<String, String> properties = new Hashtable<String, String>();
     properties.put("type",ClassUtils.getPackageName(managedClass).concat(".").concat(ClassUtils.getShortName(managedClass)));
     properties.put("name", beanKey);
     return ObjectNameManager.getInstance(domain, properties);
  }


问:
split combined pdf into original documents
Is there a way of identifying individual documents in a combined pdf and split it accordingly?

The pdf I am working on contains combined scans (with OCR, mostly) of individual documents. I would like to split it back into the original documents.

These original documents are of unstandardised length and size (hence, adobe's split by "Number of pages" or "File Size" are not an option). The "Top level bookmarks" seem to correspond to something different than individual documents, so splitting on them does not provide a useful result either.

I've created an xml version of the file. I'm not too familiar with it but having looked at it, I couldn't identify a standardised tag or something similar that indicates the start of a new document.

The answer to this question requires control over the merging process (which I don't have), while the answer to this question does not work because I have no standardised keyword on which to split.

Eventually, I would like to do this split for a few hundred pdfs. An example of a pdf to be split can be found here.

答:
As per discussions in comments one course of action is to parse the pages information (MediaBox) via python. However I prefer a few fast cmd line commands rather than write and test a heavier solution on this lightweight netbook.

Thus I would build a script to handle a loop of files and pass to windows console the files using Xpdf command line tools

Edit Actually most Python libs tend to include the poppler version (2022-01) of pdfinfo so you should be able to call or request feedback from that variant via your libs.

Using PDFinfo on your file and limit it to first 20 pages for a quick test is

pdfinfo -f 1 -l 20 yourfile.pdf
and the response will be  a text output suitable for comparison:-

```<code>Title:          Microsoft Word - 20190702_Revision_CO2_Verordnung_Detailkommenta
re_SWISS_final
Subject:
Keywords:
Author:         heim
Creator:        PDF24 Creator
Producer:       GPL Ghostscript 9.25
CreationDate:   Thu Jul 18 17:36:26 2019
ModDate:        Thu Jul 18 17:36:26 2019
Tagged:         no
Form:           none
Pages:          223
Encrypted:      no
Page    1 size: 595 x 842 pts (A4) (rotated 0 degrees)
Page    2 size: 595 x 842 pts (A4) (rotated 0 degrees)
Page    3 size: 595.32 x 841.92 pts (A4) (rotated 0 degrees)
Page    4 size: 595.44 x 842.04 pts (A4) (rotated 0 degrees)
Page    5 size: 595.44 x 842.04 pts (A4) (rotated 0 degrees)
Page    6 size: 595.2 x 841.9 pts (A4) (rotated 0 degrees)
Page    7 size: 595.45 x 841.9 pts (A4) (rotated 0 degrees)
Page    8 size: 595.45 x 841.9 pts (A4) (rotated 0 degrees)
Page    9 size: 595.2 x 841.44 pts (rotated 0 degrees)
Page   10 size: 595.2 x 841.44 pts (rotated 0 degrees)
Page   11 size: 595.2 x 841.68 pts (rotated 0 degrees)
Page   12 size: 594.54 x 840.78 pts (rotated 0 degrees)
Page   13 size: 591.85 x 835.45 pts (rotated 0 degrees)
Page   14 size: 593.75 x 835.45 pts (rotated 0 degrees)
Page   15 size: 595.2 x 841.44 pts (rotated 0 degrees)
Page   16 size: 595.32 x 841.92 pts (A4) (rotated 0 degrees)
Page   17 size: 593.5 x 840.7 pts (rotated 0 degrees)
Page   18 size: 594.72 x 840.96 pts (rotated 0 degrees)
Page   19 size: 596 x 842 pts (A4) (rotated 0 degrees)
Page   20 size: 595.2 x 841.68 pts (rotated 0 degrees)
File size:      33926636 bytes
Optimized:      no
PDF version:    1.4
</code>```

In a command line I would possibly only use the desired page ### and size: values (discarding the verbage) to make line by line match analysis easier.

We can see that in this case, as suspected by @mkl, there is some commonality in sequential pages.

The above is less than a 10% sample and may not represent the full picture but its promising enough to pair either X or Y values in sequential pages. I ran 200 pages (on this slow machine in seconds) and the output slowly flashing by had sufficient similarities to suggest this is a viable part answer to build upon.

The majority of pairs are matched in first value but the oddity was 13 & 14 which matched in the second value, HOWEVER note number 6 matches second value with 7 & 8 but is not the same document, thus cross checking such cases may be desired.

Body:
As per discussions in comments one course of action is to parse the pages information (MediaBox) via python. However I prefer a few fast cmd line commands rather than write and test a heavier solution on this lightweight netbook.

Thus I would build a script to handle a loop of files and pass to windows console the files using Xpdf command line tools

Edit Actually most Python libs tend to include the poppler version (2022-01) of pdfinfo so you should be able to call or request feedback from that variant via your libs.

Using PDFinfo on your file and limit it to first 20 pages for a quick test is

pdfinfo -f 1 -l 20 yourfile.pdf
and the response will be  a text output suitable for comparison:-

Title:          Microsoft Word - 20190702_Revision_CO2_Verordnung_Detailkommenta
re_SWISS_final
Subject:
Keywords:
Author:         heim
Creator:        PDF24 Creator
Producer:       GPL Ghostscript 9.25
CreationDate:   Thu Jul 18 17:36:26 2019
ModDate:        Thu Jul 18 17:36:26 2019
Tagged:         no
Form:           none
Pages:          223
Encrypted:      no
Page    1 size: 595 x 842 pts (A4) (rotated 0 degrees)
Page    2 size: 595 x 842 pts (A4) (rotated 0 degrees)
Page    3 size: 595.32 x 841.92 pts (A4) (rotated 0 degrees)
Page    4 size: 595.44 x 842.04 pts (A4) (rotated 0 degrees)
Page    5 size: 595.44 x 842.04 pts (A4) (rotated 0 degrees)
Page    6 size: 595.2 x 841.9 pts (A4) (rotated 0 degrees)
Page    7 size: 595.45 x 841.9 pts (A4) (rotated 0 degrees)
Page    8 size: 595.45 x 841.9 pts (A4) (rotated 0 degrees)
Page    9 size: 595.2 x 841.44 pts (rotated 0 degrees)
Page   10 size: 595.2 x 841.44 pts (rotated 0 degrees)
Page   11 size: 595.2 x 841.68 pts (rotated 0 degrees)
Page   12 size: 594.54 x 840.78 pts (rotated 0 degrees)
Page   13 size: 591.85 x 835.45 pts (rotated 0 degrees)
Page   14 size: 593.75 x 835.45 pts (rotated 0 degrees)
Page   15 size: 595.2 x 841.44 pts (rotated 0 degrees)
Page   16 size: 595.32 x 841.92 pts (A4) (rotated 0 degrees)
Page   17 size: 593.5 x 840.7 pts (rotated 0 degrees)
Page   18 size: 594.72 x 840.96 pts (rotated 0 degrees)
Page   19 size: 596 x 842 pts (A4) (rotated 0 degrees)
Page   20 size: 595.2 x 841.68 pts (rotated 0 degrees)
File size:      33926636 bytes
Optimized:      no
PDF version:    1.4

In a command line I would possibly only use the desired page ### and size: values (discarding the verbage) to make line by line match analysis easier.

We can see that in this case, as suspected by @mkl, there is some commonality in sequential pages.

The above is less than a 10% sample and may not represent the full picture but its promising enough to pair either X or Y values in sequential pages. I ran 200 pages (on this slow machine in seconds) and the output slowly flashing by had sufficient similarities to suggest this is a viable part answer to build upon.

The majority of pairs are matched in first value but the oddity was 13 & 14 which matched in the second value, HOWEVER note number 6 matches second value with 7 & 8 but is not the same document, thus cross checking such cases may be desired.


问:
How to chunk a list in Python 3?
I found the following code that is compatible with python2

```<code>from itertools import izip_longest
def grouper(n, iterable, padvalue=None):
  "grouper(3, 'abcdefg', 'x') --> ('a','b','c'), ('d','e','f'), ('g','x','x')"
  return izip_longest(*[iter(iterable)]*n, fillvalue=padvalue)
</code>```

However, this isn't working with Python 3. I get the following error

```<code>ImportError: cannot import name izip_longest
</code>```

Can someone help?

I'd like to convert my list of [1,2,3,4,5,6,7,8,9] to [[1,2,3],[4,5,6],[7,8,9]]

Edit

Now Python3 compatible

Code below is adapted from the selected answer. Simply change name from izip_longest to zip_longest.

```<code>from itertools import zip_longest
def grouper(n, iterable, padvalue=None):
  "grouper(3, 'abcdefg', 'x') --> ('a','b','c'), ('d','e','f'), ('g','x','x')"
  return zip_longest(*[iter(iterable)]*n, fillvalue=padvalue)
</code>```

答:
```<code>s = [1,2,3,4,5,6,7,8,9]
size = 4
chuck_list = [s[i:i+size] for i in range(0, len(s), size)]
</code>```

Title: How to chunk a list in Python 3?

Body:
I found the following code that is compatible with python2

from itertools import izip_longest
def grouper(n, iterable, padvalue=None):
  "grouper(3, 'abcdefg', 'x') --> ('a','b','c'), ('d','e','f'), ('g','x','x')"
  return izip_longest(*[iter(iterable)]*n, fillvalue=padvalue)

However, this isn't working with Python 3. I get the following error

ImportError: cannot import name izip_longest

Can someone help?

I'd like to convert my list of [1,2,3,4,5,6,7,8,9] to [[1,2,3],[4,5,6],[7,8,9]]

Edit

Now Python3 compatible

Code below is adapted from the selected answer. Simply change name from izip_longest to zip_longest.

from itertools import zip_longest
def grouper(n, iterable, padvalue=None):
  "grouper(3, 'abcdefg', 'x') --> ('a','b','c'), ('d','e','f'), ('g','x','x')"
  return zip_longest(*[iter(iterable)]*n, fillvalue=padvalue)


问:
how to add space between textbox and browse button for input file type
Can we add space between the browse button and textbox for input type file ?Is that possible? Aslo can i add border color for the same  textbox ?

thanks,

michaeld

答:
You should use css to do this:
Your html:

```<code>    <input type="text" class="yourclass" name="yourname" />
    <input type="submit" />
</code>```

your css:

```<code>    <style> input.yourclass { border:1px solid red; margin-right: 10px;} </style>
</code>```

Hope this puts you in the right direction

Body:
You should use css to do this:
Your html:

    <input type="text" class="yourclass" name="yourname" />
    <input type="submit" />

your css:

    <style> input.yourclass { border:1px solid red; margin-right: 10px;} </style>

Hope this puts you in the right direction


问:
Need help to sorting an array in a complicated way c# linq
I have a strict similar to this :

```<code>struct Chunk
 {
   public float d; // distance from player
   public bool active; // is it active
 }
</code>```

I have an array of this struct.

What I need:

I need to sort it so the first element is an inactive chunk that is also the furthest from the player, than the next element is active and is also the closest to the player and that is the pattern,

Inactive, furthest

Active, closest

Inactive, furthest

Active, closest

Inactive, furthest
And so on...

Currently I'm using LINQ,
And I'm doing this :

```<code>chunk = chunk.AsParallel().OrderBy(x => x.active ? x.d : -x.d).ToArray();
</code>```

But I don't know how to make it alternate one after another.

答:
It looks like you want to split this into two lists, sort them, then interleave them.</p>
```<code>var inactive = chunk.Where(x => !x.active).OrderByDescending(x => x.d);
var active = chunk.Where(x => x.active).OrderBy(x => x.d);
var interleaved = inactive.Zip(active, (a, b) => new [] { a, b }).SelectMany(x => x);
</code>```

Body:
I have a strict similar to this :

struct Chunk
 {
   public float d; // distance from player
   public bool active; // is it active
 }

I have an array of this struct.

What I need:

I need to sort it so the first element is an inactive chunk that is also the furthest from the player, than the next element is active and is also the closest to the player and that is the pattern,

Inactive, furthest

Active, closest

Inactive, furthest

Active, closest

Inactive, furthest
And so on...

Currently I'm using LINQ,
And I'm doing this :

chunk = chunk.AsParallel().OrderBy(x => x.active ? x.d : -x.d).ToArray();

But I don't know how to make it alternate one after another.

Body:
It looks like you want to split this into two lists, sort them, then interleave them.

var inactive = chunk.Where(x => !x.active).OrderByDescending(x => x.d);
var active = chunk.Where(x => x.active).OrderBy(x => x.d);
var interleaved = inactive.Zip(active, (a, b) => new [] { a, b }).SelectMany(x => x);


问:
ffmpeg using multiple filters
I'm kinda new to ffmpeg, but I found it quite useful to turn image sequences into sprite sheet, but I need to skip frames. I've tried this but it skip the 1st filter. How could I make both -vf work?</p>
```<code>ffmpeg -start_number 0150 -i %04d.png -vf framestep=10 -vf "tile=12x30" -an -vsync 0 spritesheet.png
</code>```

答:
If you use the same option two times then only its last occurence counts. You need to use one -filter_complex instead of two -vf filters, for example:

-filter_complex "[0:v]framestep=10[a];[a]tile=12x30[out]" -map [out]:v

Title: ffmpeg using multiple filters

Body:
I'm kinda new to ffmpeg, but I found it quite useful to turn image sequences into sprite sheet, but I need to skip frames. I've tried this but it skip the 1st filter. How could I make both -vf work?

ffmpeg -start_number 0150 -i %04d.png -vf framestep=10 -vf "tile=12x30" -an -vsync 0 spritesheet.png


问:
setContentView(R.Layout.main) vs startActivity(intent), which is more common?
Please tell me the difference between using startActivity(intent) and setContentView(R.Layout.main)

Which is more preferable and which should be used in which conditions?

I think when we like to perform any action we use startActivity(intent) and just to move in different page we use setContentView(R.Layout.main)

答:
If you use startActivity, in the new Activity's onCreate, you will also set the contentView(). So, with respect to time, setContentView alone is faster, since it doesn't start a new activity. Hence, your app will show the new screen faster...

On the other hand, if you call startActivity, this activity is put on the stack, so you can go back by pressing the back button. By using setContentView, you have to either manually configure the backbutton to go back to your previous layout...

Depending on the type of application, you have to determine which is best for you.
For example, to chrome-to-phone source code, shows that google uses setContentView for the complete setup phase of the app. It is faster, and they put back-buttons on the bottom of the screen to go back. Pressing the physical back-button will stop the Activity. Using this approach, they use one activity for multiple screens to gather all info needed to complete the setup.

Once the setup is complete, Google switches to the startActivity methods, to perform different actions. Here, the app uses different activities for the different tasks the users can do. Each activity is kind of a stand-alone activity, with the back button allowing for quickly switching between them.

Hope this points you in the right direction


问:
Multiline comments on field in protobuf
How to write multiline comments for message fields in .proto fields?
Official doc is not says about it.
For example I have message:

message LocationResponse {
  City city = 1; // city info, will be filled only when `with_city` option is requested
  Country country = 2; // country info, will be filled only when `with_country` option is requested
  repeated Subdivision subdivisions = 3; // subdivisions info, will be filled only when `with_subdivisions` option is requested
}
```

答:
```<code>message LocationResponse {
  // city info, will be filled only when `with_city`
  // option is requested
  City city = 1;
  // country info, will be filled only when `with_country`
  // option is requested
  Country country = 2;
  // subdivisions info, will be filled only when `with_subdivisions`
  // option is requested
  repeated Subdivision subdivisions = 3;
}
</code>```

Title: Multiline comments on field in protobuf


问:
How to pass params into link using React router v6?
This is my main section class where all routes to the links is kept

```<code>export default class Section extends React.Component {
    render() {
        return (
            <div style={{backgroundColor:"white"}}>
                   <Routes>
                   <Route path="/"  element={<Home/>} />
                    <Route path="/discover" element={<Discover/>}   />
                    <Route path="/shop/makeup" element={<Makeup/>}  />
                    <Route path="/home/:id" element={<DetailsPage/>}  />
                    </Routes>
            </div>
        )}}
</code>```

This is my card page which is getting data from the context.

```<code>import React from 'react';
import {DataContext} from './CardData.js';
import {Link} from 'react-router-dom'
import '../App.css';
export default class HomeCard extends React.Component {
    static contextType = DataContext;
    render(){
        const {products} = this.context;
  return (
    <div>
      <div className="card">
                { products.map((val,index)=>{
                   return(
                    <div className="card" key={val.id}>
                    <Card style={{ width: '14rem' }}  className="cardhead">
  <Card.Img variant="top" src={val.imgsrc} className="cardimg"/>
  <Card.Body>
    <Card.Text>{val.mname}
    </Card.Text>
    <Card
</code>```

From here i had passed the val.id to the url of the page using LINK

```<code>    <Link to={`/home/${val.id}`}>
    <Button className="overlay" variant="primary">
      {/* <a  style={{color:"white"}} href={props.link} className="card-link">View</a> */}
      View</Button> </Link>
    <Card.Text><strong>{val.price}</strong>
    </Card.Text>
    <Card.Text><strong>{val.id}</strong>
    </Card.Text>
    </Card.Footer>
  </Card.Body>
</Card>
</div>);
    </div>
  )}}
</code>```

I want to access the the link url into the details page of my product which is as follows :

```<code>export default class DetailsPage extends React.Component {
    static contextType = DataContext;
    state = {
        product: []
    }
    getProduct = () =>{
        if(this.props.match.params.id){
            const res = this.context.products;
            const data = res.filter(item =>{
                return item.id === this.props.match.params.id
            })
            this.setState({product: data})
        }};
    componentDidMount(){
        this.getProduct();
    }
    render() {
        const {product} = this.state;
        const {addCart} = this.context;
        return (
            <>
                {product.map(item =>(
                        <div className="details" key={item.id}>
                            <img src={item.imgsrc} alt=""/>
                            <div className="box">
                                <div className="row">
                                    <h2>{item.mname}</h2>
                                    <span>${item.price}</span>
                                </div>
                                <Link to="/cart" className="cart" onClick={() => addCart(item.id)}>
                                    Add to cart
                                </Link>
                            </div>   </div>  ))} </> )  }}
</code>```

Unfortunately it is giving an error saying TypeError: Cannot read property 'params' of undefined

答:
Using react-router-dom v6

Parent component (App)

<Route path="/something/:id" element={<Something />} />
```
<h3>Child component (Something) </h3>
<pre class="lang-js prettyprint-override"><code>import { useParams } from "react-router-dom";

const Something = (props) => {

    let { id } = useParams();

    useEffect(() => {
        console.log(`/something/${id}`);
    },[]);

    // .....

}
</code>```

Body:
This is my main section class where all routes to the links is kept

export default class Section extends React.Component {
    render() {
        return (

                   <Routes>
                   <Route path="/"  element={<Home/>} />
                    <Route path="/discover" element={<Discover/>}   />
                    <Route path="/shop/makeup" element={<Makeup/>}  />
                    <Route path="/home/:id" element={<DetailsPage/>}  />
                    </Routes>

        )}}

This is my card page which is getting data from the context.

import React from 'react';
import {DataContext} from './CardData.js';
import {Link} from 'react-router-dom'
import '../App.css';
export default class HomeCard extends React.Component {
    static contextType = DataContext;
    render(){
        const {products} = this.context;
  return (

                { products.map((val,index)=>{
                   return(

                    <Card style={{ width: '14rem' }}  className="cardhead">
  <Card.Img variant="top" src={val.imgsrc} className="cardimg"/>
  <Card.Body>
    <Card.Text>{val.mname}
    </Card.Text>
    <Card

From here i had passed the val.id to the url of the page using LINK

    <Link to={`/home/${val.id}`}>
    <Button className="overlay" variant="primary">
      {/* View */}
      View</Button> </Link>
    <Card.Text>{val.price}
    </Card.Text>
    <Card.Text>{val.id}
    </Card.Text>
    </Card.Footer>
  </Card.Body>
</Card>

);

  )}}

I want to access the the link url into the details page of my product which is as follows :

export default class DetailsPage extends React.Component {
    static contextType = DataContext;
    state = {
        product: []
    }
    getProduct = () =>{
        if(this.props.match.params.id){
            const res = this.context.products;
            const data = res.filter(item =>{
                return item.id === this.props.match.params.id
            })
            this.setState({product: data})
        }};
    componentDidMount(){
        this.getProduct();
    }
    render() {
        const {product} = this.state;
        const {addCart} = this.context;
        return (
            <>
                {product.map(item =>(

{item.mname}

                                    ${item.price}

                                <Link to="/cart" className="cart" onClick={() => addCart(item.id)}>
                                    Add to cart
                                </Link>

  ))} </> )  }}

Unfortunately it is giving an error saying TypeError: Cannot read property 'params' of undefined

Body:
Using react-router-dom v6

Parent component (App)

<Route path="/something/:id" element={<Something />} />

Child component (Something)

import { useParams } from "react-router-dom";

const Something = (props) => {

    let { id } = useParams();

    useEffect(() => {
        console.log(`/something/${id}`);
    },[]);

    // .....

}


问:
How to change name of java library when build with gradle?
I'm trying to build a java library for my other java projects. I'm also trying to learn gradle. There is a tutorial : https://docs.gradle.org/current/samples/sample_building_java_libraries.html shows how to build libraries with gradle.

But somehow when I use gradlew build it always gives me lib-< version >.jar and creates a folder called lib and I can't change it.

This is my settings.gradle

```<code>rootProject.name = 'myOwnLibrary'
include('lib')
</code>```

this is my build.gradle (inside lib folder)

```<code>plugins {
    // Apply the java-library plugin for API and implementation separation.
    id 'java-library'
}

version = "0.1.1"

tasks.named('jar') {
    manifest {
        attributes('Implementation-Title': project.name,
                'Implementation-Version': project.version)
    }
}

repositories {
    // Use JCenter for resolving dependencies.
    jcenter()
}

dependencies {
    // Use JUnit test framework.
    testImplementation 'junit:junit:4.13'

    // This dependency is exported to consumers, that is to say, found on their compile classpath.
    api 'org.apache.commons:commons-math3:3.6.1'

    // This dependency is used internally, and not exposed to consumers on their own compile classpath.
    implementation 'com.google.guava:guava:29.0-jre'
}
</code>```

答:
With Kotlin DSL example, you can add in your tasks jar the following snippet:

tasks.jar {
    manifest {
        attributes(mapOf("Implementation-Title" to rootProject.name,
                         "Implementation-Version" to project.version))
    }
    archiveBaseName.set(rootProject.name)
}
```

where rootProject.name, is the value localized into settings.gradle.kts file.

Body:
I'm trying to build a java library for my other java projects. I'm also trying to learn gradle. There is a tutorial : https://docs.gradle.org/current/samples/sample_building_java_libraries.html shows how to build libraries with gradle.

But somehow when I use gradlew build it always gives me lib-< version >.jar and creates a folder called lib and I can't change it.

This is my settings.gradle

rootProject.name = 'myOwnLibrary'
include('lib')

this is my build.gradle (inside lib folder)

plugins {
    // Apply the java-library plugin for API and implementation separation.
    id 'java-library'
}

version = "0.1.1"

tasks.named('jar') {
    manifest {
        attributes('Implementation-Title': project.name,
                'Implementation-Version': project.version)
    }
}

repositories {
    // Use JCenter for resolving dependencies.
    jcenter()
}

dependencies {
    // Use JUnit test framework.
    testImplementation 'junit:junit:4.13'

    // This dependency is exported to consumers, that is to say, found on their compile classpath.
    api 'org.apache.commons:commons-math3:3.6.1'

    // This dependency is used internally, and not exposed to consumers on their own compile classpath.
    implementation 'com.google.guava:guava:29.0-jre'
}

Body:
With Kotlin DSL example, you can add in your tasks jar the following snippet:

tasks.jar {
    manifest {
        attributes(mapOf("Implementation-Title" to rootProject.name,
                         "Implementation-Version" to project.version))
    }
    archiveBaseName.set(rootProject.name)
}

where rootProject.name, is the value localized into settings.gradle.kts file.


问:
Azure BICEP deploy if doesn't already exist
I'm not sure if this is possible, but what I'm trying to do is create a virtual network from one virtualNetwork.main.bicep file and then create a subnet from another subnet.main.bicep within the virtual network. Now I can do this, but the problem I have is if I rerun the virtual network virtualNetwork.main.bicep it will remove any subnets that have been created by the subnet.main.bicep file

I know I can just add all subnets to the virtualNetwork.main.bicep but the idea is that I can hand over the creation of subnets to other people whilst maintaining a global networking configuration.

So is there any way that I can only stop the virtual network file from deleting what's already there?

Hope this makes sense.

Cheers

答:
Checking to see if a resource already exists is an ask in Bicep that isn't yet implemented.

Further, you're looking at creating a virtual network from multiple modules and I fear you're going to be disappointed there as well, as that's not really supported per the discussion here. The guidance provided here suggests:

It is instead recommended to create all the subnets in the array property inside of the vnet

And unfortunately this suggests that you have to create all the subnets at once to accommodate the API shortcomings. Sorry!


问:
Java on VSCode Extension Pack for Java can't detect jdk
I am trying to run java on vscode however the 'Extension Pack for Java' keeps asking me to redownload the jdk. I am able to run java on intellij and have been using that but since I use vscode for everything else I would like to get it to work on my main editor.

Here are the settings related to java

"java.help.firstView": "gettingStarted",
    "java.home":"/Library/Java/JavaVirtualMachines/amazon-corretto-17.jdk/Contents/Home/bin/java",
    "java.jdt.ls.java.home": "/Library/Java/JavaVirtualMachines/amazon-corretto-17.jdk/Contents/Home/bin/java",
    "java.configuration.runtimes": [
  {
    "name": "JavaSE-17",
    "path": "/Library/Java/JavaVirtualMachines/microsoft-17.jdk/Contents/Home/bin/java",
  },
  {
    "name": "JavaSE-17",
    "path": "/Library/Java/JavaVirtualMachines/temurin-17.jdk/Contents/Home/bin/java",
  },
  {
    "name": "JavaSE-17",
    "path": "/Library/Java/JavaVirtualMachines/amazon-corretto-17.jdk/Contents/Home/bin/java",
    "default": true
  },
],```

enter image description here

Error
The java.home variable defined in Visual Studio Code settings points to a missing or inaccessible folder (/Library/Java/JavaVirtualMachines/adoptopenjdk-17.jdk/Contents/Home)

any ideas?

All other languages I use work fine, it just seems to be java.

答:
Assume you are using the latest Java extensions, here are some suggestions:

java.home has been deprecated, please don't use it and use java.jdt.ls.java.home instead

The latest Java extension already embeds a jre 17, you can find it in $home/.vscode/extensions/redhat.java-1.x.0/jre. Ideally there is no need to specify java.jdt.ls.java.home, unless your platform is not covered.

If your platform is not covered, then you need to manually set java.jdt.ls.java.home, which should point to the home path of your JDK installation. So please update it to /Library/Java/JavaVirtualMachines/amazon-corretto-17.jdk/Contents/Home.

java.configuration.runtimes is used to map different JDK versions to their installation path. Please make sure each version only appear once in this setting.

Body:
I am trying to run java on vscode however the 'Extension Pack for Java' keeps asking me to redownload the jdk. I am able to run java on intellij and have been using that but since I use vscode for everything else I would like to get it to work on my main editor.

Here are the settings related to java

"java.help.firstView": "gettingStarted",
    "java.home":"/Library/Java/JavaVirtualMachines/amazon-corretto-17.jdk/Contents/Home/bin/java",
    "java.jdt.ls.java.home": "/Library/Java/JavaVirtualMachines/amazon-corretto-17.jdk/Contents/Home/bin/java",
    "java.configuration.runtimes": [
  {
    "name": "JavaSE-17",
    "path": "/Library/Java/JavaVirtualMachines/microsoft-17.jdk/Contents/Home/bin/java",
  },
  {
    "name": "JavaSE-17",
    "path": "/Library/Java/JavaVirtualMachines/temurin-17.jdk/Contents/Home/bin/java",
  },
  {
    "name": "JavaSE-17",
    "path": "/Library/Java/JavaVirtualMachines/amazon-corretto-17.jdk/Contents/Home/bin/java",
    "default": true
  },
],

enter image description here

Error
The java.home variable defined in Visual Studio Code settings points to a missing or inaccessible folder (/Library/Java/JavaVirtualMachines/adoptopenjdk-17.jdk/Contents/Home)

any ideas?

All other languages I use work fine, it just seems to be java.


问:
R: instrument function to capture all assignments
Given a regular R function f, I'd like to be able to create a new function f_debug that acts just like f, but lets me keep track of all the assignments to function-local variables that happened inside it.

For example:

f <- function(x, y) {
  z <- x + y
  df <- data.frame(z=z)
  df
}

# This function doesn't work as intended - would like it to (in the case of `f` above)
# write out a list containing `z` and `df` to an RDS file
capturing <- function(func) {
  e <- new.env()
  altered <- function(...) {
    parent <- parent.frame()
    e <- something...(func, environment(), parent, etc., etc.)
    result <- func(...)
    saveRDS(as.list(e), 'foo.rds')
    result
  }
  environment(func) <- e
  altered
}

f_debug <- capturing(f)
```

I'm not sure whether my knowledge gap to do this is large or small, anyone have a solution?

答:
What you are describing is already implemented in base R with utils::dump.frames, in an even more sophisticated way. It saves the frame (environment) associated with each call in the call stack to an object of class "dump.frames", which you can explore retroactively with utils::debugger as if you had actually run your code under a debugger.

capturing <- function(func, ...) {
    cc <- as.call(c(quote(utils::dump.frames), list(...)))
    cc <- call("on.exit", cc, add = TRUE)
    body(func) <- call("{", cc, body(func))
    func
}
```
<p><code>capturing</code> injects the call <code>on.exit(utils::dump.frames(...), add = TRUE)</code> into the body of <code>func</code> and returns the modified function.
Here, <code>...</code> is a list of arguments to <code>dump.frames</code>:</p>
<ul>
<li><code>dumpto</code>, a character string giving the name to be used for the <code>"dump.frames"</code> object</li>
<li><code>to.file</code>, a logical flag indicating whether the <code>"dump.frames"</code> object should be assigned in the global environment or <code>save</code>-ed to <code>paste0(dumpto, ".rda")</code> in the current working directory</li>
<li><code>include.GlobalEnv</code>, a logical flag indicating whether the global environment should be saved as well</li>
</ul>
<p>A quick example, which you should try yourself:</p>
<pre class="lang-r prettyprint-override"><code>tmp <- tempfile()
dir.create(tmp)
cwd <- setwd(tmp)

f <- function(x, y) {
    z <- x + y
    z + 1
}
g <- capturing(f, dumpto = "zzz", to.file = TRUE)
h <- function(a, b) {
    d <- g(a, b)
    d + 1
}
h12 <- h(1, 2)

load("zzz.rda")
zzz
## $`h(1, 2)`
## <environment: 0x14c16cb58>
##
## $`#2: g(a, b)`
## <environment: 0x14c16ca40>
##
## attr(,"error.message")
## [1] ""
## attr(,"class")
## [1] "dump.frames"

ls(zzz[[1L]])
## [1] "a" "b"

ls(zzz[[2L]])
## [1] "z" "x" "y"

utils::debugger(zzz)
## Message:  Available environments had calls:
## 1: h(1, 2)
## 2: #2: g(a, b)
##
## Enter an environment number, or 0 to exit
## Selection: 2
## Browsing in the environment with call:
##    #2: g(a, b)
## Called from: debugger.look(ind)
## Browse[1]> ls()
## [1] "x" "y" "z"
## Browse[1]> x == 1 && y == 2 && z == x + y
## [1] TRUE
## Browse[1]> Q

setwd(cwd)
unlink(tmp, recursive = TRUE)
</code>```

See ?browser if you are unfamiliar with R's environment browser.

My capturing function has the limitation that on.exit calls in the body of func must also use add = TRUE. If you have written func yourself, then it is not much of a limitation at all, and passing add = TRUE is a good habit anyway.

Ultimately, there is no completely safe way to inject code into functions, but, in an interactive setting, I would say that this level of "unsafety" is fine.

Body:
Given a regular R function f, I'd like to be able to create a new function f_debug that acts just like f, but lets me keep track of all the assignments to function-local variables that happened inside it.

For example:

f <- function(x, y) {
  z <- x + y
  df <- data.frame(z=z)
  df
}

# This function doesn't work as intended - would like it to (in the case of `f` above)
# write out a list containing `z` and `df` to an RDS file
capturing <- function(func) {
  e <- new.env()
  altered <- function(...) {
    parent <- parent.frame()
    e <- something...(func, environment(), parent, etc., etc.)
    result <- func(...)
    saveRDS(as.list(e), 'foo.rds')
    result
  }
  environment(func) <- e
  altered
}

f_debug <- capturing(f)

I'm not sure whether my knowledge gap to do this is large or small, anyone have a solution?

Body:
What you are describing is already implemented in base R with utils::dump.frames, in an even more sophisticated way. It saves the frame (environment) associated with each call in the call stack to an object of class "dump.frames", which you can explore retroactively with utils::debugger as if you had actually run your code under a debugger.

capturing <- function(func, ...) {
    cc <- as.call(c(quote(utils::dump.frames), list(...)))
    cc <- call("on.exit", cc, add = TRUE)
    body(func) <- call("{", cc, body(func))
    func
}

capturing injects the call on.exit(utils::dump.frames(...), add = TRUE) into the body of func and returns the modified function.
Here, ... is a list of arguments to dump.frames:

dumpto, a character string giving the name to be used for the "dump.frames" object

to.file, a logical flag indicating whether the "dump.frames" object should be assigned in the global environment or save-ed to paste0(dumpto, ".rda") in the current working directory

include.GlobalEnv, a logical flag indicating whether the global environment should be saved as well

A quick example, which you should try yourself:

tmp <- tempfile()
dir.create(tmp)
cwd <- setwd(tmp)

f <- function(x, y) {
    z <- x + y
    z + 1
}
g <- capturing(f, dumpto = "zzz", to.file = TRUE)
h <- function(a, b) {
    d <- g(a, b)
    d + 1
}
h12 <- h(1, 2)

load("zzz.rda")
zzz
## $`h(1, 2)`
## <environment: 0x14c16cb58>
##
## $`#2: g(a, b)`
## <environment: 0x14c16ca40>
##
## attr(,"error.message")
## [1] ""
## attr(,"class")
## [1] "dump.frames"

ls(zzz[[1L]])
## [1] "a" "b"

ls(zzz[[2L]])
## [1] "z" "x" "y"

utils::debugger(zzz)
## Message:  Available environments had calls:
## 1: h(1, 2)
## 2: #2: g(a, b)
##
## Enter an environment number, or 0 to exit
## Selection: 2
## Browsing in the environment with call:
##    #2: g(a, b)
## Called from: debugger.look(ind)
## Browse[1]> ls()
## [1] "x" "y" "z"
## Browse[1]> x == 1 && y == 2 && z == x + y
## [1] TRUE
## Browse[1]> Q

setwd(cwd)
unlink(tmp, recursive = TRUE)

See ?browser if you are unfamiliar with R's environment browser.

My capturing function has the limitation that on.exit calls in the body of func must also use add = TRUE. If you have written func yourself, then it is not much of a limitation at all, and passing add = TRUE is a good habit anyway.

Ultimately, there is no completely safe way to inject code into functions, but, in an interactive setting, I would say that this level of "unsafety" is fine.


问:
Is there any relation between fps and how fast a surfaces moves on the screen?
Here is an example code:

import pygame
import sys

pygame.init()
screen = pygame.display.set_mode((1000, 500))

clock = pygame.time.Clock()

square = pygame.Surface((350, 350))
square.fill((0, 0, 0))
x_pos = 1000

while True:
    screen.fill((255, 255, 255))
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

    if x_pos <= -350:
        x_pos = 1000
    x_pos -= 5
    screen.blit(square, (x_pos, 50))

    clock.tick(60)
    pygame.display.update()
```

Questions:

1 - Does the .tick() method defines how many fps your game runs at? If not, what does it actually do?

2 - The higher the value passed in the .tick() method, the faster the square on the example goes to the left, why does that happen?

3 - Assuming that the .tick() method defines how many fps your game is going to run at, in some games like valorant, league of legends and any other game, when the fps is higher, the game only looks smoother, not faster like in the examples, is there any reason for that?

Thanks!

答:
pygame.tick() is just fps. You can read more about it at https://www.pygame.org/docs/ref/time.html#pygame.time.Clock.tick

You can think of FPS as how many times the while loops runs every second. If you run x_pos += 1 every frame, the higher the FPS, the more times that line of code will run; In return, the more times that line of code runs, the faster the square moves.

The reason games look smoother at higher FPS is because of the refresh rate on your monitor (Hz). The refresh rate is literally how many times your monitor updates, meaning if your FPS is lower than your Hz, it will look clunky. Any FPS above your monitors refresh rate won't affect your experience in any way.

The reason other games don't get faster with higher FPS is because of delta time, which takes the time elapsed between each frame and changes the move speed based on how many milliseconds passed. (Feel free to add more/correct me in comments)

If you're curious about how to implement delta time in pygame, I recommend watching https://www.youtube.com/watch?v=XuyrHE6GIsc

Body:
Here is an example code:

import pygame
import sys

pygame.init()
screen = pygame.display.set_mode((1000, 500))

clock = pygame.time.Clock()

square = pygame.Surface((350, 350))
square.fill((0, 0, 0))
x_pos = 1000

while True:
    screen.fill((255, 255, 255))
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

    if x_pos <= -350:
        x_pos = 1000
    x_pos -= 5
    screen.blit(square, (x_pos, 50))

    clock.tick(60)
    pygame.display.update()

Questions:

1 - Does the .tick() method defines how many fps your game runs at? If not, what does it actually do?

2 - The higher the value passed in the .tick() method, the faster the square on the example goes to the left, why does that happen?

3 - Assuming that the .tick() method defines how many fps your game is going to run at, in some games like valorant, league of legends and any other game, when the fps is higher, the game only looks smoother, not faster like in the examples, is there any reason for that?

Thanks!


问:
Group URLs into single object output in API response
So I'll try to explain this as best as possible, but I'm having some issues with how the links are being rendered so I'll go into more detail below.

Here is the full method:

```<code>public function link_urls($text)
{
    if (!$urls = $this->get('entities', 'urls')) {
        return $text;
    }
    foreach ($urls as $url) {
        $text = str_replace(
            $url->url,
            '<a href="' . $url->url . '" target="_blank">' . $url->display_url . '</a>',
            $text
        );
    }

    return $text;
}
</code>```

What this method does is it takes the ['text'] param response from the API and then it goes through and searches for URLs and appends HTML outputs.

Let's say that we have $text which outputs the following tweet data:

```<code>string(316) “As we continue to celebrate #BlackHistoryMonth , our next Black Artist Spotlight  is local painter @EbonyLewisArt https:// t.co/LaRa7GDk4i”
</code>```

This particular tweet has 4 images, but Twitter groups them all into one "tweet" link as shown above.

Next, I'm checking the tweets $urls object that it returns, which is $urls = $this->get('entities', 'urls') which gives me:

```<code>object(stdClass)#1958 (5) {
  ["start"]=>
  int(115)
  ["end"]=>
  int(138)
  ["url"]=>
  string(23) "https:// t.co/LaRa7GDk4i"
  ["expanded_url"]=>
  string(65) "https://twitter.com/dallasmavs/status/1491079415375495168/photo/1"
  ["display_url"]=>
  string(26) "pic.twitter.com/LaRa7GDk4i"
}
object(stdClass)#1737 (5) {
  ["start"]=>
  int(115)
  ["end"]=>
  int(138)
  ["url"]=>
  string(23) "https:// t.co/LaRa7GDk4i"
  ["expanded_url"]=>
  string(65) "https://twitter.com/dallasmavs/status/1491079415375495168/photo/1"
  ["display_url"]=>
  string(26) "pic.twitter.com/LaRa7GDk4i"
}
object(stdClass)#1735 (5) {
  ["start"]=>
  int(115)
  ["end"]=>
  int(138)
  ["url"]=>
  string(23) "https:// t.co/LaRa7GDk4i"
  ["expanded_url"]=>
  string(65) "https://twitter.com/dallasmavs/status/1491079415375495168/photo/1"
  ["display_url"]=>
  string(26) "pic.twitter.com/LaRa7GDk4i"
}
object(stdClass)#1736 (5) {
  ["start"]=>
  int(115)
  ["end"]=>
  int(138)
  ["url"]=>
  string(23) "https:// t.co/LaRa7GDk4i"
  ["expanded_url"]=>
  string(65) "https://twitter.com/dallasmavs/status/1491079415375495168/photo/1"
  ["display_url"]=>
  string(26) "pic.twitter.com/LaRa7GDk4i"
}
</code>```

Here is the problem:

I'm calling a foreach loop which grabs all the URLs and converts $url->url with an  tag and displaying the $url->display_url as shown below:

```<code>foreach ($urls as $url) {
    $text = str_replace(
        $url->url,
        '<a href="' . $url->url . '" target="_blank">' . $url->display_url . '</a>',
        $text
    );
}
</code>```

The problem is that $text just has one URL to look on and the foreach loops through 4 times which causes issues and outputs the following:

As we continue to celebrate #BlackHistoryMonth , our next Black Artist
Spotlight  is local painter @EbonyLewisArt
pic.twitter.com/LaRa7GDk4i”
target=”_blank”>pic.twitter.com/LaRa7GDk4i”
target=”_blank”>pic.twitter.com/LaRa7GDk4i”
target=”_blank”>pic.twitter.com/LaRa7GDk4i

When I have one $urls object with one link in $text it's perfectly fine, the problem shows up when Twitter groups the links in $text and outputs multiple objects.

Here are my questions:

If there are multiple objects which are exactly the same, can I delete the other objects and just output one?

In the foreach, if the objects are the same, can I somehow skip all but one?

All help is appreciated on this!

答:
Kindly change your foreach loop to this

```<code>foreach ($urls as $url) {
    if( strpos($text, $url->url) !== false ){
        $text = str_replace(
            $url->url,
            '<a href="' . str_replace(' ', '', $url->url) . '" target="_blank">' . $url->display_url . '</a>',
            $text
        );
        break;
    }
}
</code>```

Body:
So I'll try to explain this as best as possible, but I'm having some issues with how the links are being rendered so I'll go into more detail below.

Here is the full method:

public function link_urls($text)
{
    if (!$urls = $this->get('entities', 'urls')) {
        return $text;
    }
    foreach ($urls as $url) {
        $text = str_replace(
            $url->url,
            'url . '" target="_blank">' . $url->display_url . '',
            $text
        );
    }

    return $text;
}

What this method does is it takes the ['text'] param response from the API and then it goes through and searches for URLs and appends HTML outputs.

Let's say that we have $text which outputs the following tweet data:

string(316) “As we continue to celebrate #BlackHistoryMonth , our next Black Artist Spotlight  is local painter @EbonyLewisArt https:// t.co/LaRa7GDk4i”

This particular tweet has 4 images, but Twitter groups them all into one "tweet" link as shown above.

Next, I'm checking the tweets $urls object that it returns, which is $urls = $this->get('entities', 'urls') which gives me:

object(stdClass)#1958 (5) {
  ["start"]=>
  int(115)
  ["end"]=>
  int(138)
  ["url"]=>
  string(23) "https:// t.co/LaRa7GDk4i"
  ["expanded_url"]=>
  string(65) "https://twitter.com/dallasmavs/status/1491079415375495168/photo/1"
  ["display_url"]=>
  string(26) "pic.twitter.com/LaRa7GDk4i"
}
object(stdClass)#1737 (5) {
  ["start"]=>
  int(115)
  ["end"]=>
  int(138)
  ["url"]=>
  string(23) "https:// t.co/LaRa7GDk4i"
  ["expanded_url"]=>
  string(65) "https://twitter.com/dallasmavs/status/1491079415375495168/photo/1"
  ["display_url"]=>
  string(26) "pic.twitter.com/LaRa7GDk4i"
}
object(stdClass)#1735 (5) {
  ["start"]=>
  int(115)
  ["end"]=>
  int(138)
  ["url"]=>
  string(23) "https:// t.co/LaRa7GDk4i"
  ["expanded_url"]=>
  string(65) "https://twitter.com/dallasmavs/status/1491079415375495168/photo/1"
  ["display_url"]=>
  string(26) "pic.twitter.com/LaRa7GDk4i"
}
object(stdClass)#1736 (5) {
  ["start"]=>
  int(115)
  ["end"]=>
  int(138)
  ["url"]=>
  string(23) "https:// t.co/LaRa7GDk4i"
  ["expanded_url"]=>
  string(65) "https://twitter.com/dallasmavs/status/1491079415375495168/photo/1"
  ["display_url"]=>
  string(26) "pic.twitter.com/LaRa7GDk4i"
}

Here is the problem:

I'm calling a foreach loop which grabs all the URLs and converts $url->url with an  tag and displaying the $url->display_url as shown below:

foreach ($urls as $url) {
    $text = str_replace(
        $url->url,
        'url . '" target="_blank">' . $url->display_url . '',
        $text
    );
}

The problem is that $text just has one URL to look on and the foreach loops through 4 times which causes issues and outputs the following:

As we continue to celebrate #BlackHistoryMonth , our next Black Artist
Spotlight  is local painter @EbonyLewisArt
pic.twitter.com/LaRa7GDk4i”
target=”_blank”>pic.twitter.com/LaRa7GDk4i”
target=”_blank”>pic.twitter.com/LaRa7GDk4i”
target=”_blank”>pic.twitter.com/LaRa7GDk4i

When I have one $urls object with one link in $text it's perfectly fine, the problem shows up when Twitter groups the links in $text and outputs multiple objects.

Here are my questions:

If there are multiple objects which are exactly the same, can I delete the other objects and just output one?

In the foreach, if the objects are the same, can I somehow skip all but one?

All help is appreciated on this!

Body:
Kindly change your foreach loop to this

foreach ($urls as $url) {
    if( strpos($text, $url->url) !== false ){
        $text = str_replace(
            $url->url,
            '<a href="' . str_replace(' ', '', $url->url) . '" target="_blank">' . $url->display_url . '</a>',
            $text
        );
        break;
    }
}


问:
AZURE: Can I host NuGet.Server in Azure?
I want to host a nuget.server to share private nuget packages with my dev team.

This link:
https://learn.microsoft.com/en-us/nuget/hosting-packages/nuget-server

shows me how to build a nuget.server, but it says that it needs to run under IIS.

Can I deploy a nuget.server application to azure instead of running it under IIS?

It looks like Azure artifacts requires using a CI/CD pipeline, but my dev team is not up to using pipelines yet.  For now, all applications are manually deployed to production from Visual Studio.

Any suggestions?

答:
Yes you can setup private NuGet Server outside Azure DevOps, but need more setting for the purpose of access.
Of course, you can use private NuGet Server inside Azure DevOps, you can find it in Azure DevOps - Artifacts - Create Feed.

Please review zivkan's comments about how to setup a private NuGet Server.

You must create service connection in Azure DevOps if you want to access(restore/push) your private NuGet Server outside Azure DevOps.

How to setup NuGet service connection:
Azure DevOps - Project Setting - Service Connections - New Service Connection - NuGet

Then you can use added NuGet service connection in your pipeline.


问:
How to trigger azure logic app from Google pubsub service
I need to create an Azure logic app that listen to google cloud pubsub, consume the message and do a JSON transform.
Is there a simple way to directly trigger Azure Logic App when a new message in Google pubsub?

答:
As of now, there is no direct or simple way to connect to Google Pubsub through Logic apps you can have a look at Google Connectors and Azure Logic App connectors for further details

Also, you can raise a feature request in Azure Feedback Portal and Microsoft Q&A which also be helpful for other community members who want to have a similar connection.


问:
Assign multiple properties of an object with primeng's p-dropdown
I have an object like this assigned to the ngmodel:

```<code>export class operator {
  id: string;
  name: string;
  numUser: number;
  storeName: string;
  storeCode: number;
  activeOn: string;
}
</code>```

and on my dropdown i'm assigning a list of objects like this (I'll call it "option" for now):

```<code>[
  {
    "storeCode": 2,
    "storeName": "storeName",
    "dateOfRegistration": "12/12/12",
    "inHbltAtuCrra": "string1",
    "inNegoPmt": "string2"
  },
]
</code>```

So, in my html I want to, if this 'option' is selected, assign storeCode and storeName to the Operator object. Is there even a way to do that? I couldn't find anything, just one property with [(ngModel)]="operator.storeCode".

My p-dropdown:

```<code>  <p-dropdown
    [showClear]="true"
    [options]="stores"
    [(ngModel)]="operator.storeCode"
    [filter]="true"
    optionLabel="storeName"
    optionValue="storeCode"
    filterBy="storeName"
    placeholder="Choose store"
  >
  </p-dropdown>
</code>```

答:
Delete the optionValue line and the value will be the entire object by default.

```
<p>If you only need a few properties use the <code>onChange</code> event</p>
<pre class="lang-html prettyprint-override"><code>  <p-dropdown
    [showClear]="true"
    [options]="stores"
    (onChange)="onChange($event)"
    [filter]="true"
    optionLabel="storeName"
    filterBy="storeName"
    placeholder="Choose store"
  >
  </p-dropdown>
</code>```

Then in the component.ts

onChange(op: operator){
  this.operator.storeCode = op.storeCode;
  this.operator.storeName = op.storeName;
}
```

Body:
I have an object like this assigned to the ngmodel:

export class operator {
  id: string;
  name: string;
  numUser: number;
  storeName: string;
  storeCode: number;
  activeOn: string;
}

and on my dropdown i'm assigning a list of objects like this (I'll call it "option" for now):

[
  {
    "storeCode": 2,
    "storeName": "storeName",
    "dateOfRegistration": "12/12/12",
    "inHbltAtuCrra": "string1",
    "inNegoPmt": "string2"
  },
]

So, in my html I want to, if this 'option' is selected, assign storeCode and storeName to the Operator object. Is there even a way to do that? I couldn't find anything, just one property with [(ngModel)]="operator.storeCode".

My p-dropdown:

Body:
Delete the optionValue line and the value will be the entire object by default.

  <p-dropdown
    [showClear]="true"
    [options]="stores"
    [(ngModel)]="operator"
    [filter]="true"
    optionLabel="storeName"
    filterBy="storeName"
    placeholder="Choose store"
  >
  </p-dropdown>

If you only need a few properties use the onChange event

  <p-dropdown
    [showClear]="true"
    [options]="stores"
    (onChange)="onChange($event)"
    [filter]="true"
    optionLabel="storeName"
    filterBy="storeName"
    placeholder="Choose store"
  >
  </p-dropdown>

Then in the component.ts

onChange(op: operator){
  this.operator.storeCode = op.storeCode;
  this.operator.storeName = op.storeName;
}


问:
Aggregate jsonb object inside nested jsonb object array without expanding the array in PostgreSQL
Let's say I have a city model that has a neighborhood model which contains jsonb[] field of families, which is an array containing jsonb objects, each object has a data object inside with count and income fields

ID
data

123
{"city": {"neighborhood": {"families": [{"name": "Miller","data": {"count": 3,"income": 1200}},{"name": "Bennet","data": {"count": 4,"income": 700}}]}}}

456
{"city": {"neighborhood": {"families": [{"name": "Olsen","data": {"count": 7,"income": 1100}},{"name": "Yang","data": {"count": 1,"income": 7000}}]}}}

I want to aggregate the maximum count for each row, so the required output will be

ID
count

123
4

456
7

I can achieve it with a subquery using jsonb_each to expand each family to a row and then aggregate the results, but I'm worried about the performance impact of this operation because each row may contains many families,
Do I have a way to do it without expanding the results?

答:
```<code>select
    main.id,
    max(main."count") as "count"
from
    (
        select
            t1.id,
            (jsonb_array_elements_text(t2.value::jsonb)::jsonb->'data'->'count')::integer as "count"
        from table1 t1
        join jsonb_each_text(t1."data"->'city'->'neighborhood') t2 on true
    ) main
group by main.id
</code>```

Result of this query:

id
count

456
7

123
4

Body:
select
    main.id,
    max(main."count") as "count"
from
    (
        select
            t1.id,
            (jsonb_array_elements_text(t2.value::jsonb)::jsonb->'data'->'count')::integer as "count"
        from table1 t1
        join jsonb_each_text(t1."data"->'city'->'neighborhood') t2 on true
    ) main
group by main.id

Result of this query:

id
count

456
7

123
4


问:
MS Access SQL "INSERT INTO" statement produces date in wrong format despite correct regional setting
My computer's regional date setting is dd/mm/yyyy. I am using MS Access. I would like to insert records into a database using the SQL INSERT INTO statement. When I try to insert a date using the #dd/mm/yyyy# syntax, and view the resulting record in the table after, it turns out the record displays the date in the format mm/dd/yyyy instead, but ONLY for the first 10 days of the month; if the day is 11 onwards, the record displays dd/mm/yyyy as intended.

For example if in SQL code I input #09/02/2022#, the table will display the record with the date 02/09/2022 instead. However if my SQL code is#11/02/2022#, then the correct order 11/02/2022 is shown in the record.

Please help.

答:
Ok, the way this works?

You don't have to care, know, or think about the users regional format settings.

So, if you drop some control on a form? Just make sure that control is set to a date type format. Your done.

BUT ONE big whopper:

IN ANY AND ALL cases, your string based date format MUST be in USA format. Or you can use ISO date format.

```<code> dim MyDate   as Date

 MyDate = me.InvoiceDate
</code>```

So, now we have a internal format date variable. How to insert into a table?

```<code>dim strSQL  as string

strSQL = "INSERT INTO tblInvoice (InvoiceNum, InvoiceDate, InvoiceAmount " & _
         "VALUES (1234, " & quDate(MyDate) & ",50)"
</code>```

So, you ALWAYS format the date value into USA format.

You can type that format command over and over, but that fast becomes tiring.

so, I use a little helper function:

```<code>Public Function quDate(dt As Date) As String

   quDate = "#" & Format(dt, "mm\/dd\/yyyy") & "#"

End Function

Public Function quDateT(dt As Date) As String

     ' return formatted date  with time

     quDateT = "#" & Format(dt, "mm\/dd\/yyyy HH:NN:SS") & "#"

  End Function
</code>```

So, you don't have to care about the date and regional format, but for a in-line SQL insert command that you build in code? Yes, you MUST convert to USA format of mm/dd/yyyy.

So, you can display dates in any format. For forms, for reports - not a problem.

However, the ONLY exception here is your code that builds a insert statement. That date string format must be #mm/dd/yyyy#.

Or, ISO:

```<code> #yyyy-mm-dd#
</code>```

So, either format is fine, but it is a hard and fast rule that you must conform to.

So, from a text box on a form, if not data bound, then you want to ensure that the text box is set as a date type text box (fomrat date).

then in code:

```<code>dim strSQL as string

strSQL = "INSERT INTO tblFun (BirthDate) " & _
        "VALUES (#" & format(txtDate,"mm/dd/yyyy") & "#)"

currentdb.Execute strSQL
</code>```

Or, if you have that helper function, then this:

```<code>strSQL = "INSERT INTO tblFun (BirthDate) " & _
        "VALUES (" & qudate(txtDate) & ")"

</code>```

Body:
Ok, the way this works?

You don't have to care, know, or think about the users regional format settings.

So, if you drop some control on a form? Just make sure that control is set to a date type format. Your done.

BUT ONE big whopper:

IN ANY AND ALL cases, your string based date format MUST be in USA format. Or you can use ISO date format.

 dim MyDate   as Date

 MyDate = me.InvoiceDate

So, now we have a internal format date variable. How to insert into a table?

dim strSQL  as string

strSQL = "INSERT INTO tblInvoice (InvoiceNum, InvoiceDate, InvoiceAmount " & _
         "VALUES (1234, " & quDate(MyDate) & ",50)"

So, you ALWAYS format the date value into USA format.

You can type that format command over and over, but that fast becomes tiring.

so, I use a little helper function:

Public Function quDate(dt As Date) As String

   quDate = "#" & Format(dt, "mm\/dd\/yyyy") & "#"

End Function

Public Function quDateT(dt As Date) As String

     ' return formatted date  with time

     quDateT = "#" & Format(dt, "mm\/dd\/yyyy HH:NN:SS") & "#"

  End Function

So, you don't have to care about the date and regional format, but for a in-line SQL insert command that you build in code? Yes, you MUST convert to USA format of mm/dd/yyyy.

So, you can display dates in any format. For forms, for reports - not a problem.

However, the ONLY exception here is your code that builds a insert statement. That date string format must be #mm/dd/yyyy#.

Or, ISO:

 #yyyy-mm-dd#

So, either format is fine, but it is a hard and fast rule that you must conform to.

So, from a text box on a form, if not data bound, then you want to ensure that the text box is set as a date type text box (fomrat date).

then in code:

dim strSQL as string

strSQL = "INSERT INTO tblFun (BirthDate) " & _
        "VALUES (#" & format(txtDate,"mm/dd/yyyy") & "#)"

currentdb.Execute strSQL

Or, if you have that helper function, then this:

strSQL = "INSERT INTO tblFun (BirthDate) " & _
        "VALUES (" & qudate(txtDate) & ")"


问:
How can I convert a gpa calculator to use upper and lower case grade arguments?
I am creating a GPA calculator which takes in 4 grades and gives the GPA. I want it to be able to use upper case letters 'A' and lower case letters 'a' and so on through 'F' 'f'. Right now it will only use upper case letters. How can I convert it to use both without changing the dictionary?</p>
```<code>import sys
def gpa_calculator(grade1, grade2, grade3, grade4):
    points = 0
    i = 0
    grade_c ={'A':4.0, 'A-':3.66, 'B+':3.33, 'B':3.0,
      'B-':2.66,'C+':2.33,'C':2.0,'C-':1.66,'D+':1.33,'D':1.00,'D-':.66,'F':0.00}

    if grades != []:
        for grade in grades:
            points += grade_c[grade]
        gpa = points / len(grades)
        return gpa
    else:
        return None

    grade1 = sys.argv[1]
    grade2 = sys.argv[2]
    grade3 = sys.argv[3]
    grade4 = sys.argv[4]

    grades = grade1, grade2, grade3, grade4
    grades = gpa_calculator(grade1, grade2, grade3, grade4)
    print('My GPA is',(grades))
</code>```

答:
You have at least two options

1  Add the "lower case" version of the keys to the dictionary as the dictionary key is case-sensitive. Thereby creating a larger dictionary and somewhat unnecessary repeated code.

```<code>grade_c = {'A':4.0, 'A-':3.66, 'B+':3.33, 'B':3.0, 'B-':2.66,'C+':2.33,'C':2.0,'C-':1.66,'D+':1.33,'D':1.00,'D-':.66,'F':0.00, 'a':4.0, 'a-':3.66, 'b+':3.33, 'b':3.0, 'b-':2.66,'c+':2.33,'c':2.0,'c-':1.66,'d+':1.33,'d':1.00,'d-':.66,'f':0.00 }
</code>```

Keep your dictionary as is and take the passed in command line arguments and use the str.upper() method to convert and store them as uppercase. The user can pass in either any case and it will be converted to uppercase for handling by your current dictionary and code.

    grade1 = sys.argv[1].upper()
    grade2 = sys.argv[2].upper()
    grade3 = sys.argv[3].upper()
    grade4 = sys.argv[4].upper()
```

Body:
I am creating a GPA calculator which takes in 4 grades and gives the GPA. I want it to be able to use upper case letters 'A' and lower case letters 'a' and so on through 'F' 'f'. Right now it will only use upper case letters. How can I convert it to use both without changing the dictionary?

import sys
def gpa_calculator(grade1, grade2, grade3, grade4):
    points = 0
    i = 0
    grade_c ={'A':4.0, 'A-':3.66, 'B+':3.33, 'B':3.0,
      'B-':2.66,'C+':2.33,'C':2.0,'C-':1.66,'D+':1.33,'D':1.00,'D-':.66,'F':0.00}

    if grades != []:
        for grade in grades:
            points += grade_c[grade]
        gpa = points / len(grades)
        return gpa
    else:
        return None

    grade1 = sys.argv[1]
    grade2 = sys.argv[2]
    grade3 = sys.argv[3]
    grade4 = sys.argv[4]

    grades = grade1, grade2, grade3, grade4
    grades = gpa_calculator(grade1, grade2, grade3, grade4)
    print('My GPA is',(grades))

Body:
You have at least two options

1  Add the "lower case" version of the keys to the dictionary as the dictionary key is case-sensitive. Thereby creating a larger dictionary and somewhat unnecessary repeated code.

grade_c = {'A':4.0, 'A-':3.66, 'B+':3.33, 'B':3.0, 'B-':2.66,'C+':2.33,'C':2.0,'C-':1.66,'D+':1.33,'D':1.00,'D-':.66,'F':0.00, 'a':4.0, 'a-':3.66, 'b+':3.33, 'b':3.0, 'b-':2.66,'c+':2.33,'c':2.0,'c-':1.66,'d+':1.33,'d':1.00,'d-':.66,'f':0.00 }

Keep your dictionary as is and take the passed in command line arguments and use the str.upper() method to convert and store them as uppercase. The user can pass in either any case and it will be converted to uppercase for handling by your current dictionary and code.

    grade1 = sys.argv[1].upper()
    grade2 = sys.argv[2].upper()
    grade3 = sys.argv[3].upper()
    grade4 = sys.argv[4].upper()


问:
How to "reverse" string that acts as a date time?
I'm working on a Vue project and I have a textfield that takes "date-time" to string variable like this DD-MM-YYYY.

I want to convert it to MySQL format (YYYY-MM-DD)

Example input: 24-05-2022

Example output: 2022-05-24

So since

```<code>dateInput: '24-05-2022'
dateInput.split("").reverse().join("")
</code>```

Would change the dateInput value to:

```<code>2202-50-42
</code>```

I'm wondering how to reverse the string without affecting numbers next to eachother?

EDIT -------------------------------------------------------------------------------------------------------

Forgot to mention I'm using NuxtJs with Vue so the syntax is a little different.

Works now with:

Data

```<code>dateInput: '24-05-2022',
array: [],
newDate: ''
</code>```

Methods

```<code>reverseDate () {
    this.array = this.dateInput.split('-')
    this.newDate = this.array[2] + '-' + this.array[1] + '-' + this.array[0]
}
</code>```

Created

```<code>this.reverseDate()
</code>```

答:
Your first try was close to be correct, you just missed including the '-'.
This code would also work:

let dateInput = '24-05-2022';
let reversed = dateInput.split('-').reverse().join('-');
console.log(reversed) // outputs: 2022-05-24
```

And if you would need a Date object, new Date(reversed) works like a charm.

Body:
I'm working on a Vue project and I have a textfield that takes "date-time" to string variable like this DD-MM-YYYY.

I want to convert it to MySQL format (YYYY-MM-DD)

Example input: 24-05-2022

Example output: 2022-05-24

So since

dateInput: '24-05-2022'
dateInput.split("").reverse().join("")

Would change the dateInput value to:

2202-50-42

I'm wondering how to reverse the string without affecting numbers next to eachother?

EDIT -------------------------------------------------------------------------------------------------------

Forgot to mention I'm using NuxtJs with Vue so the syntax is a little different.

Works now with:

Data

dateInput: '24-05-2022',
array: [],
newDate: ''

Methods

reverseDate () {
    this.array = this.dateInput.split('-')
    this.newDate = this.array[2] + '-' + this.array[1] + '-' + this.array[0]
}

Created

this.reverseDate()

Body:
Your first try was close to be correct, you just missed including the '-'.
This code would also work:

let dateInput = '24-05-2022';
let reversed = dateInput.split('-').reverse().join('-');
console.log(reversed) // outputs: 2022-05-24

And if you would need a Date object, new Date(reversed) works like a charm.


问:
Java Micro Edition (JME) SDK for Mac OS X or Linux
The question is clear from the title.

Is there an SDK for the Java Micro Edition available for Mac OS X or Linux? Or does one need Windows XP to develop JME applications?

答:
May be this is helpful, I've found a Java ME Developer Studio for Mac OS X, developed by Motorola, I haven't tested yet, it's only and EA Release, I'll try this one, and I'll let u know in a subsequent post,

http://developer.motorola.com/docstools/motodevstudio/javame/downloads/

Cheers

OwnerDisplayName: hhafez

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Chris Hanson

OwnerDisplayName: Mark Devlyn


问:
R GAM visualisation - Negative Binomial
This is a follow on question from my question answered by previously for a generic gaussian GAM model in R. This time I tried running a negative binomial GAM with the same dataset and I have attached the plot below. I am not sure if it is plotting what I want it to, as it is showing both two error intervals instead of how the previous GAM showed just the modelled error interval. [.

```<code>mod_gam3 <-gam(y ~s(ï..x), data=Bird.data, family=nb, method="REML)

mod_gam3$fitted.values
result <-data.frame(data = c(mod_gam3$fitted.values, Bird.data$y),
Year =rep(1991:2019, times ``= 2), 'source' = c(rep('Modelled', times = 29),
rep('Observed', times = 29)))
result$se=c(predict(mod_gam3, se=T)$se, rep(NA,29))

ggplot(result, aes(x=Year, y =data, colour= source, fill=source))+
geom_point()+
geom_smooth(aes(ymin=data-1.96*se, ymax=+1.96*se), alpha=0.2)+
labs(x="Year", y ="Bird Island Total Debris Count")+
scale_y_continous(limits =c(-200,1000))
</code>```

答:
There seem to a number of typos in your code above.

I think best to pass your data directly to ggplot, and specify within the geom_smooth() function, the method, the formula, and the method.args.

```<code>ggplot(Bird.data, aes(x,y)) +
  geom_point() +
  geom_smooth(method="gam", formula=y~s(x), method.args=list(family="nb", method="REML"))
</code>```

Update: if you want to approximate the plot that you get from the direct method, above, but this time adding markers for the actual predicted data points at the same points where you have data, you can estimate ymin and ymax directly, and then generate the plot like this:

```<code>mod_gam3 <-gam(y ~s(x), data=Bird.data, family="nb", method="REML")

result <-data.frame(
  data = c(mod_gam3$fitted.values, Bird.data$y),
  Year =rep(1991:2019, times = 2),
  source = c(rep('Modelled', times = 29),
             rep('Observed', times = 29)
             )
  )
result$se=c(predict(mod_gam3, se=T)$se, rep(NA,29))

## set ymin and ymax columns properly
result$ymin = exp(log(result$data)-1.96*result$se)
result$ymax = exp(log(result$data)+1.96*result$se)

ggplot(result, aes(x=Year, y =data, colour= source, fill=source))+
  geom_point() +
  geom_line(data = result[result$source=="Modelled",]) +
  geom_ribbon(
    data = result[result$source=="Modelled",],
    aes(x=Year,ymin=ymin, ymax=ymax),alpha=0.2)+
  labs(x="Year", y ="Bird Island Total Debris Count")

</code>```

Title: R GAM visualisation - Negative Binomial

Body:
This is a follow on question from my question answered by previously for a generic gaussian GAM model in R. This time I tried running a negative binomial GAM with the same dataset and I have attached the plot below. I am not sure if it is plotting what I want it to, as it is showing both two error intervals instead of how the previous GAM showed just the modelled error interval. [.

mod_gam3 <-gam(y ~s(ï..x), data=Bird.data, family=nb, method="REML)

mod_gam3$fitted.values
result <-data.frame(data = c(mod_gam3$fitted.values, Bird.data$y),
Year =rep(1991:2019, times ``= 2), 'source' = c(rep('Modelled', times = 29),
rep('Observed', times = 29)))
result$se=c(predict(mod_gam3, se=T)$se, rep(NA,29))

ggplot(result, aes(x=Year, y =data, colour= source, fill=source))+
geom_point()+
geom_smooth(aes(ymin=data-1.96*se, ymax=+1.96*se), alpha=0.2)+
labs(x="Year", y ="Bird Island Total Debris Count")+
scale_y_continous(limits =c(-200,1000))

Body:
There seem to a number of typos in your code above.

I think best to pass your data directly to ggplot, and specify within the geom_smooth() function, the method, the formula, and the method.args.

ggplot(Bird.data, aes(x,y)) +
  geom_point() +
  geom_smooth(method="gam", formula=y~s(x), method.args=list(family="nb", method="REML"))

Update: if you want to approximate the plot that you get from the direct method, above, but this time adding markers for the actual predicted data points at the same points where you have data, you can estimate ymin and ymax directly, and then generate the plot like this:

mod_gam3 <-gam(y ~s(x), data=Bird.data, family="nb", method="REML")

result <-data.frame(
  data = c(mod_gam3$fitted.values, Bird.data$y),
  Year =rep(1991:2019, times = 2),
  source = c(rep('Modelled', times = 29),
             rep('Observed', times = 29)
             )
  )
result$se=c(predict(mod_gam3, se=T)$se, rep(NA,29))

## set ymin and ymax columns properly
result$ymin = exp(log(result$data)-1.96*result$se)
result$ymax = exp(log(result$data)+1.96*result$se)

ggplot(result, aes(x=Year, y =data, colour= source, fill=source))+
  geom_point() +
  geom_line(data = result[result$source=="Modelled",]) +
  geom_ribbon(
    data = result[result$source=="Modelled",],
    aes(x=Year,ymin=ymin, ymax=ymax),alpha=0.2)+
  labs(x="Year", y ="Bird Island Total Debris Count")


问:
Python - ezsheets error: KeyError: Status
I tried following the steps in

https://automatetheboringstuff.com/2e/chapter14/

and tried to get the spreadsheet title from a sheet I just created but got the following error.

How can I fix this, can someone please help?

答: In my case, the problem was that I enabled a different API that he app to be enabled. Usually if you encounter this error. Just press the link provided in the error below and follow the steps outlined by Google. This would work fine :)</p>


问:
How can I retrieve Wiktionary word content?
How may Wiktionary's API be used to determine whether or not a word exists?</p>

答: You can download a dump of Wiktionary data.  There's more information in the FAQ.  For your purposes, the definitions dump is probably a better choice than the XML dump.</p>


问:
More elegant (shorter) solution for this regex pattern
I have spent three days banging my head on how to find a single solution to match anything between either single or double quotes with escaped single or doublequotes within actual source string and to replace matching text .. and I think that I have succeeded. Multi-line or single-line - it works. That is, this regex can be used to alter/change/sanitize 'text' or "text" or strings in other words, in any source code *(eg: file_get_contents ('some_class.php')) and to leave everything else untouched, assuming that code comments are already removed before such action.

Here is regex wrapped in singlequotes ..

```<code>'@"[^"\\\\]*(?:\\\\.[^"\\\\]*)*"|\'[^\'\\\\]*(?:\\\\.[^\'\\\\]*)*\'@msu'
</code>```

.. and here is regex wrapped within doublequotes.

```<code>"@\"[^\"\\\\]*(?:\\\\.[^\"\\\\]*)*\"|'[^'\\\\]*(?:\\\\.[^'\\\\]*)*'@msu"
</code>```

It is perfeclty matching with source code like this ...

// Very nasty php array

$Damn = [

  'a' => "' lorem ipsum '",

  'b' => '"\" ipsu\'m lorem  ',

  'c' => " \' YabadabaDooya \" ",

  'd\"' => '

     f"

     o\'"o

                 \'bar" ',

  'e' => "'",

  "f" => '"'

];

```

Since this is working as I expect, and I am actually not a PCRE guru (don't ask how much 'pain' I've had in the past three days D: until I came up to this solution), if there's anyone who knows how, and is willing to help by shrinking the above regex into more elegant/shorter solution, that would be superb. I assume that | (or) in the middle of the pattern can be placed onto beginning, just once .. and I tried God only knows what .. to accomplish that, but no luck.

So, the general question is - how would shorter variant of the above pattern look alike ?

答:
For Spooky, try this Multi-Delimiter Common Core approach

which is mostly your regex.

```<code><<<PCRE

    (["'`])((?:\\.|(?!\1|\\).)*)(\1)

PCRE;
</code>```

https://regex101.com/r/LLWa6L/1

```<code><<<PCRE_EXPLAINED

     ( ["'`] )              # (1), The delimiters
     (                      # (2 start)
        (?:
           \\ .                   # Escape anything
         |                       # or,
           (?! \1 | \\ )          # Not a delimiter nor an escape
           .                      # Any character
        )*
     )                      # (2 end)
     ( \1 )                 # (3), Backreference to the delimiter

PCRE_EXPLAINED;
</code>```

Body:
I have spent three days banging my head on how to find a single solution to match anything between either single or double quotes with escaped single or doublequotes within actual source string and to replace matching text .. and I think that I have succeeded. Multi-line or single-line - it works. That is, this regex can be used to alter/change/sanitize 'text' or "text" or strings in other words, in any source code *(eg: file_get_contents ('some_class.php')) and to leave everything else untouched, assuming that code comments are already removed before such action.

Here is regex wrapped in singlequotes ..

'@"[^"\\\\]*(?:\\\\.[^"\\\\]*)*"|\'[^\'\\\\]*(?:\\\\.[^\'\\\\]*)*\'@msu'

.. and here is regex wrapped within doublequotes.

"@\"[^\"\\\\]*(?:\\\\.[^\"\\\\]*)*\"|'[^'\\\\]*(?:\\\\.[^'\\\\]*)*'@msu"

It is perfeclty matching with source code like this ...

// Very nasty php array

$Damn = [

  'a' => "' lorem ipsum '",

  'b' => '"\" ipsu\'m lorem  ',

  'c' => " \' YabadabaDooya \" ",

  'd\"' => '

     f"

     o\'"o

                 \'bar" ',

  'e' => "'",

  "f" => '"'

];

Since this is working as I expect, and I am actually not a PCRE guru (don't ask how much 'pain' I've had in the past three days D: until I came up to this solution), if there's anyone who knows how, and is willing to help by shrinking the above regex into more elegant/shorter solution, that would be superb. I assume that | (or) in the middle of the pattern can be placed onto beginning, just once .. and I tried God only knows what .. to accomplish that, but no luck.

So, the general question is - how would shorter variant of the above pattern look alike ?

Body:
For Spooky, try this Multi-Delimiter Common Core approach

which is mostly your regex.

<<<PCRE

    (["'`])((?:\\.|(?!\1|\\).)*)(\1)

PCRE;

https://regex101.com/r/LLWa6L/1

<<<PCRE_EXPLAINED

     ( ["'`] )              # (1), The delimiters
     (                      # (2 start)
        (?:
           \\ .                   # Escape anything
         |                       # or,
           (?! \1 | \\ )          # Not a delimiter nor an escape
           .                      # Any character
        )*
     )                      # (2 end)
     ( \1 )                 # (3), Backreference to the delimiter

PCRE_EXPLAINED;


答:
My solution is not clean but it worked (my case is creating a new partition with dynamic name). In your case, using SET to create variables for partition name as well as query.

```<code>SET @pt= concat('p', year(now()), month(now()));

SET @query = concat('select max(ttime) from table partition(', @pt, ')');
</code>```

You can confirm partition name and query syntax by:

```<code>SELECT @pt, @query;
</code>```

Now execute your query:

```<code>PREPARE stmt FROM @query;

EXECUTE stmt;
</code>```

Title: How to select from partition while concatenating its name in MySQL

Body:
I have the same problem like this one:
how to select dynamically in select * from <table_name> partiton (Partition name)? but in Mysql.

When using:

select concat('p', year(now()), month(now()));

Response is:

+----------------------------------------+
| concat('p', year(now()), month(now())) |
+----------------------------------------+
| p20153                                 |
+----------------------------------------+

When trying to use:

select max(ttime) from table partition(select concat('p', year(now()), month(now()))));

I get an error:

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'select concat('p', year(now()), month(now()))))' at line 1

of course when trying select max(ttime) from table partition(p20153) works as expected:

root@localhost [tom]> select max(ttime) from table partition(p20153);
+---------------------+
| max(ttime)          |
+---------------------+
| 2015-03-16 09:54:34 |
+---------------------+
1 row in set (0.00 sec)

Notice the dynamic part is the partition name and not the table name.
Sample data:

root@localhost [tom]> select id, ttime, value from table partition(p20153) limit 10;
+----------+---------------------+----------+
| id       | ttime               | value    |
+----------+---------------------+----------+
| 13964275 | 2015-03-01 00:05:11 | 16450824 |
| 13964291 | 2015-03-01 00:08:12 | 15964352 |
| 13964332 | 2015-03-01 00:09:42 | 14701984 |
| 13964379 | 2015-03-01 00:13:27 |    26128 |
| 13964411 | 2015-03-01 00:16:29 | 11073744 |
| 13964452 | 2015-03-01 00:20:34 | 14747992 |
| 13964486 | 2015-03-01 00:23:35 |   177800 |
| 13964507 | 2015-03-01 00:26:36 | 16786408 |
| 13964542 | 2015-03-01 00:28:28 |  8749552 |
| 13964571 | 2015-03-01 00:31:30 | 16932344 |
+----------+---------------------+----------+
10 rows in set (0.00 sec)

Body:
My solution is not clean but it worked (my case is creating a new partition with dynamic name). In your case, using SET to create variables for partition name as well as query.

SET @pt= concat('p', year(now()), month(now()));

SET @query = concat('select max(ttime) from table partition(', @pt, ')');

You can confirm partition name and query syntax by:

SELECT @pt, @query;

Now execute your query:

PREPARE stmt FROM @query;

EXECUTE stmt;