问:
Spring Boot on Tomcat 9 Fails to Map Controllers (404's)
My Spring boot application packaged as ROOT.war on tomcat9 using Java 11 appears to load successfully but fails to map the controllers. I can view every page by going right to the .jsp but my controller's map the URL's without .jsp. If I go to the mapped URL I get the standard 404 page.

This app works locally but expresses this behavior on my remote VM.

I've not seen this before and can't find anything relevant in my logs. I have another application with the exact same setup that works fine. What am I missing and/or what should I try next?

Here is my context file:

```<code><?xml version="1.0" encoding="UTF-8"?>
<Context antiResourceLocking="true" path=""/>
</code>```

Using standard spring application setup:

```<code>@SpringBootApplication
public class Application extends SpringBootServletInitializer{

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
</code>```

And a basic request mapping and ModelAndView response:

```<code>@RestController
public class PageController extends BasePageController {
    private static final Logger LOGGER = LoggerFactory.getLogger(PageController.class);

    @Autowired       private Configuration configuration;

    @Autowired
    private OrderManager orderManager;

    @RequestMapping(value = "/", method=RequestMethod.GET)
    public ModelAndView indexSlash(HttpServletRequest arg0, HttpServletResponse arg1) {
</code>```

This works fine locally and for another app with the same setup, making me think its some minor version issue. I am using tomcat 9.0.34 and Java 11.0.7. There is nothing in my app log. Here is my catalina.out file after startup:

```<code>NOTE: Picked up JDK_JAVA_OPTIONS:  --add-opens=java.base/java.lang=ALL-UNNAMED --add-opens=java.base/java.io=ALL-UNNAMED --add-opens=java.rmi/sun.rmi.transport=ALL-UNNAMED
31-May-2020 15:33:46.744 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Server version name:   Apache Tomcat/9.0.34
31-May-2020 15:33:46.748 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Server built:          Apr 3 2020 12:02:52 UTC
31-May-2020 15:33:46.748 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Server version number: 9.0.34.0
31-May-2020 15:33:46.749 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log OS Name:               Linux
31-May-2020 15:33:46.749 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log OS Version:            5.3.0-1022-azure
31-May-2020 15:33:46.749 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Architecture:          amd64
31-May-2020 15:33:46.749 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Java Home:             /usr/lib/jvm/java-11-openjdk-amd64
31-May-2020 15:33:46.749 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log JVM Version:           11.0.7+10-post-Ubuntu-2ubuntu218.04
31-May-2020 15:33:46.750 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log JVM Vendor:            Ubuntu
31-May-2020 15:33:46.750 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log CATALINA_BASE:         /usr/local/tomcat9
31-May-2020 15:33:46.751 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log CATALINA_HOME:         /usr/local/tomcat9
31-May-2020 15:33:46.786 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: --add-opens=java.base/java.lang=ALL-UNNAMED
31-May-2020 15:33:46.787 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: --add-opens=java.base/java.io=ALL-UNNAMED
31-May-2020 15:33:46.787 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: --add-opens=java.rmi/sun.rmi.transport=ALL-UNNAMED
31-May-2020 15:33:46.787 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Djava.util.logging.config.file=/usr/local/tomcat9/conf/logging.properties
31-May-2020 15:33:46.787 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager
31-May-2020 15:33:46.788 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Djdk.tls.ephemeralDHKeySize=2048
31-May-2020 15:33:46.788 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Djava.protocol.handler.pkgs=org.apache.catalina.webresources
31-May-2020 15:33:46.789 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Dorg.apache.catalina.security.SecurityListener.UMASK=0027
31-May-2020 15:33:46.789 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Dignore.endorsed.dirs=
31-May-2020 15:33:46.789 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Dcatalina.base=/usr/local/tomcat9
31-May-2020 15:33:46.789 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Dcatalina.home=/usr/local/tomcat9
31-May-2020 15:33:46.792 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Djava.io.tmpdir=/usr/local/tomcat9/temp
31-May-2020 15:33:46.792 INFO [main] org.apache.catalina.core.AprLifecycleListener.lifecycleEvent The APR based Apache Tomcat Native library which allows optimal performance in production environments was not $
31-May-2020 15:33:47.542 INFO [main] org.apache.coyote.AbstractProtocol.init Initializing ProtocolHandler ["http-nio-8080"]
31-May-2020 15:33:47.606 INFO [main] org.apache.catalina.startup.Catalina.load Server initialization in [1,342] milliseconds
31-May-2020 15:33:47.738 INFO [main] org.apache.catalina.core.StandardService.startInternal Starting service [Catalina]
31-May-2020 15:33:47.744 INFO [main] org.apache.catalina.core.StandardEngine.startInternal Starting Servlet engine: [Apache Tomcat/9.0.34]
31-May-2020 15:33:47.800 INFO [main] org.apache.catalina.startup.HostConfig.deployWAR Deploying web application archive [/usr/local/tomcat9/webapps/ROOT.war]
31-May-2020 15:33:47.831 INFO [main] org.apache.catalina.startup.ExpandWar.expand An expanded directory [/usr/local/tomcat9/webapps/ROOT] was found with a last modified time that did not match the associated W$
31-May-2020 15:33:54.545 INFO [main] org.apache.jasper.servlet.TldScanner.scanJars At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs $
31-May-2020 15:33:55.095 INFO [main] org.apache.catalina.startup.HostConfig.deployWAR Deployment of web application archive [/usr/local/tomcat9/webapps/ROOT.war] has finished in [7,295] ms
31-May-2020 15:33:55.100 INFO [main] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory [/usr/local/tomcat9/webapps/host-manager]
31-May-2020 15:33:55.166 INFO [main] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory [/usr/local/tomcat9/webapps/host-manager] has finished in [66] ms
31-May-2020 15:33:55.167 INFO [main] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory [/usr/local/tomcat9/webapps/docs]
31-May-2020 15:33:55.207 INFO [main] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory [/usr/local/tomcat9/webapps/docs] has finished in [40] ms
31-May-2020 15:33:55.208 INFO [main] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory [/usr/local/tomcat9/webapps/examples]
31-May-2020 15:33:55.581 INFO [main] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory [/usr/local/tomcat9/webapps/examples] has finished in [373] ms
31-May-2020 15:33:55.581 INFO [main] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory [/usr/local/tomcat9/webapps/manager]
31-May-2020 15:33:55.625 INFO [main] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory [/usr/local/tomcat9/webapps/manager] has finished in [43] ms
31-May-2020 15:33:55.633 INFO [main] org.apache.coyote.AbstractProtocol.start Starting ProtocolHandler ["http-nio-8080"]
31-May-2020 15:33:55.667 INFO [main] org.apache.catalina.startup.Catalina.start Server startup in [8,059] milliseconds
</code>```

答:
@RequestMapping is missing.</p>

```<code>@RestController
@RequestMapping("/page")
public class PageController extends BasePageController { }
</code>```

Body:
My Spring boot application packaged as ROOT.war on tomcat9 using Java 11 appears to load successfully but fails to map the controllers. I can view every page by going right to the .jsp but my controller's map the URL's without .jsp. If I go to the mapped URL I get the standard 404 page.

This app works locally but expresses this behavior on my remote VM.

I've not seen this before and can't find anything relevant in my logs. I have another application with the exact same setup that works fine. What am I missing and/or what should I try next?

Here is my context file:

<?xml version="1.0" encoding="UTF-8"?>
<Context antiResourceLocking="true" path=""/>

Using standard spring application setup:

@SpringBootApplication
public class Application extends SpringBootServletInitializer{

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

And a basic request mapping and ModelAndView response:

@RestController
public class PageController extends BasePageController {
    private static final Logger LOGGER = LoggerFactory.getLogger(PageController.class);

    @Autowired       private Configuration configuration;

    @Autowired
    private OrderManager orderManager;

    @RequestMapping(value = "/", method=RequestMethod.GET)
    public ModelAndView indexSlash(HttpServletRequest arg0, HttpServletResponse arg1) {

This works fine locally and for another app with the same setup, making me think its some minor version issue. I am using tomcat 9.0.34 and Java 11.0.7. There is nothing in my app log. Here is my catalina.out file after startup:

NOTE: Picked up JDK_JAVA_OPTIONS:  --add-opens=java.base/java.lang=ALL-UNNAMED --add-opens=java.base/java.io=ALL-UNNAMED --add-opens=java.rmi/sun.rmi.transport=ALL-UNNAMED
31-May-2020 15:33:46.744 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Server version name:   Apache Tomcat/9.0.34
31-May-2020 15:33:46.748 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Server built:          Apr 3 2020 12:02:52 UTC
31-May-2020 15:33:46.748 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Server version number: 9.0.34.0
31-May-2020 15:33:46.749 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log OS Name:               Linux
31-May-2020 15:33:46.749 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log OS Version:            5.3.0-1022-azure
31-May-2020 15:33:46.749 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Architecture:          amd64
31-May-2020 15:33:46.749 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Java Home:             /usr/lib/jvm/java-11-openjdk-amd64
31-May-2020 15:33:46.749 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log JVM Version:           11.0.7+10-post-Ubuntu-2ubuntu218.04
31-May-2020 15:33:46.750 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log JVM Vendor:            Ubuntu
31-May-2020 15:33:46.750 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log CATALINA_BASE:         /usr/local/tomcat9
31-May-2020 15:33:46.751 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log CATALINA_HOME:         /usr/local/tomcat9
31-May-2020 15:33:46.786 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: --add-opens=java.base/java.lang=ALL-UNNAMED
31-May-2020 15:33:46.787 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: --add-opens=java.base/java.io=ALL-UNNAMED
31-May-2020 15:33:46.787 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: --add-opens=java.rmi/sun.rmi.transport=ALL-UNNAMED
31-May-2020 15:33:46.787 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Djava.util.logging.config.file=/usr/local/tomcat9/conf/logging.properties
31-May-2020 15:33:46.787 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager
31-May-2020 15:33:46.788 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Djdk.tls.ephemeralDHKeySize=2048
31-May-2020 15:33:46.788 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Djava.protocol.handler.pkgs=org.apache.catalina.webresources
31-May-2020 15:33:46.789 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Dorg.apache.catalina.security.SecurityListener.UMASK=0027
31-May-2020 15:33:46.789 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Dignore.endorsed.dirs=
31-May-2020 15:33:46.789 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Dcatalina.base=/usr/local/tomcat9
31-May-2020 15:33:46.789 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Dcatalina.home=/usr/local/tomcat9
31-May-2020 15:33:46.792 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Djava.io.tmpdir=/usr/local/tomcat9/temp
31-May-2020 15:33:46.792 INFO [main] org.apache.catalina.core.AprLifecycleListener.lifecycleEvent The APR based Apache Tomcat Native library which allows optimal performance in production environments was not $
31-May-2020 15:33:47.542 INFO [main] org.apache.coyote.AbstractProtocol.init Initializing ProtocolHandler ["http-nio-8080"]
31-May-2020 15:33:47.606 INFO [main] org.apache.catalina.startup.Catalina.load Server initialization in [1,342] milliseconds
31-May-2020 15:33:47.738 INFO [main] org.apache.catalina.core.StandardService.startInternal Starting service [Catalina]
31-May-2020 15:33:47.744 INFO [main] org.apache.catalina.core.StandardEngine.startInternal Starting Servlet engine: [Apache Tomcat/9.0.34]
31-May-2020 15:33:47.800 INFO [main] org.apache.catalina.startup.HostConfig.deployWAR Deploying web application archive [/usr/local/tomcat9/webapps/ROOT.war]
31-May-2020 15:33:47.831 INFO [main] org.apache.catalina.startup.ExpandWar.expand An expanded directory [/usr/local/tomcat9/webapps/ROOT] was found with a last modified time that did not match the associated W$
31-May-2020 15:33:54.545 INFO [main] org.apache.jasper.servlet.TldScanner.scanJars At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs $
31-May-2020 15:33:55.095 INFO [main] org.apache.catalina.startup.HostConfig.deployWAR Deployment of web application archive [/usr/local/tomcat9/webapps/ROOT.war] has finished in [7,295] ms
31-May-2020 15:33:55.100 INFO [main] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory [/usr/local/tomcat9/webapps/host-manager]
31-May-2020 15:33:55.166 INFO [main] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory [/usr/local/tomcat9/webapps/host-manager] has finished in [66] ms
31-May-2020 15:33:55.167 INFO [main] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory [/usr/local/tomcat9/webapps/docs]
31-May-2020 15:33:55.207 INFO [main] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory [/usr/local/tomcat9/webapps/docs] has finished in [40] ms
31-May-2020 15:33:55.208 INFO [main] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory [/usr/local/tomcat9/webapps/examples]
31-May-2020 15:33:55.581 INFO [main] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory [/usr/local/tomcat9/webapps/examples] has finished in [373] ms
31-May-2020 15:33:55.581 INFO [main] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory [/usr/local/tomcat9/webapps/manager]
31-May-2020 15:33:55.625 INFO [main] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory [/usr/local/tomcat9/webapps/manager] has finished in [43] ms
31-May-2020 15:33:55.633 INFO [main] org.apache.coyote.AbstractProtocol.start Starting ProtocolHandler ["http-nio-8080"]
31-May-2020 15:33:55.667 INFO [main] org.apache.catalina.startup.Catalina.start Server startup in [8,059] milliseconds

Body:
@RequestMapping is missing.

@RestController
@RequestMapping("/page")
public class PageController extends BasePageController { }


来源: stackexchange

问:
preg_match in JavaScript?
Is it possible in JavaScript to do something like preg_match does in PHP ?

I would like to be able to get two numbers from string:

```<code>var text = 'price[5][68]';
</code>```

into two separated variables:

```<code>var productId = 5;
var shopId    = 68;
</code>```

Edit:
I also use MooTools if it would help.

答:
Some Googling brought me to this :

function preg_match (regex, str) {
  return (new RegExp(regex).test(str))
}
console.log(preg_match("^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,6}$","test"))
console.log(preg_match("^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,6}$","what@google.com"))```

See https://locutus.io for more info.

ContentLicense: CC BY-SA 2.5

Title: preg_match in JavaScript?

Body:
Is it possible in JavaScript to do something like preg_match does in PHP ?

I would like to be able to get two numbers from string:

var text = 'price[5][68]';

into two separated variables:

var productId = 5;
var shopId    = 68;

Edit:
I also use MooTools if it would help.

Body:
Some Googling brought me to this :

function preg_match (regex, str) {
  return (new RegExp(regex).test(str))
}
console.log(preg_match("^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,6}$","test"))
console.log(preg_match("^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,6}$","what@google.com"))

See https://locutus.io for more info.

ContentLicense: CC BY-SA 4.0


问:
React Native - Set email sender in CC
My code roughly looks as follows

<ListItem onPress={() => Linking.openURL('mailto:' + "destination.address@gmail.com" + '?subject=My Subject&body=' + 'My message')}>
</ListItem>```

When the user clicks on the component, the share dialog should appear offering all the available email clients and such. As the title says, I would like to add the sender in CC but I have not found a way to know the address such address. This answer suggests there is no way to achieve this. If that is the case, is there any reasonable work around.

答:
Use & operator and add cc like this.</p>

```<code><ListItem onPress={() => Linking.openURL('mailto:somethingemail@gmail.com?subject=abcdefg&cc=anotherdude@gmail.com&body=body')}>
</code>```

Title: React Native - Set email sender in CC

Body:
My code roughly looks as follows

<ListItem onPress={() => Linking.openURL('mailto:' + "destination.address@gmail.com" + '?subject=My Subject&body=' + 'My message')}>
</ListItem>

When the user clicks on the component, the share dialog should appear offering all the available email clients and such. As the title says, I would like to add the sender in CC but I have not found a way to know the address such address. This answer suggests there is no way to achieve this. If that is the case, is there any reasonable work around.

Body:
Use & operator and add cc like this.

<ListItem onPress={() => Linking.openURL('mailto:somethingemail@gmail.com?subject=abcdefg&cc=anotherdude@gmail.com&body=body')}>


问:
How to change image set on Button
I want to change the button image on buttons click event. Here is what i am trying.

```<code>-(IBAction)editObjectImage:(id)sender
{
    if (editButtonState == NO)
    {
        [editButton setImage:nil forState:UIControlStateNormal];
        [editButton setImage:[UIImage imageNamed:@"done2.png"] forState:UIControlStateNormal];
    }
    else
    {
        [editButton setImage:nil forState:UIControlStateNormal];
        [editButton setImage:[UIImage imageNamed:@"edit.png"] forState:UIControlStateNormal];
    }
}
</code>```

But my Button image is not changing. What's wrong with code?

答:
On button click you have to set image like this;</p>

```<code>[editButton setImage:[UIImage imageNamed:@"image.png"] forState:UIControlStateHighlighted];
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to change image set on Button

Body:
I want to change the button image on buttons click event. Here is what i am trying.

-(IBAction)editObjectImage:(id)sender
{
    if (editButtonState == NO)
    {
        [editButton setImage:nil forState:UIControlStateNormal];
        [editButton setImage:[UIImage imageNamed:@"done2.png"] forState:UIControlStateNormal];
    }
    else
    {
        [editButton setImage:nil forState:UIControlStateNormal];
        [editButton setImage:[UIImage imageNamed:@"edit.png"] forState:UIControlStateNormal];
    }
}

But my Button image is not changing. What's wrong with code?

Body:
On button click you have to set image like this;

[editButton setImage:[UIImage imageNamed:@"image.png"] forState:UIControlStateHighlighted];


问:
Using Mutate and/or Apply Function on horse racing ratings dataframe to find average of two values
I am still new to the group and R.
I am working on a horse racing database.
The dataframe below displays the performance ratings achieved by seven different race
horse (rows 1 to 7). The performance ratings for each horse (column) are labelled DaH1 to DaH3,
where DaH1 is the most recent performance rating and DaH3 is the 3rd from recent performance
rating.  The dataset also has some NA values.  These are races that took place under different
conditions to todays race so are not considered as valid performances for consideration.

```<code>> racehorse_data
  DaH1 DaH2 DaH3
1    0  124  121
2  124  117  119
3  121  125  123
4  123  120  119
5    0  125   NA
6   NA    0    0
7  110   NA  123

</code>```

I have generated some basic stats on the dataset such as mean and max (see code below).
I would now like to generate some calculations on the ratings of each racehorse using custom functions.
I am reading about the apply functions and mutate but am struggling to create code that
will enable me to find what I describe as the average of the best two performances over the last
three races (for each horse, row)
So for example, for horse 3, the average of the best two performances is 124, using (123+125)/2.
Where there is only 2 values for consideration due to NA values I would just evaluate the ratings two
ratings that I have.
My idea was to sort or order the rating values in each row by highest first and then take the
average of the highest 2.  I'm trying this with Apply and Mutate but not quite getting there.
The code is below.  I'd be grateful for any help the group can prove.
Thanks

```<code>racehorse_data$Mean <- apply(racehorse_data,1,mean,na.rm=T)
racehorse_data$Max <- apply(racehorse_data,1,max,na.rm=T)

</code>```

Gives:

```<code>
  DaH1 DaH2 DaH3      Mean Max
1    0  124  121  81.66667 124
2  124  117  119 120.00000 124
3  121  125  123 123.00000 125
4  123  120  119 120.66667 123
5    0  125   NA  62.50000 125
6   NA    0    0   0.00000   0
7  110   NA  123 116.50000 123

</code>```

Thanks
Graham

答:
```<code>racehorse_data <- data.frame(DaH1 = c(0, 124, 121, 123, 0, NA, 110),
                   DaH2 = c(123, 117, 125, 120, 125, 0, NA),
                   DaH3 = c(121, 119, 123, 119, NA, 0, 123))
</code>```

I would start with creating function to calculate 2nd best result (since we can find the best one with max)

```<code>find_second <- function(x){
  n <- length(x)
  sort(x, partial=n-1, na.last = FALSE)[n-1]
}
</code>```

And now we can create 2 columns with best and second best result and calculate mean of those 2 values:

```<code>racehorse_data$second_best <- apply(racehorse_data,1, find_second)
racehorse_data$Max <- apply(racehorse_data,1,max,na.rm=T)
racehorse_data$Mean <- rowMeans(cbind(racehorse_data$second_best, racehorse_data$Max), na.rm = TRUE)
</code>```

result:

```<code>> racehorse_data
  DaH1 DaH2 DaH3 second_best Max  Mean
1    0  123  121         121 123 122.0
2  124  117  119         119 124 121.5
3  121  125  123         123 125 124.0
4  123  120  119         120 123 121.5
5    0  125   NA           0 125  62.5
6   NA    0    0           0   0   0.0
7  110   NA  123         110 123 116.5
</code>```

Body:
I am still new to the group and R.
I am working on a horse racing database.
The dataframe below displays the performance ratings achieved by seven different race
horse (rows 1 to 7). The performance ratings for each horse (column) are labelled DaH1 to DaH3,
where DaH1 is the most recent performance rating and DaH3 is the 3rd from recent performance
rating.  The dataset also has some NA values.  These are races that took place under different
conditions to todays race so are not considered as valid performances for consideration.

> racehorse_data
  DaH1 DaH2 DaH3
1    0  124  121
2  124  117  119
3  121  125  123
4  123  120  119
5    0  125   NA
6   NA    0    0
7  110   NA  123

I have generated some basic stats on the dataset such as mean and max (see code below).
I would now like to generate some calculations on the ratings of each racehorse using custom functions.
I am reading about the apply functions and mutate but am struggling to create code that
will enable me to find what I describe as the average of the best two performances over the last
three races (for each horse, row)
So for example, for horse 3, the average of the best two performances is 124, using (123+125)/2.
Where there is only 2 values for consideration due to NA values I would just evaluate the ratings two
ratings that I have.
My idea was to sort or order the rating values in each row by highest first and then take the
average of the highest 2.  I'm trying this with Apply and Mutate but not quite getting there.
The code is below.  I'd be grateful for any help the group can prove.
Thanks

racehorse_data$Mean <- apply(racehorse_data,1,mean,na.rm=T)
racehorse_data$Max <- apply(racehorse_data,1,max,na.rm=T)

Gives:

  DaH1 DaH2 DaH3      Mean Max
1    0  124  121  81.66667 124
2  124  117  119 120.00000 124
3  121  125  123 123.00000 125
4  123  120  119 120.66667 123
5    0  125   NA  62.50000 125
6   NA    0    0   0.00000   0
7  110   NA  123 116.50000 123

Thanks
Graham

Body:
racehorse_data <- data.frame(DaH1 = c(0, 124, 121, 123, 0, NA, 110),
                   DaH2 = c(123, 117, 125, 120, 125, 0, NA),
                   DaH3 = c(121, 119, 123, 119, NA, 0, 123))

I would start with creating function to calculate 2nd best result (since we can find the best one with max)

find_second <- function(x){
  n <- length(x)
  sort(x, partial=n-1, na.last = FALSE)[n-1]
}

And now we can create 2 columns with best and second best result and calculate mean of those 2 values:

racehorse_data$second_best <- apply(racehorse_data,1, find_second)
racehorse_data$Max <- apply(racehorse_data,1,max,na.rm=T)
racehorse_data$Mean <- rowMeans(cbind(racehorse_data$second_best, racehorse_data$Max), na.rm = TRUE)

result:

> racehorse_data
  DaH1 DaH2 DaH3 second_best Max  Mean
1    0  123  121         121 123 122.0
2  124  117  119         119 124 121.5
3  121  125  123         123 125 124.0
4  123  120  119         120 123 121.5
5    0  125   NA           0 125  62.5
6   NA    0    0           0   0   0.0
7  110   NA  123         110 123 116.5


问:
How to get the smallest item from the second items of a tuple list?
First of all sorry for the confusing title, I had no idead how to explain my problem without an example.

I have the following graph

```<code>graph = {
    1: [(3, 5), (4, 1),  (5, 4)],
    2: [(5, 9)],
    3: [(5, 1), (6, 1)],
    4: [(2, 11), (8, 2)],
    5: [(4, 6), (2, 6)],
    6: [(7, 1)],
    7: [(5, 7), (2, 1)],
    8: [(2, 6)],
}
</code>```

I want to be able to get the smallest number from the second item of the tupels for a given number. For example, if I gave the function the number 1 I would want it to return the 1 from the second tupel. If the input was 4 instead I would expect it to return a 2 form the second tupel.

My current approach is min((graph[s])[1]), but this doesn't really work and mostly returns Index Errors.

Edit:
I solved the problem with (min(graph[s])[0], min(graph[s])[1])[1] now (for some reason) it works in all cases (the problems were with lists that only contained one tupel).

答:
Try this:</p>

```<code>def get_smallest_num(key):
    return min(map(lambda x: x[1], graph[key]))

print(get_smallest_num(1)) # 1
print(get_smallest_num(5)) # 6
</code>```

Body:
First of all sorry for the confusing title, I had no idead how to explain my problem without an example.

I have the following graph

graph = {
    1: [(3, 5), (4, 1),  (5, 4)],
    2: [(5, 9)],
    3: [(5, 1), (6, 1)],
    4: [(2, 11), (8, 2)],
    5: [(4, 6), (2, 6)],
    6: [(7, 1)],
    7: [(5, 7), (2, 1)],
    8: [(2, 6)],
}

I want to be able to get the smallest number from the second item of the tupels for a given number. For example, if I gave the function the number 1 I would want it to return the 1 from the second tupel. If the input was 4 instead I would expect it to return a 2 form the second tupel.

My current approach is min((graph[s])[1]), but this doesn't really work and mostly returns Index Errors.

Edit:
I solved the problem with (min(graph[s])[0], min(graph[s])[1])[1] now (for some reason) it works in all cases (the problems were with lists that only contained one tupel).

Body:
Try this:

def get_smallest_num(key):
    return min(map(lambda x: x[1], graph[key]))

print(get_smallest_num(1)) # 1
print(get_smallest_num(5)) # 6


问:
Closure compiler not detecting json inside script tag
In my page I have a dynamically created section that outputs some JSON code:

```

But when compressing the closure compiler sends this error message:

ERROR - [JSC_PARSE_ERROR] Parse error. Semi-colon expected { "@type": "WebPage","name": "page-test-tabs","url": "/content/my-site/en/page-test"}

Can you guys please give me some guidance here for this issue?

答: Closure Compiler only recognizes JavaScript.  As JavaScript,  the { opens a statement block, not an object literal.  </p>

Body:
In my page I have a dynamically created section that outputs some JSON code:

But when compressing the closure compiler sends this error message:

ERROR - [JSC_PARSE_ERROR] Parse error. Semi-colon expected { "@type": "WebPage","name": "page-test-tabs","url": "/content/my-site/en/page-test"}

Can you guys please give me some guidance here for this issue?


问:
Search in array query result in php/mysql
I have the mysql results ($date_options) as below

```<code>Array (
    [0] => stdClass Object (
        [id] => 4
        [start_date] => 2010-09-29
    )
    [1] => stdClass Object (
        [id] => 13
        [start_date] => 2010-10-06
    )
)
</code>```

I need to be able to search in the "id" field if some value existed. I tried this and it didn't work:

```<code>array_search($event_id, $date_options, true)
</code>```

$event_id is has the id value. I only want to look in id and not in start_date

How to solve this?

Thanks

答:
This is Tested you may try it, I have used in my one of projects

```<code>function FindData($fKey, $find_val, $res) {
        $arr = $res;//json_decode($res, true);
        foreach ($arr as $key => $value) {
            if ($value[$fKey] == $find_val) {
                return $value;
            }
        }
    }
</code>```

example:

```<code>$row = FindData('KeyName', 'Value', 'ArrayData or mySql Result Set');
</code>```

It wont hit MySQL Database each time to fetch patricular data.

Body:
I have the mysql results ($date_options) as below

Array (
    [0] => stdClass Object (
        [id] => 4
        [start_date] => 2010-09-29
    )
    [1] => stdClass Object (
        [id] => 13
        [start_date] => 2010-10-06
    )
)

I need to be able to search in the "id" field if some value existed. I tried this and it didn't work:

array_search($event_id, $date_options, true)

$event_id is has the id value. I only want to look in id and not in start_date

How to solve this?

Thanks

Body:
This is Tested you may try it, I have used in my one of projects

function FindData($fKey, $find_val, $res) {
        $arr = $res;//json_decode($res, true);
        foreach ($arr as $key => $value) {
            if ($value[$fKey] == $find_val) {
                return $value;
            }
        }
    }

example:

$row = FindData('KeyName', 'Value', 'ArrayData or mySql Result Set');

It wont hit MySQL Database each time to fetch patricular data.


问:
(Windows) `dartdoc` generating documentation files for every base library in the Dart's and Flutter's SDKs when running against my (tiny) package
The first problem I encountered — and which I think is related to the main one — is with respect to the FLUTTER_ROOT variable.

I don't know why it wasn't preset at some point in the installation, but, anyway, I just can't seem to set it from within VS Code, not even if I open it with administrator permissions.

If I run dartdoc in VS Code I get the following error:

```<code>Documenting <package_name>...

dartdoc failed: Top level package requires Flutter but FLUTTER_ROOT environment variable not set.
</code>```

My configurations:

My top-level bin folder for Flutter is located at C:\src\flutter\flutter.

My FLUTTER_ROOT environment variable has the C:\src\flutter\flutter value for both my user and the system.

If I run it with permissions in Powershell or Command Prompt, it parses every dart core library (dart-async, dart-collection, dart-core, etc.) and every Flutter core library, which I think is understandable to generate my library's docs, but then it also generates docs for all of those dart core libraries. Is this the intended behavior?

答:
I also had trouble with FLUTTER_ROOT environment variable from dartdoc, but solved it by setting the environment variable as shown in the image below.

<img src="https://i.stack.imgur.com/CR5Va.png" alt="FLUTTER_ROOT">

Body:
The first problem I encountered — and which I think is related to the main one — is with respect to the FLUTTER_ROOT variable.

I don't know why it wasn't preset at some point in the installation, but, anyway, I just can't seem to set it from within VS Code, not even if I open it with administrator permissions.

If I run dartdoc in VS Code I get the following error:

Documenting <package_name>...

dartdoc failed: Top level package requires Flutter but FLUTTER_ROOT environment variable not set.

My configurations:

My top-level bin folder for Flutter is located at C:\src\flutter\flutter.

My FLUTTER_ROOT environment variable has the C:\src\flutter\flutter value for both my user and the system.

If I run it with permissions in Powershell or Command Prompt, it parses every dart core library (dart-async, dart-collection, dart-core, etc.) and every Flutter core library, which I think is understandable to generate my library's docs, but then it also generates docs for all of those dart core libraries. Is this the intended behavior?


问:
find how many elements from the beginning of the array must be added to get a total of more than 10
I have an array with numbers. Need to find how many elements from the beginning of the array must be added to get a total of more than 10. In the code I have to use reduce

    let arr = [2, 3, 1, 0, 4, 5, 4];

The console in this case must display the number 6.

My code didn't work:

```<code>let arr = [2, 3, 1, 0, 4, 5, 4];
let sumNumber = arr.reduce((sum, elem, index) => {

    let ourSum = 0;
    while (ourSum <= 10) {
        return sum + elem;
    }
    index++

}, 0)
console.log(sumNumber);
</code>```

答:
This is one solution:</p>

```<code>const arr = [2, 3, 1, 0, 4, 5, 4]

const sumNumber = arr.reduce(
  (acc, cur, index) => {
    if (typeof acc === 'number') { // If the accumulator is a number...
      return acc // Just return it
    }
    const sum = acc.sum + cur
    if (sum > 10) { // If sum is greater than 10...
      return index + 1 // ...return a number
    }
    return { sum } // Return an object with sum with the new value
  },
  { sum: 0 } // Start with an object with the `sum` property of 0
)

console.log(sumNumber)
</code>```

Body:
I have an array with numbers. Need to find how many elements from the beginning of the array must be added to get a total of more than 10. In the code I have to use reduce

    let arr = [2, 3, 1, 0, 4, 5, 4];

The console in this case must display the number 6.

My code didn't work:

let arr = [2, 3, 1, 0, 4, 5, 4];
let sumNumber = arr.reduce((sum, elem, index) => {

    let ourSum = 0;
    while (ourSum <= 10) {
        return sum + elem;
    }
    index++

}, 0)
console.log(sumNumber);

Body:
This is one solution:

const arr = [2, 3, 1, 0, 4, 5, 4]

const sumNumber = arr.reduce(
  (acc, cur, index) => {
    if (typeof acc === 'number') { // If the accumulator is a number...
      return acc // Just return it
    }
    const sum = acc.sum + cur
    if (sum > 10) { // If sum is greater than 10...
      return index + 1 // ...return a number
    }
    return { sum } // Return an object with sum with the new value
  },
  { sum: 0 } // Start with an object with the `sum` property of 0
)

console.log(sumNumber)


问:
How can I initialize this semaphore
I asked this question about multithreading in servlet, and many people suggest using a static variable.

If I set a static variable and I need to initialize it. For example public static Semaphore permits;

At first, I tried to initialize it in the init() method of a filter associated with the servlet:

```<code>public void init(FilterConfig conf) throws ServletException {
        // TODO Auto-generated method stub
    try{
            limit = Integer.parseInt(conf.getInitParameter("filterLimit"));
            permits = new Semaphore(limit);
    }catch(Exception ex){
            conf.getServletContext().log("Fail to set the parameter : permits.");
            throw new ServletException(ex.getMessage());
    }

}
</code>```

Then I thought that with so many threads, every threads executing the init() method will initialize the semaphore, it should be not working.

Then I tried to use a static initializer:

```<code>static{
        try{
            limit = Integer.parseInt(conf.getInitParameter("filterLimit"));
            permits = new Semaphore(limit);
        }catch(Exception ex){
            conf.getServletContext().log("Fail to set the parameter : permits.");
            throw new ServletException(ex.getMessage());
        }

 }
</code>```

But I cannot use the conf object as it is passed from the init() method. I want to get the limit number from web.xml, instead of hardcoding it. Any idea to solve this?

答: Simply check limit for null before initializing.</p>

Title: How can I initialize this semaphore

Body:
I asked this question about multithreading in servlet, and many people suggest using a static variable.

If I set a static variable and I need to initialize it. For example public static Semaphore permits;

At first, I tried to initialize it in the init() method of a filter associated with the servlet:

public void init(FilterConfig conf) throws ServletException {
        // TODO Auto-generated method stub
    try{
            limit = Integer.parseInt(conf.getInitParameter("filterLimit"));
            permits = new Semaphore(limit);
    }catch(Exception ex){
            conf.getServletContext().log("Fail to set the parameter : permits.");
            throw new ServletException(ex.getMessage());
    }

}

Then I thought that with so many threads, every threads executing the init() method will initialize the semaphore, it should be not working.

Then I tried to use a static initializer:

static{
        try{
            limit = Integer.parseInt(conf.getInitParameter("filterLimit"));
            permits = new Semaphore(limit);
        }catch(Exception ex){
            conf.getServletContext().log("Fail to set the parameter : permits.");
            throw new ServletException(ex.getMessage());
        }

 }

But I cannot use the conf object as it is passed from the init() method. I want to get the limit number from web.xml, instead of hardcoding it. Any idea to solve this?


问:
accelerometer is sampled at high frequency , how to convert UTC time to float time?
```<code> import pandas as pd
 df = pd.DataFrame(['Time':['16:47:55.510','16:47:55.511','16:47:55.410']})
 df

 output:
            Time
 0      16:47:55.510
 1      16:47:55.511
 2      16:47:55.410
</code>```

how to convert this time values to float value using python?

答:
If the time is in h:m:s.ms format you can do something like this:</p>

```<code>hours, minutes, seconds = df.Time[0].split(':')
total_seconds = int(hours) * 3600 + int(minutes) * 60 + float(seconds)
</code>```

Body:
 import pandas as pd
 df = pd.DataFrame(['Time':['16:47:55.510','16:47:55.511','16:47:55.410']})
 df

 output:
            Time
 0      16:47:55.510
 1      16:47:55.511
 2      16:47:55.410

how to convert this time values to float value using python?

Body:
If the time is in h:m:s.ms format you can do something like this:

hours, minutes, seconds = df.Time[0].split(':')
total_seconds = int(hours) * 3600 + int(minutes) * 60 + float(seconds)


问:
Converting each row of a dataframe into a string and assigning it as a column to another dataset in pandas
I have a dataset:

```<code>id   name   address   phone   email
123  abc    123 abc   12345   info@abc.com
456  cbs    456 cbs   67890   info@cbs.com
758  nbc    789 nbc   11121   info@nbc.com
</code>```

I want to create a new dataset, where it retains the first two columns (id and name) and has the third column, which will have a string that is a combination of values of address, phone and email. In other words, I need it to look like this:

```<code>id   name   meta_str
123  abc    '123 abc   12345   info@abc.com'
456  cbs    '456 cbs   67890   info@cbs.com'
758  nbc    '789 nbc   11121   info@nbc.com'
</code>```

This is the code I have:

```<code>df_transformed = df[['id','name']]
df_meta = df[['address','phone','email']]
df_meta_str = df_meta.iloc[:].to_string(header=False, index=False)
df_transformed['meta_str'] = df_meta_str
</code>```

But what I get is:

```<code>id   name   meta_str
123  abc    '123 abc   12345   info@abc.com'
456  cbs    '123 abc   12345   info@abc.com'
758  nbc    '123 abc   12345   info@abc.com'
</code>```

I think the problem is that df_meta_str has the data in all rows combined as one big string.

What would be a way to achieve a separate string on a separate row?

答:
I will do </p>

```<code>df['meta_str']=df.loc[:,'address':].astype(str).agg(' '.join,1)
0    123abc 12345 info@abc.com
1    456cbs 67890 info@cbs.com
2    789nbc 11121 info@nbc.com
dtype: object
</code>```

Body:
I have a dataset:

id   name   address   phone   email
123  abc    123 abc   12345   info@abc.com
456  cbs    456 cbs   67890   info@cbs.com
758  nbc    789 nbc   11121   info@nbc.com

I want to create a new dataset, where it retains the first two columns (id and name) and has the third column, which will have a string that is a combination of values of address, phone and email. In other words, I need it to look like this:

id   name   meta_str
123  abc    '123 abc   12345   info@abc.com'
456  cbs    '456 cbs   67890   info@cbs.com'
758  nbc    '789 nbc   11121   info@nbc.com'

This is the code I have:

df_transformed = df[['id','name']]
df_meta = df[['address','phone','email']]
df_meta_str = df_meta.iloc[:].to_string(header=False, index=False)
df_transformed['meta_str'] = df_meta_str

But what I get is:

id   name   meta_str
123  abc    '123 abc   12345   info@abc.com'
456  cbs    '123 abc   12345   info@abc.com'
758  nbc    '123 abc   12345   info@abc.com'

I think the problem is that df_meta_str has the data in all rows combined as one big string.

What would be a way to achieve a separate string on a separate row?

Body:
I will do

df['meta_str']=df.loc[:,'address':].astype(str).agg(' '.join,1)
0    123abc 12345 info@abc.com
1    456cbs 67890 info@cbs.com
2    789nbc 11121 info@nbc.com
dtype: object


问:
Not getting ACTION_PACKAGE_REMOVED broadcast - Android 10/Settings
We want to know when apps are uninstalled from the Android device. We set up broadcast receivers (not in the manifest) concerning the device apps and process them when received. The problem: when uninstalling an app (using Android Settings -> Apps/Notifications -> AppYouWantToUninstall -> tap the trashcan) the broadcast is not received...however this only happens when the app is installed on an  Android 10 device.

Of course there are two other main ways to uninstall apps: 1) tap/hold on the app and bring up the "App Info" menu; and 2) go into the Play Store. Those other two methods deliver a broadcast of ACTION_PACKAGE_REMOVED.

All combinations of OS (Android 7, 8, 9 and 10) and the three methods of uninstalling deliver the ACTION_PACKAGE_REMOVED broadcast except for Settings uninstall method when the app is on an Android 10 device.  I'd be skeptical, too, so I'll answer a couple of likely probes: "Yes, if we use the Play Store uninstall for an app on Android 10, we do get a broadcast" and "Yes, if we use the Settings uninstall for an app on Android 7, 8, 9 we do get a broadcast"

The definition in the class:

```<code>class AppInstallBroadcastReceiver : BroadcastReceiver() {
    override fun onReceive(context: Context?, intent: Intent?) {
        if (intent == null || context == null) return
        when (intent.action) {
            Intent.ACTION_PACKAGE_ADDED ->
                enqueueWork(context, getIntent(context, ACTION_PACKAGE_ADDED, intent.data?.schemeSpecificPart))
            Intent.ACTION_PACKAGE_REPLACED ->
                enqueueWork(context, getIntent(context, ACTION_PACKAGE_REPLACED, intent.data?.schemeSpecificPart))
            Intent.ACTION_PACKAGE_CHANGED ->
                enqueueWork(context, getIntent(context, ACTION_PACKAGE_CHANGED, intent.data?.schemeSpecificPart))
            Intent.ACTION_PACKAGE_REMOVED ->
                enqueueWork(context, getIntent(context, ACTION_PACKAGE_REMOVED, intent.data?.schemeSpecificPart))
            Intent.ACTION_PACKAGE_FULLY_REMOVED ->
                enqueueWork(context, getIntent(context, ACTION_PACKAGE_FULLY_REMOVED, intent.data?.schemeSpecificPart))
                }
    }
</code>```

...and this is where we process received actions

```<code>    private suspend fun processAction(action:String, packageName: String, context: Context) {
        when (action) {
            ACTION_PACKAGE_ADDED -> updateAppInfo(context, packageName, false)
            ACTION_PACKAGE_REPLACED -> updateAppInfo(context, packageName, true)
            ACTION_PACKAGE_REMOVED -> deleteAppInfo(context, packageName)
            ACTION_PACKAGE_FULLY_REMOVED -> deleteFullyAppInfo(context, packageName)
        }
    }
</code>```

This is where we define (in the application, not the manifest) the receivers:

```<code>    private val installBroadcastReceiver = AppInstallBroadcastReceiver()
    private val installReceiverFilter = IntentFilter().apply {
        addAction(Intent.ACTION_PACKAGE_ADDED)
        addAction(Intent.ACTION_PACKAGE_REMOVED)
        addAction(Intent.ACTION_PACKAGE_FULLY_REMOVED)
        addAction(Intent.ACTION_PACKAGE_CHANGED)
        addAction(Intent.ACTION_PACKAGE_REPLACED)
        addDataScheme("package")
    }
</code>```

...and where we register, filter

```<code>    private fun registerAppChanges() {
        Timber.d("Registering the installation receiver ..")
        registerReceiver(installBroadcastReceiver, installReceiverFilter)
        registerReceiver(unlockReceiver, unlockReceiverFilter)
    }
</code>```

答:
To run a Broadcast receiver you have to know how it works. Previously when you register a broadcast receiver, it gets fired when any registered action happens even app is not in the background. Then android team make some changes to optimize battery. If your app target 26 or above, you have to declare it dynamically instead of manifest. Here is the text

Note: If your app targets API level 26 or higher, you cannot use the
  manifest to declare a receiver for implicit broadcasts (broadcasts
  that do not target your app specifically), except for a few implicit
  broadcasts that are exempted from that restriction. In most cases, you
  can use scheduled jobs instead.

So what's the option? You have to register broadcast dynamically using context or applicationContext. So app receives broadcast event as your context is alive. Here is the text from Google:

Context-registered receivers receive broadcasts as long as their
  registering context is valid. For an example, if you register within
  an Activity context, you receive broadcasts as long as the activity is
  not destroyed. If you register with the Application context, you
  receive broadcasts as long as the app is running.

So how do you listen Broadcast event even your app is not running?

As Broadcast receiver unreliable, I cannot imagine any feasible solution but you can think of running a background service all the time. This will be overkill as well. Check this answer
Making BroadcastReceiver work in the background in API 26 or above
Also this one from commonsware
Android O and the Implicit Broadcast Ban

Another solution I can think of, If API level is lower than 26 it should work as it is but for api 26 and above, in your app onResume you will check each time available apps and your current apps list. Then remove the extra app.

Body:
We want to know when apps are uninstalled from the Android device. We set up broadcast receivers (not in the manifest) concerning the device apps and process them when received. The problem: when uninstalling an app (using Android Settings -> Apps/Notifications -> AppYouWantToUninstall -> tap the trashcan) the broadcast is not received...however this only happens when the app is installed on an  Android 10 device.

Of course there are two other main ways to uninstall apps: 1) tap/hold on the app and bring up the "App Info" menu; and 2) go into the Play Store. Those other two methods deliver a broadcast of ACTION_PACKAGE_REMOVED.

All combinations of OS (Android 7, 8, 9 and 10) and the three methods of uninstalling deliver the ACTION_PACKAGE_REMOVED broadcast except for Settings uninstall method when the app is on an Android 10 device.  I'd be skeptical, too, so I'll answer a couple of likely probes: "Yes, if we use the Play Store uninstall for an app on Android 10, we do get a broadcast" and "Yes, if we use the Settings uninstall for an app on Android 7, 8, 9 we do get a broadcast"

The definition in the class:

class AppInstallBroadcastReceiver : BroadcastReceiver() {
    override fun onReceive(context: Context?, intent: Intent?) {
        if (intent == null || context == null) return
        when (intent.action) {
            Intent.ACTION_PACKAGE_ADDED ->
                enqueueWork(context, getIntent(context, ACTION_PACKAGE_ADDED, intent.data?.schemeSpecificPart))
            Intent.ACTION_PACKAGE_REPLACED ->
                enqueueWork(context, getIntent(context, ACTION_PACKAGE_REPLACED, intent.data?.schemeSpecificPart))
            Intent.ACTION_PACKAGE_CHANGED ->
                enqueueWork(context, getIntent(context, ACTION_PACKAGE_CHANGED, intent.data?.schemeSpecificPart))
            Intent.ACTION_PACKAGE_REMOVED ->
                enqueueWork(context, getIntent(context, ACTION_PACKAGE_REMOVED, intent.data?.schemeSpecificPart))
            Intent.ACTION_PACKAGE_FULLY_REMOVED ->
                enqueueWork(context, getIntent(context, ACTION_PACKAGE_FULLY_REMOVED, intent.data?.schemeSpecificPart))
                }
    }

...and this is where we process received actions

    private suspend fun processAction(action:String, packageName: String, context: Context) {
        when (action) {
            ACTION_PACKAGE_ADDED -> updateAppInfo(context, packageName, false)
            ACTION_PACKAGE_REPLACED -> updateAppInfo(context, packageName, true)
            ACTION_PACKAGE_REMOVED -> deleteAppInfo(context, packageName)
            ACTION_PACKAGE_FULLY_REMOVED -> deleteFullyAppInfo(context, packageName)
        }
    }

This is where we define (in the application, not the manifest) the receivers:

    private val installBroadcastReceiver = AppInstallBroadcastReceiver()
    private val installReceiverFilter = IntentFilter().apply {
        addAction(Intent.ACTION_PACKAGE_ADDED)
        addAction(Intent.ACTION_PACKAGE_REMOVED)
        addAction(Intent.ACTION_PACKAGE_FULLY_REMOVED)
        addAction(Intent.ACTION_PACKAGE_CHANGED)
        addAction(Intent.ACTION_PACKAGE_REPLACED)
        addDataScheme("package")
    }

...and where we register, filter

    private fun registerAppChanges() {
        Timber.d("Registering the installation receiver ..")
        registerReceiver(installBroadcastReceiver, installReceiverFilter)
        registerReceiver(unlockReceiver, unlockReceiverFilter)
    }


问:
Efficient Dictionary lookup
For my C++ application, there is a requirement to check if a word is a valid English dictionary word or not. What is the best way to do it. Is there freely available dictionary that I can make use of. I just need a collection of all possible words. How to make this lookup least expensive. Do I need to hash it. </p>

答:
With regards to the presence of a word list, it depends on the platform.
Under Linux, /usr/share/dict/words contains a list of English words
that might meet your needs.  Otherwise, there are doubtlessly such lists
available on the network.

Given the size of such lists, the most rapid access will be to load it
into a hash table. std::unsorted_set, if you have it; otherwise, many
C++ compilers come with a hash_set, although different compilers have
a slightly different interface for it, and put it in different
namespaces.  If that still has performance problems, it's possible to do
better if you know the number of entries in advance (so the table never
has to grow), and implement the hash table in an std::vector (or even a
C style array); handling collisions will be a bit more complicated,
however.

Another possibility would be a trie.  This will almost certainly result
in the least number of basic operations in the lookup, and is fairly
simple to implement.  Typical implementations will have very poor
locality, however, which could make it slower than some of the other
solutions in actual practice (or not—the only way to know is to
implement both and measure).

Title: Efficient Dictionary lookup


问:
Getter returning null when testing get methods
I am trying to get data from my database to show on a listview. The problem I am having is it seems the getters are not working properly. When I test what they are returning, it comes back null.

Any insight would be appreciated as I am lost here. Thanks in advance.

Here is where I initialise the class:

```<code>    public ArrayList<GameStats> getAllData() {
    ArrayList<GameStats> arrayList = new ArrayList<>();
    SQLiteDatabase db = this.getReadableDatabase();

    Cursor cursor = db.rawQuery("SELECT * FROM savedGamesTable", null);

    while(cursor.moveToNext()){
        int id = cursor.getInt(0);
        String lName = cursor.getString(1);
        int lScore = cursor.getInt(2);
        String rName = cursor.getString(3);
        int rScore = cursor.getInt(4);
        String notes = cursor.getString(5);

        GameStats gameStats = new GameStats(id, lName, lScore, rName, rScore, notes);
        arrayList.add(gameStats);

    }
    return arrayList;
}
</code>```

Here is where I am trying to use the getters:

```<code>    public View getView(int position, View convertView, ViewGroup parent) {

        LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = inflater.inflate(R.layout.activity_saved_games, null);
        TextView lName = convertView.findViewById(R.id.lName);
        TextView lScore = convertView.findViewById(R.id.lScore);
        TextView rName = convertView.findViewById(R.id.rName);
        TextView rScore = convertView.findViewById(R.id.rScore);
        TextView notes = convertView.findViewById(R.id.notes);

    GameStats gameStats = arrayList.get(position);
    testVar = gameStats.getlName();
    Log.d("MyAdaptor","gameStats = " + var);
    lName.setText(gameStats.getlName());
    lScore.setText(String.valueOf(gameStats.getlScore()));
    rName.setText(gameStats.getrName());
    rScore.setText(String.valueOf(gameStats.getrScore()));
    notes.setText(gameStats.getNotes());
    return convertView;
}
</code>```

Here is the model class:

```<code>public class GameStats {
int id, lScore, rScore;
String lName, rName, notes;

public GameStats(int id, String lName, int lScore, String rName, int rScore, String notes) {

}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public int getlScore() {
    return lScore;
}

public void setlScore(int lScore) {
    this.lScore = lScore;
}

public int getrScore() {
    return rScore;
}

public void setrScore(int rScore) {
    this.rScore = rScore;
}

public String getlName() {
    return lName;
}

public void setlName(String lName) {
    this.lName = lName;
}

public String getrName() {
    return rName;
}

public void setrName(String rName) {
    this.rName = rName;
}

public String getNotes() {
    return notes;
}

public void setNotes(String notes) {
    this.notes = notes;
}
</code>```

}

and here is where I am calling the methods:

```<code>public class SavedGameScreen extends AppCompatActivity {

ListView lv1;
ArrayList<GameStats> arrayList;
MyAdaptor myAdaptor;
DatabaseHelper databaseHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_saved_game_screen);
    lv1 = findViewById(R.id.lv1);
    databaseHelper = new DatabaseHelper(this);
    arrayList = new ArrayList<>();
    loadData();
}

private void loadData() {
    arrayList = databaseHelper.getAllData();
    myAdaptor = new MyAdaptor(this, arrayList);
    lv1.setAdapter(myAdaptor);
    myAdaptor.notifyDataSetChanged();
}
</code>```

}

