问:
List items displaying as inline block when function is set to display them as block onclick
So I was trying to make a mobilenav menu, but what happens is when I click on my hamburger, it causes the list items to display as inline-block, but the function is set to display them as block level elements.

HTML

```<code><div class="nav-options">
  <i class="fas fa-bars" onclick="mobilenav()"></i>
  <ul id="myLinks">
    <li>Home</li>
    <li>About</li>
    <li>Contact</li>
  </ul>
</div>
</code>```

CSS

```<code>#myLinks {
    text-align: right;
}

#myLinks li {
    list-style: none;
    display: inline-block;
    padding: 0.5rem 2rem;
    font-size: 20px;
}

.nav-options i {
    display: none;
}

#myLinks li:hover {
    background-color: #ff3f05;
    cursor: pointer;
    transition: all 0.5s;
}
</code>```

CSS for mobile view:

```<code>.nav-options i {
    display: block;
    font-size: 25px;
    text-align: right;
}

.nav-options #myLinks {
    display: none;
    padding: 0px;
}
</code>```

JS

```<code>function mobilenav() {
    var links = document.getElementById("myLinks");
    if (links.style.display === "block") {
        links.style.display = "none";
      } else {
    links.style.display = "block";
  }
}
</code>```

答:
While you are assigning the display property of the
 elements, you are controlling the display property of the
 element. In the solution below I removed the display properties from the CSS file. The load event is fired when the page loads, and both the
 element and the
 element are assigned a display style. Then when the  element is clicked, the click event occurs and the display property is toggled.

let icon = document.getElementById("icon");
var linkContainer = document.getElementById("myLinks"); /*
 element */
var linkElements = document.querySelectorAll('li');     /*
 elements */

window.addEventListener('load', (event) => {
  linkContainer.style.display = "block";

  linkElements.forEach(li => {
    li.style.display = "block";
  });
});

function log() {
  console.clear();
  console.log(`<ul> display style: ${linkContainer.style.display}`);
  console.log(`<li> display style: ${linkElements[0].style.display}`);
}

icon.addEventListener("click", function(e) {
  log();

  if(linkContainer.style.display === "block")
    linkContainer.style.display = "none";
  else
    linkContainer.style.display = "block";
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#myLinks {
  text-align: right;
}
#myLinks li {
  list-style: none;
  /* display: inline-block; */
  padding: 0.5rem 2rem;
  font-size: 20px;
}
.nav-options i {
  display: none;
}
#myLinks li:hover {
  background-color: #ff3f05;
  cursor: pointer;
  transition: all 0.5s;
}
.nav-options i {
  display: block;
  font-size: 25px;
  text-align: right;
}
.nav-options #myLinks {
  display: none;
  padding: 0px;
}</code>```

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" integrity="sha512-9usAa10IRO0HhonpyAIVpjrylPvoDwiPUiKdWk5t3PyolY1cOd4DSE0Ga+ri4AuTroPR5aQvXU9xC6qOPnzFeg==" crossorigin="anonymous" referrerpolicy="no-referrer" />

Home

About

Contact

```

Body:
So I was trying to make a mobilenav menu, but what happens is when I click on my hamburger, it causes the list items to display as inline-block, but the function is set to display them as block level elements.

HTML

Home

About

Contact

CSS

#myLinks {
    text-align: right;
}

#myLinks li {
    list-style: none;
    display: inline-block;
    padding: 0.5rem 2rem;
    font-size: 20px;
}

.nav-options i {
    display: none;
}

#myLinks li:hover {
    background-color: #ff3f05;
    cursor: pointer;
    transition: all 0.5s;
}

CSS for mobile view:

.nav-options i {
    display: block;
    font-size: 25px;
    text-align: right;
}

.nav-options #myLinks {
    display: none;
    padding: 0px;
}

JS

function mobilenav() {
    var links = document.getElementById("myLinks");
    if (links.style.display === "block") {
        links.style.display = "none";
      } else {
    links.style.display = "block";
  }
}

Body:
While you are assigning the display property of the <li> elements, you are controlling the display property of the <ul> element. In the solution below I removed the display properties from the CSS file. The load event is fired when the page loads, and both the <ul> element and the <li> element are assigned a display style. Then when the <i> element is clicked, the click event occurs and the display property is toggled.

let icon = document.getElementById("icon");
var linkContainer = document.getElementById("myLinks"); /* <ul> element */
var linkElements = document.querySelectorAll('li');     /* <li> elements */

window.addEventListener('load', (event) => {
  linkContainer.style.display = "block";

  linkElements.forEach(li => {
    li.style.display = "block";
  });
});

function log() {
  console.clear();
  console.log(`<ul> display style: ${linkContainer.style.display}`);
  console.log(`<li> display style: ${linkElements[0].style.display}`);
}

icon.addEventListener("click", function(e) {
  log();

  if(linkContainer.style.display === "block")
    linkContainer.style.display = "none";
  else
    linkContainer.style.display = "block";
});

#myLinks {
  text-align: right;
}
#myLinks li {
  list-style: none;
  /* display: inline-block; */
  padding: 0.5rem 2rem;
  font-size: 20px;
}
.nav-options i {
  display: none;
}
#myLinks li:hover {
  background-color: #ff3f05;
  cursor: pointer;
  transition: all 0.5s;
}
.nav-options i {
  display: block;
  font-size: 25px;
  text-align: right;
}
.nav-options #myLinks {
  display: none;
  padding: 0px;
}

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" integrity="sha512-9usAa10IRO0HhonpyAIVpjrylPvoDwiPUiKdWk5t3PyolY1cOd4DSE0Ga+ri4AuTroPR5aQvXU9xC6qOPnzFeg==" crossorigin="anonymous" referrerpolicy="no-referrer" />

<div class="nav-options">
  <i id="icon" class="fas fa-bars"></i>

  <ul id="myLinks">
    <li>Home</li>
    <li>About</li>
    <li>Contact</li>
  </ul>
</div>


来源: stackexchange

问:
Add Percentage Sign in Table in R
How do I add percentage sign to this table?
table(sample.1$Department)/50*100

I want to add the percentage sign to the numbers here. E.g. 28%, 46%, 8%, etc.

答:
The object class from table() is a bit obnoxious to work with, unfortunately.

Here is an example using the data from the package palmerpenguins:

```<code>library(palmerpenguins)

t <- table(penguins$species)/50*100
</code>```
```<code>> t

   Adelie Chinstrap    Gentoo
      304       136       248

</code>```
```<code>t2 <- sub("$", "%", t)
names(t2) <- names(t)
</code>```
```<code>> t2
   Adelie Chinstrap    Gentoo
   "304%"    "136%"    "248%"
</code>```

What sub() does here is to match the regex for the end of the element in the table (i.e., $) and to add "%" at the end. Unfortunately, this doesn't keep the header of the table, but it transforms it into a vector with the same order, so we can just overwrite it using names()

ContentLicense: CC BY-SA 4.0

Title: Add Percentage Sign in Table in R

Body:
The object class from table() is a bit obnoxious to work with, unfortunately.

Here is an example using the data from the package palmerpenguins:

library(palmerpenguins)

t <- table(penguins$species)/50*100

> t

   Adelie Chinstrap    Gentoo
      304       136       248

t2 <- sub("$", "%", t)
names(t2) <- names(t)

> t2
   Adelie Chinstrap    Gentoo
   "304%"    "136%"    "248%"

What sub() does here is to match the regex for the end of the element in the table (i.e., $) and to add "%" at the end. Unfortunately, this doesn't keep the header of the table, but it transforms it into a vector with the same order, so we can just overwrite it using names()


问:
.NET error handling
I have been writing .NET applications and have been impressed with the error handling included in the framework.

When catching an error that has been throw by the processes or somewhere in the code I like to include the message (ex.Message, which is usually pretty general) but also the stacktrace (ex.stacktrace) which helps to trace the problem back to a specific spot.

For a simple example let's say for instance that we are recording numbers to a log in a method:

```<code>public void ExampleMethod(int number){
    try{
        int num = number
        ...open connection to file
        ...write number to file
    }
    catch(Exception ex){
        .... deal with exception (ex.message,ex.stacktrace etc...)
    }
    finally{
    ...close file connection
    }
}
</code>```

Is there any way to see the method called (in this case ExampleMethod) with the specific number that was passed that potentially crashed the method call? I believe you could log this perhaps in the catch block but I am interested essentially in catching the method call and parameters that caused the system to throw the exception.

Any ideas?

答:
If you want to know the value of the parameters in your method, then there is only one way, IMO, to do it - you need to repackage the exception with data.

For example:

```<code> int param1 = 10;
 string param2 = "Hello World";

 try
 {
     SomeMethod(param1, param2)
 }
 catch(SomeExpectedException e)
 {
      throw new MyParameterSensitiveException(e, param1, param2);
 }
</code>```

You basically repackage the original exception as the inner exception of another exception, and additionally supply the parameters you used to call the method. Then you could inspect that in some way to figure out what went wrong.

ContentLicense: CC BY-SA 3.0

Title: .NET error handling

Body:
I have been writing .NET applications and have been impressed with the error handling included in the framework.

When catching an error that has been throw by the processes or somewhere in the code I like to include the message (ex.Message, which is usually pretty general) but also the stacktrace (ex.stacktrace) which helps to trace the problem back to a specific spot.

For a simple example let's say for instance that we are recording numbers to a log in a method:

public void ExampleMethod(int number){
    try{
        int num = number
        ...open connection to file
        ...write number to file
    }
    catch(Exception ex){
        .... deal with exception (ex.message,ex.stacktrace etc...)
    }
    finally{
    ...close file connection
    }
}

Is there any way to see the method called (in this case ExampleMethod) with the specific number that was passed that potentially crashed the method call? I believe you could log this perhaps in the catch block but I am interested essentially in catching the method call and parameters that caused the system to throw the exception.

Any ideas?

Body:
If you want to know the value of the parameters in your method, then there is only one way, IMO, to do it - you need to repackage the exception with data.

For example:

 int param1 = 10;
 string param2 = "Hello World";

 try
 {
     SomeMethod(param1, param2)
 }
 catch(SomeExpectedException e)
 {
      throw new MyParameterSensitiveException(e, param1, param2);
 }

You basically repackage the original exception as the inner exception of another exception, and additionally supply the parameters you used to call the method. Then you could inspect that in some way to figure out what went wrong.


问:
Error in pom.xml due to ribbon dependency
Getting the project build error message

```<code>Project build error:
         'dependencies.dependency.version' for org.springframework.cloud:spring-cloud-starter-ribbon:
</code>```

This my pom.xml file.

