问:
Tabulate based on number of times ID occurs AND another column value R
I'm formatting a table for a study to count how many times a person had a biological sample collected. The table shows how many separate clinic visits a person had a sample type collected.

I want to count how many times an ID appeared for each sample type. For example, if a person with ID = "1234" had the ID appear 4 times with "DNA" in the SAMPLETYPE column, then they had DNA collected at 4 visits. I want the table to look like this:

SAMPLETYPE
1 VISIT
2 VISITS
3 VISITS

DNA
80
47
24

RNA
36
12
6

SERUM
112
89
65

My dataframe is structured like this:

```<code>SAMPLETYPE <- c("DNA","DNA","RNA","PLASMA","RNA","RNA","DNA","PLASMA","PLASMA","PLASMA",
"RNA","RNA","RNA")
ID <- c("1","1","1","2","3","2","4","4","4","5","1","1","1")
df <- data.frame(ID,SAMPLETYPE)

df
   ID SAMPLETYPE
1   1        DNA
2   1        DNA
3   1        RNA
4   2     PLASMA
5   3        RNA
6   2        RNA
7   4        DNA
8   4     PLASMA
9   4     PLASMA
10  5     PLASMA

</code>```

Above, ID = 1 had DNA collected at 2 visits and had RNA collected at 1 visit. The expected output would be:

SAMPLETYPE
1 VISIT
2 VISITS
3 VISITS

DNA
1
1
0

RNA
3
0
1

PLASMA
2
1
0

How would I manipulate this dataframe in R to build a table in the format of the example?

答:
```<code>library(tidyverse)
df %>%
  count(SAMPLETYPE, ID) %>%   # count the combinations
  count(SAMPLETYPE, n) %>%    # count the frequency of combinations
  pivot_wider(names_from = n, names_prefix = "visits_",
              values_from = nn, values_fill = 0)
</code>```

I get different output from the most recent example data. For example, it looks like ID 1 had 4 RNA visits, and ID 2 & 3 each had 1.

```<code># A tibble: 3 x 4
  SAMPLETYPE visits_1 visits_2 visits_4
  <chr>         <int>    <int>    <int>
1 DNA               1        1        0
2 PLASMA            2        1        0
3 RNA               2        0        1
</code>```

Body:
I'm formatting a table for a study to count how many times a person had a biological sample collected. The table shows how many separate clinic visits a person had a sample type collected.

I want to count how many times an ID appeared for each sample type. For example, if a person with ID = "1234" had the ID appear 4 times with "DNA" in the SAMPLETYPE column, then they had DNA collected at 4 visits. I want the table to look like this:

SAMPLETYPE
1 VISIT
2 VISITS
3 VISITS

DNA
80
47
24

RNA
36
12
6

SERUM
112
89
65

My dataframe is structured like this:

SAMPLETYPE <- c("DNA","DNA","RNA","PLASMA","RNA","RNA","DNA","PLASMA","PLASMA","PLASMA",
"RNA","RNA","RNA")
ID <- c("1","1","1","2","3","2","4","4","4","5","1","1","1")
df <- data.frame(ID,SAMPLETYPE)

df
   ID SAMPLETYPE
1   1        DNA
2   1        DNA
3   1        RNA
4   2     PLASMA
5   3        RNA
6   2        RNA
7   4        DNA
8   4     PLASMA
9   4     PLASMA
10  5     PLASMA

Above, ID = 1 had DNA collected at 2 visits and had RNA collected at 1 visit. The expected output would be:

SAMPLETYPE
1 VISIT
2 VISITS
3 VISITS

DNA
1
1
0

RNA
3
0
1

PLASMA
2
1
0

How would I manipulate this dataframe in R to build a table in the format of the example?

Body:
library(tidyverse)
df %>%
  count(SAMPLETYPE, ID) %>%   # count the combinations
  count(SAMPLETYPE, n) %>%    # count the frequency of combinations
  pivot_wider(names_from = n, names_prefix = "visits_",
              values_from = nn, values_fill = 0)

I get different output from the most recent example data. For example, it looks like ID 1 had 4 RNA visits, and ID 2 & 3 each had 1.

# A tibble: 3 x 4
  SAMPLETYPE visits_1 visits_2 visits_4
  <chr>         <int>    <int>    <int>
1 DNA               1        1        0
2 PLASMA            2        1        0
3 RNA               2        0        1


来源: stackexchange

问:
Why is there no download dSYM button in Testflight for my app?
If I navigate to the Build Metadata section for my app within App Store Connect then the Includes Symbols section just says Yes, there is no blue Download dSYM button there.

The XCode build build options Debug Information Format is set to DWARF with dSYM.

So why is there no dSYM on App Store Connect?

答:
Apple responded and said they are looking into the issue:

Thanks for letting us know! Our teams are looking into this. To stay updated on the progress and help with the investigation, please be sure to file a feedback report or contact support directly.

ASC Doesn't generate DSYM file - https://developer.apple.com/forums/thread/700051?answerId=704176022#704176022

ContentLicense: CC BY-SA 4.0


问:
What exact command is to install pm2 on offline RHEL
First of all it's not a duplicate question of below:-

How to install npm -g on offline server

https://stackoverflow.com/questions/40976100/how-to-installl-pm2-on-offline-server

I install npmbox (https://github.com/arei/npmbox) on my offline REHL server but I'm still do not know how to install pm2 or any other package using that.

Please advise.

答:
An alternate way to install pm2 offline is:

Create the tar file with the above steps mentioned by @soren.

in my case Installation hung while executing "npm install pm2.tar.gz".

```<code>npm install pm2.tar.gz

[..................] - fetchMetadata: sill resolveWithNewModule pm2@5.1.2 checking installable status
[..................] - fetchMetadata: sill resolveWithNewModule pm2@5.1.2 checking installable status
</code>```

to get this resolved I have added the npm registry but that did not work.

```<code>npm config set registry="http://registry.npmjs.org"
</code>```

Server's are into the DMZ or in a private subnet that's it's was not working.

Solution:-

Get the install path of the node_module directory

```<code>#npm config get prefix
</code>```

Extract the tar file & Copy the pm2 directory to node_module

```<code> #tar -zxvf pm2.tar.gz
 #cp pm2 /usr/local/lib/node_modules/npm/node_modules/ -r
</code>```

cd into the /usr/bin & Crete the simlink for pm2

```<code> # cd /usr/bin
 #ln -s /usr/local/lib/node_modules/npm/node_modules/pm2/bin/pm2 pm2
</code>```

check pm2 command output & its output.

```<code>    # pm2
    usage: pm2 [options] <command>

    pm2 -h, --help             all available commands and options
    pm2 examples               display pm2 usage examples
    pm2 <command> -h           help on a specific command

    Access pm2 files in ~/.pm2
</code>```

ContentLicense: CC BY-SA 3.0

Body:
An alternate way to install pm2 offline is:

Create the tar file with the above steps mentioned by @soren.

in my case Installation hung while executing "npm install pm2.tar.gz".

npm install pm2.tar.gz

[..................] - fetchMetadata: sill resolveWithNewModule pm2@5.1.2 checking installable status
[..................] - fetchMetadata: sill resolveWithNewModule pm2@5.1.2 checking installable status

to get this resolved I have added the npm registry but that did not work.

npm config set registry="http://registry.npmjs.org"

Server's are into the DMZ or in a private subnet that's it's was not working.

Solution:-

Get the install path of the node_module directory

#npm config get prefix

Extract the tar file & Copy the pm2 directory to node_module

 #tar -zxvf pm2.tar.gz
 #cp pm2 /usr/local/lib/node_modules/npm/node_modules/ -r

cd into the /usr/bin & Crete the simlink for pm2

 # cd /usr/bin
 #ln -s /usr/local/lib/node_modules/npm/node_modules/pm2/bin/pm2 pm2

check pm2 command output & its output.

    # pm2
    usage: pm2 [options] <command>

    pm2 -h, --help             all available commands and options
    pm2 examples               display pm2 usage examples
    pm2 <command> -h           help on a specific command

    Access pm2 files in ~/.pm2


问:
Unable to access HealthKit permissions for my app in Settings
I recently published an app to the App Store that reads several metrics from HealthKit. It all seems to be working correctly in the app (permissions screen loads fine and data is being read okay) but when I go to Settings > Privacy > Health > MY APP, there is just a blank screen with no data.

I've seen this bug with other apps (MyFitnessPal, Balance) and a forum recommended deleting and reinstalling, which fixed it for them. But it doesn't fix my app at all.

Can anyone think of something I might have missed that's creating this issue?

Thanks

答:
This should be addressed in iOS 15.4 Beta 1. Can you try there?

You should also be able to access your apps authorizations from within Health App. Go to Profile View and navigate to your app under the Apps view.


问:
Docker Failed to Initialize on Windows 10
I have an issue with running the Docker Desktop on my Windows 10 PC. After trying to run it I got an error:

Docker failed to initialize - Docker Desktop is shutting down

I already tried reinstalling (as admin), restarting PC, restarting docker services, removing content from .../AppData/Local/Docker and .../AppData/Roaming/Docker folders, but still receiving the same error message.

Does anyone have an idea how can I fix it?

Thank you a lot!

答: Downgrade to the older version solved my issue</p>


问:
HTML disable zoom on page apart from the images
I'm creating a simple PWA, and I'm trying to make it looks like a native mobile application though I'm having several problems with the pinch-in.

I've added this code to my layout.html (I'm using Flask for the backend)

```<code><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
</code>```

Although it really works as I want, there are some images that I want the user to be able to zoom in, and I know is not recommended to disable the scalable zoom for mobile but really, this is what I want, no zoom on the entire page apart from the imgs tag I have.
I'd like to have a pure css/js solution or at most something that does not need npm even a cdn is good for me

答:
Set height and/or width of elements that ARE NOT images to vh or vw.

https://www.w3schools.com/cssref/css_units.asp
vh - viewport height - represents fraction of screen height. When you zoom in - (for example) font stays the same size

```<code>div {
   font-size: 2vh;
}
</code>```

Body:
I'm creating a simple PWA, and I'm trying to make it looks like a native mobile application though I'm having several problems with the pinch-in.

I've added this code to my layout.html (I'm using Flask for the backend)

<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">

Although it really works as I want, there are some images that I want the user to be able to zoom in, and I know is not recommended to disable the scalable zoom for mobile but really, this is what I want, no zoom on the entire page apart from the imgs tag I have.
I'd like to have a pure css/js solution or at most something that does not need npm even a cdn is good for me

Body:
Set height and/or width of elements that ARE NOT images to vh or vw.

https://www.w3schools.com/cssref/css_units.asp
vh - viewport height - represents fraction of screen height. When you zoom in - (for example) font stays the same size

div {
   font-size: 2vh;
}


问:
TypeError: max() got an unexpected keyword argument 'key'
Python 3.9.7
Running example code and getting the error: TypeError: max() got an unexpected keyword argument 'key'</p>
```<code>lis=[(101, 153), (255, 827), (361, 961)]
from operator import itemgetter
max(lis,key=itemgetter(1))[0]
</code>```

答:
Try:

import builtins
lis=[(101, 153), (255, 827), (361, 961)]
from operator import itemgetter
builtins.max(lis,key=itemgetter(1))[0]
```

If it works, it should confirm that you redefined max somewhere along the way.

Body:
Python 3.9.7
Running example code and getting the error: TypeError: max() got an unexpected keyword argument 'key'

lis=[(101, 153), (255, 827), (361, 961)]
from operator import itemgetter
max(lis,key=itemgetter(1))[0]

Body:
Try:

import builtins
lis=[(101, 153), (255, 827), (361, 961)]
from operator import itemgetter
builtins.max(lis,key=itemgetter(1))[0]

If it works, it should confirm that you redefined max somewhere along the way.


问:
Java NullPointerException when there are no variables not initialiased
I am creating this login form using java swing and what I basically do is I get the values from the relevant JtextFields and send them onto another class. Thereafter I check it with the database records. However the program is always displaying a NullPointerException everytime I run it. I tested every variable and saw that none of them contain any Null Values at all.

This is the first method (in the LoginPage class) that gets the values from the JTextField

```<code>public void actionPerformed(ActionEvent e) {
String user=textField.getText();
String pass=String.valueOf(passwordField.getPassword());

//try{
//if((user!=null)&&(pass!=null)){
//  System.out.println("user is not null");

ui.sendLogin(user,pass);

//}else{}
//}catch(NullPointerException ex){
    //System.out.println("Entered catch block og view"+ex.getMessage());
//}
</code>```

}

Thereafter it calls this method (in class LoginController)

```<code>public void sendLogin(String user, String pass) {
try{
    System.out.println("values from sendLogin"+user+"pass"+pass);
    model.verifyUser(user,pass);
}catch(NullPointerException ex){
    System.out.println("Entered catch block os sendLogin"+ex);
    ex.printStackTrace();
}
}
</code>```

Finally the verifyUser method (in class LoginModel) checks it with the database

```<code> public void verifyUser(String user,String pass){
        String username="";
        String password="";
        String acc="";
         try{
             String sql="SELECT * FROM users";
             con1.getInstance();
             Statement st = con1.getConn().createStatement();
             ResultSet rs=st.executeQuery(sql);
             rs.next();
             username=rs.getString("username");
             password=rs.getString("password");
             acc=rs.getString("accountType");
             if(username.equals(user)&&password.equals(pass)){
                 System.out.println("Logged into the system");
                 global_username=username;
                 accountType=acc;
             }else{
                 System.out.println("Unsuccessful login"+username+user+password+pass);
             }
            st.execute(sql);
        } catch (SQLException s){
            System.out.println("SQL statement is not executed!"+s);
        }

}
</code>```

This is the Stack Trace

```<code>java.lang.NullPointerException
    at org.application.view.LoginController.sendLogin(LoginController.java:64)
    at org.application.view.LoginPage$2.actionPerformed(LoginPage.java:94)
user is not null
values from sendLoginapassabc
Entered catch block os sendLoginjava.lang.NullPointerException
    at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
    at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
    at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
    at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
    at java.awt.Component.processMouseEvent(Unknown Source)
    at javax.swing.JComponent.processMouseEvent(Unknown Source)
    at java.awt.Component.processEvent(Unknown Source)
    at java.awt.Container.processEvent(Unknown Source)
    at java.awt.Component.dispatchEventImpl(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Window.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    at java.awt.EventQueue.access$000(Unknown Source)
    at java.awt.EventQueue$1.run(Unknown Source)
    at java.awt.EventQueue$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
    at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue$2.run(Unknown Source)
    at java.awt.EventQueue$2.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)
</code>```

答: I bet the model variable is null.

Body:
I am creating this login form using java swing and what I basically do is I get the values from the relevant JtextFields and send them onto another class. Thereafter I check it with the database records. However the program is always displaying a NullPointerException everytime I run it. I tested every variable and saw that none of them contain any Null Values at all.

This is the first method (in the LoginPage class) that gets the values from the JTextField

public void actionPerformed(ActionEvent e) {
String user=textField.getText();
String pass=String.valueOf(passwordField.getPassword());

//try{
//if((user!=null)&&(pass!=null)){
//  System.out.println("user is not null");

ui.sendLogin(user,pass);

//}else{}
//}catch(NullPointerException ex){
    //System.out.println("Entered catch block og view"+ex.getMessage());
//}

}

Thereafter it calls this method (in class LoginController)

public void sendLogin(String user, String pass) {
try{
    System.out.println("values from sendLogin"+user+"pass"+pass);
    model.verifyUser(user,pass);
}catch(NullPointerException ex){
    System.out.println("Entered catch block os sendLogin"+ex);
    ex.printStackTrace();
}
}

Finally the verifyUser method (in class LoginModel) checks it with the database

 public void verifyUser(String user,String pass){
        String username="";
        String password="";
        String acc="";
         try{
             String sql="SELECT * FROM users";
             con1.getInstance();
             Statement st = con1.getConn().createStatement();
             ResultSet rs=st.executeQuery(sql);
             rs.next();
             username=rs.getString("username");
             password=rs.getString("password");
             acc=rs.getString("accountType");
             if(username.equals(user)&&password.equals(pass)){
                 System.out.println("Logged into the system");
                 global_username=username;
                 accountType=acc;
             }else{
                 System.out.println("Unsuccessful login"+username+user+password+pass);
             }
            st.execute(sql);
        } catch (SQLException s){
            System.out.println("SQL statement is not executed!"+s);
        }

}

This is the Stack Trace

java.lang.NullPointerException
    at org.application.view.LoginController.sendLogin(LoginController.java:64)
    at org.application.view.LoginPage$2.actionPerformed(LoginPage.java:94)
user is not null
values from sendLoginapassabc
Entered catch block os sendLoginjava.lang.NullPointerException
    at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
    at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
    at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
    at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
    at java.awt.Component.processMouseEvent(Unknown Source)
    at javax.swing.JComponent.processMouseEvent(Unknown Source)
    at java.awt.Component.processEvent(Unknown Source)
    at java.awt.Container.processEvent(Unknown Source)
    at java.awt.Component.dispatchEventImpl(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Window.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    at java.awt.EventQueue.access$000(Unknown Source)
    at java.awt.EventQueue$1.run(Unknown Source)
    at java.awt.EventQueue$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
    at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue$2.run(Unknown Source)
    at java.awt.EventQueue$2.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)

Body: I bet the model variable is null.


问:
Can't type anything while running code in netbeans
Ok so I'm having troubles with netbeans. When I run the code I can't type anything, i can only paste something and that's annoying. Let's just have a very simple example, here's the code:

```<code>    #include <iostream>

int main() {
    int number;
    std::cout << "Give me a number: " << std::endl;
    std::cin >> number;
    std::cout << "You gave me " << number << ". Thank you." << std::endl;
}
</code>```

Ok when I hit run it shows me "Give me number". Under that text there is a white box which becomes black when i click it and i can't type anything, so only way to move forward is copying the number and the paste it.

答:
On your Netbeans IDE,
Right click on your Project > Properties > Run > Console Type >> Then change it to external console.

This way "cin" will work with you and record your input.

Body:
Ok so I'm having troubles with netbeans. When I run the code I can't type anything, i can only paste something and that's annoying. Let's just have a very simple example, here's the code:

    #include <iostream>

int main() {
    int number;
    std::cout << "Give me a number: " << std::endl;
    std::cin >> number;
    std::cout << "You gave me " << number << ". Thank you." << std::endl;
}

Ok when I hit run it shows me "Give me number". Under that text there is a white box which becomes black when i click it and i can't type anything, so only way to move forward is copying the number and the paste it.


问:
RuntimeError: Model class mainpage_authentication.models.User doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS
Before applying models to my project everything was okay. But when I just applied them, the system crushed. I'm a freshmen learning Django, so will be grateful for an explanation, and a solution, if possible.

My code:

admin.py

```<code>from django.contrib import admin
from .models import User

admin.site.register(User)
</code>```

apps.py

```<code>from django.apps import AppConfig

class AuthenticationPageConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'mainpage_authentication'
</code>```

forms.py

```<code>from django import forms
from .models import User

class AuthenticationLoginForm(forms.Form):
    class Meta:
        model = User
        fields = ['username', 'password']
</code>```

models.py

```<code>from django.db import models

class User(models.Model):
    username = models.CharField(max_length=100)
    password = models.CharField(max_length=100)
</code>```

settings.py

```<code>INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'mainpage_authentication',
]
</code>```

views.py

```<code>from django.shortcuts import render
from django import views
from mainpage_authentication.forms import AuthenticationLoginForm

class MainPageView(views.View):
    def get(self, request):
        return render(request, 'mainpage.html')

class AuthenticationLoginPageView(views.View):
    def get(self, request):
        form: AuthenticationLoginForm = AuthenticationLoginForm()
        return render(request, 'authentication-page.html', {"form": form})
</code>```

答:
You can use

```<code>from mainpage_authentication.models import User
</code>```

instead of

```<code>from .models import User
</code>```

Basically use an absolute import instead of a relative import for that model.

Body:
Before applying models to my project everything was okay. But when I just applied them, the system crushed. I'm a freshmen learning Django, so will be grateful for an explanation, and a solution, if possible.

My code:

admin.py

from django.contrib import admin
from .models import User

admin.site.register(User)

apps.py

from django.apps import AppConfig

class AuthenticationPageConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'mainpage_authentication'

forms.py

from django import forms
from .models import User

class AuthenticationLoginForm(forms.Form):
    class Meta:
        model = User
        fields = ['username', 'password']

models.py

from django.db import models

class User(models.Model):
    username = models.CharField(max_length=100)
    password = models.CharField(max_length=100)

settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'mainpage_authentication',
]

views.py

from django.shortcuts import render
from django import views
from mainpage_authentication.forms import AuthenticationLoginForm

class MainPageView(views.View):
    def get(self, request):
        return render(request, 'mainpage.html')

class AuthenticationLoginPageView(views.View):
    def get(self, request):
        form: AuthenticationLoginForm = AuthenticationLoginForm()
        return render(request, 'authentication-page.html', {"form": form})

Body:
You can use

from mainpage_authentication.models import User

instead of

from .models import User

Basically use an absolute import instead of a relative import for that model.


问:
Converting a PyG graph to a NetworkX graph
I am trying to convert my PyG graph to a NetworkX graph using to_networkx

According to the docs I can optionally pass node and edge attributes as str iterables, in addition to the Data object.

Below are by node and edge attribute lists, with values converted to strings:

```<code>Nodes:  ['3.3375725746154785', '2.0086510181427',..., '1.5960148572921753', '3.621992349624634']