答:
Please change the constructor as below and see if that works,</p>

```<code>public GameStats(int id, String lName, int lScore, String rName, int rScore, String notes) {
    this.id = id;
    this.lName = IName;
    this.lScore = IScore;
    this.rName = rName;
    this.rScore = rScore;
    this.notes = notes;
    }
</code>```

Body:
I am trying to get data from my database to show on a listview. The problem I am having is it seems the getters are not working properly. When I test what they are returning, it comes back null.

Any insight would be appreciated as I am lost here. Thanks in advance.

Here is where I initialise the class:

    public ArrayList<GameStats> getAllData() {
    ArrayList<GameStats> arrayList = new ArrayList<>();
    SQLiteDatabase db = this.getReadableDatabase();

    Cursor cursor = db.rawQuery("SELECT * FROM savedGamesTable", null);

    while(cursor.moveToNext()){
        int id = cursor.getInt(0);
        String lName = cursor.getString(1);
        int lScore = cursor.getInt(2);
        String rName = cursor.getString(3);
        int rScore = cursor.getInt(4);
        String notes = cursor.getString(5);

        GameStats gameStats = new GameStats(id, lName, lScore, rName, rScore, notes);
        arrayList.add(gameStats);

    }
    return arrayList;
}

Here is where I am trying to use the getters:

    public View getView(int position, View convertView, ViewGroup parent) {

        LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = inflater.inflate(R.layout.activity_saved_games, null);
        TextView lName = convertView.findViewById(R.id.lName);
        TextView lScore = convertView.findViewById(R.id.lScore);
        TextView rName = convertView.findViewById(R.id.rName);
        TextView rScore = convertView.findViewById(R.id.rScore);
        TextView notes = convertView.findViewById(R.id.notes);

    GameStats gameStats = arrayList.get(position);
    testVar = gameStats.getlName();
    Log.d("MyAdaptor","gameStats = " + var);
    lName.setText(gameStats.getlName());
    lScore.setText(String.valueOf(gameStats.getlScore()));
    rName.setText(gameStats.getrName());
    rScore.setText(String.valueOf(gameStats.getrScore()));
    notes.setText(gameStats.getNotes());
    return convertView;
}