```<code> <?xml version="1.0" encoding="UTF-8"?>
        <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
            <modelVersion>4.0.0</modelVersion>
            <parent>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-parent</artifactId>
                <version>2.1.4.RELEASE</version>
                <relativePath/> <!-- lookup parent from repository -->
            </parent>
            <groupId>com.in28minutes.microservices</groupId>
            <artifactId>currency-conversion-service</artifactId>
            <version>0.0.1-SNAPSHOT</version>
            <name>currency-conversion-service</name>
            <description>Demo project for Spring Boot</description>

            <properties>
                <java.version>1.8</java.version>
                <spring-cloud.version>Greenwich.SR3</spring-cloud.version>
            </properties>

            <dependencies>
                <dependency>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-actuator</artifactId>
                </dependency>
                <dependency>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-web</artifactId>
                </dependency>
                <dependency>
                    <groupId>org.springframework.cloud</groupId>
                    <artifactId>spring-cloud-starter-config</artifactId>
                </dependency>
                <dependency>
                    <groupId>org.springframework.cloud</groupId>
                     <artifactId>spring-cloud-netflix-core</artifactId>
                </dependency>
                <!-- <dependency>
                    <groupId>org.springframework.cloud</groupId>
                    <artifactId>spring-cloud-starter-ribbon</artifactId>
                </dependency>  -->
                <dependency>
                    <groupId>org.springframework.cloud</groupId>
                    <artifactId>spring-cloud-starter-openfeign</artifactId>
                </dependency>
                <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-ribbon</artifactId>
        </dependency>
                <dependency>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-devtools</artifactId>
                    <scope>runtime</scope>
                    <optional>true</optional>
                </dependency>
                <dependency>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-test</artifactId>
                    <scope>test</scope>
                </dependency>
            </dependencies>

            <dependencyManagement>
                <dependencies>
                    <dependency>
                        <groupId>org.springframework.cloud</groupId>
                        <artifactId>spring-cloud-dependencies</artifactId>
                        <version>${spring-cloud.version}</version>
                        <type>pom</type>
                        <scope>import</scope>
                    </dependency>
                </dependencies>
            </dependencyManagement>

            <build>
                <plugins>
                    <plugin>
                        <groupId>org.springframework.boot</groupId>
                        <artifactId>spring-boot-maven-plugin</artifactId>
                    </plugin>
                </plugins>
            </build>

        </project>
</code>```

答:
You've got to add the spring-cloud-starter-netflix-ribbon dependency in your pom.xml file:

```<code> <dependency>
     <groupId> org.springframework.cloud </groupId>
     <artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
     <version>2.2.10.RELEASE</version>
 </dependency>
</code>```

Body:
Getting the project build error message

Project build error:
         'dependencies.dependency.version' for org.springframework.cloud:spring-cloud-starter-ribbon:

This my pom.xml file.

 <?xml version="1.0" encoding="UTF-8"?>
        <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
            <modelVersion>4.0.0</modelVersion>
            <parent>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-parent</artifactId>
                <version>2.1.4.RELEASE</version>
                <relativePath/>
            </parent>
            <groupId>com.in28minutes.microservices</groupId>
            <artifactId>currency-conversion-service</artifactId>
            <version>0.0.1-SNAPSHOT</version>
            <name>currency-conversion-service</name>
            <description>Demo project for Spring Boot</description>

            <properties>
                <java.version>1.8</java.version>
                <spring-cloud.version>Greenwich.SR3</spring-cloud.version>
            </properties>

            <dependencies>
                <dependency>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-actuator</artifactId>
                </dependency>
                <dependency>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-web</artifactId>
                </dependency>
                <dependency>
                    <groupId>org.springframework.cloud</groupId>
                    <artifactId>spring-cloud-starter-config</artifactId>
                </dependency>
                <dependency>
                    <groupId>org.springframework.cloud</groupId>
                     <artifactId>spring-cloud-netflix-core</artifactId>
                </dependency>

                <dependency>
                    <groupId>org.springframework.cloud</groupId>
                    <artifactId>spring-cloud-starter-openfeign</artifactId>
                </dependency>
                <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-ribbon</artifactId>
        </dependency>
                <dependency>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-devtools</artifactId>
                    <scope>runtime</scope>
                    <optional>true</optional>
                </dependency>
                <dependency>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-test</artifactId>
                    <scope>test</scope>
                </dependency>
            </dependencies>

            <dependencyManagement>
                <dependencies>
                    <dependency>
                        <groupId>org.springframework.cloud</groupId>
                        <artifactId>spring-cloud-dependencies</artifactId>
                        <version>${spring-cloud.version}</version>
                        <type>pom</type>
                        <scope>import</scope>
                    </dependency>
                </dependencies>
            </dependencyManagement>

            <build>
                <plugins>
                    <plugin>
                        <groupId>org.springframework.boot</groupId>
                        <artifactId>spring-boot-maven-plugin</artifactId>
                    </plugin>
                </plugins>
            </build>

        </project>

Body:
You've got to add the spring-cloud-starter-netflix-ribbon dependency in your pom.xml file:

 <dependency>
     <groupId> org.springframework.cloud </groupId>
     <artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
     <version>2.2.10.RELEASE</version>
 </dependency>


问:
How to insert a loop block/statement after scanf
My code is below. I am using C language. I want to repeat the action from the start if the user types Y but I am confused how can I make that happen. I tried to look for a solution but the results are not what I wanted. What should I do about it?</p>
```<code>#include <stdio.h>

int main(){

int A,B;
char Y, N, C;

        printf("Enter value 1: ");
        scanf("%i", &B);
        printf("\nEnter value 2: ");
        scanf("%i", &A);

printf("= %i", A+B);

printf("\n\nAdd again? Y or N\n");
scanf("%c", &C);

if (C==Y){
    This should contain code that will repeat the action again.
}
else if(C==N){
    printf("PROGRAM USE ENDED.");
}
else{
    printf("Error.");
}
}
</code>```

答:
You need a do while loop that checks if pressed key is y or not

```<code>int main(void) {
float x,y,sum;
char ch;
do {
printf ("Enter the first number:");
scanf ("%f",&x);
printf ("Enter the second number:");
scanf ("%f",&y);
sum=x+y;
printf ("The total number is:%f\n",sum);
printf ("Do you want to repeat the operation Y/N: ");
scanf (" %c", &ch);
}
while (ch == 'y' || ch == 'Y');
}
</code>```

Body:
My code is below. I am using C language. I want to repeat the action from the start if the user types Y but I am confused how can I make that happen. I tried to look for a solution but the results are not what I wanted. What should I do about it?

#include <stdio.h>

int main(){

int A,B;
char Y, N, C;

        printf("Enter value 1: ");
        scanf("%i", &B);
        printf("\nEnter value 2: ");
        scanf("%i", &A);

printf("= %i", A+B);

printf("\n\nAdd again? Y or N\n");
scanf("%c", &C);

if (C==Y){
    This should contain code that will repeat the action again.
}
else if(C==N){
    printf("PROGRAM USE ENDED.");
}
else{
    printf("Error.");
}
}

Body:
You need a do while loop that checks if pressed key is y or not

int main(void) {
float x,y,sum;
char ch;
do {
printf ("Enter the first number:");
scanf ("%f",&x);
printf ("Enter the second number:");
scanf ("%f",&y);
sum=x+y;
printf ("The total number is:%f\n",sum);
printf ("Do you want to repeat the operation Y/N: ");
scanf (" %c", &ch);
}
while (ch == 'y' || ch == 'Y');
}


问:
Using Spring IoC to set up enum values
Is there a way to set up such enum values via Spring IoC at construction time?

What I would like to do is to inject, at class load time, values that are hard-coded in the code snippet below:

```<code>public enum Car
{
        NANO ("Very Cheap", "India"),
        MERCEDES ("Expensive", "Germany"),
        FERRARI ("Very Expensive", "Italy");

        public final String cost;
        public final String madeIn;

        Car(String cost, String madeIn)
        {
                this.cost= cost;
                this.madeIn= madeIn;
        }

}
</code>```

Let's say that the application must be deployed in Germany, where Nanos are "Nearly free", or in India where Ferraris are "Unaffordable". In both countries, there are only three cars (deterministic set), no more no less, hence an enum, but their "inner" values may differ. So, this is a case of contextual initialization of immutables.

答:
All right, this is a bit complex but you may find a way to integrate it.  Enums are not meant to change at runtime, so this is a reflection hack.  Sorry I don't have the Spring implementation part, but you could just build a bean to take in the enum class or object, and another field that would be the new value or values.

```<code>Constructor con = MyEnum.class.getDeclaredConstructors()[0];
Method[] methods = con.getClass().getDeclaredMethods();
for (Method m : methods) {
  if (m.getName().equals("acquireConstructorAccessor")) {
    m.setAccessible(true);
    m.invoke(con, new Object[0]);
  }
}
Field[] fields = con.getClass().getDeclaredFields();
Object ca = null;
for (Field f : fields) {
  if (f.getName().equals("constructorAccessor")) {
    f.setAccessible(true);
    ca = f.get(con);
  }
}
Method m = ca.getClass().getMethod(
  "newInstance", new Class[] { Object[].class });
m.setAccessible(true);
MyEnum v = (MyEnum) m.invoke(ca, new Object[] {
  new Object[] { "MY_NEW_ENUM_VALUE", Integer.MAX_VALUE } });
  System.out.println(v.getClass() + ":" + v.name() + ":" + v.ordinal());
</code>```

This is taken from this site.

OwnerDisplayName: Olivier

Title: Using Spring IoC to set up enum values

Body:
Is there a way to set up such enum values via Spring IoC at construction time?

What I would like to do is to inject, at class load time, values that are hard-coded in the code snippet below:

public enum Car
{
        NANO ("Very Cheap", "India"),
        MERCEDES ("Expensive", "Germany"),
        FERRARI ("Very Expensive", "Italy");

        public final String cost;
        public final String madeIn;

        Car(String cost, String madeIn)
        {
                this.cost= cost;
                this.madeIn= madeIn;
        }

}

Let's say that the application must be deployed in Germany, where Nanos are "Nearly free", or in India where Ferraris are "Unaffordable". In both countries, there are only three cars (deterministic set), no more no less, hence an enum, but their "inner" values may differ. So, this is a case of contextual initialization of immutables.

LastEditorDisplayName: Olivier

Body:
All right, this is a bit complex but you may find a way to integrate it.  Enums are not meant to change at runtime, so this is a reflection hack.  Sorry I don't have the Spring implementation part, but you could just build a bean to take in the enum class or object, and another field that would be the new value or values.

Constructor con = MyEnum.class.getDeclaredConstructors()[0];
Method[] methods = con.getClass().getDeclaredMethods();
for (Method m : methods) {
  if (m.getName().equals("acquireConstructorAccessor")) {
    m.setAccessible(true);
    m.invoke(con, new Object[0]);
  }
}
Field[] fields = con.getClass().getDeclaredFields();
Object ca = null;
for (Field f : fields) {
  if (f.getName().equals("constructorAccessor")) {
    f.setAccessible(true);
    ca = f.get(con);
  }
}
Method m = ca.getClass().getMethod(
  "newInstance", new Class[] { Object[].class });