Edges:  ['0.9940207804344958', '0.48573804411542043', ..., '0.7245483440145621', '0.24117984598949904']
</code>```

to_networkx runs fine when I only pass it the Data object. However, when I also pass these attribute lists, I get the below error:

```<code>G[u][v][key] = values[key][i]
KeyError: '0.30194718370332896'
</code>```

I've looked at the source code, but can't make out what it is doing. Could someone please help explain what is wrong with my attribute lists and what I need to change for them to be accepted.

What I can make out is that this error is specifically referring to my edge attributes. If I remove them, I get the following similar error related to the node attributes:

```<code>feat_dict.update({key: values[key][i]})
KeyError: '0.0'
</code>```

How I construct my graph and pass it to to_networkx:

```<code>n1 = np.repeat(np.array([0,1,2,3,4,5,6]),5)
n2 = np.array([0,1,2,3,4,0,1,2,3,4,0,1,2,3,4,0,1,2,3,4,0,1,2,3,4,0,1,2,3,4,0,1,2,3,4])
cat = np.stack((n1,n2), axis=0)
e = torch.tensor(cat, dtype=torch.long)
edge_index = e.t().clone().detach()
edge_attr = torch.tensor(np.random.rand(35,1))

x = torch.tensor([[0], [0], [0], [0], [0], [1], [1]], dtype=torch.float)

data = Data(x=x, edge_index=edge_index.t().contiguous(), edge_attr = edge_attr)
</code>```

Before I pass the node and edge attributes, I do the string conversion to conform to the str iterable requirment:

```<code>networkx_node_values = list(map(str, data.x.t()[0].tolist()))
networkx_edge_values = list(map(str, edge_attr.t()[0].tolist()))

networkX_graph = to_networkx(data, node_attrs = networkx_node_values, edge_attrs = networkx_edge_values)
</code>```

答:
You need to pass the names of the attributes as a list:

```<code>to_networkx(<PyTorchGeometricDataObject>, node_attrs=[<Name of Node Attribute 1>, <Name of Node Attributes 2>, ... ], edge_attr=[<Edge Attribute 1>, ...])
</code>```

Or in context, based on your given minimal example:

```<code>import numpy as np
import torch
from torch_geometric.data import Data
from torch_geometric.utils import to_networkx

n1 = np.repeat(np.array([0,1,2,3,4,5,6]),5)
n2 = np.array([0,1,2,3,4,0,1,2,3,4,0,1,2,3,4,0,1,2,3,4,0,1,2,3,4,0,1,2,3,4,0,1,2,3,4])
cat = np.stack((n1,n2), axis=0)
e = torch.tensor(cat, dtype=torch.long)
edge_index = e.t().clone().detach()
edge_attr = torch.tensor(np.random.rand(35,1))

x = torch.tensor([[0], [0], [0], [0], [0], [1], [1]], dtype=torch.float)

data = Data(x=x, edge_index=edge_index.t().contiguous(), edge_attr = edge_attr)
print(data)
# Data(edge_attr=[35, 1], edge_index=[2, 35], x=[7, 1])

networkX_graph = to_networkx(data, node_attrs=["x"], edge_attrs=["edge_attr"])

print(networkX_graph.nodes(data=True))
# [(0, {'x': 0.0}), (1, {'x': 0.0}),...
print(networkX_graph.edges(data=True))
# [(0, 0, {'edge_attr': 0.3412137594357493}), ...
</code>```

Body:
I am trying to convert my PyG graph to a NetworkX graph using to_networkx

According to the docs I can optionally pass node and edge attributes as str iterables, in addition to the Data object.

Below are by node and edge attribute lists, with values converted to strings:

Nodes:  ['3.3375725746154785', '2.0086510181427',..., '1.5960148572921753', '3.621992349624634']

Edges:  ['0.9940207804344958', '0.48573804411542043', ..., '0.7245483440145621', '0.24117984598949904']

to_networkx runs fine when I only pass it the Data object. However, when I also pass these attribute lists, I get the below error:

G[u][v][key] = values[key][i]
KeyError: '0.30194718370332896'

I've looked at the source code, but can't make out what it is doing. Could someone please help explain what is wrong with my attribute lists and what I need to change for them to be accepted.

What I can make out is that this error is specifically referring to my edge attributes. If I remove them, I get the following similar error related to the node attributes:

feat_dict.update({key: values[key][i]})
KeyError: '0.0'

How I construct my graph and pass it to to_networkx:

n1 = np.repeat(np.array([0,1,2,3,4,5,6]),5)
n2 = np.array([0,1,2,3,4,0,1,2,3,4,0,1,2,3,4,0,1,2,3,4,0,1,2,3,4,0,1,2,3,4,0,1,2,3,4])
cat = np.stack((n1,n2), axis=0)
e = torch.tensor(cat, dtype=torch.long)
edge_index = e.t().clone().detach()
edge_attr = torch.tensor(np.random.rand(35,1))

x = torch.tensor([[0], [0], [0], [0], [0], [1], [1]], dtype=torch.float)

data = Data(x=x, edge_index=edge_index.t().contiguous(), edge_attr = edge_attr)

Before I pass the node and edge attributes, I do the string conversion to conform to the str iterable requirment:

networkx_node_values = list(map(str, data.x.t()[0].tolist()))
networkx_edge_values = list(map(str, edge_attr.t()[0].tolist()))

networkX_graph = to_networkx(data, node_attrs = networkx_node_values, edge_attrs = networkx_edge_values)

Body:
You need to pass the names of the attributes as a list:

to_networkx(<PyTorchGeometricDataObject>, node_attrs=[<Name of Node Attribute 1>, <Name of Node Attributes 2>, ... ], edge_attr=[<Edge Attribute 1>, ...])

Or in context, based on your given minimal example:

import numpy as np
import torch
from torch_geometric.data import Data
from torch_geometric.utils import to_networkx

n1 = np.repeat(np.array([0,1,2,3,4,5,6]),5)
n2 = np.array([0,1,2,3,4,0,1,2,3,4,0,1,2,3,4,0,1,2,3,4,0,1,2,3,4,0,1,2,3,4,0,1,2,3,4])
cat = np.stack((n1,n2), axis=0)
e = torch.tensor(cat, dtype=torch.long)
edge_index = e.t().clone().detach()
edge_attr = torch.tensor(np.random.rand(35,1))

x = torch.tensor([[0], [0], [0], [0], [0], [1], [1]], dtype=torch.float)

data = Data(x=x, edge_index=edge_index.t().contiguous(), edge_attr = edge_attr)
print(data)
# Data(edge_attr=[35, 1], edge_index=[2, 35], x=[7, 1])

networkX_graph = to_networkx(data, node_attrs=["x"], edge_attrs=["edge_attr"])

print(networkX_graph.nodes(data=True))
# [(0, {'x': 0.0}), (1, {'x': 0.0}),...
print(networkX_graph.edges(data=True))
# [(0, 0, {'edge_attr': 0.3412137594357493}), ...


问:
How to fix css in django cycle?
I want to do div titleblog and do magrin-top:100px,but it isnt working in django cycle..Idk why.I tried to do class='titleblog',but it wasnt working). P.S css file is attached at html file.CSS file is working,because navigation panel is displaying.

blog.html

```<code><div class="titleblog">
{% for i in objects  %}
<a href="{{i.id}}">{{i.titleblog}}</a>
<b>{{i.message | lower}}</b>
{% endfor %}
</div>
</code>```

home.css

```<code>.titleblog{
    margin-top: 100px;
}
</code>```

答:
You can try</p>
```<code>{% for i in objects  %}
<div class="titleblog">
    <a href="{{i.id}}">{{i.titleblog}}</a>
    <b>{{i.message | lower}}</b>
</div>
{% endfor %}
</code>```

Title: How to fix css in django cycle?

Body:
I want to do div titleblog and do magrin-top:100px,but it isnt working in django cycle..Idk why.I tried to do <a class='titleblog',but it wasnt working). P.S css file is attached at html file.CSS file is working,because navigation panel is displaying.

blog.html

{% for i in objects  %}
{{i.titleblog}}
{{i.message | lower}}
{% endfor %}

home.css

.titleblog{
    margin-top: 100px;
}

Body:
You can try

{% for i in objects  %}
<div class="titleblog">
    <a href="{{i.id}}">{{i.titleblog}}</a>
    <b>{{i.message | lower}}</b>
</div>
{% endfor %}


问:
Pass jq output to curl
I want to be use a number of values from jq piped to curl. I have json data with a structure that looks something like this

```<code>{
  "apps": {
    "code": "200",
    "name": "app1",
  },
  "result": "1"
}
{
  "apps": {
    "code": "200",
    "name": "app2",
  },
  "result": "5"
}
...
...
...

</code>```

What I want to do is to take the values of every apps.name and result and pass that to curl:

```<code>curl -XPOST http://localhost --data-raw 'app=$appsName result=$result'
</code>```

The curl command will then run X amount of times depending on how many objects there are.
In jq I came up with this but I don't know how or the best way of passing this to curl in a loop.

```<code>jq -r '.result as $result | .apps as $apps | $apps.name + " " + $result myfile.json
</code>```

答:
I think xargs is better than while loops. Maybe just personal preference.

jq -r '"app=\( .apps.name ) result=\( .result )"' \
  | xargs -r -I{} curl -XPOST http://localhost --data-raw "{}"
```

Title: Pass jq output to curl

Body:
I want to be use a number of values from jq piped to curl. I have json data with a structure that looks something like this

{
  "apps": {
    "code": "200",
    "name": "app1",
  },
  "result": "1"
}
{
  "apps": {
    "code": "200",
    "name": "app2",
  },
  "result": "5"
}
...
...
...

What I want to do is to take the values of every apps.name and result and pass that to curl:

curl -XPOST http://localhost --data-raw 'app=$appsName result=$result'

The curl command will then run X amount of times depending on how many objects there are.
In jq I came up with this but I don't know how or the best way of passing this to curl in a loop.

jq -r '.result as $result | .apps as $apps | $apps.name + " " + $result myfile.json


问:
Error: error creating Storage gateway SMB file Share: InvalidGatewayRequestExeption
I tried to run following terraform code o create test smb share but got error

see code

```<code>provider "aws" {
  region = "us-east-1"
}

resource "aws_storagegateway_smb_file_share" "test_smb_share" {
  authentication        = "ActiveDirectory"
  gateway_arn           = "arn:aws:storagegateway:us-east-1:145429107744:gateway/sgw-4xxxxxxx"
  default_storage_class = "S3_STANDARD"
  location_arn          = "arn:aws:s3:::xxxxxxxx"
  role_arn              = "arn:aws:iam::145429107744:role/service-role/StorageGatewayBucketAccessRolee896cdf0-cb46-4471-a0de-119f69f87e"
  valid_user_list       = ["@Domain Admins","@Admins"]
  kms_encrypted         = "true"
  kms_key_arn           = "arn:aws:kms:us-east-1:145429107744:key/8c4b962b-c00a-4a32-8fbd-76b174efb609"
  tags = {
                atomdev     =   "prod"
                atomdomain  =   "xxxxxx"
                atomos      =   "file system"
                atompid     =   "32"
                atomrole    =   "storage"
  }
}
</code>```