Here is the model class:

public class GameStats {
int id, lScore, rScore;
String lName, rName, notes;

public GameStats(int id, String lName, int lScore, String rName, int rScore, String notes) {

}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public int getlScore() {
    return lScore;
}

public void setlScore(int lScore) {
    this.lScore = lScore;
}

public int getrScore() {
    return rScore;
}

public void setrScore(int rScore) {
    this.rScore = rScore;
}

public String getlName() {
    return lName;
}

public void setlName(String lName) {
    this.lName = lName;
}

public String getrName() {
    return rName;
}

public void setrName(String rName) {
    this.rName = rName;
}

public String getNotes() {
    return notes;
}

public void setNotes(String notes) {
    this.notes = notes;
}

}

and here is where I am calling the methods:

public class SavedGameScreen extends AppCompatActivity {

ListView lv1;
ArrayList<GameStats> arrayList;
MyAdaptor myAdaptor;
DatabaseHelper databaseHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_saved_game_screen);
    lv1 = findViewById(R.id.lv1);
    databaseHelper = new DatabaseHelper(this);
    arrayList = new ArrayList<>();
    loadData();
}

private void loadData() {
    arrayList = databaseHelper.getAllData();
    myAdaptor = new MyAdaptor(this, arrayList);
    lv1.setAdapter(myAdaptor);
    myAdaptor.notifyDataSetChanged();
}

}