m.setAccessible(true);
MyEnum v = (MyEnum) m.invoke(ca, new Object[] {
  new Object[] { "MY_NEW_ENUM_VALUE", Integer.MAX_VALUE } });
  System.out.println(v.getClass() + ":" + v.name() + ":" + v.ordinal());

This is taken from this site.

OwnerDisplayName: Greg Noe

ContentLicense: CC BY-SA 2.5


问:
VSC PowerShell. After npm updating packages .ps1 cannot be loaded because running scripts is disabled on this system
I design websites in VSC and PowerShell is my default terminal.

After updating and deploying a website to firebase earlier, I was prompted to update firebase tools - which I did using npm. Immediately after I cannot run/access any firebase scripts wthout the folllowing error:

firebase : File C:\Users\mada7\AppData\Roaming\npm\firebase.ps1 cannot be loaded because running scripts is disabled on this system. For more information, see about_Execution_Policies at https:/go.microsoft.com/fwlink/?LinkID=135170. At line:1 char:1

firebase
  + CategoryInfo          : SecurityError: (:) [], PSSecurityException
  + FullyQualifiedErrorId : UnauthorizedAccess

I've spent a few hours searching around and can't find a solid answer the problem. Many threads are several years old and I find it bizarre I've not had this problem in the past year until today.
I can still access firebase scripts if I set my default terminal to cmd.

Assuming the problem was related to firebase-tools I've carried on working but have now updated vue.js and get the error again when trying to run any vue commands in powershell:

vue : File C:\Users\mada7\AppData\Roaming\npm\vue.ps1 cannot be loaded because running scripts is disabled on this system. For more information, see about_Execution_Policies at https:/go.microsoft.com/fwlink/?LinkID=135170. At line:1 char:1

vue
  + CategoryInfo          : SecurityError: (:) [], PSSecurityException
  + FullyQualifiedErrorId : UnauthorizedAccess

VSCode Version:
Version: 1.37.1 (user setup)
Commit: f06011a
Date: 2019-08-15T16:17:55.855Z
Electron: 4.2.7
Chrome: 69.0.3497.128
Node.js: 10.11.0
V8: 6.9.427.31-electron.0
OS: Windows_NT x64 10.0.18362
OS Version:
Windows 10 Home
Version - 1903
OS build - 18362.295

I've been reading around and seen many threads around permissions for scripts, but I haven't changed any - indeed the PowerShell scripts worked right up until I updated my packages. No other settings touched in the mean time. I don't want to be changing PowerShell settings unnecessarily.

答: If you have this issue in VS Code, close PowerShell terminal and open a Command Prompt terminal instead.</p>


问:
Cloud Functions - Unknown error while fetching the archive
I've been unable to access the source code for any of my Cloud Functions across multiple Google Cloud Projects for well over a week. When clicking through to the Source tab of a function I see a greyed out area with the message "Unknown error while fetching the archive".

On clicking Edit I'm met with "We can't display source code of this function." The error persists even if I try to set up a new Cloud Function. Then I get an error with no accompanying message.

There doesn't seem to be any issue with billing, I've tried logging in as a different user and I'm unable to find any documentation online. Has anyone been able to resolve this successfully?

答:
In most scenarios, this error arises due to billing issues related to the account. However, since you confirm your case is not so, I suggest you try logging in with an incognito window once.

If it doesn't help, make sure to try out the steps mentioned in here.


问:
How to set default folder in JupyterLab file browser?
I was wondering if there is a way to set a default folder every time I open JupyterLab. Is there any command I can run through Anaconda PowerShell Prompt? Or a JSON property I can modify in settings tab? Thanks in advance!</p>

答:
According to the jupyter.org:
I configured like this.

Terminal command active your envirnment by conda activate Your_env_name and then jupyter lab --generate-config. jupyter_lab_config.py should be created in dir /home/$USER/.jupyter directory.

Find
# c.LabApp.app_settings_dir = '' and uncomment.

Then give your directory like this.
c.LabApp.app_settings_dir = '/home/$USER/Documents/Jupyter_Notebook'

Similar for jupyter notebook. jupyter notebook --generate-config and then nu-comment and edit like c.NotebookApp.notebook_dir = '/home/UserName/Documents/Jupyter_Notebook'

**NB: /home/$USER/Documents/Jupyter_Notebook is my changed default dir. Change it according to your need. **


问:
How to encrypt a password and save it in MySQL database.
Now I am just saving the password as it is

```<code>protected void Save_Click(object sender, EventArgs e)
    {

        string userName = Label13.Text;
        DateTime now = DateTime.Now;
        MySqlConnection connectionString = new MySqlConnection("Server=127.0.0.1;Database=surelyknown;Uid=root");
        connectionString.Open();
        MySqlDataAdapter adapter = new MySqlDataAdapter();
        MySqlCommand command = new MySqlCommand();
adapter.InsertCommand = new MySqlCommand("INSERT INTO tbl_user (FirstName,LastName,Email,U_Password,CompanyName,UserPermission,PhoneNumber,Created,Modified,Active,CreatedBy,tbl_organisation_OrganisationID) VALUES(@FirstName,@LastName,@Email,@U_Password,@CompanyName,@UserPermission,@PhoneNumber,@Created,@Modified,@Active,@CreatedBy,@tbl_organisation_OrganisationID)", connectionString);
    adapter.InsertCommand.Parameters.Add("@FirstName", MySqlDbType.VarChar).Value = FirstName.Text;
            adapter.InsertCommand.Parameters.Add("@LastName", MySqlDbType.VarChar).Value = Surname.Text;
            adapter.InsertCommand.Parameters.Add("@Email", MySqlDbType.VarChar).Value = Email.Text;
            adapter.InsertCommand.Parameters.Add("@U_Password", MySqlDbType.VarChar).Value = Password.Text;
            adapter.InsertCommand.Parameters.Add("@CompanyName", MySqlDbType.VarChar).Value = Convert.ToString(nID);
</code>```

and when the user login to the website how can the encrypted password used to do authentication. i want to do the decryption in the server side itself. please help

答: First, you should salt and hash your passwords. When you say you want to do that on the server side, do you mean on the database server side, or the application server?</p>

Body:
Now I am just saving the password as it is