aws_storagegateway_smb_file_share.test_smb_share: Creating...
╷
│ Error: error creating Storage Gateway SMB File Share: InvalidGatewayRequestException: OverlappingLocations
│ {
│   RespMetadata: {
│     StatusCode: 400,
│     RequestID: "e8f7466d-23af-4a4c-a457-d39a0f99406d"
│   },
│   Error_: {
│     ErrorCode: "OverlappingLocations"
│   },
│   Message_: "OverlappingLocations"
│ }
│
│   with aws_storagegateway_smb_file_share.test_smb_share,
│   on main.tf line 5, in resource "aws_storagegateway_smb_file_share" "test_smb_share":
│    5: resource "aws_storagegateway_smb_file_share" "test_smb_share" {
│

any idea?

答:
If you try to run two shares on the same SGW that have overlapping S3 locations, you'll get this error.  For example:

```<code>\\my-s3-bucket\folder1\data
\\my-s3-bucket\folder1
</code>```

^ those would overlap, since one would contain a subset of the other

Body:
I tried to run following terraform code o create test smb share but got error

see code

provider "aws" {
  region = "us-east-1"
}

resource "aws_storagegateway_smb_file_share" "test_smb_share" {
  authentication        = "ActiveDirectory"
  gateway_arn           = "arn:aws:storagegateway:us-east-1:145429107744:gateway/sgw-4xxxxxxx"
  default_storage_class = "S3_STANDARD"
  location_arn          = "arn:aws:s3:::xxxxxxxx"
  role_arn              = "arn:aws:iam::145429107744:role/service-role/StorageGatewayBucketAccessRolee896cdf0-cb46-4471-a0de-119f69f87e"
  valid_user_list       = ["@Domain Admins","@Admins"]
  kms_encrypted         = "true"
  kms_key_arn           = "arn:aws:kms:us-east-1:145429107744:key/8c4b962b-c00a-4a32-8fbd-76b174efb609"
  tags = {
                atomdev     =   "prod"
                atomdomain  =   "xxxxxx"
                atomos      =   "file system"
                atompid     =   "32"
                atomrole    =   "storage"
  }
}

aws_storagegateway_smb_file_share.test_smb_share: Creating...
╷
│ Error: error creating Storage Gateway SMB File Share: InvalidGatewayRequestException: OverlappingLocations
│ {
│   RespMetadata: {
│     StatusCode: 400,
│     RequestID: "e8f7466d-23af-4a4c-a457-d39a0f99406d"
│   },
│   Error_: {
│     ErrorCode: "OverlappingLocations"
│   },
│   Message_: "OverlappingLocations"
│ }
│
│   with aws_storagegateway_smb_file_share.test_smb_share,
│   on main.tf line 5, in resource "aws_storagegateway_smb_file_share" "test_smb_share":
│    5: resource "aws_storagegateway_smb_file_share" "test_smb_share" {
│

any idea?

Body:
If you try to run two shares on the same SGW that have overlapping S3 locations, you'll get this error.  For example:

\\my-s3-bucket\folder1\data
\\my-s3-bucket\folder1

^ those would overlap, since one would contain a subset of the other


问:
Importing a Flask extension in Quart using Blueprints
I am currently building a basic application in which I am carrying out measurements with a sensor connected to the hosting Raspberry Pi. To do so, I have decided to go for Quart, as it allows me to run them in the background. I am currently trying to use the cache such that the data can be used by the JS frontend (eg. for downloading, live plotting) through eg. websockets and by other requests. I want to do this with the extension Flask-Caching, which is supported by Quart according to pgjones. However, once I try to initialize the extensions, I get

```<code>Traceback (most recent call last):
  File "/home/andromedan/kubo_sound/webapp/kubo_masking/venv/bin/quart", line 8, in <module>
    sys.exit(main())
  File "/home/andromedan/kubo_sound/webapp/kubo_masking/venv/lib/python3.8/site-packages/quart/cli.py", line 344, in main
    cli.main(args=args, prog_name=name)
  File "/home/andromedan/kubo_sound/webapp/kubo_masking/venv/lib/python3.8/site-packages/quart/cli.py", line 235, in main
    return super().main(*args, **kwargs)
  File "/home/andromedan/kubo_sound/webapp/kubo_masking/venv/lib/python3.8/site-packages/click/core.py", line 1053, in main
    rv = self.invoke(ctx)
  File "/home/andromedan/kubo_sound/webapp/kubo_masking/venv/lib/python3.8/site-packages/click/core.py", line 1653, in invoke
    cmd_name, cmd, args = self.resolve_command(ctx, args)
  File "/home/andromedan/kubo_sound/webapp/kubo_masking/venv/lib/python3.8/site-packages/click/core.py", line 1700, in resolve_command
    cmd = self.get_command(ctx, cmd_name)
  File "/home/andromedan/kubo_sound/webapp/kubo_masking/venv/lib/python3.8/site-packages/quart/cli.py", line 220, in get_command
    command = info.load_app().cli.get_command(ctx, name)  # type: ignore
  File "/home/andromedan/kubo_sound/webapp/kubo_masking/venv/lib/python3.8/site-packages/quart/cli.py", line 72, in load_app
    module = import_module(import_name)
  File "/home/andromedan/anaconda3/lib/python3.8/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 783, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "/home/andromedan/kubo_sound/webapp/kubo_masking/run.py", line 7, in <module>
    app = create_app()
  File "/home/andromedan/kubo_sound/webapp/kubo_masking/app/__init__.py", line 15, in create_app
    cache.init_app(app, config=config.CACHE)
  File "/home/andromedan/kubo_sound/webapp/kubo_masking/venv/lib/python3.8/site-packages/flask_caching/__init__.py", line 220, in init_app
    self._set_cache(app, config)
  File "/home/andromedan/kubo_sound/webapp/kubo_masking/venv/lib/python3.8/site-packages/flask_caching/__init__.py", line 251, in _set_cache
    app.extensions["cache"][self] = cache_factory(
  File "/home/andromedan/kubo_sound/webapp/kubo_masking/venv/lib/python3.8/site-packages/flask_caching/backends/filesystemcache.py", line 95, in factory
    return cls(*args, **kwargs)
  File "/home/andromedan/kubo_sound/webapp/kubo_masking/venv/lib/python3.8/site-packages/flask_caching/backends/filesystemcache.py", line 76, in __init__
    os.makedirs(self._path)
  File "/home/andromedan/anaconda3/lib/python3.8/os.py", line 208, in makedirs
    head, tail = path.split(name)
  File "/home/andromedan/anaconda3/lib/python3.8/posixpath.py", line 103, in split
    p = os.fspath(p)
TypeError: expected str, bytes or os.PathLike object, not NoneType
</code>```

tracing back to the line

cache.init_app(app, config=config.CACHE)
```
<p>in my app factory. This is the app factory</p>
<pre class="lang-py prettyprint-override"><code>import quart.flask_patch

from quart import Quart
from config import Config

# import extensions instance
from flask_caching import Cache

cache = Cache()

def create_app(config=Config):
    app = Quart(__name__)
    app.config.from_object(config)

    # initialize extension instances
    cache.init_app(app, config=config.CACHE)

    # register blueprints of applications
    from app.main import main as main_bp
    app.register_blueprint(main_bp)

    from app.measurement import measurement as measurement_bp
    app.register_blueprint(measurement_bp)

    return app
</code>```

and runfile code

# import the create app application factory
from app import create_app

# import the application config classes
from config import Config

app = create_app()

if __name__ == '__main__':
app.run()
```

The CACHE attribute Config is given by the dictionary {'CACHE_TYPE': 'FileSystemCache'}.

I have tried other options such as cache = Cache(app, config=config.CACHE) to initialize the extension, none of them worked...

Bonus Question: What is the difference between the cache types mentioned in the flask docs?

Thank you!

答: The CACHE attribute in the Config is missing CACHE_DIR, which will define where the FileSystemCache stores cached data. For example, if the CACHE attribute Config was the dictionary {'CACHE_TYPE': 'FileSystemCache', 'CACHE_DIR': '/tmp'}

Body:
I am currently building a basic application in which I am carrying out measurements with a sensor connected to the hosting Raspberry Pi. To do so, I have decided to go for Quart, as it allows me to run them in the background. I am currently trying to use the cache such that the data can be used by the JS frontend (eg. for downloading, live plotting) through eg. websockets and by other requests. I want to do this with the extension Flask-Caching, which is supported by Quart according to pgjones. However, once I try to initialize the extensions, I get

Traceback (most recent call last):
  File "/home/andromedan/kubo_sound/webapp/kubo_masking/venv/bin/quart", line 8, in <module>
    sys.exit(main())
  File "/home/andromedan/kubo_sound/webapp/kubo_masking/venv/lib/python3.8/site-packages/quart/cli.py", line 344, in main
    cli.main(args=args, prog_name=name)
  File "/home/andromedan/kubo_sound/webapp/kubo_masking/venv/lib/python3.8/site-packages/quart/cli.py", line 235, in main
    return super().main(*args, **kwargs)
  File "/home/andromedan/kubo_sound/webapp/kubo_masking/venv/lib/python3.8/site-packages/click/core.py", line 1053, in main
    rv = self.invoke(ctx)
  File "/home/andromedan/kubo_sound/webapp/kubo_masking/venv/lib/python3.8/site-packages/click/core.py", line 1653, in invoke
    cmd_name, cmd, args = self.resolve_command(ctx, args)
  File "/home/andromedan/kubo_sound/webapp/kubo_masking/venv/lib/python3.8/site-packages/click/core.py", line 1700, in resolve_command
    cmd = self.get_command(ctx, cmd_name)
  File "/home/andromedan/kubo_sound/webapp/kubo_masking/venv/lib/python3.8/site-packages/quart/cli.py", line 220, in get_command
    command = info.load_app().cli.get_command(ctx, name)  # type: ignore
  File "/home/andromedan/kubo_sound/webapp/kubo_masking/venv/lib/python3.8/site-packages/quart/cli.py", line 72, in load_app
    module = import_module(import_name)
  File "/home/andromedan/anaconda3/lib/python3.8/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 783, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "/home/andromedan/kubo_sound/webapp/kubo_masking/run.py", line 7, in <module>
    app = create_app()
  File "/home/andromedan/kubo_sound/webapp/kubo_masking/app/__init__.py", line 15, in create_app
    cache.init_app(app, config=config.CACHE)
  File "/home/andromedan/kubo_sound/webapp/kubo_masking/venv/lib/python3.8/site-packages/flask_caching/__init__.py", line 220, in init_app
    self._set_cache(app, config)
  File "/home/andromedan/kubo_sound/webapp/kubo_masking/venv/lib/python3.8/site-packages/flask_caching/__init__.py", line 251, in _set_cache
    app.extensions["cache"][self] = cache_factory(
  File "/home/andromedan/kubo_sound/webapp/kubo_masking/venv/lib/python3.8/site-packages/flask_caching/backends/filesystemcache.py", line 95, in factory
    return cls(*args, **kwargs)
  File "/home/andromedan/kubo_sound/webapp/kubo_masking/venv/lib/python3.8/site-packages/flask_caching/backends/filesystemcache.py", line 76, in __init__
    os.makedirs(self._path)
  File "/home/andromedan/anaconda3/lib/python3.8/os.py", line 208, in makedirs
    head, tail = path.split(name)
  File "/home/andromedan/anaconda3/lib/python3.8/posixpath.py", line 103, in split
    p = os.fspath(p)
TypeError: expected str, bytes or os.PathLike object, not NoneType

tracing back to the line

cache.init_app(app, config=config.CACHE)

in my app factory. This is the app factory

import quart.flask_patch

from quart import Quart
from config import Config

# import extensions instance
from flask_caching import Cache

cache = Cache()

def create_app(config=Config):
    app = Quart(__name__)
    app.config.from_object(config)

    # initialize extension instances
    cache.init_app(app, config=config.CACHE)

    # register blueprints of applications
    from app.main import main as main_bp
    app.register_blueprint(main_bp)

    from app.measurement import measurement as measurement_bp
    app.register_blueprint(measurement_bp)

    return app

and runfile code

# import the create app application factory
from app import create_app

# import the application config classes
from config import Config

app = create_app()

if __name__ == '__main__':
app.run()

The CACHE attribute Config is given by the dictionary {'CACHE_TYPE': 'FileSystemCache'}.

I have tried other options such as cache = Cache(app, config=config.CACHE) to initialize the extension, none of them worked...

Bonus Question: What is the difference between the cache types mentioned in the flask docs?

Thank you!


问:
Replace a dependency version in pom.xml programmatically?
Assuming I have a pom.xml containing a parent dependency like this:

```<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>com.example</groupId>
        <artifactId>some-parent</artifactId>
        <version>1.0.0-SNAPSHOT</version>
    </parent>
</project>
</code>```

Is there a way I can replace the 1.0.0-SNAPSHOT version programmatically, maybe via a script?

My use case:

I have lots of pom.xml files that I need to change the parent version of

I'm using git-xargs to make changes across multiple repos, so I can apply a bash script to each pom.xml to change it.

For example, I can do the following, but this will update all occurrences of 1.0.0-SNAPSHOT in the pom.xml, and I want to limit it to just the some-parent artifact that has a version 1.0.0-SNAPSHOT:

```<code>git-xargs \
  --branch-name test-branch \
  --github-org <your-github-org> \
  --commit-message "Update pom.xml" \
  sed -i 's/1.0.0-SNAPSHOT/2.0.1/g' pom.xml
</code>```

As per the git-xargs docs, I can use any type of script to process the pom.xml, bash, python, ruby etc: https://github.com/gruntwork-io/git-xargs#how-to-supply-commands-or-scripts-to-run

UPDATE:

The following xmlstarlet approach works up to a point:

```<code>if [[ $(xmlstarlet sel -N my=http://maven.apache.org/POM/4.0.0 -t -v '//my:project/my:parent/my:artifactId' pom.xml) == "some-parent" && $(xmlstarlet sel -N my=http://maven.apache.org/POM/4.0.0 -t -v '//my:project/my:parent/my:version' pom.xml) == "1.0.0-SNAPSHOT" ]]; then xmlstarlet edit -L -N my=http://maven.apache.org/POM/4.0.0 --update '//my:project/my:parent/my:version' --value '2.0.6' pom.xml; fi
</code>```

xmlstarlet is correctly updating the xml element I want, but its also reordering the xsi:schemaLocation, xmlns and xmlns:xsi at the top of my file.

It's updating it from:

```<code><project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
</code>```

to:

```<code><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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
</code>```

which is no good for me.

答:
This works, using a combination of xmlstarlet and mvn:</p>
```<code>#! /usr/bin/env bash
if [[ $(xmlstarlet sel -N my=http://maven.apache.org/POM/4.0.0 -t -v '//my:project/my:parent/my:artifactId' pom.xml) == "some-parent" && \
      $(xmlstarlet sel -N my=http://maven.apache.org/POM/4.0.0 -t -v '//my:project/my:parent/my:version' pom.xml) == "4.0.0-SNAPSHOT" ]]; then
    mvn versions:update-parent -DparentVersion=[4.0.0-661]
    mvn versions:commit
fi
</code>```

Body:
Assuming I have a pom.xml containing a parent dependency like this:

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>com.example</groupId>
        <artifactId>some-parent</artifactId>
        <version>1.0.0-SNAPSHOT</version>
    </parent>
</project>

Is there a way I can replace the 1.0.0-SNAPSHOT version programmatically, maybe via a script?

My use case:

I have lots of pom.xml files that I need to change the parent version of

I'm using git-xargs to make changes across multiple repos, so I can apply a bash script to each pom.xml to change it.

For example, I can do the following, but this will update all occurrences of 1.0.0-SNAPSHOT in the pom.xml, and I want to limit it to just the some-parent artifact that has a version 1.0.0-SNAPSHOT:

git-xargs \
  --branch-name test-branch \
  --github-org <your-github-org> \
  --commit-message "Update pom.xml" \
  sed -i 's/1.0.0-SNAPSHOT/2.0.1/g' pom.xml

As per the git-xargs docs, I can use any type of script to process the pom.xml, bash, python, ruby etc: https://github.com/gruntwork-io/git-xargs#how-to-supply-commands-or-scripts-to-run

UPDATE:

The following xmlstarlet approach works up to a point:

if [[ $(xmlstarlet sel -N my=http://maven.apache.org/POM/4.0.0 -t -v '//my:project/my:parent/my:artifactId' pom.xml) == "some-parent" && $(xmlstarlet sel -N my=http://maven.apache.org/POM/4.0.0 -t -v '//my:project/my:parent/my:version' pom.xml) == "1.0.0-SNAPSHOT" ]]; then xmlstarlet edit -L -N my=http://maven.apache.org/POM/4.0.0 --update '//my:project/my:parent/my:version' --value '2.0.6' pom.xml; fi

xmlstarlet is correctly updating the xml element I want, but its also reordering the xsi:schemaLocation, xmlns and xmlns:xsi at the top of my file.

It's updating it from:

<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

to:

<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">

which is no good for me.

Body:
This works, using a combination of xmlstarlet and mvn:

#! /usr/bin/env bash
if [[ $(xmlstarlet sel -N my=http://maven.apache.org/POM/4.0.0 -t -v '//my:project/my:parent/my:artifactId' pom.xml) == "some-parent" && \
      $(xmlstarlet sel -N my=http://maven.apache.org/POM/4.0.0 -t -v '//my:project/my:parent/my:version' pom.xml) == "4.0.0-SNAPSHOT" ]]; then
    mvn versions:update-parent -DparentVersion=[4.0.0-661]
    mvn versions:commit
fi


问:
WSO2 IS - Blazor SPA 'Invalid request client_id not found in request as parameter.'
When trying to login as the default admin user against WSO2 Identity Server from my Blazor SPA I get the following error:

but the authentication succeeds and the user is logged in.

The settings in my Service Provider are the following:

and the code for connecting to WSO2 IS:

Program.cs

```<code>builder.Services.AddOidcAuthentication(options =>{
{
  builder.Configuration.Bind("Local", options.ProviderOptions);
});
</code>```

Appsettings.json

```<code>{
  "Local": {
    "Authority": "https://localhost:9443/oauth2/oidcdiscovery",
    "ClientId": "lUf05M1d3IRvpdOkZgLSt9TRZX8a",
    "ResponseType": "code",
    "DefaultScopes": [],
    "RedirectUri": "authentication/login-callback",
    "PostLogoutRedirectUri": "signedOut"
  }
}
</code>```

When the option "Allow authentication without the client secret" in the Service Provider is unchecked, authentication results in an error and the user cannot log in.

Response:

```<code>error_description: Unsupported Client Authentication Method!
error: invalid_client
</code>```

Is this the expected behaviour?

OAuth Version: OAuth-2.0

Allowed grant types:

Code,Implicit,Password,Client Credential, Refresh Token

答:
The error client_id not found in request as parameter. is logged for a request related to OIDC session management. It occures when the OIDC session management iframe is loaded without the client id query paramter.

The 401 error for the token request is expected if "Allow authentication without client secret" is unchecked and you are not passing the client secret in the token request.

Body:
When trying to login as the default admin user against WSO2 Identity Server from my Blazor SPA I get the following error:

but the authentication succeeds and the user is logged in.

The settings in my Service Provider are the following:

and the code for connecting to WSO2 IS:

Program.cs

builder.Services.AddOidcAuthentication(options =>{
{
  builder.Configuration.Bind("Local", options.ProviderOptions);
});

Appsettings.json

{
  "Local": {
    "Authority": "https://localhost:9443/oauth2/oidcdiscovery",
    "ClientId": "lUf05M1d3IRvpdOkZgLSt9TRZX8a",
    "ResponseType": "code",
    "DefaultScopes": [],
    "RedirectUri": "authentication/login-callback",
    "PostLogoutRedirectUri": "signedOut"
  }
}

When the option "Allow authentication without the client secret" in the Service Provider is unchecked, authentication results in an error and the user cannot log in.

Response:

error_description: Unsupported Client Authentication Method!
error: invalid_client

Is this the expected behaviour?

OAuth Version: OAuth-2.0

Allowed grant types:

Code,Implicit,Password,Client Credential, Refresh Token


问:
docker compose inside docker in a docker
I am pretty new to docker and was following the documentation found here, trying deploy several containers inside dind using docker-compose 1.14.0 I get the following

```<code>docker run -v /home/dudarev/compose/:/compose/ --privileged docker:dind /compose/docker-compose
/usr/local/bin/dockerd-entrypoint.sh: exec: line 21: /compose/docker-compose: not found
</code>```

Did I miss something?

答:
here is a full dockerfile to run docker-compose inside docker</p>
```<code>FROM ubuntu:21.04
RUN apt-get update
RUN apt-get upgrade -y
RUN apt-get install -y python3
RUN apt-get install -y pip
RUN apt-get install -y curl
RUN curl -L "https://github.com/docker/compose/releases/download/1.29.2/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
RUN chmod +x /usr/local/bin/docker-compose
</code>```

Body:
I am pretty new to docker and was following the documentation found here, trying deploy several containers inside dind using docker-compose 1.14.0 I get the following

docker run -v /home/dudarev/compose/:/compose/ --privileged docker:dind /compose/docker-compose
/usr/local/bin/dockerd-entrypoint.sh: exec: line 21: /compose/docker-compose: not found

Did I miss something?

Body:
here is a full dockerfile to run docker-compose inside docker

FROM ubuntu:21.04
RUN apt-get update
RUN apt-get upgrade -y
RUN apt-get install -y python3
RUN apt-get install -y pip
RUN apt-get install -y curl
RUN curl -L "https://github.com/docker/compose/releases/download/1.29.2/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
RUN chmod +x /usr/local/bin/docker-compose


问:
Intercept TAB key in RichEdit
There are lot of similar questions on here, but I couldn't find an answer for my problem.

I have a TRichEdit and want to implement some custom behaviour when the user presses Tab. I set the rich edit's WantTabs property to True and tried to add my custom behaviour in OnKeyDown, which works fine, but unfortunately after that the "normal" tab behaviour is executed as well (inserting a tab character in the edit). I tried setting Key to 0 in the event handler but that doesn't help.

How can I prevent the "normal" tab behaviour from being executed?

答:
Use the OnKeyPress event instead:

```<code>procedure TForm1.RichEdit1KeyPress(Sender: TObject; var Key: Char);
begin
  if Key = chr(VK_TAB) then
  begin
    beep;
    Key := #0;
  end;
end;
</code>```

Alternatively, if you really need to use the OnKeyDown event, simply remove the key messages:

```<code>procedure TForm1.RichEdit1KeyDown(Sender: TObject; var Key: Word;
  Shift: TShiftState);
var
  msg: TMsg;
begin
  if Key = VK_TAB then
  begin
    beep;
    while PeekMessage(msg, RichEdit1.Handle, WM_KEYFIRST, WM_KEYLAST,
      PM_REMOVE) do;
  end;
end;
</code>```

Title: Intercept TAB key in RichEdit

Body:
Use the OnKeyPress event instead:

procedure TForm1.RichEdit1KeyPress(Sender: TObject; var Key: Char);
begin
  if Key = chr(VK_TAB) then
  begin
    beep;
    Key := #0;
  end;
end;

Alternatively, if you really need to use the OnKeyDown event, simply remove the key messages:

procedure TForm1.RichEdit1KeyDown(Sender: TObject; var Key: Word;
  Shift: TShiftState);
var
  msg: TMsg;
begin
  if Key = VK_TAB then
  begin
    beep;
    while PeekMessage(msg, RichEdit1.Handle, WM_KEYFIRST, WM_KEYLAST,
      PM_REMOVE) do;
  end;
end;


问:
Send Array of hashes to class to create a user from each
I have a array of hashes

```<code>pets = [
    {
    "firstName": "Brianna",
     "lastName": "Parson",
     "children": ["sam","Joe"],
     "buddys": {

    },

    {
     "firstName": "jeffery",
     "lastName": "thomas",

     }
     }
    ]
</code>```

How do you send a class an array of hashes?

答:
Here is a simple class.

class Person
  def initialize(full_name, job, num_children, num_pets)
    @full_name = full_name
    @job = job
    @num_children = num_children
    @num_pets = num_pets
  end

  def to_s
    format(
      '%s is a %s and has %d children and %d pets',
      @full_name,
      @job,
      @num_children,
      @num_pets
    )
  end
end
```

This is just an example. Your final class design will depend on your application.

See http://ruby-doc.com/docs/ProgrammingRuby/ for a more complete introduction to classes.

Body:
I have a array of hashes

pets = [
    {
    "firstName": "Brianna",
     "lastName": "Parson",
     "children": ["sam","Joe"],
     "buddys": {

    },

    {
     "firstName": "jeffery",
     "lastName": "thomas",

     }
     }
    ]

How do you send a class an array of hashes?

Body:
Here is a simple class.

class Person
  def initialize(full_name, job, num_children, num_pets)
    @full_name = full_name
    @job = job
    @num_children = num_children
    @num_pets = num_pets
  end

  def to_s
    format(
      '%s is a %s and has %d children and %d pets',
      @full_name,
      @job,
      @num_children,
      @num_pets
    )
  end
end

This is just an example. Your final class design will depend on your application.

See http://ruby-doc.com/docs/ProgrammingRuby/ for a more complete introduction to classes.


答:
You should avoid working with xml as plain text files, but if you have no other options you may give it a try. sed ranges (/starting-regex/,/ending-regex/{commands}) allows to restrict your replacement within specific context. I.e. this oneliner:

sed -e '/<parent/,/\/parent/{/artifactId>some-parent/,/parent/{s/1.0.0-SNAPSHOT/2.0.0-SNAPSHOT/g}}'

will replace only version strings, which are between <parent and /parent strings, and between some-parent and parent lines, thus should only match artifacts some-parent. Obviously, there are multiple cases when it will fail, but for simple files this could work. Your ranges may be further nested.

Title: Replace a dependency version in pom.xml programmatically?


问:
User Prompt Array Question for Javascript
EDIT: Thanks to someone's response, I got a portion working. It now adds topping prices no problem. However, it adds a price even when a user doesn't put toppings into the prompt. I've updated my code below.

EDIT 2: For full code, here's my github link. It's updated with the below code (and the rest of the coding) https://github.com/cas389/m4-hw6-ju-cheryl.

I'm in a JavaScript class, and I am stuck on this portion of my homework assignment. Basically, we are creating a pizza ordering system where a user would fill out if they want thin/thick/pan crust, which toppings they want, if they want extra cheese and finally if they want delivery.

I have everything except the pizza toppings part. This is the information for this section (including the comments the teacher gave us as "hints") along with what I've been trying to make work. I've cut out all the sections I've already finished.

```<code>function getPizzaOrder() {
  var extraCheeseUpcharge = 1.5
  var thickCrustUpcharge = 2
  var deliveryFee = 3.5
  var toppingsFee = 1.5
  var basePrice = 10

  var toppings = prompt("Please enter additional toppings (comma separated)")
      // HINT: prompt() will return an empty string "" if the user presses 'OK' without entering a value
      // if the user enters toppings, use .split(",") to separate toppings into an array
      // if no toppings are given, make sure pizza.toppings is set to []
      // if the user has added toppings, add toppingsFee multiplied by
      // the number of toppings added to pizza.cost
      // YOUR CODE HERE

       pizza.toppings = [];
       pizza.toppings = toppings.split(',');
       for (let i = 0; i < pizza.toppings.length; i++){
           pizza.cost += toppingsFee;
       }
       console.log(pizza.toppings);

  return pizza
}
</code>```

答:
Access element through index. And first of all You should declare pizza

```<code>let pizza;
pizza.toppings = [];
      pizza.toppings = toppings.split(',');
      for (let i = 0; i < pizza.toppings.length; i++){
       pizza.cost += +pizza.toppings[i] * toppingsFee;
      }
</code>```

Body:
EDIT: Thanks to someone's response, I got a portion working. It now adds topping prices no problem. However, it adds a price even when a user doesn't put toppings into the prompt. I've updated my code below.

EDIT 2: For full code, here's my github link. It's updated with the below code (and the rest of the coding) https://github.com/cas389/m4-hw6-ju-cheryl.

I'm in a JavaScript class, and I am stuck on this portion of my homework assignment. Basically, we are creating a pizza ordering system where a user would fill out if they want thin/thick/pan crust, which toppings they want, if they want extra cheese and finally if they want delivery.

I have everything except the pizza toppings part. This is the information for this section (including the comments the teacher gave us as "hints") along with what I've been trying to make work. I've cut out all the sections I've already finished.

function getPizzaOrder() {
  var extraCheeseUpcharge = 1.5
  var thickCrustUpcharge = 2
  var deliveryFee = 3.5
  var toppingsFee = 1.5
  var basePrice = 10

  var toppings = prompt("Please enter additional toppings (comma separated)")
      // HINT: prompt() will return an empty string "" if the user presses 'OK' without entering a value
      // if the user enters toppings, use .split(",") to separate toppings into an array
      // if no toppings are given, make sure pizza.toppings is set to []
      // if the user has added toppings, add toppingsFee multiplied by
      // the number of toppings added to pizza.cost
      // YOUR CODE HERE

       pizza.toppings = [];
       pizza.toppings = toppings.split(',');
       for (let i = 0; i < pizza.toppings.length; i++){
           pizza.cost += toppingsFee;
       }
       console.log(pizza.toppings);

  return pizza
}

Body:
Access element through index. And first of all You should declare pizza

let pizza;
pizza.toppings = [];
      pizza.toppings = toppings.split(',');
      for (let i = 0; i < pizza.toppings.length; i++){
       pizza.cost += +pizza.toppings[i] * toppingsFee;
      }


问:
GPG "Good Signature" achieved but not passing to GitLab
I'm looking for potential solutions or ways to investigate what I think is a breakdown between git and GitLab.

My company requires commits to be signed and I've been able to successfully set up GPG and sign in the terminal. I generated the GPG key, added it to git and made sure it's added to my GitLab profile.

I used git log -1 --show-signature to verify that my signature was "good" in the terminal, but it seems like GitLab isn't recognizing the signature for some reason. I'm not getting any error message in the terminal or anywhere else to aid in troubleshooting unfortunately.

I'm relatively new to git, so I'm hoping there are some more experienced devs who may have run into this issue in the past. Any help would be appreciated!

This is the message I get when I try to git push origin --> remote:

```<code>GitLab: Commit must be signed with a GPG key To
gitlab.xxxxx.net:revenue-operations/xxxxxxx.git ! [remote rejected]
2022-02-07-hotfix -> 2022-02-07-hotfix (pre-receive hook declined)
error: failed to push some refs to
'gitlab.xxxxx.net:revenue-operations/xxxxxxxx.git'
</code>```

答:
Your key must be added to your GitLab account. You can do that at https://gitlab.example.com/-/profile/gpg_keys in modern versions of GitLab.

The email on the GPG key should match the committer email and be a verified email on your GitLab account.

Body:
I'm looking for potential solutions or ways to investigate what I think is a breakdown between git and GitLab.

My company requires commits to be signed and I've been able to successfully set up GPG and sign in the terminal. I generated the GPG key, added it to git and made sure it's added to my GitLab profile.

I used git log -1 --show-signature to verify that my signature was "good" in the terminal, but it seems like GitLab isn't recognizing the signature for some reason. I'm not getting any error message in the terminal or anywhere else to aid in troubleshooting unfortunately.

I'm relatively new to git, so I'm hoping there are some more experienced devs who may have run into this issue in the past. Any help would be appreciated!

This is the message I get when I try to git push origin --> remote:

GitLab: Commit must be signed with a GPG key To
gitlab.xxxxx.net:revenue-operations/xxxxxxx.git ! [remote rejected]
2022-02-07-hotfix -> 2022-02-07-hotfix (pre-receive hook declined)
error: failed to push some refs to
'gitlab.xxxxx.net:revenue-operations/xxxxxxxx.git'


问:
Actionscript 3, addChild to stage and addEventListener not working together
I just wanna add an image from my library on the stage and have an event listener on it so when i click on it, it will do something. imgFromMyLib is already set to the image i want from my library. Please help. What is the easiest way to do this ?</p>

```<code>import flash.display.Bitmap;
import flash.events.*;
import flash.display.Sprite;

function pwned(evt:MouseEvent):void
{
        trace ("a");
}

var myImg:imgFromMyLib = new imgFromMyLib();
var myBitmap:Bitmap = new Bitmap(myImg);
myBitmap.addEventListener(MouseEvent.CLICK, pwned);
addChild(myBitmap);
</code>```

答:
```<code>var myImg:imgFromMyLib = new imgFromMyLib(0,0);
var myBitmap:Bitmap = new Bitmap(myImg);
var mc:MovieClip =  new MovieClip();
mc.graphics.beginFill(0x333333,1);
mc.graphics.drawRect(0,0,myBitmap.width, myBitmap.height);
mc.graphics.endFill();
addChild(mc);
mc.addEventListener(MouseEvent.CLICK, pwned);
mc.addChild(myBitmap);

function pwned(evt:MouseEvent):void
{
        trace ("a");
}
</code>```

try this....

Body:
I just wanna add an image from my library on the stage and have an event listener on it so when i click on it, it will do something. imgFromMyLib is already set to the image i want from my library. Please help. What is the easiest way to do this ?

import flash.display.Bitmap;
import flash.events.*;
import flash.display.Sprite;

function pwned(evt:MouseEvent):void
{
        trace ("a");
}

var myImg:imgFromMyLib = new imgFromMyLib();
var myBitmap:Bitmap = new Bitmap(myImg);
myBitmap.addEventListener(MouseEvent.CLICK, pwned);
addChild(myBitmap);

Body:
var myImg:imgFromMyLib = new imgFromMyLib(0,0);
var myBitmap:Bitmap = new Bitmap(myImg);
var mc:MovieClip =  new MovieClip();
mc.graphics.beginFill(0x333333,1);
mc.graphics.drawRect(0,0,myBitmap.width, myBitmap.height);
mc.graphics.endFill();
addChild(mc);
mc.addEventListener(MouseEvent.CLICK, pwned);
mc.addChild(myBitmap);

function pwned(evt:MouseEvent):void
{
        trace ("a");
}

try this....


问:
Using ramda.js, how to replace a value in a nested structure?
I'm trying to leverage the technique shown here for replacing values in an object with ramda.js. Unlike the linked reference, my object has many more nesting layers, and so it fails.

In the following example, we have an object that details attractions in cities. First it specifies the cities, the we dive in into nyc, then to zoos, then StatenIslandZoo, and finally we get to zooInfo that holds two records for two animals. In each one, we have the aniaml's name in the value associated with the animal key. I want to correct the value's string by replacing it with another string and return a new copy of the entire cityAttractions object.

const cityAttractions = {
    "cities": {
        "nyc": {
            "towers": ["One World Trade Center", "Central Park Tower", "Empire State Building"],
            "zoos": {
                "CentralParkZoo": {},
                "BronxZoo": {},
                "StatenIslandZoo": {
                    "zooInfo": [
                        {
                            "animal": "zebra_typo", // <- replace with "zebra"
                            "weight": 100
                        },
                        {
                            "animal": "wrongstring_lion", // <- replace with "lion"
                            "weight": 1005
                        }
                    ]
                }
            }
        },
        "sf": {},
        "dc": {}
    }
}
```
<p>So I defined a function very similar to this one:</p>
<pre class="lang-js prettyprint-override"><code>const R = require("ramda")

const myAlter = (myPath, whereValueEquals, replaceWith, obj) => R.map(
    R.when(R.pathEq(myPath, whereValueEquals), R.assocPath(myPath, replaceWith)),
    obj
)
</code>```

And then called myAlter() and stored the ouput into altered:

const altered = myAlter(["cities", "nyc", "zoos", "StatenIslandZoo", "zooInfo", "animal"], "zebra_typo", "zebra", cityAttractions)
```
<p>But when checking, I realize no replacement had happend:</p>
<pre class="lang-js prettyprint-override"><code>console.log(altered.cities.nyc.zoos.StatenIslandZoo.zooInfo)
// [
//   { animal: 'zebra_typo', weight: 100 },
//   { animal: 'wrongstring_lion', weight: 1005 }
// ]
</code>```

Some troubleshooting

If I we go back and examine the original cityAttractions object, then we can first extract just the level of cityAttractions.cities.nyc.zoos.StatenIslandZoo.zooInfo, then acting on that with myAlter() does work.

const ZooinfoExtraction = R.path(["cities", "nyc", "zoos", "StatenIslandZoo", "zooInfo"])(cityAttractions)
console.log(ZooinfoExtraction)
// [
//   { animal: 'zebra_typo', weight: 100 },
//   { animal: 'wrongstring_lion', weight: 1005 }
// ]

console.log(myAlter(["animal"], "zebra_typo", "zebra", ZooinfoExtraction))
// here it works!
// [
//   { animal: 'zebra', weight: 100 },
//   { animal: 'wrongstring_lion', weight: 1005 }
// ]
```
<p>So for some reason, <code>myAlter()</code> works on the extracted <code>ZooinfoExtraction</code> but not on the original <code>cityAttractions</code>. Which is a problem because I need the entire original structure (just replacing the specified values).</p>
<hr />
<p>EDIT - <em>troubleshooting 2</em></p>
<hr />
<p>I guess the problem relies in the fact that</p>
<pre class="lang-js prettyprint-override"><code>R.path(["cities", "nyc", "zoos", "StatenIslandZoo", "zooInfo", "animal"], cityAttractions)
</code>```

returns undefined.

答:
Using Lenses

Another lens-based approach is to write a new lens function.  Ramda only supplies lensProp, lensIndex and lensPath.  But we could write one that matches the first array element where the animal matches.  I can reuse a lensMatch function I've used in other answers and then configure it with const animalLens = lensMatch ('animal').  Then we can compose that with other lenses to get to the property we want to change.  It might look like this:

const lensMatch = (propName) => (key) => lens (
  find (propEq (propName, key)),
  (val, arr, idx = findIndex (propEq (propName, key), arr)) =>
      update (idx > -1 ? idx : length (arr), val, arr)
)

const animalLens = lensMatch ('animal')

const updateAnimalName = (oldName, newName, attractions) =>  set (compose (
  lensPath (['cities', 'nyc', 'zoos', 'StatenIslandZoo', 'zooInfo']),
  animalLens (oldName),
  lensProp ('animal')
), newName, attractions)

const cityAttractions = {cities: {nyc: {towers: ["One World Trade Center", "Central Park Tower", "Empire State Building"], zoos: {CentralParkZoo: {}, BronxZoo: {}, StatenIslandZoo: {zooInfo: [{animal: "zebra_typo", weight: 100}, {animal: "wrongstring_lion", weight: 1005}]}}}, sf: {}, dc: {}}}

console .log (
  updateAnimalName ('zebra_typo', 'zebra', cityAttractions)
)```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper {max-height: 100% !important; top: 0}</code>```

```
</div>
</div>
</p>
<p>Obviously we could then fold this over multiple animal names (say zebra and lion) if you wanted.</p>
<h2>A generic replacement function</h2>
<p>Another entirely different approach would be -- if the typo values are unlikely to appear elsewhere in your data structure -- to simply walk the whole tree, replacing all <code>"zebra_typo"</code> with <code>"zebra"</code>.  That would be a simple recursion:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const replaceVal = (oldVal, newVal) => (o) =>
  o == oldVal
    ? newVal
  : Array .isArray (o)
    ? o .map (replaceVal (oldVal, newVal))
  : Object (o) === o
    ? Object .fromEntries (Object .entries (o) .map (([k, v]) => [k, replaceVal (oldVal, newVal) (v)]))
  : o

const cityAttractions = {cities: {nyc: {towers: ["One World Trade Center", "Central Park Tower", "Empire State Building"], zoos: {CentralParkZoo: {}, BronxZoo: {}, StatenIslandZoo: {zooInfo: [{animal: "zebra_typo", weight: 100}, {animal: "wrongstring_lion", weight: 1005}]}}}, sf: {}, dc: {}}}

console .log (
  replaceVal ('zebra_typo', 'zebra') (cityAttractions)
)</code>```

.as-console-wrapper {max-height: 100% !important; top: 0}```

This approach is quite generic, but is more targeted at replacing all "foo" values with "bar" ones, regardless of level.  But it might work for your case.

Body:
I'm trying to leverage the technique shown here for replacing values in an object with ramda.js. Unlike the linked reference, my object has many more nesting layers, and so it fails.

In the following example, we have an object that details attractions in cities. First it specifies the cities, the we dive in into nyc, then to zoos, then StatenIslandZoo, and finally we get to zooInfo that holds two records for two animals. In each one, we have the aniaml's name in the value associated with the animal key. I want to correct the value's string by replacing it with another string and return a new copy of the entire cityAttractions object.

const cityAttractions = {
    "cities": {
        "nyc": {
            "towers": ["One World Trade Center", "Central Park Tower", "Empire State Building"],
            "zoos": {
                "CentralParkZoo": {},
                "BronxZoo": {},
                "StatenIslandZoo": {
                    "zooInfo": [
                        {
                            "animal": "zebra_typo", // <- replace with "zebra"
                            "weight": 100
                        },
                        {
                            "animal": "wrongstring_lion", // <- replace with "lion"
                            "weight": 1005
                        }
                    ]
                }
            }
        },
        "sf": {},
        "dc": {}
    }
}

So I defined a function very similar to this one:

const R = require("ramda")

const myAlter = (myPath, whereValueEquals, replaceWith, obj) => R.map(
    R.when(R.pathEq(myPath, whereValueEquals), R.assocPath(myPath, replaceWith)),
    obj
)

And then called myAlter() and stored the ouput into altered:

const altered = myAlter(["cities", "nyc", "zoos", "StatenIslandZoo", "zooInfo", "animal"], "zebra_typo", "zebra", cityAttractions)

But when checking, I realize no replacement had happend:

console.log(altered.cities.nyc.zoos.StatenIslandZoo.zooInfo)
// [
//   { animal: 'zebra_typo', weight: 100 },
//   { animal: 'wrongstring_lion', weight: 1005 }
// ]

Some troubleshooting

If I we go back and examine the original cityAttractions object, then we can first extract just the level of cityAttractions.cities.nyc.zoos.StatenIslandZoo.zooInfo, then acting on that with myAlter() does work.

const ZooinfoExtraction = R.path(["cities", "nyc", "zoos", "StatenIslandZoo", "zooInfo"])(cityAttractions)
console.log(ZooinfoExtraction)
// [
//   { animal: 'zebra_typo', weight: 100 },
//   { animal: 'wrongstring_lion', weight: 1005 }
// ]

console.log(myAlter(["animal"], "zebra_typo", "zebra", ZooinfoExtraction))
// here it works!
// [
//   { animal: 'zebra', weight: 100 },
//   { animal: 'wrongstring_lion', weight: 1005 }
// ]

So for some reason, myAlter() works on the extracted ZooinfoExtraction but not on the original cityAttractions. Which is a problem because I need the entire original structure (just replacing the specified values).

EDIT - troubleshooting 2

I guess the problem relies in the fact that

R.path(["cities", "nyc", "zoos", "StatenIslandZoo", "zooInfo", "animal"], cityAttractions)

returns undefined.

Body:
Using Lenses

Another lens-based approach is to write a new lens function.  Ramda only supplies lensProp, lensIndex and lensPath.  But we could write one that matches the first array element where the animal matches.  I can reuse a lensMatch function I've used in other answers and then configure it with const animalLens = lensMatch ('animal').  Then we can compose that with other lenses to get to the property we want to change.  It might look like this:

const lensMatch = (propName) => (key) => lens (
  find (propEq (propName, key)),
  (val, arr, idx = findIndex (propEq (propName, key), arr)) =>
      update (idx > -1 ? idx : length (arr), val, arr)
)

const animalLens = lensMatch ('animal')

const updateAnimalName = (oldName, newName, attractions) =>  set (compose (
  lensPath (['cities', 'nyc', 'zoos', 'StatenIslandZoo', 'zooInfo']),
  animalLens (oldName),
  lensProp ('animal')
), newName, attractions)

const cityAttractions = {cities: {nyc: {towers: ["One World Trade Center", "Central Park Tower", "Empire State Building"], zoos: {CentralParkZoo: {}, BronxZoo: {}, StatenIslandZoo: {zooInfo: [{animal: "zebra_typo", weight: 100}, {animal: "wrongstring_lion", weight: 1005}]}}}, sf: {}, dc: {}}}

console .log (
  updateAnimalName ('zebra_typo', 'zebra', cityAttractions)
)

.as-console-wrapper {max-height: 100% !important; top: 0}

<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.28.0/ramda.min.js"></script>
<script> const {lens, find, propEq, findIndex, update, length, set, lensPath, compose, lensProp} = R </script>

Obviously we could then fold this over multiple animal names (say zebra and lion) if you wanted.

A generic replacement function

Another entirely different approach would be -- if the typo values are unlikely to appear elsewhere in your data structure -- to simply walk the whole tree, replacing all "zebra_typo" with "zebra".  That would be a simple recursion:

const replaceVal = (oldVal, newVal) => (o) =>
  o == oldVal
    ? newVal
  : Array .isArray (o)
    ? o .map (replaceVal (oldVal, newVal))
  : Object (o) === o
    ? Object .fromEntries (Object .entries (o) .map (([k, v]) => [k, replaceVal (oldVal, newVal) (v)]))
  : o

const cityAttractions = {cities: {nyc: {towers: ["One World Trade Center", "Central Park Tower", "Empire State Building"], zoos: {CentralParkZoo: {}, BronxZoo: {}, StatenIslandZoo: {zooInfo: [{animal: "zebra_typo", weight: 100}, {animal: "wrongstring_lion", weight: 1005}]}}}, sf: {}, dc: {}}}

console .log (
  replaceVal ('zebra_typo', 'zebra') (cityAttractions)
)

.as-console-wrapper {max-height: 100% !important; top: 0}

This approach is quite generic, but is more targeted at replacing all "foo" values with "bar" ones, regardless of level.  But it might work for your case.


问:
How to convert numbers to words without using num2word library?
I need to turn numbers from 1 - 99 into words. This is what I got so far:

```<code>num2words1 = {1: 'One', 2: 'Two', 3: 'Three', 4: 'Four', 5: 'Five', \
            6: 'Six', 7: 'Seven', 8: 'Eight', 9: 'Nine', 10: 'Ten', \
            11: 'Eleven', 12: 'Twelve', 13: 'Thirteen', 14: 'Fourteen', \
            15: 'Fifteen', 16: 'Sixteen', 17: 'Seventeen', 18: 'Eighteen', 19: 'Nineteen'}
num2words2 = ['Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety']

def number(Number):

    if (Number > 1) or (Number < 19):
        return (num2words1[Number])
    elif (Number > 20) or (Number < 99):
        return (num2words2[Number])
    else:
        print("Number Out Of Range")
        main()

def main():
    num = eval(input("Please enter a number between 0 and 99: "))
    number(num)
main()
</code>```

Now, the BIGGEST problem that I have so far is that the if, elif and else statements DO NOT seem to work. Only the first if statement runs.

The second problem is creating the string version of the numbers from 20-99....

P.S. Yes, I know about the num2word library, but I am not allowed to use it.

答:
If you are from Indian subcontinent where they use Lakhs, Crores etc. instead of Million, Billion etc. you can use this Function -

It is recursive and does not take care of decimals. You can split your number into two and print by concatenating the integer and fractional parts.

```<code>def Words(n):
    units = ["Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"]
    teens = ["Ten","Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"]
    tens = ["Twenty","Thirty", "Fourty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"]

    if n <=9:
        return units[n]
    elif n >= 10 and n <= 19:
        return teens[n-10]
    elif n >= 20 and n <= 99:
        return tens[(n//10)-2] + " " + (units[n % 10] if n % 10 !=0 else "")
    elif n >= 100 and n <= 999:
        return Words(n//100) + " Hundred " + (Words(n % 100) if n % 100 !=0 else "")
    elif n >= 1000 and n <= 99999:
        return Words(n//1000) + " Thousand " + (Words(n % 1000) if n % 1000 !=0 else "")
    elif n >= 100000 and n <= 9999999:
        return Words(n//100000) + " Lakh " + (Words(n % 100000) if n % 100000 !=0 else "")
    elif n >= 10000000:
        return Words(n//10000000) + " Crore " + (Words(n % 10000000) if n % 10000000 !=0 else "")
</code>```

This above function will generate words for number of any magnitude!

To test this i used the following code in Python -

```<code>from words import Words
import random as r
import time as t

# Forever loop generated random nos
# and prints in text
while True:
    rn = r.randrange(0,1000000)
    print("%7d      %s" % (rn, Words(rn)))
    t.sleep(0.25)
</code>```

The above program generates random numbers between zero to a million and prints the word equivalent every quarter second!

Body:
I need to turn numbers from 1 - 99 into words. This is what I got so far:

num2words1 = {1: 'One', 2: 'Two', 3: 'Three', 4: 'Four', 5: 'Five', \
            6: 'Six', 7: 'Seven', 8: 'Eight', 9: 'Nine', 10: 'Ten', \
            11: 'Eleven', 12: 'Twelve', 13: 'Thirteen', 14: 'Fourteen', \
            15: 'Fifteen', 16: 'Sixteen', 17: 'Seventeen', 18: 'Eighteen', 19: 'Nineteen'}
num2words2 = ['Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety']

def number(Number):

    if (Number > 1) or (Number < 19):
        return (num2words1[Number])
    elif (Number > 20) or (Number < 99):
        return (num2words2[Number])
    else:
        print("Number Out Of Range")
        main()

def main():
    num = eval(input("Please enter a number between 0 and 99: "))
    number(num)
main()

Now, the BIGGEST problem that I have so far is that the if, elif and else statements DO NOT seem to work. Only the first if statement runs.

The second problem is creating the string version of the numbers from 20-99....

P.S. Yes, I know about the num2word library, but I am not allowed to use it.

Body:
If you are from Indian subcontinent where they use Lakhs, Crores etc. instead of Million, Billion etc. you can use this Function -

It is recursive and does not take care of decimals. You can split your number into two and print by concatenating the integer and fractional parts.

def Words(n):
    units = ["Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"]
    teens = ["Ten","Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"]
    tens = ["Twenty","Thirty", "Fourty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"]

    if n <=9:
        return units[n]
    elif n >= 10 and n <= 19:
        return teens[n-10]
    elif n >= 20 and n <= 99:
        return tens[(n//10)-2] + " " + (units[n % 10] if n % 10 !=0 else "")
    elif n >= 100 and n <= 999:
        return Words(n//100) + " Hundred " + (Words(n % 100) if n % 100 !=0 else "")
    elif n >= 1000 and n <= 99999:
        return Words(n//1000) + " Thousand " + (Words(n % 1000) if n % 1000 !=0 else "")
    elif n >= 100000 and n <= 9999999:
        return Words(n//100000) + " Lakh " + (Words(n % 100000) if n % 100000 !=0 else "")
    elif n >= 10000000:
        return Words(n//10000000) + " Crore " + (Words(n % 10000000) if n % 10000000 !=0 else "")

This above function will generate words for number of any magnitude!

To test this i used the following code in Python -

from words import Words
import random as r
import time as t

# Forever loop generated random nos
# and prints in text
while True:
    rn = r.randrange(0,1000000)
    print("%7d      %s" % (rn, Words(rn)))
    t.sleep(0.25)

The above program generates random numbers between zero to a million and prints the word equivalent every quarter second!


问:
How to run a R script twice a day?
I had a R script configured to run via cron every day at 10am

```<code>library(cronR)
cmd2 = cron_rscript("CargueDiario_RedcapCovid_ODS.R", rscript_log="/home/admonda/R/projects/contagios_covid_santander/log/cargue_diario.log", log_append = T, log_timestamp = T)

cron_add(command = cmd2, frequency = 'daily', at = "10:00" , days_of_week = "*", id = 'FCVREDCAPCOVID_ODS_DIARIO', description = "FCVREDCAPCOVID_ODS_DIARIO")

cron_ls("FCVREDCAPCOVID_ODS_DIARIO")
## cronR job
## id:   FCVREDCAPCOVID_ODS_DIARIO
## tags:
## desc: FCVREDCAPCOVID_ODS_DIARIO
0 10 * * 0,1,2,3,4,5,6 /usr/lib/R/bin/Rscript '/home/admonda/R/projects/contagios_covid_santander/CargueDiario_RedcapCovid_ODS.R'  >> '/home/admonda/R/projects/contagios_covid_santander/log/cargue_diario.log' 2>&1
</code>```

Now i need to change it so it runs twice a day (10:00 and 22:00). I have already deleted it from CRON and I would like to make sure this is the correct new command:

```<code>cron_add(command = cmd2, frequency = 'daily', at = c("10:00","22:00") , days_of_week = "*", id = 'FCVREDCAPCOVID_ODS_DIARIO', description = "FCVREDCAPCOVID_ODS_DIARIO")
</code>```

答:
You still can use your original line, just change 10 to 10,22.

```<code>0 10,22 * * * /usr/lib/R/bin/Rscript '/home/admonda/R/projects/contagios_covid_santander/CargueDiario_RedcapCovid_ODS.R'  >> '/home/admonda/R/projects/contagios_covid_santander/log/cargue_diario.log' 2>&1 >/dev/null 2>&1
</code>```

Title: How to run a R script twice a day?

Body:
I had a R script configured to run via cron every day at 10am

library(cronR)
cmd2 = cron_rscript("CargueDiario_RedcapCovid_ODS.R", rscript_log="/home/admonda/R/projects/contagios_covid_santander/log/cargue_diario.log", log_append = T, log_timestamp = T)

cron_add(command = cmd2, frequency = 'daily', at = "10:00" , days_of_week = "*", id = 'FCVREDCAPCOVID_ODS_DIARIO', description = "FCVREDCAPCOVID_ODS_DIARIO")

cron_ls("FCVREDCAPCOVID_ODS_DIARIO")
## cronR job
## id:   FCVREDCAPCOVID_ODS_DIARIO
## tags:
## desc: FCVREDCAPCOVID_ODS_DIARIO
0 10 * * 0,1,2,3,4,5,6 /usr/lib/R/bin/Rscript '/home/admonda/R/projects/contagios_covid_santander/CargueDiario_RedcapCovid_ODS.R'  >> '/home/admonda/R/projects/contagios_covid_santander/log/cargue_diario.log' 2>&1

Now i need to change it so it runs twice a day (10:00 and 22:00). I have already deleted it from CRON and I would like to make sure this is the correct new command:

cron_add(command = cmd2, frequency = 'daily', at = c("10:00","22:00") , days_of_week = "*", id = 'FCVREDCAPCOVID_ODS_DIARIO', description = "FCVREDCAPCOVID_ODS_DIARIO")

Body:
You still can use your original line, just change 10 to 10,22.

0 10,22 * * * /usr/lib/R/bin/Rscript '/home/admonda/R/projects/contagios_covid_santander/CargueDiario_RedcapCovid_ODS.R'  >> '/home/admonda/R/projects/contagios_covid_santander/log/cargue_diario.log' 2>&1 >/dev/null 2>&1