Body:
Please change the constructor as below and see if that works,

public GameStats(int id, String lName, int lScore, String rName, int rScore, String notes) {
    this.id = id;
    this.lName = IName;
    this.lScore = IScore;
    this.rName = rName;
    this.rScore = rScore;
    this.notes = notes;
    }


问:
performance issue on left join with subquery to find out the latest date
```<code>SELECT m.*, pc.call_date
                    FROM messages m
                    LEFT JOIN customers c ON m.device_user_id = c.device_user_id
                    LEFT JOIN phone_call pc ON pc.id = (
                        SELECT MAX(pc2.id)
                        FROM phone_call pc2
                        WHERE pc2.device_user_id = c.device_user_id OR pc2.customer_id = c.customer_id
                    )
</code>```

The issue with the above is the left join phone_call table to find out the latest phone call made for each record. phone_call table has GBs of data. With left join phone_call, it takes more than 30 secs to return data. without it less than a sec. so that table is the issue. is there a better way to achieve the same result as the above query?

答: Well, you will probably not like this answer, but, if this is going to be an important data and a frequent query, I would put last_call_date as a field in customer's table.

Body:
SELECT m.*, pc.call_date
                    FROM messages m
                    LEFT JOIN customers c ON m.device_user_id = c.device_user_id
                    LEFT JOIN phone_call pc ON pc.id = (
                        SELECT MAX(pc2.id)
                        FROM phone_call pc2
                        WHERE pc2.device_user_id = c.device_user_id OR pc2.customer_id = c.customer_id
                    )