protected void Save_Click(object sender, EventArgs e)
    {

        string userName = Label13.Text;
        DateTime now = DateTime.Now;
        MySqlConnection connectionString = new MySqlConnection("Server=127.0.0.1;Database=surelyknown;Uid=root");
        connectionString.Open();
        MySqlDataAdapter adapter = new MySqlDataAdapter();
        MySqlCommand command = new MySqlCommand();
adapter.InsertCommand = new MySqlCommand("INSERT INTO tbl_user (FirstName,LastName,Email,U_Password,CompanyName,UserPermission,PhoneNumber,Created,Modified,Active,CreatedBy,tbl_organisation_OrganisationID) VALUES(@FirstName,@LastName,@Email,@U_Password,@CompanyName,@UserPermission,@PhoneNumber,@Created,@Modified,@Active,@CreatedBy,@tbl_organisation_OrganisationID)", connectionString);
    adapter.InsertCommand.Parameters.Add("@FirstName", MySqlDbType.VarChar).Value = FirstName.Text;
            adapter.InsertCommand.Parameters.Add("@LastName", MySqlDbType.VarChar).Value = Surname.Text;
            adapter.InsertCommand.Parameters.Add("@Email", MySqlDbType.VarChar).Value = Email.Text;
            adapter.InsertCommand.Parameters.Add("@U_Password", MySqlDbType.VarChar).Value = Password.Text;
            adapter.InsertCommand.Parameters.Add("@CompanyName", MySqlDbType.VarChar).Value = Convert.ToString(nID);

and when the user login to the website how can the encrypted password used to do authentication. i want to do the decryption in the server side itself. please help


问:
There was an unexpected error (type=Not Found, status=505),
1.This is my entity class.

```<code>
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Leads {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;
    private String firstName;
    private String lastname;
    private String email;
    private String source;
    private String mobile;
    public long getId() {
        return id;
    }
    public void setId(long id) {
        this.id = id;
    }
    public String getFirstName() {
        return firstName;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public String getLastname() {
        return lastname;
    }
    public void setLastname(String lastname) {
        this.lastname = lastname;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getSource() {
        return source;
    }
    public void setSource(String source) {
        this.source = source;
    }
    public String getMobile() {
        return mobile;
    }
    public void setMobile(String mobile) {
        this.mobile = mobile;
    }
}
</code>```

This is my  controller layer

```<code>package com.mento1.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.mento1.entities.Leads;
import com.mento1.service.LeadsService;

@Controller
public class LeadsController {

    @Autowired
    private LeadsService leadService;

    @RequestMapping("/leads")
    public String showLeadsPage() {
        return "saveLeads";
    }

    @RequestMapping("/saveLead")
    public String saveLead(@ModelAttribute("lead")Leads lead, ModelMap modelMap) {
        leadService.saveLead(lead);
        modelMap.addAttribute("msg", "Lead is saved");
        return "saveLeads";
    }
}
</code>```

3.This is my view layer

```<code><%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>lead</title>
</head>
<body>
    <h2>Create new leads</h2>
    <form action="saveLead" method="post">
    ```
        first name <input type="text" name="firstName"/>
        last name  <input type="text" name= "lastName"/>
        email      <input type="text" name="email" />
        source     <select name="source">
                 <option value="News Paper">News Paper</option>
                 <option value="TV Commercial">TV Commercial</option>
                 <option value="Online">Online</option>
                 <option value="radio">radio</option>
            </select>

        mobile     <input type="text" name="mobile" />
                   <input type="Submit" value="save" />
        ```
    </form>
</body>
</html>
</code>```

application properties file- here I have configure my data base

```<code>spring.datasource.url=jdbc:mysql://localhost:3306/mentoDB
spring.datasource.username=root
spring.datasource.password=Subrat02

spring.mvc.view.suffix=.jsp
spring.mvc.view.prefix=/WEB-INF/jsps/

</code>```

This is my Repository layer extended jpa repository

```<code>package com.mento1.repositories;

import org.springframework.data.jpa.repository.JpaRepository;

import com.mento1.entities.Leads;

public interface LeadsRepository extends JpaRepository<Leads, Long> {

}

</code>```

6.This is my service layer interface

```<code>package com.mento1.service;

import com.mento1.entities.Leads;

public interface LeadsService {

        public void saveLead(Leads lead);
}
</code>```

This is my service layer class.

```<code>package com.mento1.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.mento1.entities.Leads;
import com.mento1.repositories.LeadsRepository;

@Service
public class LeadsServiceImpl implements LeadsService {

    @Autowired
    private LeadsRepository leadRepo;

    @Override
    public void saveLead(Leads lead) {
        leadRepo.save(lead);

    }

}
</code>```

Error Coming:-

Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.

Sun Feb 13 09:24:29 IST 2022
There was an unexpected error (type=Not Found, status=505)

The problem is I am not able to save the data in the data base.

```<code></code>```

答:
I reviewed your codes. I think your problem is related to entity class. You don't have got constructor methods in Leads class. You must be add this methods with parameter and non-parameter. This really a huge problem.
And you haven't got all annotations. I recommend to use"Lombok" dependencies for constructor and annotations. You don't need to write getter/setter or constructor methods if you use Lombok.
Then you add Lombok to dependencies and set up it. (You can search to how install lombok to spring-boot project). You just should add some annotations to your entity.

I write my entity class as an example.

```<code>package datum....entities.concretes;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Data
@Entity
@Table(name = "column_table")
@AllArgsConstructor
@NoArgsConstructor
public class ColumnTable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "clmn_id")
public int clmnId;

@Column(name = "database_id")
public int databaseId;

@Column(name = "schema_id")
public int schemaId;

@Column(name = "table_id")
public int tableId;

@Column(name = "column_id")
public int columnId;

@Column(name = "column_name")
public String columnName;

@Column(name = "type_name")
public String typeName;

@Column(name = "max_len")
public int maxLen;

@Column(name = "prec")
public int prec;

@Column(name = "nullable")
public int nullable;

@Column(name = "columnDescription")
public String columnDescription;

@Column(name = "sample_name")
public String sampleName;
}
</code>```

Body:
1.This is my entity class.

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Leads {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;
    private String firstName;
    private String lastname;
    private String email;
    private String source;
    private String mobile;
    public long getId() {
        return id;
    }
    public void setId(long id) {
        this.id = id;
    }
    public String getFirstName() {
        return firstName;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public String getLastname() {
        return lastname;
    }
    public void setLastname(String lastname) {
        this.lastname = lastname;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getSource() {
        return source;
    }
    public void setSource(String source) {
        this.source = source;
    }
    public String getMobile() {
        return mobile;
    }
    public void setMobile(String mobile) {
        this.mobile = mobile;
    }
}

This is my  controller layer

package com.mento1.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.mento1.entities.Leads;
import com.mento1.service.LeadsService;

@Controller
public class LeadsController {

    @Autowired
    private LeadsService leadService;

    @RequestMapping("/leads")
    public String showLeadsPage() {
        return "saveLeads";
    }

    @RequestMapping("/saveLead")
    public String saveLead(@ModelAttribute("lead")Leads lead, ModelMap modelMap) {
        leadService.saveLead(lead);
        modelMap.addAttribute("msg", "Lead is saved");
        return "saveLeads";
    }
}

3.This is my view layer

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>

<meta charset="ISO-8859-1">
<title>lead</title>

Create new leads

    <form action="saveLead" method="post">

        first name <input type="text" name="firstName"/>
        last name  <input type="text" name= "lastName"/>
        email      <input type="text" name="email" />
        source     <select name="source">
                 <option value="News Paper">News Paper</option>
                 <option value="TV Commercial">TV Commercial</option>
                 <option value="Online">Online</option>
                 <option value="radio">radio</option>
            </select>

        mobile     <input type="text" name="mobile" />
                   <input type="Submit" value="save" />

    </form>

application properties file- here I have configure my data base

spring.datasource.url=jdbc:mysql://localhost:3306/mentoDB
spring.datasource.username=root
spring.datasource.password=Subrat02

spring.mvc.view.suffix=.jsp
spring.mvc.view.prefix=/WEB-INF/jsps/

This is my Repository layer extended jpa repository

package com.mento1.repositories;

import org.springframework.data.jpa.repository.JpaRepository;

import com.mento1.entities.Leads;

public interface LeadsRepository extends JpaRepository<Leads, Long> {

}

6.This is my service layer interface

package com.mento1.service;

import com.mento1.entities.Leads;

public interface LeadsService {

        public void saveLead(Leads lead);
}

This is my service layer class.

package com.mento1.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.mento1.entities.Leads;
import com.mento1.repositories.LeadsRepository;

@Service
public class LeadsServiceImpl implements LeadsService {

    @Autowired
    private LeadsRepository leadRepo;

    @Override
    public void saveLead(Leads lead) {
        leadRepo.save(lead);

    }

}

Error Coming:-

Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.

Sun Feb 13 09:24:29 IST 2022
There was an unexpected error (type=Not Found, status=505)

The problem is I am not able to save the data in the data base.

Body:
I reviewed your codes. I think your problem is related to entity class. You don't have got constructor methods in Leads class. You must be add this methods with parameter and non-parameter. This really a huge problem.
And you haven't got all annotations. I recommend to use"Lombok" dependencies for constructor and annotations. You don't need to write getter/setter or constructor methods if you use Lombok.
Then you add Lombok to dependencies and set up it. (You can search to how install lombok to spring-boot project). You just should add some annotations to your entity.

I write my entity class as an example.

package datum....entities.concretes;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Data
@Entity
@Table(name = "column_table")
@AllArgsConstructor
@NoArgsConstructor
public class ColumnTable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "clmn_id")
public int clmnId;

@Column(name = "database_id")
public int databaseId;

@Column(name = "schema_id")
public int schemaId;

@Column(name = "table_id")
public int tableId;

@Column(name = "column_id")
public int columnId;

@Column(name = "column_name")
public String columnName;

@Column(name = "type_name")
public String typeName;

@Column(name = "max_len")
public int maxLen;

@Column(name = "prec")
public int prec;

@Column(name = "nullable")
public int nullable;

@Column(name = "columnDescription")
public String columnDescription;

@Column(name = "sample_name")
public String sampleName;
}


问:
why ALL(SELECT) doesn't work to get max value
I'm working on Weather Observation Station 15 from Hackerrank (Hackerrank Question)

It asked

Query the Western Longitude (LONG_W) for the largest Northern Latitude (LAT_N) in STATION that is less than 137.2345 . Round your answer to decimal places.

STATION Table got 5 columns: ID, CITY, STATE, LAT_N, LONG_W.

Below is the my query and I'm trying to figure out why it does not work.

```<code>SELECT ROUND(LONG_W, 4) FROM STATION
WHERE LAT_N >= ALL(SELECT LAT_N FROM STATION WHERE LAT_N < '137.2345')
</code>```

When I tried a different query and this works

```<code>SELECT ROUND(LONG_W, 4) FROM STATION
WHERE LAT_N = (SELECT MAX(LAT_N) FROM STATION WHERE LAT_N < '137.2345')
</code>```

What's wrong with the first query? Thanks.

答:
This query :

```<code>select round (long_w,4)
from station
where lat_n<137.2345
order by lat_n desc
limit 1;
</code>```

firstly, it is selecting all rows with lat_n less than 137.2345.

secondly, it orders the result by lat_n in descending order so the first
row has the largest lat_n that is less than 137.2345.

Thirdly, I set a limit equal to 1 to only get the first row, then I get the round of long_w using the round function.

Syntax

ROUND(number, decimals, operation)

Body:
I'm working on Weather Observation Station 15 from Hackerrank (Hackerrank Question)

It asked

Query the Western Longitude (LONG_W) for the largest Northern Latitude (LAT_N) in STATION that is less than 137.2345 . Round your answer to decimal places.

STATION Table got 5 columns: ID, CITY, STATE, LAT_N, LONG_W.

Below is the my query and I'm trying to figure out why it does not work.

SELECT ROUND(LONG_W, 4) FROM STATION
WHERE LAT_N >= ALL(SELECT LAT_N FROM STATION WHERE LAT_N < '137.2345')

When I tried a different query and this works

SELECT ROUND(LONG_W, 4) FROM STATION
WHERE LAT_N = (SELECT MAX(LAT_N) FROM STATION WHERE LAT_N < '137.2345')

What's wrong with the first query? Thanks.

Body:
This query :

select round (long_w,4)
from station
where lat_n<137.2345
order by lat_n desc
limit 1;

firstly, it is selecting all rows with lat_n less than 137.2345.

secondly, it orders the result by lat_n in descending order so the first
row has the largest lat_n that is less than 137.2345.

Thirdly, I set a limit equal to 1 to only get the first row, then I get the round of long_w using the round function.

Syntax

ROUND(number, decimals, operation)


问:
Kotlin Unresolved reference: btn_start but i define it in my layout
Here is my code in activity_main.xml

```<code><Button
            android:id="@+id/btn_start"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="16dp"
            android:background="@color/white"
            android:text="Start"
            android:textColor="#757575"
            android:textSize="18sp">

        </Button>
</code>```

But when i code

```<code>class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    btn_start
</code>```

it will give me error to unresolved reference (btn_start)

答:
Kotlin Android Extensions is deprecated, which means that using Kotlin
synthetics for view binding is no longer supported.

Please refer to the official documentation here

Body:
Here is my code in activity_main.xml

<Button
            android:id="@+id/btn_start"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="16dp"
            android:background="@color/white"
            android:text="Start"
            android:textColor="#757575"
            android:textSize="18sp">

        </Button>

But when i code

class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    btn_start

it will give me error to unresolved reference (btn_start)


问:
Query to return data from SQL Server table based on date criteria
I have the following piece of code in C# that I use to select some rows from a SQL Server table based on a date criteria.

```<code>DateTime From, DateTime To
SqlParameter[] oParam = new SqlParameter[3];
oParam[0] = new SqlParameter("@From", From.Date);
oParam[1] = new SqlParameter("@To", To.Date);
DataTable dt = clsDatabaseHistory.ExecuteReader("SELECT * FROM tblHistory WHERE Date_Requested BETWEEN @From and @To", oParam);
</code>```

If for example From=18/08/2011 and To=18/08/2011 and there is data in the table tblHistory that has the Date_Requested value as 18/08/2011 the query does not return it.

But if I change the value of To from 18/08/2011 to To=19/08/2011 the query returns me all the values from the table that have a Date_Requested value of 18/08/2011, but none from the 19/08/2011.

How can something like that be possible and what query should I use to return rows where the date field is between date1 and date2.

Something like :

```<code>select * rows where datevalue >= date1 and datevalue <= date2
</code>```

Thank you.

答:
Change your query to use >= and < </p>

```<code>select * rows where datevalue >= date1 and datevalue < date2 + 1
</code>```

Body:
I have the following piece of code in C# that I use to select some rows from a SQL Server table based on a date criteria.

DateTime From, DateTime To
SqlParameter[] oParam = new SqlParameter[3];
oParam[0] = new SqlParameter("@From", From.Date);
oParam[1] = new SqlParameter("@To", To.Date);
DataTable dt = clsDatabaseHistory.ExecuteReader("SELECT * FROM tblHistory WHERE Date_Requested BETWEEN @From and @To", oParam);

If for example From=18/08/2011 and To=18/08/2011 and there is data in the table tblHistory that has the Date_Requested value as 18/08/2011 the query does not return it.

But if I change the value of To from 18/08/2011 to To=19/08/2011 the query returns me all the values from the table that have a Date_Requested value of 18/08/2011, but none from the 19/08/2011.

How can something like that be possible and what query should I use to return rows where the date field is between date1 and date2.

Something like :

select * rows where datevalue >= date1 and datevalue <= date2

Thank you.

Body:
Change your query to use >= and <

select * rows where datevalue >= date1 and datevalue < date2 + 1


问:
Spark-shell error on windows "Illegal character in path at index 32"
I am trying to setup spark on my new windows laptop. I am getting below error while running spark-shell :

"
ERROR Main: Failed to initialize Spark session.
java.lang.reflect.InvocationTargetException
Caused by: java.net.URISyntaxException: Illegal character in path at index 32: spark://DESKTOP-RCMDGS4:49985/C:\classes"

I am using below s/w :
Spark 3.2.1
Java 11
Hadoop: winutils

I have set below environment variables :
HADOOP_HOME, SPARK_HOME, JAVA_HOME, PATH

答: This is known issue in latest spark version. Downgrade to 3.0.3 could fix the issue.</p>


问:
How to create an increasing index based on a certain condition?
Suppose I have this dataframe:

```<code>df <- data.frame(co11 = c(rep(1, 5), 5, 6, rep(1, 3), 2, 3, 4, 5, 8, rep(1, 2), rep(2, 2), 8, 10))
</code>```

I would like to create another column (col2) with increasing group index whenever a value in a row is at least 5. To illustrate, here is the resulting df that I would like to get:

```<code>   co11  col2
1     1     1
2     1     1
3     1     1
4     1     1
5     1     1
6     5     2
7     6     3
8     1     3
9     1     3
10    1     3
11    2     3
12    3     3
13    4     3
14    5     4
15    8     5
16    1     5
17    1     5
18    2     5
19    2     5
20    8     6
21   10     7
</code>```

Is there an available function in dplyr that can do this?

Body:
Suppose I have this dataframe:

df <- data.frame(co11 = c(rep(1, 5), 5, 6, rep(1, 3), 2, 3, 4, 5, 8, rep(1, 2), rep(2, 2), 8, 10))

I would like to create another column (col2) with increasing group index whenever a value in a row is at least 5. To illustrate, here is the resulting df that I would like to get:

   co11  col2
1     1     1
2     1     1
3     1     1
4     1     1
5     1     1
6     5     2
7     6     3
8     1     3
9     1     3
10    1     3
11    2     3
12    3     3
13    4     3
14    5     4
15    8     5
16    1     5
17    1     5
18    2     5
19    2     5
20    8     6
21   10     7

Is there an available function in dplyr that can do this?

Body:
Waldi's answer is very good, here is a slightly modified version:

library(dplyr)

df %>%
  group_by(col2 =cumsum(co11 >= 5)+1)

 co11 col2
1     1    1
2     1    1
3     1    1
4     1    1
5     1    1
6     5    2
7     6    3
8     1    3
9     1    3
10    1    3
11    2    3
12    3    3
13    4    3
14    5    4
15    8    5
16    1    5
17    1    5
18    2    5
19    2    5
20    8    6
21   10    7


问:
Why can the as operator be used with Nullable<T>?
According to the documentation of the as operator, as "is used to perform certain types of conversions between compatible reference types".  Since Nullable is actually a value type, I would expect as not to work with it.  However, this code compiles and runs:

```<code>object o = 7;
int i = o as int? ?? -1;
Console.WriteLine(i); // output: 7
</code>```

Is this correct behavior?  Is the documentation for as wrong?  Am I missing something?

答:
I read:

Note that the as operator only performs reference conversions and boxing conversions. The as operator cannot perform other conversions, such as user-defined conversions, which should instead be performed by using cast expressions.

And boxing conversions.....

Body:
According to the documentation of the as operator, as "is used to perform certain types of conversions between compatible reference types".  Since Nullable is actually a value type, I would expect as not to work with it.  However, this code compiles and runs:

object o = 7;
int i = o as int? ?? -1;
Console.WriteLine(i); // output: 7

Is this correct behavior?  Is the documentation for as wrong?  Am I missing something?


问:
While coding a login I want to set a limit to just allow you to try 3 times before resetting it
Disclaimer: Some code is in Spanish, let me know if you need it in English, also I didn't knew how to add the second HTML (plus IDK if it is relevant) please tell me if you need that too so I can change it.

I'm working on an ATM project, and I'm at the login part of it. I have 2 HTML pages, the first is the login and the second is the ATM (Ignore that part because is not finished yet)

Things I want to do:

If it validates the login, it will direct you to the .html page to work on the ATM

If the information is wrong it will give you 2 more tries and after the last one it will tell you that you ran out of tries and will start the count over and redirecting you to the first page. (This is the part where I need help for now)

// Variables para limite de intentos
let entryCount = 0
let entryLimit = 3
let error = false

// Variables para cambio de pagina
let mainScreen = document.getElementById('mainScreen')
let contentAccountScreen = document.createTextNode("Account Screen")
let accountScreen = document.createElement("span").setAttribute("id","accountScreen")

// Login 1
function login() {
    let response
    user = document.getElementById('user')
    pass = document.getElementById('password')
    if (user.value === 'Emilio' && pass.value === "abc123"){
        changeMainScreen.replaceChild(contentAccountScreen, mainScreen)
    } if (response != pass && entryCount < entryLimit) {
        entryCount++;
        alert('Contraseña o usuario invalido, intentelo nuevamente')
        window.location.href = "index.html"
    } else(entryCount<entryLimit)
    {
        alert('Pasaste el limite de intentos')
        window.location.href = "index.html"
    }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.cuerpo{
    display: flex;
    background-color: #dad158;
    align-items: center;
    width: 100vw;
    height: 100vh;
}

.boton{
    margin-top: 1rem;
}

h1 {
    text-align: center;
    margin-bottom: 100px;
}

/* Estilos calculadora */
body{
    font-size: 18px;
    font-family: 'Roboto', sans-serif;
    margin: 0;
    padding: 0;
}
#contenedor {
    max-width: 1024px;
    margin: 0 auto;
}
.cajacentro {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    margin: 12% auto !important;
    width: 450px;
    height: 100%;
    background-color: #212121;
    padding:3%;
}
section header h5, section header h2, aside h4, aside p{
    color: #ffffff;
    margin: 10px 0;
    text-align: right;
}
.tamañoresultados{
    font-size: 0.6rem;
}
.columna1{
    height: 100%;
    width: 65%;
}
.columna2{
    height: 100%;
    width: 25%;
}
.gridbotones{
    display: grid;
    grid-template-columns: 1fr 1fr 1fr 1fr;
    grid-template-rows: 1fr 1fr 1fr 1fr;
    gap: 0px 0px;
    grid-template-areas:
        ". . . ."
        ". . . ."
        ". . . ."
        ". . . .";
}
button{
    background-color: #212121;
    color: #ffffff;
    border: 1px solid #ffffff;
    padding: 10px 0;
    cursor: pointer;
}
button:hover{
    background-color: #424242;
}</code>```

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
    <link rel="stylesheet" href="css/styles.css">

    <title>ATM</title>

ATM

            <input type="" class="form-control" id="user" placeholder="username">
            Usuario

            <input type="password" class="form-control" id="password" placeholder="Password">
            Contraseña

            <button type="submit" class="btn btn-outline-success" onclick="login(location.href='cajero.html')">Ingresar</button>

```

答:
You just need to modify js a bit as follows:

// Variables para limite de intentos
let entryCount = 0
let entryLimit = 3
let error = false

// Variables para cambio de pagina
let mainScreen = document.getElementById('mainScreen')
let contentAccountScreen = document.createTextNode("Account Screen")
let accountScreen = document.createElement("span").setAttribute("id","accountScreen")

// Login 1
function login() {
    let response
    user = document.getElementById('user')
    pass = document.getElementById('password')
    if (user.value === 'Emilio' && pass.value === "abc123"){
        changeMainScreen.replaceChild(contentAccountScreen, mainScreen)
    } if (response != pass && entryCount < entryLimit) {
        entryCount++;
        alert('Contraseña o usuario invalido, intentelo nuevamente')
        window.location.href = "index.html"
    } else(entryCount >= entryLimit)
    {
        alert('Pasaste el limite de intentos')
        window.location.href = "index.html"
    }
}
```

You just had to add entryCount >= entryLimit for it to work.

Just a suggestion, never trust client-side validation i.e. one can easily attempt unlimited times by just entering entryLimit = 100000 in the console.

Body:
Disclaimer: Some code is in Spanish, let me know if you need it in English, also I didn't knew how to add the second HTML (plus IDK if it is relevant) please tell me if you need that too so I can change it.

I'm working on an ATM project, and I'm at the login part of it. I have 2 HTML pages, the first is the login and the second is the ATM (Ignore that part because is not finished yet)

Things I want to do:

If it validates the login, it will direct you to the .html page to work on the ATM

If the information is wrong it will give you 2 more tries and after the last one it will tell you that you ran out of tries and will start the count over and redirecting you to the first page. (This is the part where I need help for now)

// Variables para limite de intentos
let entryCount = 0
let entryLimit = 3
let error = false

// Variables para cambio de pagina
let mainScreen = document.getElementById('mainScreen')
let contentAccountScreen = document.createTextNode("Account Screen")
let accountScreen = document.createElement("span").setAttribute("id","accountScreen")

// Login 1
function login() {
    let response
    user = document.getElementById('user')
    pass = document.getElementById('password')
    if (user.value === 'Emilio' && pass.value === "abc123"){
        changeMainScreen.replaceChild(contentAccountScreen, mainScreen)
    } if (response != pass && entryCount < entryLimit) {
        entryCount++;
        alert('Contraseña o usuario invalido, intentelo nuevamente')
        window.location.href = "index.html"
    } else(entryCount<entryLimit)
    {
        alert('Pasaste el limite de intentos')
        window.location.href = "index.html"
    }
}

.cuerpo{
    display: flex;
    background-color: #dad158;
    align-items: center;
    width: 100vw;
    height: 100vh;
}

.boton{
    margin-top: 1rem;
}

h1 {
    text-align: center;
    margin-bottom: 100px;
}

/* Estilos calculadora */
body{
    font-size: 18px;
    font-family: 'Roboto', sans-serif;
    margin: 0;
    padding: 0;
}
#contenedor {
    max-width: 1024px;
    margin: 0 auto;
}
.cajacentro {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    margin: 12% auto !important;
    width: 450px;
    height: 100%;
    background-color: #212121;
    padding:3%;
}
section header h5, section header h2, aside h4, aside p{
    color: #ffffff;
    margin: 10px 0;
    text-align: right;
}
.tamañoresultados{
    font-size: 0.6rem;
}
.columna1{
    height: 100%;
    width: 65%;
}
.columna2{
    height: 100%;
    width: 25%;
}
.gridbotones{
    display: grid;
    grid-template-columns: 1fr 1fr 1fr 1fr;
    grid-template-rows: 1fr 1fr 1fr 1fr;
    gap: 0px 0px;
    grid-template-areas:
        ". . . ."
        ". . . ."
        ". . . ."
        ". . . .";
}
button{
    background-color: #212121;
    color: #ffffff;
    border: 1px solid #ffffff;
    padding: 10px 0;
    cursor: pointer;
}
button:hover{
    background-color: #424242;
}

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
    <link rel="stylesheet" href="css/styles.css">

    <title>ATM</title>

ATM

            <input type="" class="form-control" id="user" placeholder="username">
            Usuario

            <input type="password" class="form-control" id="password" placeholder="Password">
            Contraseña

            <button type="submit" class="btn btn-outline-success" onclick="login(location.href='cajero.html')">Ingresar</button>

Body:
You just need to modify js a bit as follows:

// Variables para limite de intentos
let entryCount = 0
let entryLimit = 3
let error = false

// Variables para cambio de pagina
let mainScreen = document.getElementById('mainScreen')
let contentAccountScreen = document.createTextNode("Account Screen")
let accountScreen = document.createElement("span").setAttribute("id","accountScreen")

// Login 1
function login() {
    let response
    user = document.getElementById('user')
    pass = document.getElementById('password')
    if (user.value === 'Emilio' && pass.value === "abc123"){
        changeMainScreen.replaceChild(contentAccountScreen, mainScreen)
    } if (response != pass && entryCount < entryLimit) {
        entryCount++;
        alert('Contraseña o usuario invalido, intentelo nuevamente')
        window.location.href = "index.html"
    } else(entryCount >= entryLimit)
    {
        alert('Pasaste el limite de intentos')
        window.location.href = "index.html"
    }
}

You just had to add entryCount >= entryLimit for it to work.

Just a suggestion, never trust client-side validation i.e. one can easily attempt unlimited times by just entering entryLimit = 100000 in the console.


问:
How can I use accumulate like reduce2 function in purrr?
I would like to use the accumulate function with two input vectors and the reduce2 function. The documentation for accumulate implies that two input vectors can be given and that accumulate can work with reduce2. However, I am having trouble.

Here is an example, inspired by the documentation from reduce2.

This is the example from reduce2

```<code>> paste2 <- function(x, y, sep = ".") paste(x, y, sep = sep)
> letters[1:4] %>% reduce2(.y=c("-", ".", "-"), paste2)
[1] "a-b.c-d"
</code>```

Here are several attempts to use accumulate similarly to reduce2. None properly iterate through both letters[1:4] and c("-",".","-").

```<code>> letters[1:4] %>% accumulate(.y=c("-", ".", "-"),paste2)
Error in .f(x, y, ...) : unused argument (.y = c("-", ".", "-"))

> letters[1:4] %>% accumulate(c("-", ".", "-"),paste2)
[[1]]
[1] "a"

[[2]]
NULL

> letters[1:4] %>% accumulate(sep=c("-", ".", "-"),paste2)
[1] "a"       "a-b"     "a-b-c"   "a-b-c-d"
</code>```

How would I use accumulate to see the intermediate results given by the reduce2 example?

答:
A few months after this post accumulate2 was introduced that gives the results OP was after:

library(purrr)

paste2 <- function(x, y, sep = ".") paste(x, y, sep = sep)
accumulate2(letters[1:4], c("-", ".", "-"), paste2)

#> [[1]]
#> [1] "a"
#>
#> [[2]]
#> [1] "a-b"
#>
#> [[3]]
#> [1] "a-b.c"
#>
#> [[4]]
#> [1] "a-b.c-d"
```

Body:
I would like to use the accumulate function with two input vectors and the reduce2 function. The documentation for accumulate implies that two input vectors can be given and that accumulate can work with reduce2. However, I am having trouble.

Here is an example, inspired by the documentation from reduce2.

This is the example from reduce2

> paste2 <- function(x, y, sep = ".") paste(x, y, sep = sep)
> letters[1:4] %>% reduce2(.y=c("-", ".", "-"), paste2)
[1] "a-b.c-d"

Here are several attempts to use accumulate similarly to reduce2. None properly iterate through both letters[1:4] and c("-",".","-").

> letters[1:4] %>% accumulate(.y=c("-", ".", "-"),paste2)
Error in .f(x, y, ...) : unused argument (.y = c("-", ".", "-"))

> letters[1:4] %>% accumulate(c("-", ".", "-"),paste2)
[[1]]
[1] "a"

[[2]]
NULL

> letters[1:4] %>% accumulate(sep=c("-", ".", "-"),paste2)
[1] "a"       "a-b"     "a-b-c"   "a-b-c-d"

How would I use accumulate to see the intermediate results given by the reduce2 example?


问:
Changing Data Class From Live Data
I have a BaseViewModel that basically has the function to get the user data like so:

```<code>abstract class BaseViewModel(
    private val repository: BaseRepository
) : ViewModel() {
    private var _userResponse: MutableLiveData<Resource<UserResponse>> = MutableLiveData()
    val userResponse: LiveData<Resource<UserResponse>> get() = _userResponse

    fun getUserData() = viewModelScope.launch {
        _userResponse.value = Resource.Loading
        _userResponse.value = repository.getLoggedInUserData()
    }
}
</code>```

In my Fragment, I access this data by just calling viewModel.getUserData(). This works. However, I'd like to now be able to edit the data. For example, the data class of UserResponse looks like this:

```<code>data class UserResponse(
    var id: Int,
    var username: String,
    var email: String
)
</code>```

In other fragments, I'd like to edit username and email for example. How do I do access the UserResponse object and edit it? Is this a good way of doing things? The getUserData should be accessed everywhere and that is why I'm including it in the abstract BaseViewModel. Whenever the UserResponse is null, I do the following check:

```<code>if (viewModel.userResponse.value == null) {
    viewModel.getUserData()
}
</code>```

答:
The ideal way to update userResponse you should change/edit _userResponse so that your userResponse we'll give you the updated data.

it should be something like this

```<code>_userResponse.value = Resource<UserResponse>()
</code>```

Title: Changing Data Class From Live Data

Body:
I have a BaseViewModel that basically has the function to get the user data like so:

abstract class BaseViewModel(
    private val repository: BaseRepository
) : ViewModel() {
    private var _userResponse: MutableLiveData<Resource<UserResponse>> = MutableLiveData()
    val userResponse: LiveData<Resource<UserResponse>> get() = _userResponse

    fun getUserData() = viewModelScope.launch {
        _userResponse.value = Resource.Loading
        _userResponse.value = repository.getLoggedInUserData()
    }
}

In my Fragment, I access this data by just calling viewModel.getUserData(). This works. However, I'd like to now be able to edit the data. For example, the data class of UserResponse looks like this:

data class UserResponse(
    var id: Int,
    var username: String,
    var email: String
)

In other fragments, I'd like to edit username and email for example. How do I do access the UserResponse object and edit it? Is this a good way of doing things? The getUserData should be accessed everywhere and that is why I'm including it in the abstract BaseViewModel. Whenever the UserResponse is null, I do the following check:

if (viewModel.userResponse.value == null) {
    viewModel.getUserData()
}

Body:
The ideal way to update userResponse you should change/edit _userResponse so that your userResponse we'll give you the updated data.

it should be something like this

_userResponse.value = Resource<UserResponse>()


问:
Wrapping currency expression in a constant in SwiftUI
I am learning Swift and Xcode and there is a task that I have problems wrapping my mind around.
There are three places where I use value formatter:

```<code>format: .currency(code: Locale.current.currencyCode ?? "PLN")
</code>```

I packed it into a constant and it doesn't throw any errors:

```<code>let currencyFormatter = { (amount: Double) -> FloatingPointFormatStyle<Double>.Currency in
.currency(code: Locale.current.currencyCode ?? "PLN")
}
</code>```

The execution though does throw several errors (they don't change if I swap the closure to void instead of accepting Double):

```<code>Text(totalPerPerson, format: currencyFormatter)
</code>```

Some of the errors:
1.

```<code>Cannot convert value of type 'Double' to expected argument type '((Double) -> FloatingPointFormatStyle<Double>.Currency).FormatInput'
</code>```

```<code>Initializer 'init(_:format:)' requires that '((Double) -> FloatingPointFormatStyle<Double>.Currency).FormatInput' conform to 'Equatable'
</code>```

答:
The correct constant should be as</p>
```<code>let currencyFormatter = FloatingPointFormatStyle<Double>.Currency.currency(code: Locale.current.currencyCode ?? "PLN")
</code>```

Body:
I am learning Swift and Xcode and there is a task that I have problems wrapping my mind around.
There are three places where I use value formatter:

format: .currency(code: Locale.current.currencyCode ?? "PLN")

I packed it into a constant and it doesn't throw any errors:

let currencyFormatter = { (amount: Double) -> FloatingPointFormatStyle<Double>.Currency in
.currency(code: Locale.current.currencyCode ?? "PLN")
}

The execution though does throw several errors (they don't change if I swap the closure to void instead of accepting Double):

Text(totalPerPerson, format: currencyFormatter)

Some of the errors:
1.

Cannot convert value of type 'Double' to expected argument type '((Double) -> FloatingPointFormatStyle<Double>.Currency).FormatInput'

Initializer 'init(_:format:)' requires that '((Double) -> FloatingPointFormatStyle<Double>.Currency).FormatInput' conform to 'Equatable'

Body:
The correct constant should be as

let currencyFormatter = FloatingPointFormatStyle<Double>.Currency.currency(code: Locale.current.currencyCode ?? "PLN")


问:
finding time complexity for the below java code
I have tried to find the time complexity for the below code but I am not sure whether it is right or not. can anyone help me on finding the time complexity for the below code.  the code language is JAVA.

code:

```<code>    // importing the necessary header files for the program
// header files are imported using the keyword import
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

//creating a class called "Partone". class can be created using the keyword class
public class Partone
{

        public static void main(String[] args) throws IOException
        {

                // opening a file named "hikernet1"
                File inputFile = new File("hikernet1.txt");
                int maxTransmission = 0; //declaring maxTransmission as Integer data type and setting as 0

                //reading the content of the file
                Scanner reader = new Scanner(inputFile);

                // inputCoordinatedAndTransmissionRange
                String[] iCATR = reader.useDelimiter("\\A").next().replaceAll("\n", ",").replace("\r", "").split(",");

                for (int i = 0; i < Integer.parseInt(iCATR[0]); i++)
                {
                        int transmissions = 0; //declaring transmissions as integer data type and setting is as 0
                        String[] thisHiker = iCATR[i+1].split(" ");
                        int transMissionRange = Integer.parseInt(thisHiker[2]);
                        for (int j = 0; j < Integer.parseInt(iCATR[0]); j++)
                        {
                                int distance = (int) Math.sqrt(
                                                Math.pow(Integer.parseInt(thisHiker[0])-Integer.parseInt(iCATR[j+1].split(" ")[0]), 2) + //x2-x1
                                                Math.pow(Integer.parseInt(thisHiker[1])-Integer.parseInt(iCATR[j+1].split(" ")[1]), 2)); //y2-y1

                                if (distance<=transMissionRange)
                                {
                                        transmissions++;
                                }
                        }

                        if (transmissions>maxTransmission)  //checking the condition
                        {
                                maxTransmission = transmissions;
                        }
                }

                System.out.println(" The Maximum Transmission: "+maxTransmission);

                //the outpit will be displayed in the hikernet1out file
                FileWriter fw = new FileWriter("hikernet1out.txt"); //hikernet1out is the name of the output file
                fw.write(""+maxTransmission);
                fw.close(); //closing the file

                reader.close(); //closing all the files

        }

} //end of the program
</code>```

any help would be appreciated much . thanks in advance.

答:
Integer.parseInt(iCATR[0]); retruning any value let consider n.

The inner loop is running n times for every iteration of the outer loop.

The total number of nested loop itration = total number of iteration of outer loop . total number of iteration of inner loop = n * n  = n^2

For each iteration nested loop doing O(1) operation.

Total time complexity =  O(n^2)*O(1) = O(n^2).

Body:
I have tried to find the time complexity for the below code but I am not sure whether it is right or not. can anyone help me on finding the time complexity for the below code.  the code language is JAVA.

code:

    // importing the necessary header files for the program
// header files are imported using the keyword import
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

//creating a class called "Partone". class can be created using the keyword class
public class Partone
{

        public static void main(String[] args) throws IOException
        {

                // opening a file named "hikernet1"
                File inputFile = new File("hikernet1.txt");
                int maxTransmission = 0; //declaring maxTransmission as Integer data type and setting as 0

                //reading the content of the file
                Scanner reader = new Scanner(inputFile);

                // inputCoordinatedAndTransmissionRange
                String[] iCATR = reader.useDelimiter("\\A").next().replaceAll("\n", ",").replace("\r", "").split(",");

                for (int i = 0; i < Integer.parseInt(iCATR[0]); i++)
                {
                        int transmissions = 0; //declaring transmissions as integer data type and setting is as 0
                        String[] thisHiker = iCATR[i+1].split(" ");
                        int transMissionRange = Integer.parseInt(thisHiker[2]);
                        for (int j = 0; j < Integer.parseInt(iCATR[0]); j++)
                        {
                                int distance = (int) Math.sqrt(
                                                Math.pow(Integer.parseInt(thisHiker[0])-Integer.parseInt(iCATR[j+1].split(" ")[0]), 2) + //x2-x1
                                                Math.pow(Integer.parseInt(thisHiker[1])-Integer.parseInt(iCATR[j+1].split(" ")[1]), 2)); //y2-y1

                                if (distance<=transMissionRange)
                                {
                                        transmissions++;
                                }
                        }

                        if (transmissions>maxTransmission)  //checking the condition
                        {
                                maxTransmission = transmissions;
                        }
                }

                System.out.println(" The Maximum Transmission: "+maxTransmission);

                //the outpit will be displayed in the hikernet1out file
                FileWriter fw = new FileWriter("hikernet1out.txt"); //hikernet1out is the name of the output file
                fw.write(""+maxTransmission);
                fw.close(); //closing the file

                reader.close(); //closing all the files

        }

} //end of the program

any help would be appreciated much . thanks in advance.


问:
jQuery index on each function
I am curious why I need this index

```<code>$(document).ready(function() {
        $(".divToggle").each(function(index){
            var buttonId = $(this)[0].attributes["id"].value.toString();
            var idParts = buttonId.split('_');
            var uniquePart = idParts[0] + "_" + idParts[1] + "_" + "divContentPanel";
            $(this).click(function() {
                 $("#" + uniquePart).toggle("slow");
            });
        });
    });
</code>```

Why do I need the "[0]" in "var buttonId = $(this)[0]…"  Without it, I get an attributes["id"] is null error..

答:
```<code>$(this)[0]
</code>```

Is doing 2 things -

Getting you the first element in the matched set, as you're looping round a set of results  one by one the index is probably redundant in this case

Returning a 'normal' JavaScript DOM object rather than a jQuery wrapped object

Looking at your code I believe you could achieve the same result by doing this -

```<code>var buttonId = this.id;
</code>```

Title: jQuery index on each function

Body:
I am curious why I need this index

$(document).ready(function() {
        $(".divToggle").each(function(index){
            var buttonId = $(this)[0].attributes["id"].value.toString();
            var idParts = buttonId.split('_');
            var uniquePart = idParts[0] + "_" + idParts[1] + "_" + "divContentPanel";
            $(this).click(function() {
                 $("#" + uniquePart).toggle("slow");
            });
        });
    });

Why do I need the "[0]" in "var buttonId = $(this)[0]…"  Without it, I get an attributes["id"] is null error..

Body:
$(this)[0]

Is doing 2 things -

Getting you the first element in the matched set, as you're looping round a set of results  one by one the index is probably redundant in this case

Returning a 'normal' JavaScript DOM object rather than a jQuery wrapped object

Looking at your code I believe you could achieve the same result by doing this -

var buttonId = this.id;


问:
Quasar 2 Vue 3 "ReferenceError: process is not defined" error
I bump into ReferenceError: process is not defined error for my Quasar 2 application deployed to firebase. Howver, running it locally with quasar dev does not see the error. Any advice and insight is appreciated.

答: Solved by installing NPM process package.


问:
Password reset token generation fails
I'm trying to create password reset feature in my ASP.NET Core MVC project. The validation process is done by jQuery. The method for this purpose is:

```<code>[HttpPost]
    public async Task<JsonResult> ResetPassword(string username, string newPassword)
    {
        var user = await _userManager.FindByNameAsync(username);
        var token = await _userManager.GeneratePasswordResetTokenAsync(user);
        if(user != null)
        {
            var result = await _userManager.ResetPasswordAsync(user, token, newPassword);
            if (result.Succeeded)
            {
                return Json(new { success = true});
            }
            else
            {
                return Json(new { success = false });
            }
        }
        else
        {
            return Json(new { success = false });
        }
    }
</code>```

The problem is that _userManager.GeneratePasswordResetTokenAsync(user) causes the context to be disposed and the process stops there. How can I solve this?

答:
I solved this problem by registering token:</p>
```<code>builder.Services.AddIdentity<AppUser, AppRole>(options =>
{
    options.User.RequireUniqueEmail = false;
    options.Password.RequireDigit = true;
    options.Password.RequiredUniqueChars = 0;
    options.Password.RequireUppercase = false;
    options.Password.RequireNonAlphanumeric = false;
    options.Password.RequiredLength = 6;
    options.Tokens.PasswordResetTokenProvider = TokenOptions.DefaultProvider;
}).AddEntityFrameworkStores<IdentityAppContext>().AddDefaultTokenProviders();
</code>```

Title: Password reset token generation fails

Body:
I'm trying to create password reset feature in my ASP.NET Core MVC project. The validation process is done by jQuery. The method for this purpose is:

[HttpPost]
    public async Task<JsonResult> ResetPassword(string username, string newPassword)
    {
        var user = await _userManager.FindByNameAsync(username);
        var token = await _userManager.GeneratePasswordResetTokenAsync(user);
        if(user != null)
        {
            var result = await _userManager.ResetPasswordAsync(user, token, newPassword);
            if (result.Succeeded)
            {
                return Json(new { success = true});
            }
            else
            {
                return Json(new { success = false });
            }
        }
        else
        {
            return Json(new { success = false });
        }
    }

The problem is that _userManager.GeneratePasswordResetTokenAsync(user) causes the context to be disposed and the process stops there. How can I solve this?

Body:
I solved this problem by registering token:

builder.Services.AddIdentity<AppUser, AppRole>(options =>
{
    options.User.RequireUniqueEmail = false;
    options.Password.RequireDigit = true;
    options.Password.RequiredUniqueChars = 0;
    options.Password.RequireUppercase = false;
    options.Password.RequireNonAlphanumeric = false;
    options.Password.RequiredLength = 6;
    options.Tokens.PasswordResetTokenProvider = TokenOptions.DefaultProvider;
}).AddEntityFrameworkStores<IdentityAppContext>().AddDefaultTokenProviders();


问:
Simulate "No operations allowed after connection closed"
I'm getting this error "No operations allowed after connection closed" from grils2x/mysql/dbcp occasionally and I couldn't find a solution.

because I get the error hours later, like next day after a restart, it's difficult to fix it.

I feel like I need to replicate it in a predictable manner and so I can find a definitive fix.

What parameter set can I use for MySQL and Grails side that ends up with that error immediately after it is run?

答:
I ended up setting two timeouts manually , and make a connection afterwards , and see the following in mysql logs , to confirm connection was aborted after 10 seconds.

2022-02-12T22:03:53.690960Z 493 [Note] Aborted connection 493 to db: 'quantanywhere_2' user: 'root' host: '172.17.0.1' (Got timeout reading communication packets)

SET @@GLOBAL.wait_timeout=10;
SET @@SESSION.wait_timeout=10;

And following should be ok with the default wait_timeout of 28800 seconds=8 hours.

```<code>            validationInterval = 28000
            testWhileIdle=true
            maxActive = 50
            maxIdle = 25
            maxWait = 10000
            maxAge: 600000
            minIdle = 5
            validationQuery="select 1"
            validationQueryTimeout=3
            initialSize = 10
            minEvictableIdleTimeMillis = 60000
            timeBetweenEvictionRunsMillis = 5000
            numTestsPerEvictionRun = 3
            testOnBorrow = true
            testWhileIdle = true
            testOnReturn = false
            removeAbandoned = true
            removeAbandonedTimeout = 120
</code>```

Body:
I ended up setting two timeouts manually , and make a connection afterwards , and see the following in mysql logs , to confirm connection was aborted after 10 seconds.

2022-02-12T22:03:53.690960Z 493 [Note] Aborted connection 493 to db: 'quantanywhere_2' user: 'root' host: '172.17.0.1' (Got timeout reading communication packets)

SET @@GLOBAL.wait_timeout=10;
SET @@SESSION.wait_timeout=10;

And following should be ok with the default wait_timeout of 28800 seconds=8 hours.

            validationInterval = 28000
            testWhileIdle=true
            maxActive = 50
            maxIdle = 25
            maxWait = 10000
            maxAge: 600000
            minIdle = 5
            validationQuery="select 1"
            validationQueryTimeout=3
            initialSize = 10
            minEvictableIdleTimeMillis = 60000
            timeBetweenEvictionRunsMillis = 5000
            numTestsPerEvictionRun = 3
            testOnBorrow = true
            testWhileIdle = true
            testOnReturn = false
            removeAbandoned = true
            removeAbandonedTimeout = 120


问:
Assigning a string value if input value falls within a specific range in Laravel 8
I compare an input value to multiple range of values to determine the string value for another variable.  The below code works, but I am wondering if there is a more elegant solution?</p>
```<code>...
if ($totalPoints >= 0 && $totalPoints <= 249) {
    $carClass = 'CC01';
} elseif ($totalPoints >= 250 && $totalPoints <= 299) {
    $carClass = 'CC02';
} elseif ($totalPoints >= 300 && $totalPoints <= 349) {
    $carClass = 'CC03';
} elseif ($totalPoints >= 350 && $totalPoints <= 399) {
    $carClass = 'CC04';
} elseif ($totalPoints >= 400 && $totalPoints <= 449) {
    $carClass = 'CC05';
} elseif ($totalPoints >= 450 && $totalPoints <= 499) {
    $carClass = 'CC06';
} elseif ($totalPoints >= 500 && $totalPoints <= 549) {
    $carClass = 'CC07';
} elseif ($totalPoints >= 550 && $totalPoints <= 599) {
    $carClass = 'CC08';
} elseif ($totalPoints >= 600 && $totalPoints <= 649) {
    $carClass = 'CC09';
} elseif ($totalPoints >= 650 && $totalPoints <= 699) {
    $carClass = 'CC10';
} elseif ($totalPoints >= 700 && $totalPoints <= 749) {
    $carClass = 'CC11';
} elseif ($totalPoints >= 750 && $totalPoints <= 824) {
    $carClass = 'CC12';
} elseif ($totalPoints >= 825 && $totalPoints <= 899) {
    $carClass = 'CC13';
} elseif ($totalPoints >= 900 && $totalPoints <= 974) {
    $carClass = 'CC14';
} elseif ($totalPoints >= 975 && $totalPoints <= 1049) {
    $carClass = 'CC15';
} elseif ($totalPoints >= 1050 && $totalPoints <= 1149) {
    $carClass = 'CC16';
} elseif ($totalPoints >= 1150 && $totalPoints <= 1249) {
    $carClass = 'CC17';
} elseif ($totalPoints >= 1250) {
    $carClass = 'CC18';
}
...
</code>```

Body:
I compare an input value to multiple range of values to determine the string value for another variable.  The below code works, but I am wondering if there is a more elegant solution?

...
if ($totalPoints >= 0 && $totalPoints <= 249) {
    $carClass = 'CC01';
} elseif ($totalPoints >= 250 && $totalPoints <= 299) {
    $carClass = 'CC02';
} elseif ($totalPoints >= 300 && $totalPoints <= 349) {
    $carClass = 'CC03';
} elseif ($totalPoints >= 350 && $totalPoints <= 399) {
    $carClass = 'CC04';
} elseif ($totalPoints >= 400 && $totalPoints <= 449) {
    $carClass = 'CC05';
} elseif ($totalPoints >= 450 && $totalPoints <= 499) {
    $carClass = 'CC06';
} elseif ($totalPoints >= 500 && $totalPoints <= 549) {
    $carClass = 'CC07';
} elseif ($totalPoints >= 550 && $totalPoints <= 599) {
    $carClass = 'CC08';
} elseif ($totalPoints >= 600 && $totalPoints <= 649) {
    $carClass = 'CC09';
} elseif ($totalPoints >= 650 && $totalPoints <= 699) {
    $carClass = 'CC10';
} elseif ($totalPoints >= 700 && $totalPoints <= 749) {
    $carClass = 'CC11';
} elseif ($totalPoints >= 750 && $totalPoints <= 824) {
    $carClass = 'CC12';
} elseif ($totalPoints >= 825 && $totalPoints <= 899) {
    $carClass = 'CC13';
} elseif ($totalPoints >= 900 && $totalPoints <= 974) {
    $carClass = 'CC14';
} elseif ($totalPoints >= 975 && $totalPoints <= 1049) {
    $carClass = 'CC15';
} elseif ($totalPoints >= 1050 && $totalPoints <= 1149) {
    $carClass = 'CC16';
} elseif ($totalPoints >= 1150 && $totalPoints <= 1249) {
    $carClass = 'CC17';
} elseif ($totalPoints >= 1250) {
    $carClass = 'CC18';
}
...

Body:
This might be a more compact solution:

function findInRange($number, $array)
{
    foreach ($array as $key => $value) {
        list($min, $max) = explode('-', $key);
        if (
            $number >= $min && $number <= $max) {
            return $value;
        }
    }

    return null;
}

$totalPoints = 1300;

$carClassArray = [
    "0-249" => 'CC01',
    "250-299" => 'CC02',
    "300-349" => 'CC03',
    "250-399" => 'CC04',
    "400-449" => 'CC05',
    "450-499" => 'CC06',
    "500-549" => 'CC07',
    "550-599" => 'CC08',
    "600-649" => 'CC09',
    "650-699" => 'CC10',
    "749-1000000" => 'CC11',
];
$carClass = findInRange($totalPoints, $carClassArray);

echo $carClass;


问:
Default reviewers gitlab
Long story short: I have a subgroup that contains 100 project, I want to assign default MR reviewers for this subgrouo so it can apply on all the projects there!
Is there any hacky way to do it? Gitlab doesnt offer the possibility to configure this per-subgroup level.
Thanks</p>

答:
A hacky way might be to create a job in the MR pipeline to do this using a project access token or group access token with API read/write scope.

Example using python-gitlab's CLI.

First, create a group access token and set it on the subgroup CI/CD variables settings as GROUP_ACCESS_TOKEN.

Then also set a REVIEWER_IDS variable on the subgroup with the user IDs of the default reviewers.

assign-mr:
  stage: .post  # use .post to avoid getting in the way of other jobs
  needs: []  # start immediately
  variables:
    # set these variables at the subgroup level settings:
    # User IDs of the reviewers you want to add to the MR
    # REVIEWER_IDS: "1,2,3"
    # set this as a masked variable at the subgroup settings:
    # GROUP_ACCESS_TOKEN: <secret!>

    GIT_STRATEGY: none  # skip checkout
    GITLAB_URL: "$CI_SERVER_URL"  # used by python-gitlab
    GITLAB_PRIVATE_TOKEN: "$GROUP_ACCESS_TOKEN" # used by python-gitlab

  image:
    name: registry.gitlab.com/python-gitlab/python-gitlab:latest
    entrypoint: [""]
  rules:
    - if '$CI_PIPELINE_SOURCE == "merge_request"'
  script: |
    if [[ -f ".done" ]]; then
        echo "Already successfully updated MR. Skipping!" > /dev/stderr
        exit 0
    fi
    gitlab project-merge-request update \
      --project-id "$CI_PROJECT_ID" \
      --iid "$CI_MERGE_REQUEST_IID" \
      --reviewer-ids "$REVIEWER_IDS" \
   && \
   touch .done  # marker to know if we successfully updated the MR

  cache: # use a cache so we only update the MR once (allowing changes afterwards)
    key: "$CI_MERGE_REQUEST_IID"
    paths:
      - .done
```

Title: Default reviewers gitlab


答: Just a guess, but I'd say it boxes o as an integer and then converts it to a nullable.</p>

Title: Why can the as operator be used with Nullable<T>?


问:
Pywhatkit and auto-py-to-exe
my problem is basically that made a script in python using pywhatkit, in the console, it works fine but then when i convert py into exe and try to send the message just see a cmd opening and closing immediately and nothing happens. I also put a debug in the application but nothing shows up</p>

答:
It happens because your pywhatkit dependency not added to the .EXE file.
You should open the projectname.spec file and edit the following lines:

```<code># -*- mode: python ; coding: utf-8 -*-
**from PyInstaller.utils.hooks.import collect_submodules**

block_cipher = None
**hidden_imports= collect_submodules('pywhatkit')**

a = Analysis(
    ['mine.py'],
    pathex=[],
    binaries=[],
    datas=[],
    **hiddenimports=hidden_imports,**
    hookspath=[],
    hooksconfig={},
    runtime_hooks=[],
    excludes=[],
    win_no_prefer_redirects=False,
    win_private_assemblies=False,
    cipher=block_cipher,
    noarchive=False,
)
pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher)

exe = EXE(
    pyz,
    a.scripts,
    a.binaries,
    a.zipfiles,
    a.datas,
    [],
    name='mine',
    debug=False,
    bootloader_ignore_signals=False,
    strip=False,
    upx=True,
    upx_exclude=[],
    runtime_tmpdir=None,
    console=True,
    disable_windowed_traceback=False,
    argv_emulation=False,
    target_arch=None,
    codesign_identity=None,
    entitlements_file=None,
)
</code>```

After saving the file you should run this file like the previous file.

```<code>pyinstaller --onefile projectname.spec
</code>```

like that you have to install all the dependencies.

Title: Pywhatkit and auto-py-to-exe

Body:
It happens because your pywhatkit dependency not added to the .EXE file.
You should open the projectname.spec file and edit the following lines:

# -*- mode: python ; coding: utf-8 -*-
**from PyInstaller.utils.hooks.import collect_submodules**

block_cipher = None
**hidden_imports= collect_submodules('pywhatkit')**

a = Analysis(
    ['mine.py'],
    pathex=[],
    binaries=[],
    datas=[],
    **hiddenimports=hidden_imports,**
    hookspath=[],
    hooksconfig={},
    runtime_hooks=[],
    excludes=[],
    win_no_prefer_redirects=False,
    win_private_assemblies=False,
    cipher=block_cipher,
    noarchive=False,
)
pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher)

exe = EXE(
    pyz,
    a.scripts,
    a.binaries,
    a.zipfiles,
    a.datas,
    [],
    name='mine',
    debug=False,
    bootloader_ignore_signals=False,
    strip=False,
    upx=True,
    upx_exclude=[],
    runtime_tmpdir=None,
    console=True,
    disable_windowed_traceback=False,
    argv_emulation=False,
    target_arch=None,
    codesign_identity=None,
    entitlements_file=None,
)

After saving the file you should run this file like the previous file.

pyinstaller --onefile projectname.spec

like that you have to install all the dependencies.


问:
How to reduce the size of .exe when publish it to folder as single file
I have a very small project (WinForms, it contains 2 folders and 10 classes, simple windows for input) and I want to publish it to folder as single .exe file.
When it is done the size of the file is 140MB. When I add "Trim unused assemblies" mark - 90 MB.

How can I add reduce the size this .exe file? I faced something like this before, and the size of the file was about 1 MB.

My publish config:

Configuration: Debug | Any CPU

Target framework: net5.0 windows

Deployment mode: self-contained (produce single file)

Target runtime: win x-86

答:
Set the configuration to Release instead of Debug.

That will already add some optimazation.

The self-contained part should be disabled when optimizing for size. Disabling it will leave out the .net runtime, otherwise being embedded partially which saves space, but you must be sure the user has the appropriate .net runtime installed.

If your folders contain big files which are embedded, resources like videos, then there's nothing that can be done.

If it's a small project you can consider "just to compile it". If you're not using any non standard DLLs it result in a single (smaller) exe.

I am actually pretty fond of the self-contained option: it saves me the hassle of making sure the user/system has the correct .net vesion installed.