The issue with the above is the left join phone_call table to find out the latest phone call made for each record. phone_call table has GBs of data. With left join phone_call, it takes more than 30 secs to return data. without it less than a sec. so that table is the issue. is there a better way to achieve the same result as the above query?


问:
SQL update query not updating table data
Here is my code and it shows successful but it does not update row in table.</p>

```<code>cm = new SqlCommand("update table_products set pname = @pname, pdesc = @pdesc, bid = @bid, cid = @cid, cost = @cost, price = @price, reorder = @reorder where pcode like @pcode", con);

cm.Parameters.AddWithValue("@pcode", tft_pcode.Text);
cm.Parameters.AddWithValue("@barcode", tft_barcode.Text);
cm.Parameters.AddWithValue("@pname", tft_pname.Text);
cm.Parameters.AddWithValue("@pdesc", tft_pdescription.Text);
cm.Parameters.AddWithValue("@bid", bid);
cm.Parameters.AddWithValue("@cid", cid);
cm.Parameters.AddWithValue("@cost", Double.Parse(tft_cost.Text));
cm.Parameters.AddWithValue("@price", Double.Parse(tft_price.Text));
cm.Parameters.AddWithValue("@reorder", int.Parse(tft_reorder.Text));

cm.ExecuteNonQuery();
con.Close();

MessageBox.Show("Product updated successfully");
</code>```

答:
cm.ExecuteNonQuery(); returns the number of rows affected.  In your case it's probably 0 (but still worth getting the value and checking).

In your case, it sounds like  where pcode like @pcode on the end of your query, is not matching anything in the table.

```<code>var rowsUpdated = cm.ExecuteNonQuery();
con.Close();

if(rowsUpdate>0) MessageBox.Show("Product updated successfully");
else MessageBox.Show("Product NOT updated successfully");
</code>```

Body:
Here is my code and it shows successful but it does not update row in table.

cm = new SqlCommand("update table_products set pname = @pname, pdesc = @pdesc, bid = @bid, cid = @cid, cost = @cost, price = @price, reorder = @reorder where pcode like @pcode", con);

cm.Parameters.AddWithValue("@pcode", tft_pcode.Text);
cm.Parameters.AddWithValue("@barcode", tft_barcode.Text);
cm.Parameters.AddWithValue("@pname", tft_pname.Text);
cm.Parameters.AddWithValue("@pdesc", tft_pdescription.Text);
cm.Parameters.AddWithValue("@bid", bid);
cm.Parameters.AddWithValue("@cid", cid);
cm.Parameters.AddWithValue("@cost", Double.Parse(tft_cost.Text));
cm.Parameters.AddWithValue("@price", Double.Parse(tft_price.Text));
cm.Parameters.AddWithValue("@reorder", int.Parse(tft_reorder.Text));

cm.ExecuteNonQuery();
con.Close();

MessageBox.Show("Product updated successfully");

Body:
cm.ExecuteNonQuery(); returns the number of rows affected.  In your case it's probably 0 (but still worth getting the value and checking).

In your case, it sounds like  where pcode like @pcode on the end of your query, is not matching anything in the table.

var rowsUpdated = cm.ExecuteNonQuery();
con.Close();

if(rowsUpdate>0) MessageBox.Show("Product updated successfully");
else MessageBox.Show("Product NOT updated successfully");


问:
Set cpu requests in K8s for fluctuating load
I have a service deployed in Kubernetes and I am trying to optimize the requested cpu resources.

For now, I have deployed 10 instances and set spec.containers[].resources.limits.cpu to 0.1, based on the "average" use. However, it became obvious that this average is rather useless in practice because under constant load, the load increases significantly (to 0.3-0.4 as far as I can tell).

What happens consequently, when multiple instances are deployed on the same node, is that this node is heavily overloaded; pods are no longer responsive, are killed and restarted etc.

What is the best practice to find a good value? My current best guess is to increase the requested cpu to 0.3 or 0.4; I'm looking at Grafana visualizations and see that the pods on the heavily loaded node(s) converge there under continuous load.
However, how can I know if they would use more load if they could before becoming unresponsive as the node is overloaded?

I'm actually trying to understand how to approach this in general. I would expect an "ideal" service (presuming it is CPU-focused) to use close to 0.0 when there is no load, and close to 1.0 when requests are constantly coming in. With that assumption, should I set the cpu.requests to 1.0, taking a perspective where actual constant usage is assumed?

I have read some Kubernetes best practice guides, but none of them seem to address how to set the actual value for cpu requests in practice in more depth than "find an average".

答:
In a nutshell: Main goal is to understand how much traffic a pod can handle and how much resource it consumes to do so.

CPU limits are hard to understand and can be harmful, you might want
to avoid them, see static policy documentation and relevant
github issue.

To dimension your CPU requests you will want to understand first how much a pod can consume during high load. In order to do this you can :

disable all kind of autoscaling (HPA, vertical pod autoscaler, ...)

set the number of replicas to one

lift the CPU limits

request the highest amount of CPU you can on a node (3.2 usually on 4cpu nodes)

send as much traffic as you can on the application (you can achieve simple Load Tests scenarios with locust for example)

You will eventually end up with a ratio clients-or-requests-per-sec/cpu-consumed. You can suppose the relation is linear (this might not be true if your workload complexity is O(n^2) with n the number of clients connected, but this is not the nominal case).

You can then choose the pod resource requests based on the ratio you measured. For example if you consume 1.2 cpu for 1000 requests per second you know that you can give each pod 1 cpu and it will handle up to 800 requests per second.

Once you know how much a pod can consume under its maximal load, you can start setting up cpu-based autoscaling, 70% is a good first target that can be refined if you encounter issues like latency or pods not autoscaling fast enough. This will avoid your nodes to run out of cpu if the load increases.

There are a few gotchas, for example single-threaded applications are not able to consume more than a cpu. Thus if you give it 1.5 cpu it will run out of cpu but you won't be able to visualize it from metrics as you'll believe it still can consume 0.5 cpu.


问:
What is the difference between assertIs and assertTrue in unittest module, when these methods are applied on True values?
My working environment:

```<code>OS: Ubuntu 18.04 (64 bits)
Python version: 3.8.0 (64 bits)
</code>```

I've a question about the unittest documentation, more precisely, the difference between assertTrue and assertIs methods. Here is what the online documentation says:

https://docs.python.org/3/library/unittest.html

assertTrue(expr, msg=None)

assertFalse(expr, msg=None)

Test that expr is true (or false).

Note that this is equivalent to bool(expr) is True and  not to expr is
  True (use assertIs(expr, True) for the latter).

I don't really understand the difference, that is, in the case where I have a boolean type with a True value, then why should I use assertIs instead of assertTrue? Given that bool(True) is True also returns the True boolean value I don't see the difference and impact on tests. I'd appreciate if you could kindly make some clarification.

答:
You are basically right - in most cases in tests you will probably use assertTrue for the check instead of assertIs(True).

The only really useful case where you actually need assertIs(True) would be if you want to check that the checked expression actually returns a bool value, e.g.:

def test_bool(self):
    a = True
    b = 1
    self.assertTrue(a)
    self.assertIs(a, True)
    self.assertTrue(b)
    self.assertIsNot(b, True)
```

<p>This could be interesting if you have a function that may return values of different types, and you want to ensure that it returns a concrete <code>bool</code> value. Consider a (nonsense) function:</p>

<pre class="lang-python prettyprint-override"><code>def fct(param):
    if param < 0:
        return False
    if param > 0:
        return True
    return 42

...

def test_fct(self):
    assertTrue(fct(1))  # will not ensure that it returns True
    assertTrue(fct(0))  # also passes
    assertIs(True, fct(1))  # passes as intended
    assertIs(True, fct(0))  # fails, as it should
</code>```

It can also help to ensure that your tested function that is supposed to return a bool value actually does that (and not just some value that would evaluate to True or False, like None or a number, due to some bug).

This all works of course because (like None), True and False are singleton objects, e.g. there is always only one of each of them.

Body:
My working environment:

OS: Ubuntu 18.04 (64 bits)
Python version: 3.8.0 (64 bits)

I've a question about the unittest documentation, more precisely, the difference between assertTrue and assertIs methods. Here is what the online documentation says:

https://docs.python.org/3/library/unittest.html

assertTrue(expr, msg=None)

assertFalse(expr, msg=None)

Test that expr is true (or false).

Note that this is equivalent to bool(expr) is True and  not to expr is
  True (use assertIs(expr, True) for the latter).

I don't really understand the difference, that is, in the case where I have a boolean type with a True value, then why should I use assertIs instead of assertTrue? Given that bool(True) is True also returns the True boolean value I don't see the difference and impact on tests. I'd appreciate if you could kindly make some clarification.

Body:
You are basically right - in most cases in tests you will probably use assertTrue for the check instead of assertIs(True).

The only really useful case where you actually need assertIs(True) would be if you want to check that the checked expression actually returns a bool value, e.g.:

def test_bool(self):
    a = True
    b = 1
    self.assertTrue(a)
    self.assertIs(a, True)
    self.assertTrue(b)
    self.assertIsNot(b, True)

This could be interesting if you have a function that may return values of different types, and you want to ensure that it returns a concrete bool value. Consider a (nonsense) function:

def fct(param):
    if param < 0:
        return False
    if param > 0:
        return True
    return 42

...

def test_fct(self):
    assertTrue(fct(1))  # will not ensure that it returns True
    assertTrue(fct(0))  # also passes
    assertIs(True, fct(1))  # passes as intended
    assertIs(True, fct(0))  # fails, as it should

It can also help to ensure that your tested function that is supposed to return a bool value actually does that (and not just some value that would evaluate to True or False, like None or a number, due to some bug).

This all works of course because (like None), True and False are singleton objects, e.g. there is always only one of each of them.


问:
How to print X items in a list per line
Given a list of strings I want to be able to print 4 items of that list per line with one space between them until the list is exhausted. Any ideas? Thanks

Example:

```<code>ListA = ['1', '2', '3', '4', '5', '6']
</code>```

Given this list I would like my output to be:

```<code>1 2 3 4
5 6
</code>```

答:
Alternatively, one can split the given list to chunks beforehand. See How do you split a list into evenly sized chunks? for various approaches:</p>

```<code>my_list = ['1', '2', '3', '4', '5', '6']
n = 4
chunks = (my_list[i:i+n] for i in range(0, len(my_list), n))
for chunk in chunks:
    print(*chunk)
# 1 2 3 4
# 5 6
</code>```

Title: How to print X items in a list per line

Body:
Given a list of strings I want to be able to print 4 items of that list per line with one space between them until the list is exhausted. Any ideas? Thanks

Example:

ListA = ['1', '2', '3', '4', '5', '6']

Given this list I would like my output to be:

1 2 3 4
5 6

Body:
Alternatively, one can split the given list to chunks beforehand. See How do you split a list into evenly sized chunks? for various approaches:

my_list = ['1', '2', '3', '4', '5', '6']
n = 4
chunks = (my_list[i:i+n] for i in range(0, len(my_list), n))
for chunk in chunks:
    print(*chunk)
# 1 2 3 4
# 5 6


问:
Multidimensional lists in SwiftUI that pass data
I have this model:

```<code>struct Training: Identifiable {
    let id = UUID()
    let name: String
    let workout: [Workout]?
}
</code>```

and:

```<code>struct Workout: Identifiable {
    let id = UUID()
    let name: String
    let exercices: [Exercice]?
}
</code>```

and:

```<code>struct Exercice: Identifiable {
    let id = UUID()
    let name: String
}
</code>```

The data for the models is coming from an environment object.

The app will launch with an empty list of trainings and you can add trainings within the UI. Each training has a navigtaionlink to a view to add workouts to each training and in the next step you can add exercices to each workout.

In my logic I create multidimensional arrays with the structs shown above.

The trainings view is easy:

```<code>struct TrainingsView: View {

    @EnvironmentObject var appState: AppState

    @State var showingDetail = false

    var body: some View {
        NavigationView {

            VStack {
                List {
                    ForEach (appState.trainings) { training in
                        NavigationLink(destination: WorkoutsView(training: training).environmentObject(self.appState)) {
                            Text(training.name)
                        }
                    }
                    .onDelete(perform: appState.removeTraining)
                }
                // Button to add trainings....
                .navigationBarTitle(Text("Trainings").foregroundColor(Color.white))
            }
        }
    }
}
</code>```

The WorkoutsView is looking the same but I have an issue with listing the items of the parent training:

```<code>struct WorkoutsView: View {
    // ...
    var training: Training

    var body: some View {
        VStack {
            List {
                ForEach (appState.trainings(training).workouts) { workout in // I know the appState call is incorrect, but I don't know how to access is correctly.
                    NavigationLink(destination: ExercicesView(workout)) {
                        Text(workout.name)
                    }
                }
            }
            // ...
        }
    }
}
</code>```

I already tried:

```<code>List {
    ForEach (0 ..< appState.trainings.count) {
        NavigationLink(destination: WorkoutsView(training: $0).environmentObject(self.appState)) {
            Text(appState.trainings[$0].name)
        }
    }
}
</code>```

I could use appState.trainings[training].workouts in the WorkoutsView but I'm getting the error Contextual closure type '() -> Text' expects 0 arguments, but 1 was used in closure body on the NavigationLink line and don't know what to do.

Additional question: If this is close to the solution, I don't need the struct to conform to Identifiable?

答:
You have 2 broad approaches here, depending on how you want to design your system.

1. Your child views know about the app state and can modify it directly. So, the parent needs to pass the indices/keys for the child to locate which data to modify:

```<code>struct TrainingsView: View {
   @EnvironmentObject var appState: AppState

   var body: some View {
      NavigationView {
         List(0..<appState.trainings.count) { i in
            NavigationLink(destination: WorkoutsView(trainingIndex: i)) {
               Text(self.appState.trainings[i].name)
            }
         }
      }
   }
}
</code>```

```<code>struct WorkoutsView: View {
   var trainingIdx: Int
   @EnvironmentObject var appState: AppState

   var body: some View {
      VStack() {

         TextField("training name: ", text: $appState.trainings[trainingIdx].name)

         Button(action: {self.appState.trainings[trainingIdx].workouts.append(Workout(...))}) {
            Text("Add workout")
         }
      }
   }
}

</code>```

2. Alternatively, you might say that you don't want your child views to know about the app's state - you just want them to modify some static struct that they don't own (but rather owned by their parent), then you should use use a @Binding.

The example below is conceptual to illustrate a point:

```<code>struct TrainingsView: View {
   @State var trainingA = Training(...)
   @State var trainingB = Training(...)

   var body: some Body {
      NavigationView {
         List {
            WorkoutsView(training: $trainingA)
            WorkoutsView(training: $trainingB)
         }
      }
   }
}
</code>```

```<code>struct WorkoutsView: View {
   @Binding var training: Training

   var body: some View {
      VStack() {

         TextField("training name: ", text: $training.name)

         Button(action: { self.training.workouts.append(Workout(...)) }) {
            Text("Add workout")
         }
      }
   }
}
</code>```

Body:
I have this model:

struct Training: Identifiable {
    let id = UUID()
    let name: String
    let workout: [Workout]?
}

and:

struct Workout: Identifiable {
    let id = UUID()
    let name: String
    let exercices: [Exercice]?
}

and:

struct Exercice: Identifiable {
    let id = UUID()
    let name: String
}

The data for the models is coming from an environment object.

The app will launch with an empty list of trainings and you can add trainings within the UI. Each training has a navigtaionlink to a view to add workouts to each training and in the next step you can add exercices to each workout.

In my logic I create multidimensional arrays with the structs shown above.

The trainings view is easy:

struct TrainingsView: View {

    @EnvironmentObject var appState: AppState

    @State var showingDetail = false

    var body: some View {
        NavigationView {

            VStack {
                List {
                    ForEach (appState.trainings) { training in
                        NavigationLink(destination: WorkoutsView(training: training).environmentObject(self.appState)) {
                            Text(training.name)
                        }
                    }
                    .onDelete(perform: appState.removeTraining)
                }
                // Button to add trainings....
                .navigationBarTitle(Text("Trainings").foregroundColor(Color.white))
            }
        }
    }
}

The WorkoutsView is looking the same but I have an issue with listing the items of the parent training:

struct WorkoutsView: View {
    // ...
    var training: Training

    var body: some View {
        VStack {
            List {
                ForEach (appState.trainings(training).workouts) { workout in // I know the appState call is incorrect, but I don't know how to access is correctly.
                    NavigationLink(destination: ExercicesView(workout)) {
                        Text(workout.name)
                    }
                }
            }
            // ...
        }
    }
}

I already tried:

List {
    ForEach (0 ..< appState.trainings.count) {
        NavigationLink(destination: WorkoutsView(training: $0).environmentObject(self.appState)) {
            Text(appState.trainings[$0].name)
        }
    }
}

I could use appState.trainings[training].workouts in the WorkoutsView but I'm getting the error Contextual closure type '() -> Text' expects 0 arguments, but 1 was used in closure body on the NavigationLink line and don't know what to do.

Additional question: If this is close to the solution, I don't need the struct to conform to Identifiable?

Body:
You have 2 broad approaches here, depending on how you want to design your system.

1. Your child views know about the app state and can modify it directly. So, the parent needs to pass the indices/keys for the child to locate which data to modify:

struct TrainingsView: View {
   @EnvironmentObject var appState: AppState

   var body: some View {
      NavigationView {
         List(0..<appState.trainings.count) { i in
            NavigationLink(destination: WorkoutsView(trainingIndex: i)) {
               Text(self.appState.trainings[i].name)
            }
         }
      }
   }
}

struct WorkoutsView: View {
   var trainingIdx: Int
   @EnvironmentObject var appState: AppState

   var body: some View {
      VStack() {

         TextField("training name: ", text: $appState.trainings[trainingIdx].name)

         Button(action: {self.appState.trainings[trainingIdx].workouts.append(Workout(...))}) {
            Text("Add workout")
         }
      }
   }
}

2. Alternatively, you might say that you don't want your child views to know about the app's state - you just want them to modify some static struct that they don't own (but rather owned by their parent), then you should use use a @Binding.

The example below is conceptual to illustrate a point:

struct TrainingsView: View {
   @State var trainingA = Training(...)
   @State var trainingB = Training(...)

   var body: some Body {
      NavigationView {
         List {
            WorkoutsView(training: $trainingA)
            WorkoutsView(training: $trainingB)
         }
      }
   }
}

struct WorkoutsView: View {
   @Binding var training: Training

   var body: some View {
      VStack() {

         TextField("training name: ", text: $training.name)

         Button(action: { self.training.workouts.append(Workout(...)) }) {
            Text("Add workout")
         }
      }
   }
}


问:
Algorithm to find which number in a list sum up to a certain number
I have a list of numbers. I also have a certain sum. The sum is made from a few numbers from my list (I may/may not know how many numbers it's made from). Is there a fast algorithm to get a list of possible numbers? Written in Python would be great, but pseudo-code's good too. (I can't yet read anything other than Python :P )

Example

```<code>list = [1,2,3,10]
sum = 12
result = [2,10]
</code>```

NOTE: I do know of Algorithm to find which numbers from a list of size n sum to another number (but I cannot read C# and I'm unable to check if it works for my needs. I'm on Linux and I tried using Mono but I get errors and I can't figure out how to work C# :(

AND I do know of algorithm to sum up a list of numbers for all combinations (but it seems to be fairly inefficient. I don't need all combinations.)

答:
I know I'm giving an answer 10 years later since you asked this, but i really needed to know how to do this an the way jbernadas did it was too hard for me, so i googled it for an hour and I found a python library itertools that gets the job done!

I hope this help to future newbie programmers.
You just have to import the library and use the .combinations() method, it is that simple, it returns all the subsets in a set with order, I mean:

For the set [1, 2, 3, 4] and a subset with length 3 it will not return [1, 2, 3][1, 3, 2][2, 3, 1] it will return just [1, 2, 3]

As you want ALL the subsets of a set you can iterate it:

```<code>import itertools

sequence = [1, 2, 3, 4]
for i in range(len(sequence)):
    for j in itertools.combinations(sequence, i):
        print(j)
</code>```

The output will be

()
  (1,)
  (2,)
  (3,)
  (4,)
  (1, 2)
  (1, 3)
  (1, 4)
  (2, 3)
  (2, 4)
  (3, 4)
  (1, 2, 3)
  (1, 2, 4)
  (1, 3, 4)
  (2, 3, 4)

Hope this help!

Body:
I have a list of numbers. I also have a certain sum. The sum is made from a few numbers from my list (I may/may not know how many numbers it's made from). Is there a fast algorithm to get a list of possible numbers? Written in Python would be great, but pseudo-code's good too. (I can't yet read anything other than Python :P )

Example

list = [1,2,3,10]
sum = 12
result = [2,10]

NOTE: I do know of Algorithm to find which numbers from a list of size n sum to another number (but I cannot read C# and I'm unable to check if it works for my needs. I'm on Linux and I tried using Mono but I get errors and I can't figure out how to work C# :(

AND I do know of algorithm to sum up a list of numbers for all combinations (but it seems to be fairly inefficient. I don't need all combinations.)

Body:
I know I'm giving an answer 10 years later since you asked this, but i really needed to know how to do this an the way jbernadas did it was too hard for me, so i googled it for an hour and I found a python library itertools that gets the job done!

I hope this help to future newbie programmers.
You just have to import the library and use the .combinations() method, it is that simple, it returns all the subsets in a set with order, I mean:

For the set [1, 2, 3, 4] and a subset with length 3 it will not return [1, 2, 3][1, 3, 2][2, 3, 1] it will return just [1, 2, 3]

As you want ALL the subsets of a set you can iterate it:

import itertools

sequence = [1, 2, 3, 4]
for i in range(len(sequence)):
    for j in itertools.combinations(sequence, i):
        print(j)

The output will be

()
  (1,)
  (2,)
  (3,)
  (4,)
  (1, 2)
  (1, 3)
  (1, 4)
  (2, 3)
  (2, 4)
  (3, 4)
  (1, 2, 3)
  (1, 2, 4)
  (1, 3, 4)
  (2, 3, 4)

Hope this help!


问:
Cannot Install TensorFlow on this Platform
I'm trying to install Tensorflow on a computer with a J1800 CPU. I know this CPU does not have the AVX extension. I'm trying to find a wheel package of tensorflow without an AVX extension. Every wheel I try gets the same error. Here's one example:

pip3 install https://raw.githubusercontent.com/fo40225/tensorflow-windows-wheel/master/1.14.0/py37/CPU/sse2/tensorflow-1.14.0-cp37-cp37m-win_amd64.whl

: ERROR: tensorflow-1.14.0-cp37-cp37m-win_amd64.whl is not a supported wheel on this platform.

I'm running  Python  3.8 64Bit

Does anyone know a wheel that will work on this CPU? Or am I making another mistake?

答:
Assuming you are installing tensorflow 1.14 on python 3.8. python 3.8 works with  TF 2.0 only. You can either change the python version.
If you have any version like 3.x you can current python version to those by alias

eg :

```<code>alias python3 = python3.x
</code>```

where x > 8

other wise checkout 2.0 and reinstall for the source.

Body:
Assuming you are installing tensorflow 1.14 on python 3.8. python 3.8 works with  TF 2.0 only. You can either change the python version.
If you have any version like 3.x you can current python version to those by alias

eg :

alias python3 = python3.x

where x > 8

other wise checkout 2.0 and reinstall for the source.