问:
How to change screens with react-navigation (using a button)
I'm new to react native, but I've been researching how to redirect to new activities with buttons for the last few hours with no avail. My current solution involves me using react-navigation from multiple files, with App.js creating the StackNavigator for the rest of the pages. However, whenever I press the button on Initial.js, nothing happens.

I followed Damien Manson's tutorial on Invariant Violation: The navigation prop is missing for this navigator, but the button still doesn't work. I tried referencing App before calling my button, but whenever I try to run it on the emulator, it doesn't show me an error log and it never loads. It stays at "Downloading JavaScript bundle: 100%" for minutes until the emulator itself crashes.

Here's my App.js

```<code>import Initial from './components/Initial'
import Statistics from './components/Statistics'

const RootStack = createStackNavigator({
  Default: {
    screen: Initial
  },
  Stats: {
    screen: Statistics
  }
});

const App = createAppContainer(RootStack);

export default App;
</code>```

Here's my Initial.js

```<code>import { StyleSheet, ImageBackground, Image, View, Text, Button } from 'react-native';
import { Font } from 'expo';

import App from '../App';

import {withNavigation} from 'react-navigation';
import Statistics from './Statistics';

export default class Initial extends React.Component {
    static navigationOptions = {header: null}

    componentDidMount() {
        Font.loadAsync({'pt': require('../assets/fonts/pt.ttf')});
        Font.loadAsync({'Karla': require('../assets/fonts/Karla-Regular.ttf')});
        Font.loadAsync({'Space-Mono': require('../assets/fonts/SpaceMono-Regular.ttf')});
    }

    state = { fontLoaded: false};

    async componentDidMount() {
        await Font.loadAsync({'pt': require('../assets/fonts/pt.ttf'),});
        await Font.loadAsync({'Karla': require('../assets/fonts/Karla-Regular.ttf'),});
        await Font.loadAsync({'Space-Mono': require('../assets/fonts/SpaceMono-Regular.ttf'),});
        this.setState({fontLoaded: true});
    }

    render() {
        return (
            <ImageBackground
                source = {require('../assets/blue-bin.jpg')}
                style = {styles.container}>
                <View style = {styles.parentView}>
                    {this.state.fontLoaded ? (<Text style={styles.logoText}>!arbitrary</Text>) : null}
                    <Image source = {require('../assets/sadparrot.gif')} style = {styles.logo}/>
                    <Text style = {styles.textBox}>With its easily navigatible interface, the Chicago-based app, !arbitrary, aims to educate the masses about recyclable items, while emphasizing the importance of being sustainable.</Text>
                    <View style = {styles.redirect}>
                        <Button
                            title="Start"
                            onPress={() => this.props.navigation.navigate('Statistics')}
                         />
                    </View>
                </View>
            </ImageBackground>
        );
    }
}

const styles = StyleSheet.create({
    container: {
      flex: 1,
      width: '100%',
      height: '100%',
    },
    parentView: {
      flex: 1,
      flexDirection: 'column',
      backgroundColor: 'rgba(5,9,12, 0.6)',
      justifyContent: 'center',
      alignItems: 'center'
    },
    logoText: {
      color: '#fff',
      fontSize: 36,
      fontFamily: 'pt'
    },
    textBox: {
      width: 200,
      height: 175,
      fontFamily: 'sans-serif',
      fontSize: 14,
      color: '#fff',
      borderColor: '#fff',
      borderWidth: 2,
      justifyContent: 'center',
      marginTop: 50,
      padding: 20
    },
    logo: {
      width: 200,
      height: 200
    },
    redirect: {
      width: 80,
      height: 30,
      marginTop: 30
    },
    statistics: {
      flex: 1,
      width: '100%',
      height: '100%',
      backgroundColor: '#1B384F'
    },
    bigText: {
      color: '#fff',
      fontSize: 20,
      fontFamily: 'Space-Mono'
    }
});
</code>```

Here's my Statistics.js

```<code>import { StyleSheet, ImageBackground, Image, View, Text, Button } from 'react-native';
import { Font } from 'expo';
import {withNavigation} from 'react-navigation';

class Statistics extends React.Component {
    render() {
        return(
            <Text>Avail!</Text>
        );
    }
}
export default withNavigation(Statistics);
</code>```

NOTE: I omitted my StyleSheet in Initial.js for the sake of being concise.

答:
I had the same issue. I fixed is by using withNavigation

In Statistics class,

1st, Import withNavigation.

import { withNavigation } from 'react-navigation';

Then, export Statistics class as below.

export default withNavigation(Statistics)

Body:
I'm new to react native, but I've been researching how to redirect to new activities with buttons for the last few hours with no avail. My current solution involves me using react-navigation from multiple files, with App.js creating the StackNavigator for the rest of the pages. However, whenever I press the button on Initial.js, nothing happens.

I followed Damien Manson's tutorial on Invariant Violation: The navigation prop is missing for this navigator, but the button still doesn't work. I tried referencing App before calling my button, but whenever I try to run it on the emulator, it doesn't show me an error log and it never loads. It stays at "Downloading JavaScript bundle: 100%" for minutes until the emulator itself crashes.

Here's my App.js

import Initial from './components/Initial'
import Statistics from './components/Statistics'

const RootStack = createStackNavigator({
  Default: {
    screen: Initial
  },
  Stats: {
    screen: Statistics
  }
});

const App = createAppContainer(RootStack);

export default App;

Here's my Initial.js

import { StyleSheet, ImageBackground, Image, View, Text, Button } from 'react-native';
import { Font } from 'expo';

import App from '../App';

import {withNavigation} from 'react-navigation';
import Statistics from './Statistics';

export default class Initial extends React.Component {
    static navigationOptions = {header: null}

    componentDidMount() {
        Font.loadAsync({'pt': require('../assets/fonts/pt.ttf')});
        Font.loadAsync({'Karla': require('../assets/fonts/Karla-Regular.ttf')});
        Font.loadAsync({'Space-Mono': require('../assets/fonts/SpaceMono-Regular.ttf')});
    }

    state = { fontLoaded: false};

    async componentDidMount() {
        await Font.loadAsync({'pt': require('../assets/fonts/pt.ttf'),});
        await Font.loadAsync({'Karla': require('../assets/fonts/Karla-Regular.ttf'),});
        await Font.loadAsync({'Space-Mono': require('../assets/fonts/SpaceMono-Regular.ttf'),});
        this.setState({fontLoaded: true});
    }

    render() {
        return (
            <ImageBackground
                source = {require('../assets/blue-bin.jpg')}
                style = {styles.container}>
                <View style = {styles.parentView}>
                    {this.state.fontLoaded ? (<Text style={styles.logoText}>!arbitrary</Text>) : null}
                    <Image source = {require('../assets/sadparrot.gif')} style = {styles.logo}/>
                    <Text style = {styles.textBox}>With its easily navigatible interface, the Chicago-based app, !arbitrary, aims to educate the masses about recyclable items, while emphasizing the importance of being sustainable.</Text>
                    <View style = {styles.redirect}>
                        <Button
                            title="Start"
                            onPress={() => this.props.navigation.navigate('Statistics')}
                         />
                    </View>
                </View>
            </ImageBackground>
        );
    }
}

const styles = StyleSheet.create({
    container: {
      flex: 1,
      width: '100%',
      height: '100%',
    },
    parentView: {
      flex: 1,
      flexDirection: 'column',
      backgroundColor: 'rgba(5,9,12, 0.6)',
      justifyContent: 'center',
      alignItems: 'center'
    },
    logoText: {
      color: '#fff',
      fontSize: 36,
      fontFamily: 'pt'
    },
    textBox: {
      width: 200,
      height: 175,
      fontFamily: 'sans-serif',
      fontSize: 14,
      color: '#fff',
      borderColor: '#fff',
      borderWidth: 2,
      justifyContent: 'center',
      marginTop: 50,
      padding: 20
    },
    logo: {
      width: 200,
      height: 200
    },
    redirect: {
      width: 80,
      height: 30,
      marginTop: 30
    },
    statistics: {
      flex: 1,
      width: '100%',
      height: '100%',
      backgroundColor: '#1B384F'
    },
    bigText: {
      color: '#fff',
      fontSize: 20,
      fontFamily: 'Space-Mono'
    }
});

Here's my Statistics.js

import { StyleSheet, ImageBackground, Image, View, Text, Button } from 'react-native';
import { Font } from 'expo';
import {withNavigation} from 'react-navigation';

class Statistics extends React.Component {
    render() {
        return(
            <Text>Avail!</Text>
        );
    }
}
export default withNavigation(Statistics);

NOTE: I omitted my StyleSheet in Initial.js for the sake of being concise.


来源: stackexchange

问:
Need to install pandas library directly from a python file on MacOS
I am required  to use a fresh Mac OS with no libraries unless I can find a way to download pandas using a .py file on the fresh VM. How would I do this on MacOS?</p>

答:
If you have already installed pip with your python setup, you can download the wheel file of pandas library and install it using pip.

More about it here.

ContentLicense: CC BY-SA 4.0


问:
RegEx for replacing the middle letter
Invalid regular expression: Invalid group

I tried except ( ) , fixed and changed . to $
but does not work

```<code>var name = 'ABC'
var pattern = /(?<=.{1})./
return name.replace(pattern, " * ")
</code>```

I want to replace like 'A*C'

Invalid regular expression: Invalid group

答:
Here we might just want to use start and end anchors and write a simple expression such as:

```<code>^([A-Z]).([A-Z])$
</code>```

make a replacement with:

```<code>$1*$2
</code>```

const regex = /^([A-Z]).([A-Z])$/gm;
const str = `ABC`;
const subst = `$1*$2`;

// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);

console.log(result);```

Demo

RegEx

If this expression wasn't desired, it can be modified/changed in regex101.com.

RegEx Circuit

jex.im visualizes regular expressions:

Title: RegEx for replacing the middle letter

Body:
Invalid regular expression: Invalid group

I tried except ( ) , fixed and changed . to $
but does not work

var name = 'ABC'
var pattern = /(?<=.{1})./
return name.replace(pattern, " * ")

I want to replace like 'A*C'

Invalid regular expression: Invalid group

Body:
Here we might just want to use start and end anchors and write a simple expression such as:

^([A-Z]).([A-Z])$

make a replacement with:

$1*$2

const regex = /^([A-Z]).([A-Z])$/gm;
const str = `ABC`;
const subst = `$1*$2`;

// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);

console.log(result);

Demo

RegEx

If this expression wasn't desired, it can be modified/changed in regex101.com.

RegEx Circuit

jex.im visualizes regular expressions:


问:
Adding the column value to the array in another column when the value is missing
I have a dataframe with a column that contains an arraylist containing structs of form (key, score), i.e. the value column below.
In addition, I have another column called item that contains a string.

```<code>root
 |-- value: array (nullable = true)
 |    |-- element: struct (containsNull = true)
 |    |    |-- key: string (nullable = true)
 |    |    |-- score: double (nullable = true)
 |-- id: string (nullable = true)
 |-- item: string (nullable = true)
</code>```

When the item is not null, I want to search the arraylist to see if the item is present in value.key(s). If it is not present, append (item, min) to the arraylist in value column. Here, min is the minimum value for the scores in the arraylist.
I need to preserve the order of elements in arraylist and append the new struct to the end of the list.

Sample input:

```<code>+-----------------------------------+------+------+
| value                             |  id  | item |
+-----------------------------------+------+------+
|[[e1, 0.4] , [e2, 0.3]]            | 1    | e3   |
|[[e1, 0.4] , [e2, 0.3], [e3, 0.2]] | 2    | e4   |
|[[e1, 0.4] , [e2, 0.3]]            | 3    | e1   |
|[[e1, 0.4] , [e2, 0.3]]            | 4    | null |
+-----------------------------------+------+------+
</code>```

Sample output:

```<code>+------------------------------------------------+------+------+
| value                                          |  id  | item |
+------------------------------------------------+------+------+
|[[e1, 0.4] , [e2, 0.3], [e3, 0.3]]              | 1    | e3   |
|[[e1, 0.4] , [e2, 0.3], [e3, 0.2], [e4, 0.2]]   | 2    | e4   |
|[[e1, 0.4] , [e2, 0.3]]                         | 3    | e1   |
|[[e1, 0.4] , [e2, 0.3]]                         | 4    | null |
+------------------------------------------------+------+------+
</code>```

How would the solution would be different, if I want to add the new (key, score) to the a specific position in the list? (e.g. start or middle)

答:
You can define udf function to achieve it.

```<code>import pyspark.sql.functions as F
from pyspark.sql.types import StructType,StructField,ArrayType,StringType,DoubleType

def contains(values,item):
    if not item:
        return values
    keys = [pair['key'] for pair in values]
    if item not in keys:
        scores = [pair['score'] for pair in values]
        values.append({'key':item,'score':min(scores)})
    return values

contains_udf = F.udf(contains,ArrayType(StructType([StructField('key', StringType()),
                                                    StructField('score', DoubleType())])))
df = df.withColumn("value", contains_udf('value','item'))
df.show(truncate = False)

+--------------------------------------------+---+----+
|value                                       |id |item|
+--------------------------------------------+---+----+
|[[e1, 0.4], [e2, 0.3], [e3, 0.3]]           |1  |e3  |
|[[e1, 0.4], [e2, 0.3], [e3, 0.2], [e4, 0.2]]|2  |e4  |
|[[e1, 0.4], [e2, 0.3]]                      |3  |e1  |
|[[e1, 0.4], [e2, 0.3]]                      |4  |null|
+--------------------------------------------+---+----+
</code>```

Body:
I have a dataframe with a column that contains an arraylist containing structs of form (key, score), i.e. the value column below.
In addition, I have another column called item that contains a string.

root
 |-- value: array (nullable = true)
 |    |-- element: struct (containsNull = true)
 |    |    |-- key: string (nullable = true)
 |    |    |-- score: double (nullable = true)
 |-- id: string (nullable = true)
 |-- item: string (nullable = true)

When the item is not null, I want to search the arraylist to see if the item is present in value.key(s). If it is not present, append (item, min) to the arraylist in value column. Here, min is the minimum value for the scores in the arraylist.
I need to preserve the order of elements in arraylist and append the new struct to the end of the list.

Sample input:

+-----------------------------------+------+------+
| value                             |  id  | item |
+-----------------------------------+------+------+
|[[e1, 0.4] , [e2, 0.3]]            | 1    | e3   |
|[[e1, 0.4] , [e2, 0.3], [e3, 0.2]] | 2    | e4   |
|[[e1, 0.4] , [e2, 0.3]]            | 3    | e1   |
|[[e1, 0.4] , [e2, 0.3]]            | 4    | null |
+-----------------------------------+------+------+

Sample output:

+------------------------------------------------+------+------+
| value                                          |  id  | item |
+------------------------------------------------+------+------+
|[[e1, 0.4] , [e2, 0.3], [e3, 0.3]]              | 1    | e3   |
|[[e1, 0.4] , [e2, 0.3], [e3, 0.2], [e4, 0.2]]   | 2    | e4   |
|[[e1, 0.4] , [e2, 0.3]]                         | 3    | e1   |
|[[e1, 0.4] , [e2, 0.3]]                         | 4    | null |
+------------------------------------------------+------+------+

How would the solution would be different, if I want to add the new (key, score) to the a specific position in the list? (e.g. start or middle)

Body:
You can define udf function to achieve it.

import pyspark.sql.functions as F
from pyspark.sql.types import StructType,StructField,ArrayType,StringType,DoubleType

def contains(values,item):
    if not item:
        return values
    keys = [pair['key'] for pair in values]
    if item not in keys:
        scores = [pair['score'] for pair in values]
        values.append({'key':item,'score':min(scores)})
    return values

contains_udf = F.udf(contains,ArrayType(StructType([StructField('key', StringType()),
                                                    StructField('score', DoubleType())])))
df = df.withColumn("value", contains_udf('value','item'))
df.show(truncate = False)

+--------------------------------------------+---+----+
|value                                       |id |item|
+--------------------------------------------+---+----+
|[[e1, 0.4], [e2, 0.3], [e3, 0.3]]           |1  |e3  |
|[[e1, 0.4], [e2, 0.3], [e3, 0.2], [e4, 0.2]]|2  |e4  |
|[[e1, 0.4], [e2, 0.3]]                      |3  |e1  |
|[[e1, 0.4], [e2, 0.3]]                      |4  |null|
+--------------------------------------------+---+----+


问:
Symfony2: how to get config parameters in Form classes
If I am inside a controller, I can easily read the config parameters using:

```<code>$this->container->getParameter('profession');
</code>```

But when I am in some other class, say a Form type, how can I get hold of the config parameters?

```<code>$container = new Container();
$container->getParameter('profession');
</code>```

The above code shouldn't and doesn't work.

答:
In Symfony 4.1

```<code>services:
    # ...
    _defaults:
        bind:
            $projectDir: '%kernel.project_dir%'
</code>```

```<code>use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;

class MessageGenerator
{
    private $params;

    public function __construct(ParameterBagInterface $params)
    {
        $this->params = $params;
    }

    public function someMethod()
    {
        $parameterValue = $this->params->get('parameter_name');
        // ...
    }
}
</code>```

Please refer this https://symfony.com/blog/new-in-symfony-4-1-getting-container-parameters-as-a-service

ContentLicense: CC BY-SA 3.0

Body:
If I am inside a controller, I can easily read the config parameters using:

$this->container->getParameter('profession');

But when I am in some other class, say a Form type, how can I get hold of the config parameters?

$container = new Container();
$container->getParameter('profession');

The above code shouldn't and doesn't work.

Body:
In Symfony 4.1

services:
    # ...
    _defaults:
        bind:
            $projectDir: '%kernel.project_dir%'

use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;

class MessageGenerator
{
    private $params;

    public function __construct(ParameterBagInterface $params)
    {
        $this->params = $params;
    }

    public function someMethod()
    {
        $parameterValue = $this->params->get('parameter_name');
        // ...
    }
}

Please refer this https://symfony.com/blog/new-in-symfony-4-1-getting-container-parameters-as-a-service


问:
Connect to Consul server running openshift to consul client running on localhost
When I run consul on my local machine and spring boot client with following properties in bootstrap.properties, I can see that it connects, discovers services and able to connect from one service to other using service discovery.
Bootstrap.properties:

```<code>spring.cloud.consul.host=localhost
spring.cloud.consul.port=8500
spring.cloud.consul.discovery.instance-id=consul-service2
spring.application.name=consul-service2
server.port=8083
</code>```

But now, I installed consul on openshift provided route to it. I can browse to consul UI and see that consul service has registered itself. But when I try to connect client running on localhost to consul running on openshift i get error.

```<code>com.ecwid.consul.transport.TransportException: org.apache.http.conn.ConnectTimeoutException: Connect to consul-uservices-template.f-az.uk.paas.intranet.db.com:8500 [consul-uservices-template.hju-azh.uk.paas.intranet.sdf.com/10.248.36.85] failed: connect timed out
        at com.ecwid.consul.transport.AbstractHttpTransport.executeRequest(AbstractHttpTransport.java:77) ~[consul-api-1.4.1.jar:na]
        at com.ecwid.consul.transport.AbstractHttpTransport.makePutRequest(AbstractHttpTransport.java:41) ~[consul-api-1.4.1.jar:na]
        at com.ecwid.consul.v1.ConsulRawClient.makePutRequest(ConsulRawClient.java:135) ~[consul-api-1.4.1.jar:na]
        at com.ecwid.consul.v1.agent.AgentConsulClient.agentServiceRegister(AgentConsulClient.java:273) ~[consul-api-1.4.1.jar:na]
        at com.ecwid.consul.v1.ConsulClient.agentServiceRegister(ConsulClient.java:309) ~[consul-api-1.4.1.jar:na]
</code>```

My bootstrap.properties:

```<code>spring.cloud.consul.host=consul-uservices-template.hju-azh.uk.paas.intranet.sdf.com
spring.cloud.consul.port=8500
spring.cloud.consul.discovery.instance-id consul-service2
spring.application.name=consul-service2
server.port=8083
</code>```

What i am doing is providing route path as host, am I wrong here ? I can see that it tries to connect to consul-uservices-template.hju-azh.uk.paas.intranet.sdf.com:8500 and it times out. I get 404 even on browser when i try to hit this url. It should not be accessing with port number. How can i do that ?

答:
It should not be accessing with port number.

As the route is provided via OpenShift (and you can access it the web UI too), I assume it is accessible through port 80.

If that is the case, you can specify spring boot to access consul via port 80 by change the following properties

```<code>spring.cloud.consul.port=80
</code>```

Body:
When I run consul on my local machine and spring boot client with following properties in bootstrap.properties, I can see that it connects, discovers services and able to connect from one service to other using service discovery.
Bootstrap.properties:

spring.cloud.consul.host=localhost
spring.cloud.consul.port=8500
spring.cloud.consul.discovery.instance-id=consul-service2
spring.application.name=consul-service2
server.port=8083

But now, I installed consul on openshift provided route to it. I can browse to consul UI and see that consul service has registered itself. But when I try to connect client running on localhost to consul running on openshift i get error.

com.ecwid.consul.transport.TransportException: org.apache.http.conn.ConnectTimeoutException: Connect to consul-uservices-template.f-az.uk.paas.intranet.db.com:8500 [consul-uservices-template.hju-azh.uk.paas.intranet.sdf.com/10.248.36.85] failed: connect timed out
        at com.ecwid.consul.transport.AbstractHttpTransport.executeRequest(AbstractHttpTransport.java:77) ~[consul-api-1.4.1.jar:na]
        at com.ecwid.consul.transport.AbstractHttpTransport.makePutRequest(AbstractHttpTransport.java:41) ~[consul-api-1.4.1.jar:na]
        at com.ecwid.consul.v1.ConsulRawClient.makePutRequest(ConsulRawClient.java:135) ~[consul-api-1.4.1.jar:na]
        at com.ecwid.consul.v1.agent.AgentConsulClient.agentServiceRegister(AgentConsulClient.java:273) ~[consul-api-1.4.1.jar:na]
        at com.ecwid.consul.v1.ConsulClient.agentServiceRegister(ConsulClient.java:309) ~[consul-api-1.4.1.jar:na]

My bootstrap.properties:

spring.cloud.consul.host=consul-uservices-template.hju-azh.uk.paas.intranet.sdf.com
spring.cloud.consul.port=8500
spring.cloud.consul.discovery.instance-id consul-service2
spring.application.name=consul-service2
server.port=8083

What i am doing is providing route path as host, am I wrong here ? I can see that it tries to connect to consul-uservices-template.hju-azh.uk.paas.intranet.sdf.com:8500 and it times out. I get 404 even on browser when i try to hit this url. It should not be accessing with port number. How can i do that ?

Body:
It should not be accessing with port number.

As the route is provided via OpenShift (and you can access it the web UI too), I assume it is accessible through port 80.

If that is the case, you can specify spring boot to access consul via port 80 by change the following properties

spring.cloud.consul.port=80


问:
SQL: Subtract one query from another
Let's say I have two tables called tbl1 & tbl2 (different number of columns and IDs), and I get the monthly total of each table using the following queries:

query1:

```<code>SELECT MONTHNAME(tbl1_date), SUM(col1+col2+col3+col4)
FROM myTbl1
GROUP BY YEAR(tbl1_date), MONTH(tbl1_date);
</code>```

query2:

```<code>SELECT MONTHNAME(tbl2_date), SUM(col1+col2+col3+col4+col5+col6)
FROM myTbl2
GROUP BY YEAR(tbl2_date), MONTH(tbl2_date);
</code>```

How can I subtract query2 from query1 and get the difference of SUMs?

答:
If the tables could have different months and you want all rows, then you really want a full join.  MySQL does not support that, but you can use union all and group by in this case:

```<code>SELECT yyyy, mon, SUM(s) - SUM(s2) as diff
FROM ((SELECT YEAR(tbl1_date) as yyyy,
              MONTHNAME(tbl1_date) as mon,
              SUM(col1+col2+col3+col4) as s1, 0 as s2
       FROM myTbl1
       GROUP BY YEAR(tbl1_date), MONTH(tbl1_date)
      ) UNION ALL
      (SELECT YEAR(tbl2_date) as yyyy,
              MONTHNAME(tbl2_date) as mon,
              0, SUM(col1+col2+col3+col4) as s2
       FROM myTbl12
       GROUP BY YEAR(tbl2_date), MONTH(tbl2_date)
      )
     ) ym
GROUP BY yyyy, mon;
</code>```

Title: SQL: Subtract one query from another

Body:
Let's say I have two tables called tbl1 & tbl2 (different number of columns and IDs), and I get the monthly total of each table using the following queries:

query1:

SELECT MONTHNAME(tbl1_date), SUM(col1+col2+col3+col4)
FROM myTbl1
GROUP BY YEAR(tbl1_date), MONTH(tbl1_date);

query2:

SELECT MONTHNAME(tbl2_date), SUM(col1+col2+col3+col4+col5+col6)
FROM myTbl2
GROUP BY YEAR(tbl2_date), MONTH(tbl2_date);

How can I subtract query2 from query1 and get the difference of SUMs?

Body:
If the tables could have different months and you want all rows, then you really want a full join.  MySQL does not support that, but you can use union all and group by in this case:

SELECT yyyy, mon, SUM(s) - SUM(s2) as diff
FROM ((SELECT YEAR(tbl1_date) as yyyy,
              MONTHNAME(tbl1_date) as mon,
              SUM(col1+col2+col3+col4) as s1, 0 as s2
       FROM myTbl1
       GROUP BY YEAR(tbl1_date), MONTH(tbl1_date)
      ) UNION ALL
      (SELECT YEAR(tbl2_date) as yyyy,
              MONTHNAME(tbl2_date) as mon,
              0, SUM(col1+col2+col3+col4) as s2
       FROM myTbl12
       GROUP BY YEAR(tbl2_date), MONTH(tbl2_date)
      )
     ) ym
GROUP BY yyyy, mon;


问:
How to setState from within a mapped item within React component
I'm trying to change the state of a component that is part of a mapped array of objects from a json file. I want to ONLY change the item containing the clicked button and none of the others.

I've been attempting to set a property (projectID) with an onClick and while I can get it to toggle one element of state (expanded or not expanded), it does it to ALL the returned results. So I've been trying to get the projectId (set in the data) and use that to set a conditional. But I can't seem to get projectId to update with the click. I briefly played around with context but I think there's something simpler I'm missing. I've attempted it within the onClick (as shown) and from within onViewChange, but that didn't seem to work as I can't access item.id from outside the mapped item.

I'm using a conditional based on a prop handed down from a couple levels up to set the category, showing only the objects I want. That part seems to be working. So I removed my expanded state as it's not necessary to the issue here.

```<code> import React from 'react';
 import projects from '../data/projects.json';

 class ProjectCard extends React.Component {

  constructor(props) {
    super(props);
    this.state={
        projects,
        expanded: false,
        projectId: -1
    }
  }

  onViewChange = (e) => {
    this.setState({
        expanded: !this.state.expanded
    });
    console.log(this.state.projectId)
  };

  render() {
    return (
        <React.Fragment>
        {this.state.projects.map((item) => {
            if (!this.state.expanded && item.category === this.props.category) {
                return (
                        <div key={item.id} className="project-card">
                            <div className="previewImg" style={{backgroundImage: `url(${item.previewImg}` }} ></div>
                            <div className="copy">
                                <h2>{item.title}</h2>
                                <p>{item.quickDesc}</p>
                            </div>
                            <div className="footer">
                            {item.tools.map((tool) => {
                                return (
                                    <div key={tool} className="tools" style={{backgroundImage: `url(${tool}` }}></div>
                                );
                            }
                            )}
                                <button onClick={() => this.onViewChange({projectId: item.id})} className="btn float-right"><i className="fas fa-play"></i></button>
                            </div>
                        </div>
                        );
                    }
            }

        )}
        </React.Fragment>
    );
  };
};

 export default ProjectCard;
</code>```

I've set a console log to tell me if projectId changes and it always comes back as my default value (-1). The pasted version is the only one that doesn't throw errors with regards to undefined values/objects, but still no changes. If I can get projectId to change based on the item.id from the clicked button, I think I can figure out the conditional and take it from there.

答:
You aren't actually setting the state with the new projectId in your click handler. First step is just simply passing the item's ID to the click handler, not an object:

```<code>onClick={() => this.onViewChange(item.id)}
</code>```

And second part is to actually use that argument in your click handler:

```<code>onViewChange = (id) => {
    this.setState({
        expanded: !this.state.expanded,
        projectId: id
    });
 };
</code>```

Also, setState() is asynchronous so you can't do what you did and console.log your state on the next line and expect it to have changed. Log the state at the top of your render function to see when it changes (after state/props change, render is called). Or another option is to use the optional second argument of setState, which is a callback that's executed with the new state:

```<code>this.setState({id: 5}, () => console.log(this.state.id)) <-- id will be 5
</code>```

Body:
I'm trying to change the state of a component that is part of a mapped array of objects from a json file. I want to ONLY change the item containing the clicked button and none of the others.

I've been attempting to set a property (projectID) with an onClick and while I can get it to toggle one element of state (expanded or not expanded), it does it to ALL the returned results. So I've been trying to get the projectId (set in the data) and use that to set a conditional. But I can't seem to get projectId to update with the click. I briefly played around with context but I think there's something simpler I'm missing. I've attempted it within the onClick (as shown) and from within onViewChange, but that didn't seem to work as I can't access item.id from outside the mapped item.

I'm using a conditional based on a prop handed down from a couple levels up to set the category, showing only the objects I want. That part seems to be working. So I removed my expanded state as it's not necessary to the issue here.

 import React from 'react';
 import projects from '../data/projects.json';

 class ProjectCard extends React.Component {

  constructor(props) {
    super(props);
    this.state={
        projects,
        expanded: false,
        projectId: -1
    }
  }

  onViewChange = (e) => {
    this.setState({
        expanded: !this.state.expanded
    });
    console.log(this.state.projectId)
  };

  render() {
    return (
        <React.Fragment>
        {this.state.projects.map((item) => {
            if (!this.state.expanded && item.category === this.props.category) {
                return (

                            <div className="previewImg" style={{backgroundImage: `url(${item.previewImg}` }} >

{item.title}

{item.quickDesc}

                            {item.tools.map((tool) => {
                                return (
                                    <div key={tool} className="tools" style={{backgroundImage: `url(${tool}` }}>

                                );
                            }
                            )}
                                <button onClick={() => this.onViewChange({projectId: item.id})} className="btn float-right"></button>

                        );
                    }
            }

        )}
        </React.Fragment>
    );
  };
};

 export default ProjectCard;

I've set a console log to tell me if projectId changes and it always comes back as my default value (-1). The pasted version is the only one that doesn't throw errors with regards to undefined values/objects, but still no changes. If I can get projectId to change based on the item.id from the clicked button, I think I can figure out the conditional and take it from there.

Body:
You aren't actually setting the state with the new projectId in your click handler. First step is just simply passing the item's ID to the click handler, not an object:

onClick={() => this.onViewChange(item.id)}

And second part is to actually use that argument in your click handler:

onViewChange = (id) => {
    this.setState({
        expanded: !this.state.expanded,
        projectId: id
    });
 };

Also, setState() is asynchronous so you can't do what you did and console.log your state on the next line and expect it to have changed. Log the state at the top of your render function to see when it changes (after state/props change, render is called). Or another option is to use the optional second argument of setState, which is a callback that's executed with the new state:

this.setState({id: 5}, () => console.log(this.state.id)) <-- id will be 5


问:
Windows 10 Iot Core app crashes if I try to open a PWM pin
I want to open a PWM pin to my buzzer. But If I try to call the pwmController.OpenPin(6) method, the app crashes with an System.Runtime.InteropServices.SEHException.

I had already double checked the sample sources like the ms-iot-samples. But I cannot see what my problems are.

An idea was that some permissions are missing, but if I try to add for exmaple <iot:Capability Name="lowLevelDevices" />, I cannot longer build the application.

Source

```<code>private PwmPin buzzerPin;
private PwmController pwmController;

public RainbowHAT()
{
    // ... do something else
    InitAsync();
}

private async void InitAsync()
{
    Logger.Log(this, "Init");

    // Setup PWM controller.
    if (LightningProvider.IsLightningEnabled)
    {
        LowLevelDevicesController.DefaultProvider = LightningProvider.GetAggregateProvider();
    }

    var pwmControllers = await PwmController.GetControllersAsync(LightningPwmProvider.GetPwmProvider());
    if (pwmControllers == null || pwmControllers.Count < 2)
    {
        throw new OperationCanceledException("Operation canceled due missing GPIO controller");
    }

    pwmController = pwmControllers[1];
    pwmController.SetDesiredFrequency(50);

    // Setup buzzer
    buzzerPin = pwmController.OpenPin(13); <-- CRASH
    buzzerPin.SetActiveDutyCyclePercentage(0.05);
    buzzerPin.Start();
}
</code>```

I also tried the following tip to reduce the min required Windows version, but this does not help, too.

答:
PWM Controller needs Lightning support. So you need to set the controller driver as Direct Memory Mapped Driver. Here is a sample about PWM on Raspberry Pi.

You also need to modify the code as following:

```<code>    private async void InitAsync()
    {
        Logger.Log(this, "Init");

        // Setup PWM controller.
        if (LightningProvider.IsLightningEnabled)
        {
            var pwmControllers = await PwmController.GetControllersAsync(LightningPwmProvider.GetPwmProvider());
            if (pwmControllers == null || pwmControllers.Count < 2)
            {
                throw new OperationCanceledException("Operation canceled due missing GPIO controller");
            }

            pwmController = pwmControllers[1];
            pwmController.SetDesiredFrequency(50);

            // Setup buzzer
            buzzerPin = pwmController.OpenPin(13);
            buzzerPin.SetActiveDutyCyclePercentage(0.05);
            buzzerPin.Start();
        }
    }
</code>```

Body:
I want to open a PWM pin to my buzzer. But If I try to call the pwmController.OpenPin(6) method, the app crashes with an System.Runtime.InteropServices.SEHException.

I had already double checked the sample sources like the ms-iot-samples. But I cannot see what my problems are.

An idea was that some permissions are missing, but if I try to add for exmaple <iot:Capability Name="lowLevelDevices" />, I cannot longer build the application.

Source

private PwmPin buzzerPin;
private PwmController pwmController;

public RainbowHAT()
{
    // ... do something else
    InitAsync();
}

private async void InitAsync()
{
    Logger.Log(this, "Init");

    // Setup PWM controller.
    if (LightningProvider.IsLightningEnabled)
    {
        LowLevelDevicesController.DefaultProvider = LightningProvider.GetAggregateProvider();
    }

    var pwmControllers = await PwmController.GetControllersAsync(LightningPwmProvider.GetPwmProvider());
    if (pwmControllers == null || pwmControllers.Count < 2)
    {
        throw new OperationCanceledException("Operation canceled due missing GPIO controller");
    }

    pwmController = pwmControllers[1];
    pwmController.SetDesiredFrequency(50);

    // Setup buzzer
    buzzerPin = pwmController.OpenPin(13); <-- CRASH
    buzzerPin.SetActiveDutyCyclePercentage(0.05);
    buzzerPin.Start();
}

I also tried the following tip to reduce the min required Windows version, but this does not help, too.

Body:
PWM Controller needs Lightning support. So you need to set the controller driver as Direct Memory Mapped Driver. Here is a sample about PWM on Raspberry Pi.

You also need to modify the code as following:

    private async void InitAsync()
    {
        Logger.Log(this, "Init");

        // Setup PWM controller.
        if (LightningProvider.IsLightningEnabled)
        {
            var pwmControllers = await PwmController.GetControllersAsync(LightningPwmProvider.GetPwmProvider());
            if (pwmControllers == null || pwmControllers.Count < 2)
            {
                throw new OperationCanceledException("Operation canceled due missing GPIO controller");
            }

            pwmController = pwmControllers[1];
            pwmController.SetDesiredFrequency(50);

            // Setup buzzer
            buzzerPin = pwmController.OpenPin(13);
            buzzerPin.SetActiveDutyCyclePercentage(0.05);
            buzzerPin.Start();
        }
    }


问:
can php limit actions based on ip address
i have 2 links that display notifications on my website and its being abused. is there a way to limit the amount of times a user can click the links based on ip address i dont want to block anyone i just want to reduce the amount of times a person can click this link. essentially limiting the requests that can be made </p>

答: It is generally not a good idea to rely on the client IP address because of proxies and VPN's that can mask the true value.  It would be better to set a cookie and keep track of the clicks in this manner.</p>


问:
How can I make a library face to any other program language?
I made a library which used c# GDI+.

And now I want it can be reference and use by any other program language(such as java/c++)

But I don't want to rewrite it by each program language. It is there any way for me only code once by c# and can be use to any other program language?

Thank you.

答: You can use DllExport to generate exports like you would do with for example C. Any language that has some form of C bindings can then call your exported functions.</p>


问:
How to use a REST proximity search to find speed limits and roadway information?
I am new to using here.com and am struggling with what I believe is a basic query. I have a series of gps coordinates from roadways in the Southern US and I would like to pair the coordinate data with associated speed limits and road information (e.g., functional class).

I am trying to use the proximity search function but I keep getting an error that I am not able to clearly trace.

The base of my query is using

```<code>https://pde.api.here.com/1/search/proximity.json
</code>```

I then append my app_id and code, and set proximity to a GPS coordinate. For example:

```<code>proximity=29.70127,-95.40907
</code>```

Then per the api instructions at: Here.com proximity search

I enter a layer ID and key attributes. For example to find the speed limit:

```<code>layer_ids=SPEED_LIMITS_FC1&key_attributes=FROM_REF_SPEED_LIMIT
</code>```

When I submit the query I get the following error:

```<code>{
  "faultCode": "704a79f6-20f3-4fa6-874c-5741dcaf1feb",
  "responseCode": "400",
  "message": "Provided layer does not contain geometries."
}
</code>```

It seems based on the message that I may be using the incorrect layer, however, I do know that the attributes I am asking for are present with the layer. Also, I have tried other FC (1-5) variants of the layer without success. It is not clear to me what "geometries" is referring to in the error message.

I have also checked with other more basic queries to ensure that my app_id and app_code are correctly entered and that there are no network connectivity issues.

答:
The error messages is saying.
SPEED_LIMITS_FC1 is not a thematic Layer containing geometries.
You can confirm the detail Layers in below link. layer type must be "geom" for /search/proximity.
 https://pde.api.here.com/1/doc/layers.json?app_id={{app_id}}&app_code={{app_code}}&region=WEU

Here is a sample.

```<code>https://pde.api.here.com/1/search/proximity.json?app_code={{app_code}}&app_id={{app_id}}&layer_ids=LINK_FC1&proximity=29.680334933229688,-95.39327178890237,100&key_attributes=LINK_ID
</code>```

I hope this help.

Body:
I am new to using here.com and am struggling with what I believe is a basic query. I have a series of gps coordinates from roadways in the Southern US and I would like to pair the coordinate data with associated speed limits and road information (e.g., functional class).

I am trying to use the proximity search function but I keep getting an error that I am not able to clearly trace.

The base of my query is using

https://pde.api.here.com/1/search/proximity.json

I then append my app_id and code, and set proximity to a GPS coordinate. For example:

proximity=29.70127,-95.40907

Then per the api instructions at: Here.com proximity search

I enter a layer ID and key attributes. For example to find the speed limit:

layer_ids=SPEED_LIMITS_FC1&key_attributes=FROM_REF_SPEED_LIMIT

When I submit the query I get the following error:

{
  "faultCode": "704a79f6-20f3-4fa6-874c-5741dcaf1feb",
  "responseCode": "400",
  "message": "Provided layer does not contain geometries."
}

It seems based on the message that I may be using the incorrect layer, however, I do know that the attributes I am asking for are present with the layer. Also, I have tried other FC (1-5) variants of the layer without success. It is not clear to me what "geometries" is referring to in the error message.

I have also checked with other more basic queries to ensure that my app_id and app_code are correctly entered and that there are no network connectivity issues.

Body:
The error messages is saying.
SPEED_LIMITS_FC1 is not a thematic Layer containing geometries.
You can confirm the detail Layers in below link. layer type must be "geom" for /search/proximity.
 https://pde.api.here.com/1/doc/layers.json?app_id={{app_id}}&app_code={{app_code}}&region=WEU

Here is a sample.

https://pde.api.here.com/1/search/proximity.json?app_code={{app_code}}&app_id={{app_id}}&layer_ids=LINK_FC1&proximity=29.680334933229688,-95.39327178890237,100&key_attributes=LINK_ID

I hope this help.


问:
imshow and pcolormesh show two different outputs with the same input
When I am trying to understand the difference between imshow and pcolormesh, I encounter this problem that I cannot figure out why.

For example, I have a sine wave with frequency 10kHz

```<code>import numpy as np
import matplotlib.pyplot as plt
from scipy import fft

f = 10000  # Frequency, in cycles per second, or Hertz
fs = 44100  # Sampling rate, or number of measurements per second

t = np.linspace(0, 5, 5 * fs, endpoint=False)
X = np.sin(f * 2 * np.pi * t)
</code>```

Applying fft on this signal gives the spectrogram Xs

```<code>window_size = 2048  # 2048-sample fourier windows
stride = 512        # 512 samples between windows
wps = fs/float(512) # ~86 windows/second
Xs = np.empty([int(2*wps),2048])

for i in range(Xs.shape[0]):
    Xs[i] = np.abs(fft(X[i*stride:i*stride+window_size]))
</code>```

Now I would like to plot the spectrogram Xs with both imshow and pcolormesh.

Imshow

```<code>fig = plt.figure(figsize=(20,7))
plt.imshow(Xs.T,aspect='auto',cmap='seismic')
plt.gca().invert_yaxis()
plt.colorbar()
</code>```

pcolormesh

```<code>fig = plt.figure(figsize=(20,7))
plt.pcolormesh(Xs.T,cmap='seismic')
plt.colorbar()
</code>```

Why are they different?

答:
Interestingly, adding the argument dpi solves the problems. Even setting dpi=100, which is the default value if the dpi argument is not given, the problem will still be solved.

Imshow

```<code>fig = plt.figure(figsize=(20,7), dpi=100)
plt.imshow(Xs.T,aspect='auto',cmap='seismic')
plt.gca().invert_yaxis()
plt.colorbar()
</code>```

Although the dpi argument solves the problem, I am still not clear about the reasoning behind it. Any extra suggestions are welcomed.

Body:
When I am trying to understand the difference between imshow and pcolormesh, I encounter this problem that I cannot figure out why.

For example, I have a sine wave with frequency 10kHz

import numpy as np
import matplotlib.pyplot as plt
from scipy import fft

f = 10000  # Frequency, in cycles per second, or Hertz
fs = 44100  # Sampling rate, or number of measurements per second

t = np.linspace(0, 5, 5 * fs, endpoint=False)
X = np.sin(f * 2 * np.pi * t)

Applying fft on this signal gives the spectrogram Xs

window_size = 2048  # 2048-sample fourier windows
stride = 512        # 512 samples between windows
wps = fs/float(512) # ~86 windows/second
Xs = np.empty([int(2*wps),2048])

for i in range(Xs.shape[0]):
    Xs[i] = np.abs(fft(X[i*stride:i*stride+window_size]))

Now I would like to plot the spectrogram Xs with both imshow and pcolormesh.

Imshow

fig = plt.figure(figsize=(20,7))
plt.imshow(Xs.T,aspect='auto',cmap='seismic')
plt.gca().invert_yaxis()
plt.colorbar()

pcolormesh

fig = plt.figure(figsize=(20,7))
plt.pcolormesh(Xs.T,cmap='seismic')
plt.colorbar()

Why are they different?

Body:
Interestingly, adding the argument dpi solves the problems. Even setting dpi=100, which is the default value if the dpi argument is not given, the problem will still be solved.

Imshow

fig = plt.figure(figsize=(20,7), dpi=100)
plt.imshow(Xs.T,aspect='auto',cmap='seismic')
plt.gca().invert_yaxis()
plt.colorbar()

Although the dpi argument solves the problem, I am still not clear about the reasoning behind it. Any extra suggestions are welcomed.


问:
I have a query that does 2 sums, and then the first will subtract the second, but in some cases the second is null
I have a query (in MS-Query, MSQRY32.EXE) that does 2 sums, and then the first will subtract the second, but in some cases the second is null, how do I go over this?

```<code>(Sum(CASE WHEN m.mcdmv=11 THEN m.mqtd END)-
Sum(CASE WHEN m.mcdmv=12 THEN m.mqtd END))
</code>```

This is the part of the query, but sometimes one of them or both are null, so how do I do this?

答:
First I'd ask whether it is appropriate to be summing nulls, and what you expect to get when you subtract a null from an non-null (or vice-versa).

Probably what you want to do is either eliminate records with nulls (where m.mqtd is not null) or to change all the null's to 0's (nz(m.mqtd, 0))

Body:
I have a query (in MS-Query, MSQRY32.EXE) that does 2 sums, and then the first will subtract the second, but in some cases the second is null, how do I go over this?

(Sum(CASE WHEN m.mcdmv=11 THEN m.mqtd END)-
Sum(CASE WHEN m.mcdmv=12 THEN m.mqtd END))

This is the part of the query, but sometimes one of them or both are null, so how do I do this?


问:
Keras LSTM Outputting Different Dimension than Expected
I'm running a LSTM on fMRI data. Our input data comes in with input_shape (timesteps,features) =(495,359320) and label data (495,). I'm running into an issue with what the LSTM layer is outputting.

```<code>   MAX_SLIDER_VALUE=127
   EPOCHS=3
   BATCH_SIZE=1
   LOSS='mean_squared_error'
   OPTIMIZER='RMSprop'

   model=Sequential()
`  model.add(LSTM(units=MAX_SLIDER_VALUE,` activation=keras.layers.LeakyReLU(alpha=.025),dropout=.08,input_shape=(495,359320)))
   model.add(Dense(units=MAX_SLIDER_VALUE,activation='softmax'))``

   model.compile(loss=LOSS,optimizer=OPTIMIZER, metrics=['acc','mae'])

   model.fit(np.array(train_subset_nii),np.array(train_subset_labels),
   epochs=EPOCHS,batch_size=BATCH_SIZE)
</code>```

Checking the model's output layer using the pdb debugger shows the 0th layer output should be (127,) but I'm are getting a valueError where it is outputted as (495,).

```<code>model.layers[0].input_shape
(None, 495, 359320)

model.layers[0].output_shape
(None, 127)

model.layers[1].input_shape
(None, 127)

model.layers[1].output_shape
(None, 127)

ValueError: Error when checking target: expected dense_5 to have shape (127,) but got array with shape (495,)
</code>```

Additional Note:

The code trains and runs if we change the output to match the number of time steps

```<code>MAX_SLIDER_VALUE=495
</code>```

I'm trying to figure out whats causing the disparity between (127,) and (495,).

答:
I suppose, with MAX_SLIDER_VALUE=127 your will give an output of (127,) since your dense layer is 127 neurons.

The problem is, how can you have your model compare a prediction of (127,) with your label dimension as (495,)? To me, it won't work logically in the first place.

You may try change this line:

model.add(Dense(units=MAX_SLIDER_VALUE,activation='softmax'))

into

model.add(Dense(units=495,activation='softmax'))

Let me know whether this fixed it.

Body:
I'm running a LSTM on fMRI data. Our input data comes in with input_shape (timesteps,features) =(495,359320) and label data (495,). I'm running into an issue with what the LSTM layer is outputting.

   MAX_SLIDER_VALUE=127
   EPOCHS=3
   BATCH_SIZE=1
   LOSS='mean_squared_error'
   OPTIMIZER='RMSprop'

   model=Sequential()
`  model.add(LSTM(units=MAX_SLIDER_VALUE,` activation=keras.layers.LeakyReLU(alpha=.025),dropout=.08,input_shape=(495,359320)))
   model.add(Dense(units=MAX_SLIDER_VALUE,activation='softmax'))``

   model.compile(loss=LOSS,optimizer=OPTIMIZER, metrics=['acc','mae'])

   model.fit(np.array(train_subset_nii),np.array(train_subset_labels),
   epochs=EPOCHS,batch_size=BATCH_SIZE)

Checking the model's output layer using the pdb debugger shows the 0th layer output should be (127,) but I'm are getting a valueError where it is outputted as (495,).

model.layers[0].input_shape
(None, 495, 359320)

model.layers[0].output_shape
(None, 127)

model.layers[1].input_shape
(None, 127)

model.layers[1].output_shape
(None, 127)

ValueError: Error when checking target: expected dense_5 to have shape (127,) but got array with shape (495,)

Additional Note:

The code trains and runs if we change the output to match the number of time steps

MAX_SLIDER_VALUE=495

I'm trying to figure out whats causing the disparity between (127,) and (495,).


问:
VueJS component not rendering
I have a very basic VueJS app which I'm building by following the website.

Here's the code, why is this component not rendering?

HTML:

{{ message }}

      <todo-item></todo-item>

```
<p>JS:</p>
```    new Vue({
      el: '#app',
      data: {
        message: 'Hello Vue.js!'
      }
    })

    Vue.component('todo-item', {
        template: '
This is a list item
'
    })
```

答:
I just have similar problem.
After I try what @yuriy636 said it still not rendering.
And I found that there is a component declaration in componets field like this:

```<code>Vue.component('todo-item', {
    template: '<li>This is a list item</li>',
})

new Vue({
  el: '#app',
  data: {
    message: 'Hello Vue.js!'
  },
  components: {
    'todo-item': 'todo-item',  <--- see this ?
  }
})
</code>```

After I remove 'todo-item': 'todo-item'. It works!

Hope this help other guys!

Title: VueJS component not rendering

Body:
I have a very basic VueJS app which I'm building by following the website.

Here's the code, why is this component not rendering?

HTML:

{{ message }}

      <todo-item></todo-item>

JS:

    new Vue({
      el: '#app',
      data: {
        message: 'Hello Vue.js!'
      }
    })

    Vue.component('todo-item', {
        template: '
This is a list item
'
    })

Body:
I just have similar problem.
After I try what @yuriy636 said it still not rendering.
And I found that there is a component declaration in componets field like this:

Vue.component('todo-item', {
    template: '<li>This is a list item</li>',
})

new Vue({
  el: '#app',
  data: {
    message: 'Hello Vue.js!'
  },
  components: {
    'todo-item': 'todo-item',  <--- see this ?
  }
})

After I remove 'todo-item': 'todo-item'. It works!

Hope this help other guys!


问:
align-self is not located at the end of the container and it has space available to do so
I do not know what I'm doing wrong. I want the word "content" to be at the end of the container using flexbox.

```<code>|1|     content|
</code>```

thank you.

this is my live code:

https://jsfiddle.net/0tunwopb/1/

```<code><div class="container">
  <div class="container_flex">
    <div>
      1
    </div>
    <div class="container_content">
      content
    </div>
  </div>
</div>

.container{
  width:200px;
  height:200px;
  border:1px solid blue;
}

.container_flex{
  display:flex;
  flex-direction:row;
}

.container_flex div{
  border:1px solid red;
}

.container_content{
  flex-grow:1;
  align-self:flex-end;
}
</code>```

thanks

答:
The .container_content element is already flush up against the right-hand edge of .container_flex.

If you want the text content to align to the right, you're looking for text-align: right:

.container {
  width: 200px;
  height: 200px;
  border: 1px solid blue;
}

.container_flex {
  display: flex;
  flex-direction: row;
}

.container_flex div {
  border: 1px solid red;
}

.container_content {
  flex-grow: 1;
  align-self: flex-end;
  text-align: right;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="container_flex">
    <div>
      1
    </div>
    <div class="container_content">
      content
    </div>
  </div>
</div></code>```

Body:
I do not know what I'm doing wrong. I want the word "content" to be at the end of the container using flexbox.

|1|     content|

thank you.

this is my live code:

https://jsfiddle.net/0tunwopb/1/

      1

      content

.container{
  width:200px;
  height:200px;
  border:1px solid blue;
}

.container_flex{
  display:flex;
  flex-direction:row;
}

.container_flex div{
  border:1px solid red;
}

.container_content{
  flex-grow:1;
  align-self:flex-end;
}

thanks

Body:
The .container_content element is already flush up against the right-hand edge of .container_flex.

If you want the text content to align to the right, you're looking for text-align: right:

.container {
  width: 200px;
  height: 200px;
  border: 1px solid blue;
}

.container_flex {
  display: flex;
  flex-direction: row;
}

.container_flex div {
  border: 1px solid red;
}

.container_content {
  flex-grow: 1;
  align-self: flex-end;
  text-align: right;
}

<div class="container">
  <div class="container_flex">
    <div>
      1
    </div>
    <div class="container_content">
      content
    </div>
  </div>
</div>


问:
Default web app in tomcat
Its been few days i've been searching for a solution.
My question is..I have to deploy a project in tomcat and make it as a default webapp. What I did is copied my war file and placed it in the tomcat/webapps folder. Started tomcat and changed the port to default. Now I can access my application at http://localhost/myapp .What i want is to see my application at http://localhost. How can I do this?  </p>

答: Delete the Tomcat/webapps/ROOT folder (if any), rename your WAR file to ROOT.war and restart.

Title: Default web app in tomcat


问:
Install packages from source failing - Dockerfile
I am trying to install some packages from source (including package that I have created that installed fine with R console or even when R CMD install.

However, while building docker-image using a docker file. I get this error with for this line in the docker file

```<code>RUN R -e 'install.packages("RcppDIUtilsPackage_1.0.tar.gz",repos=NULL,type="source")'
</code>```

I also tried many other commands including R CMD INSTALL all work fine to install the package except within the docker image build.

Here is the error i am encountering.

```<code>Installing package into ‘/usr/local/lib/R/site-library’
(as ‘lib’ is unspecified)
Warning: invalid package ‘RcppDIUtilsPackage_1.0.tar.gz’
Error: ERROR: no packages specified
Warning message:
In install.packages("RcppDIUtilsPackage_1.0.tar.gz", repos = NULL,  :
  installation of package ‘RcppDIUtilsPackage_1.0.tar.gz’ had non-zero exit status
</code>```

Thanks!!

Edit: The Dockerfile

```<code>FROM rocker/r-ver:3.4.4

WORKDIR /home/ubuntu/projects/DService

RUN apt-get update -qq && apt-get install -y \
  libssl-dev \
  libcurl4-gnutls-dev

RUN R -e "install.packages('plumber')"

RUN R -e "install.packages('Rcpp')"

RUN R -e 'install.packages("RcppDIUtilsPackage_1.0.tar.gz",repos=NULL,type="source")'

COPY / /

EXPOSE 8000

CMD ["Rscript", "DService.R"]

command: sudo docker build --no-cache -t dservice-docker-image .
</code>```

答:
This is an indirect solution to your problem, because I was not able to resolve the same issue.

The root of the issue may have something to do with the host environment that created the Docker image from the Dockerfile. Specifically, the R instance that is spun up to install the local packages may not being able to access the path to where your local packages are stored.

The solution for me was to just avoid local packages. Move any local repositories to remote repositories, and reference them in the Dockerfile instead. e.g.

```<code>RUN R -e "devtools::install_github('dmanuge/shinyFilesWidget') ; system('echo 14')"
</code>```

After that, rebuilt your Docker image and run it accordingly. While this is not a direct solution, I reached the critical threshold of debugging and needed to move on. :)

Body:
I am trying to install some packages from source (including package that I have created that installed fine with R console or even when R CMD install.

However, while building docker-image using a docker file. I get this error with for this line in the docker file

RUN R -e 'install.packages("RcppDIUtilsPackage_1.0.tar.gz",repos=NULL,type="source")'

I also tried many other commands including R CMD INSTALL all work fine to install the package except within the docker image build.

Here is the error i am encountering.

Installing package into ‘/usr/local/lib/R/site-library’
(as ‘lib’ is unspecified)
Warning: invalid package ‘RcppDIUtilsPackage_1.0.tar.gz’
Error: ERROR: no packages specified
Warning message:
In install.packages("RcppDIUtilsPackage_1.0.tar.gz", repos = NULL,  :
  installation of package ‘RcppDIUtilsPackage_1.0.tar.gz’ had non-zero exit status

Thanks!!

Edit: The Dockerfile

FROM rocker/r-ver:3.4.4

WORKDIR /home/ubuntu/projects/DService

RUN apt-get update -qq && apt-get install -y \
  libssl-dev \
  libcurl4-gnutls-dev

RUN R -e "install.packages('plumber')"

RUN R -e "install.packages('Rcpp')"

RUN R -e 'install.packages("RcppDIUtilsPackage_1.0.tar.gz",repos=NULL,type="source")'

COPY / /

EXPOSE 8000

CMD ["Rscript", "DService.R"]

command: sudo docker build --no-cache -t dservice-docker-image .

Body:
This is an indirect solution to your problem, because I was not able to resolve the same issue.

The root of the issue may have something to do with the host environment that created the Docker image from the Dockerfile. Specifically, the R instance that is spun up to install the local packages may not being able to access the path to where your local packages are stored.

The solution for me was to just avoid local packages. Move any local repositories to remote repositories, and reference them in the Dockerfile instead. e.g.

RUN R -e "devtools::install_github('dmanuge/shinyFilesWidget') ; system('echo 14')"

After that, rebuilt your Docker image and run it accordingly. While this is not a direct solution, I reached the critical threshold of debugging and needed to move on. :)


问:
Installing MSBuild 4.0 without Visual Studio 2010
I installed .NET 4.0 and VS 2010 RC on my laptop and MSBuild was automatically installed.  I was hoping to build a continuous integration server by just installing the .NET SDK without VS 2010, so I downloaded the .NET 4.0 Framework from Microsoft at this link.  Unfortunately, it doesn't appear to have installed MSBuild with this download (or at least I can't find it).

Is this link the appropriate link for the SDK, or is this just the runtime?  If not, where is the link for the SDK?

I kind of doubt it is the entire SDK as it is only 35MB where the .NET 3.5 SP1 download was over 200MB.

答: Using the .Net default MsBuild may not be enough. You can download the free MsBuild Tools for Visual studio here, and install all the dependencies used in your project.

ContentLicense: CC BY-SA 2.5


问:
How to allocate an executable page in a Linux kernel module?
I'm writing a Linux kernel module, and I'd like to allocate an executable page. Plain kmalloc() returns a pointer within a non-executable page, and I get a kernel panic when executing code there. It has to work on Ubuntu Karmic x86, 2.6.31-20-generic-pae.

答:
```<code>/**
 * vmalloc_exec - allocate virtually contiguous, executable memory
 * @size:     allocation size
 *
 * Kernel-internal function to allocate enough pages to cover @size
 * the page level allocator and map them into contiguous and
 * executable kernel virtual space.
 *
 * For tight control over page level allocator and protection flags
 * use __vmalloc() instead.
 *
 * Return: pointer to the allocated memory or %NULL on error
 */
void *vmalloc_exec(unsigned long size)
{
    return __vmalloc_node(size, 1, GFP_KERNEL, PAGE_KERNEL_EXEC,
                  NUMA_NO_NODE, __builtin_return_address(0));
}
</code>```


问:
Determine if individuals in a dataframe met a certain condition in a given time period in R
I have data which looks like this

```<code>pop_df <- data.frame(
  uniq_ID = c("AFG1234", "WED1234", "POJ1234", "DER234", "QWE1234", "BGR1234", "ABC1234", "DSE1234", "UHJ1234", "POI234",
              "EDC1234", "BGT1234", "MJI1234", "WEX1234", "FGH1234", "UJN1234", "LOK1234", "DRT1234", "URD1234", "MVR1234",
              "AFG1234", "WED1234", "POJ1234", "DER234", "QWE1234", "BGR1234", "ABC1234", "DSE1234", "UHJ1234", "POI234",
              "EDC1234", "BGT1234", "MJI1234", "WEX1234", "FGH1234", "UJN1234", "LOK1234", "DRT1234", "URD1234", "MVR1234",
              "AFG1234", "WED1234", "POJ1234", "DER234", "QWE1234", "BGR1234", "ABC1234", "DSE1234", "UHJ1234", "POI234",
              "EDC1234", "BGT1234", "MJI1234", "WEX1234", "FGH1234", "UJN1234", "LOK1234", "DRT1234", "URD1234", "MVR1234",
              "AFG1234", "WED1234", "POJ1234", "DER234", "QWE1234", "BGR1234", "ABC1234", "DSE1234", "UHJ1234", "POI234",
              "EDC1234", "BGT1234", "MJI1234", "WEX1234", "FGH1234", "UJN1234", "LOK1234", "DRT1234", "URD1234", "MVR1234"),
  Quarter = c((rep("20170101",20)), (rep("20170401",20)), (rep("20170701",20)), (rep("20171001",20))),
  contact = sample(c(0,1), replace = T, size = 80),
  )
</code>```

This is a list of unique IDs, the quarter (ie three month period in the year), and whether or not they made contact with a doctor in that quarter.
What I want to know is if someone made contact in the entire year of 2017, based on the value of "contact".
So, for each unique ID, if contact == 1 in any quarter, then they made contact in 2017.

My desired output is a new variable, called contact_year, where the value is 1 for each unique ID if that unique ID made contact in any quarter.

Thanks.

答:
We could sum the contact info and find out the uniq_ID which has value greater than 0.

```<code>library(dplyr)

pop_df %>%
  group_by(uniq_ID) %>%
  mutate(contact_year = as.integer(sum(contact) > 0))
</code>```

which in base R would be using ave

```<code>pop_df$contact_year <- as.integer(with(pop_df, ave(contact, uniq_ID,FUN = sum) > 0))
</code>```

If we have more years and would like to do it for each ID in each year, we can extract the year information

```<code>library(dplyr)
library(lubridate)

pop_df %>%
  group_by(uniq_ID, year = year(ymd(Quarter))) %>%
  mutate(contact_year = as.integer(sum(contact) > 0))
</code>```

This gives you same number of rows as your original pop_df with contact_year information repeated for each uniq_ID. You might also consider using summarise in dplyr and aggregate in base R which would give you only one row per ID.

Body:
I have data which looks like this

pop_df <- data.frame(
  uniq_ID = c("AFG1234", "WED1234", "POJ1234", "DER234", "QWE1234", "BGR1234", "ABC1234", "DSE1234", "UHJ1234", "POI234",
              "EDC1234", "BGT1234", "MJI1234", "WEX1234", "FGH1234", "UJN1234", "LOK1234", "DRT1234", "URD1234", "MVR1234",
              "AFG1234", "WED1234", "POJ1234", "DER234", "QWE1234", "BGR1234", "ABC1234", "DSE1234", "UHJ1234", "POI234",
              "EDC1234", "BGT1234", "MJI1234", "WEX1234", "FGH1234", "UJN1234", "LOK1234", "DRT1234", "URD1234", "MVR1234",
              "AFG1234", "WED1234", "POJ1234", "DER234", "QWE1234", "BGR1234", "ABC1234", "DSE1234", "UHJ1234", "POI234",
              "EDC1234", "BGT1234", "MJI1234", "WEX1234", "FGH1234", "UJN1234", "LOK1234", "DRT1234", "URD1234", "MVR1234",
              "AFG1234", "WED1234", "POJ1234", "DER234", "QWE1234", "BGR1234", "ABC1234", "DSE1234", "UHJ1234", "POI234",
              "EDC1234", "BGT1234", "MJI1234", "WEX1234", "FGH1234", "UJN1234", "LOK1234", "DRT1234", "URD1234", "MVR1234"),
  Quarter = c((rep("20170101",20)), (rep("20170401",20)), (rep("20170701",20)), (rep("20171001",20))),
  contact = sample(c(0,1), replace = T, size = 80),
  )

This is a list of unique IDs, the quarter (ie three month period in the year), and whether or not they made contact with a doctor in that quarter.
What I want to know is if someone made contact in the entire year of 2017, based on the value of "contact".
So, for each unique ID, if contact == 1 in any quarter, then they made contact in 2017.

My desired output is a new variable, called contact_year, where the value is 1 for each unique ID if that unique ID made contact in any quarter.

Thanks.

Body:
We could sum the contact info and find out the uniq_ID which has value greater than 0.

library(dplyr)

pop_df %>%
  group_by(uniq_ID) %>%
  mutate(contact_year = as.integer(sum(contact) > 0))

which in base R would be using ave

pop_df$contact_year <- as.integer(with(pop_df, ave(contact, uniq_ID,FUN = sum) > 0))

If we have more years and would like to do it for each ID in each year, we can extract the year information

library(dplyr)
library(lubridate)

pop_df %>%
  group_by(uniq_ID, year = year(ymd(Quarter))) %>%
  mutate(contact_year = as.integer(sum(contact) > 0))

This gives you same number of rows as your original pop_df with contact_year information repeated for each uniq_ID. You might also consider using summarise in dplyr and aggregate in base R which would give you only one row per ID.


问:
RegEx for replacing the middle letter
Invalid regular expression: Invalid group

I tried except ( ) , fixed and changed . to $
but does not work

```<code>var name = 'ABC'
var pattern = /(?<=.{1})./
return name.replace(pattern, " * ")
</code>```

I want to replace like 'A*C'

Invalid regular expression: Invalid group

答:
For 'ABC' to become A * C or CDE to become C * E, you can just used substr.. :)

function run(){
  var s = "ABC";
  var index = 1;
  s = s.substr(0, index) + ' * ' + s.substr(index + 1);
  alert(s);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  <button onclick="run()">Test</button>
</body>
</html></code>```

Title: RegEx for replacing the middle letter

Body:
Invalid regular expression: Invalid group

I tried except ( ) , fixed and changed . to $
but does not work

var name = 'ABC'
var pattern = /(?<=.{1})./
return name.replace(pattern, " * ")

I want to replace like 'A*C'

Invalid regular expression: Invalid group

Body:
For 'ABC' to become A * C or CDE to become C * E, you can just used substr.. :)

function run(){
  var s = "ABC";
  var index = 1;
  s = s.substr(0, index) + ' * ' + s.substr(index + 1);
  alert(s);
}

<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  <button onclick="run()">Test</button>
</body>
</html>


问:
Need to fix error not found in module - Angular
I'm practicing angular, but received this error while compiling my code:

```<code>Module not found: Error: Can't resolve './app.component.css' in 'D:\hello-world-app\src\app'
i ｢wdm｣: Failed to compile.
</code>```

My app.component.html

Angular

<courses></courses>
```

<p>My courses.component.ts</p>

<pre class="lang-js prettyprint-override"><code>// tslint:disable-next-line: import-spacing
import{Component} from '@angular/core';

@Component({
  selector: 'courses', //<courses>
  template: '<h2>Courses</h2>'
})
export class CoursesComponent {

}

</code>```

My app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'hello-world-app';
}

```

<p>My app.module.ts</p>

<pre class="lang-js prettyprint-override"><code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { CoursesComponent } from './courses.component';

@NgModule({
  declarations: [
    AppComponent,
    CoursesComponent
  ],
  imports: [
    BrowserModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

</code>```

答:
Angular is failing to find (resolve) the file, just as the error states. In order to fix the error, you need to either add the file, or delete the line styleUrls: ['./app.component.css']

If you do not want to avoid the file reference and are using angular cli (if you're not, you probably should be), you can use --inlineStyle=true when generating a component. Granted, if you're using angular cli, the css file should have been created when the component was generated.

Odds are either you copy pasted some stuff, or mistakenly deleted that file. Either way, Angular will always complain when it can't find something you're referencing. (Much like pretty much every other programming framework/system/language)

Body:
I'm practicing angular, but received this error while compiling my code:

Module not found: Error: Can't resolve './app.component.css' in 'D:\hello-world-app\src\app'
i ｢wdm｣: Failed to compile.

My app.component.html

Angular

<courses></courses>

My courses.component.ts

// tslint:disable-next-line: import-spacing
import{Component} from '@angular/core';

@Component({
  selector: 'courses', //<courses>
  template: '
Courses
'
})
export class CoursesComponent {

}

My app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'hello-world-app';
}

My app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { CoursesComponent } from './courses.component';

@NgModule({
  declarations: [
    AppComponent,
    CoursesComponent
  ],
  imports: [
    BrowserModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }


问:
entering input causing link change
This sort of links back to a previous question that I made. The goal was to change the iframe src with a text input. After lots of experimentation, it worked. However, this has arisen a new problem. After I enter the link and submit it, it adds /?link=linkhere to the end of the page and refreshes it. Then, once it's refreshed, the original src comes back, making it useless.
Here's the most important code:

```<code> <iframe
  id="minecraftFrame"
  src="//classic.minecraft.net"
  height="500"
  width="800"
  frameborder="0"
  scrolling="no"
  allowfullscreen="true">
</iframe>
<input type="text" id="myInput" name="input">
<button class="button" onclick="changeChannel()">Go</button>
<script>
function changeChannel(){
  document.getElementById("iFrame").src = document.getElementById("myInput").value;
}
</script>
</code>```

I'm unsure of what to try at this point, since I'm not too experienced with javascript. I just don't want the main page to refresh after change the src.

答:
Your code included this --- document.getElementById("iFrame").src
the id of the iframe is "minecraftFrame" and not "iFrame"
or you could use document.querySelector('iFrame')

and stop the page reload with

```<code>  function changeChannel(e) {
  e.preventDefault();
  // Code goes here
}
</code>```

Title: entering input causing link change

Body:
This sort of links back to a previous question that I made. The goal was to change the iframe src with a text input. After lots of experimentation, it worked. However, this has arisen a new problem. After I enter the link and submit it, it adds /?link=linkhere to the end of the page and refreshes it. Then, once it's refreshed, the original src comes back, making it useless.
Here's the most important code:

<input type="text" id="myInput" name="input">
<button class="button" onclick="changeChannel()">Go</button>

I'm unsure of what to try at this point, since I'm not too experienced with javascript. I just don't want the main page to refresh after change the src.

Body:
Your code included this --- document.getElementById("iFrame").src
the id of the iframe is "minecraftFrame" and not "iFrame"
or you could use document.querySelector('iFrame')

and stop the page reload with

  function changeChannel(e) {
  e.preventDefault();
  // Code goes here
}


问:
How to I resolve this error? Field never assigned and will always have null value
I have created 4 c# scripts. When I run my 2d unity game I see this warning in my console.

"Assets\Scripts\GameHandler.cs(7,34): warning CS0649: Field
  'GameHandler.car' is never assigned to, and will always have its
  default value null"

I am creating a game similar to snake, using c# scripts in unity 2d. Never used unity before or c#, this is my first project. So far its going well, However, i keep getting this warning which is causing my game to crash.
I've attached 2 of my scripts the first gamehandler is where this issue is and I think its referring to the class Car which i attached below. It's a lot of code so I do apologise, I just have no clue.

```<code>public class GameHandler : MonoBehaviour
{
    [SerializeField] private Car car;

    private LevelGrid levelGrid;

    // Start is called before the first frame update
    private void Start()
    {
        Debug.Log("GameHandler.Start");

        //GameObject carHeadGameObject = new GameObject();
        //SpriteRenderer carSpriteRenderer = carHeadGameObject.AddComponent<SpriteRenderer>();
        //carSpriteRenderer.sprite = GameAssets.instance.carHeadSprite;

        levelGrid = new LevelGrid(20,20); //width,height of grid

        car.Setup(levelGrid);
        levelGrid.Setup(car);
    }

    }
--------------------------------------
    using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Car : MonoBehaviour
{
    private enum Direction
    {
        Left,
        Right,
        Up,
        Down
    }

    private enum State
    {
        Alive,
        Dead
    }

    private State state;
    private Vector2Int gridPosition; //uses ints instead of floats useful for grid positiioning
    private float gridMoveTimer; //time remaining until next movement
    private float gridMoveTimerMax; // time between moves

    private Direction gridMoveDirection;

    private LevelGrid levelGrid;
    private int carsize;
    private List<CarMovePosition> carMovePositionList;
    private List<Carsize> carSizeList;

    public void Setup(LevelGrid levelGrid) {
        this.levelGrid = levelGrid;
    }

    private void Awake() {
        gridPosition = new Vector2Int(10,10); //initalise grid position into middle of grid
        gridMoveTimerMax = .2f; //car to move along grid every 1/2 second
        gridMoveTimer = gridMoveTimerMax; //0f
        gridMoveDirection = Direction.Right; // default move right

        carMovePositionList = new List<CarMovePosition>();
        carsize = 0;
        carSizeList = new List<Carsize>();

        state = State.Alive;
    }

    private void Update()
    {
        switch (state)
        {
            case State.Alive:
            HandleInput(); // checks for keyboard input
            HandleGridMovement();
                break;
            case State.Dead:
                break;
        }

    }

    private void HandleInput()
    {
        if (Input.GetKeyDown(KeyCode.UpArrow))
        {
            if (gridMoveDirection != Direction.Down)
            { // can only go up if not going down
                gridMoveDirection = Direction.Up;
            }
        }
        //return true on up arrow press

        if (Input.GetKeyDown(KeyCode.DownArrow))
        {
            if (gridMoveDirection != Direction.Up)
            {
                gridMoveDirection = Direction.Down;

            }
        }
        if (Input.GetKeyDown(KeyCode.LeftArrow))
        {
            if (gridMoveDirection != Direction.Right)
            {
                gridMoveDirection = Direction.Left;
            }
        }
        if (Input.GetKeyDown(KeyCode.RightArrow))
        {
            if (gridMoveDirection != Direction.Left)
            {
                gridMoveDirection = Direction.Right;
            }
        }
    }

    private void HandleGridMovement()
    {
        gridMoveTimer += Time.deltaTime; // amount of time left since last update
        if (gridMoveTimer >= gridMoveTimerMax)//if true then 1 sec since last move
        {
            gridMoveTimer -= gridMoveTimerMax;

            CarMovePosition previousCarMovePosition = null;

            if (carMovePositionList.Count > 0){
                previousCarMovePosition = carMovePositionList[0];
            }

            CarMovePosition carMovePosition = new CarMovePosition(previousCarMovePosition, gridPosition, gridMoveDirection);
            carMovePositionList.Insert(0, carMovePosition);

            Vector2Int gridMoveDirectionVector;
            switch (gridMoveDirection) {
                default:
                case Direction.Right: gridMoveDirectionVector = new Vector2Int(+1, 0);break;
                case Direction.Left: gridMoveDirectionVector = new Vector2Int(-1, 0); break;
                case Direction.Up: gridMoveDirectionVector = new Vector2Int(0, +1); break;
                case Direction.Down: gridMoveDirectionVector = new Vector2Int(0, -1); break;
            }
            gridPosition += gridMoveDirectionVector;

            bool cargotfuel = levelGrid.Trycarfuel(gridPosition);
            if (cargotfuel)
            {
                carsize++;
                CreateCarSize();
            }

            if (carMovePositionList.Count >= carsize + 1)
            {
                carMovePositionList.RemoveAt(carMovePositionList.Count - 1);
            }

            foreach (Carsize carsize in carSizeList)
            {
                Vector2Int carSizeGridPosition = carsize.GetGridPosition();
                if (gridPosition == carSizeGridPosition)
                {

                    //print("Gameover");
                    state = State.Dead;
                }
            }

            transform.position = new Vector3(gridPosition.x, gridPosition.y);
            //move transform based on location of gridPosition

            transform.eulerAngles = new Vector3(0, 0, GetAngleFromVector(gridMoveDirectionVector) - 90);
            //modify transform to face the correct way

            UpdateCarSize();

        }
    }

    private void CreateCarSize()
    {
        carSizeList.Add(new Carsize(carSizeList.Count));
    }

    private void UpdateCarSize(){
        for (int i = 0; i < carSizeList.Count; i++) {
            carSizeList[i].SetCarMovePosition(carMovePositionList[i]);
            //carSizeList[i].SetGridPosition(carMovePositionList[i].GetGridPosition());
        }
    }

    private float GetAngleFromVector(Vector2Int dir)
    {
        float n = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
        if (n < 0) n += 360;
        return n;
    }

    public Vector2Int GetGridPosition()
    {
        return gridPosition;
    }

    //returns car list of positions full with body
    public List<Vector2Int> Getcargridpositionlist(){
        List<Vector2Int> gridPositionList = new List<Vector2Int>() { gridPosition };
        foreach (CarMovePosition carMovePosition in carMovePositionList)
        {
            gridPositionList.Add(carMovePosition.GetGridPosition());
        }
        return gridPositionList;
    }

    private class Carsize{

        private CarMovePosition carMovePosition;
        private Transform transform;

        public Carsize(int sizeIndex){
            GameObject carsGameObject = new GameObject("carBody", typeof(SpriteRenderer));
            carsGameObject.GetComponent<SpriteRenderer>().sprite = GameAssets.instance.carsSprite;
            carsGameObject.GetComponent<SpriteRenderer>().sortingOrder = -sizeIndex;
            transform = carsGameObject.transform;
        }

        public void SetCarMovePosition(CarMovePosition carMovePosition){
            this.carMovePosition = carMovePosition;

            transform.position = new Vector3(carMovePosition.GetGridPosition().x, carMovePosition.GetGridPosition().y);

            float angle;
            switch (carMovePosition.GetDirection()){
            default:
                case Direction.Up:// going up
                    switch (carMovePosition.GetPreviousDirection()){
                        default:
                            angle = 0; break;
                        case Direction.Left: // was going left
                            angle = 0 + 45; break;
                        case Direction.Right:// was going right
                            angle = 0 - 45; break;
                    }
                    break;
                case Direction.Down:
                    switch (carMovePosition.GetPreviousDirection()){
                        default:
                            angle = 180; break;
                        case Direction.Left:
                            angle = 180 + 45; break;
                        case Direction.Right:
                            angle = 180 - 45; break;
                    }
                    break;
                case Direction.Left:
                    switch (carMovePosition.GetPreviousDirection()){
                        default:
                            angle = -90; break;
                        case Direction.Down:
                            angle = -45; break;
                        case Direction.Up:
                            angle = 45; break;
                    }
                    break;
                case Direction.Right: // going right
                    switch (carMovePosition.GetPreviousDirection()){
                    default:
                        angle = 90; break;
                    case Direction.Down: // previously going down
                        angle = 45; break;
                    }
                    break;
            }
            transform.eulerAngles = new Vector3(0, 0, angle);
        }

        public Vector2Int GetGridPosition()
        {
            return carMovePosition.GetGridPosition();
        }
    }

    private class CarMovePosition{

        private CarMovePosition previousCarMovePosition;
        private Vector2Int gridPosition;
        private Direction direction;

        public CarMovePosition(CarMovePosition previousCarMovePosition, Vector2Int gridPosition, Direction direction){
            this.previousCarMovePosition = previousCarMovePosition;
            this.gridPosition = gridPosition;
            this.direction = direction;
        }

        public Vector2Int GetGridPosition(){
            return gridPosition;
        }

        public Direction GetDirection(){
            return direction;
        }

        public Direction GetPreviousDirection(){
            if (previousCarMovePosition == null){
                return Direction.Right;
            } else {
                return previousCarMovePosition.direction;
            }
        }

    }
    }
</code>```

It may be the case of clicking/dragging something in unity2d itself which I had to do before. But I am so lost now.

答:
It's telling you that

```<code>[SerializeField] private Car car;
</code>```

is not initialized in code, but that's fine, because you're initializing it in the inspector. If you want to get rid of the warning, you can set it to null:

```<code>[SerializeField] private Car car = null;
</code>```

Body:
I have created 4 c# scripts. When I run my 2d unity game I see this warning in my console.

"Assets\Scripts\GameHandler.cs(7,34): warning CS0649: Field
  'GameHandler.car' is never assigned to, and will always have its
  default value null"

I am creating a game similar to snake, using c# scripts in unity 2d. Never used unity before or c#, this is my first project. So far its going well, However, i keep getting this warning which is causing my game to crash.
I've attached 2 of my scripts the first gamehandler is where this issue is and I think its referring to the class Car which i attached below. It's a lot of code so I do apologise, I just have no clue.

public class GameHandler : MonoBehaviour
{
    [SerializeField] private Car car;

    private LevelGrid levelGrid;

    // Start is called before the first frame update
    private void Start()
    {
        Debug.Log("GameHandler.Start");

        //GameObject carHeadGameObject = new GameObject();
        //SpriteRenderer carSpriteRenderer = carHeadGameObject.AddComponent<SpriteRenderer>();
        //carSpriteRenderer.sprite = GameAssets.instance.carHeadSprite;

        levelGrid = new LevelGrid(20,20); //width,height of grid

        car.Setup(levelGrid);
        levelGrid.Setup(car);
    }

    }
--------------------------------------
    using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Car : MonoBehaviour
{
    private enum Direction
    {
        Left,
        Right,
        Up,
        Down
    }

    private enum State
    {
        Alive,
        Dead
    }

    private State state;
    private Vector2Int gridPosition; //uses ints instead of floats useful for grid positiioning
    private float gridMoveTimer; //time remaining until next movement
    private float gridMoveTimerMax; // time between moves

    private Direction gridMoveDirection;

    private LevelGrid levelGrid;
    private int carsize;
    private List<CarMovePosition> carMovePositionList;
    private List<Carsize> carSizeList;

    public void Setup(LevelGrid levelGrid) {
        this.levelGrid = levelGrid;
    }

    private void Awake() {
        gridPosition = new Vector2Int(10,10); //initalise grid position into middle of grid
        gridMoveTimerMax = .2f; //car to move along grid every 1/2 second
        gridMoveTimer = gridMoveTimerMax; //0f
        gridMoveDirection = Direction.Right; // default move right

        carMovePositionList = new List<CarMovePosition>();
        carsize = 0;
        carSizeList = new List<Carsize>();

        state = State.Alive;
    }

    private void Update()
    {
        switch (state)
        {
            case State.Alive:
            HandleInput(); // checks for keyboard input
            HandleGridMovement();
                break;
            case State.Dead:
                break;
        }

    }

    private void HandleInput()
    {
        if (Input.GetKeyDown(KeyCode.UpArrow))
        {
            if (gridMoveDirection != Direction.Down)
            { // can only go up if not going down
                gridMoveDirection = Direction.Up;
            }
        }
        //return true on up arrow press

        if (Input.GetKeyDown(KeyCode.DownArrow))
        {
            if (gridMoveDirection != Direction.Up)
            {
                gridMoveDirection = Direction.Down;

            }
        }
        if (Input.GetKeyDown(KeyCode.LeftArrow))
        {
            if (gridMoveDirection != Direction.Right)
            {
                gridMoveDirection = Direction.Left;
            }
        }
        if (Input.GetKeyDown(KeyCode.RightArrow))
        {
            if (gridMoveDirection != Direction.Left)
            {
                gridMoveDirection = Direction.Right;
            }
        }
    }

    private void HandleGridMovement()
    {
        gridMoveTimer += Time.deltaTime; // amount of time left since last update
        if (gridMoveTimer >= gridMoveTimerMax)//if true then 1 sec since last move
        {
            gridMoveTimer -= gridMoveTimerMax;

            CarMovePosition previousCarMovePosition = null;

            if (carMovePositionList.Count > 0){
                previousCarMovePosition = carMovePositionList[0];
            }

            CarMovePosition carMovePosition = new CarMovePosition(previousCarMovePosition, gridPosition, gridMoveDirection);
            carMovePositionList.Insert(0, carMovePosition);

            Vector2Int gridMoveDirectionVector;
            switch (gridMoveDirection) {
                default:
                case Direction.Right: gridMoveDirectionVector = new Vector2Int(+1, 0);break;
                case Direction.Left: gridMoveDirectionVector = new Vector2Int(-1, 0); break;
                case Direction.Up: gridMoveDirectionVector = new Vector2Int(0, +1); break;
                case Direction.Down: gridMoveDirectionVector = new Vector2Int(0, -1); break;
            }
            gridPosition += gridMoveDirectionVector;

            bool cargotfuel = levelGrid.Trycarfuel(gridPosition);
            if (cargotfuel)
            {
                carsize++;
                CreateCarSize();
            }

            if (carMovePositionList.Count >= carsize + 1)
            {
                carMovePositionList.RemoveAt(carMovePositionList.Count - 1);
            }

            foreach (Carsize carsize in carSizeList)
            {
                Vector2Int carSizeGridPosition = carsize.GetGridPosition();
                if (gridPosition == carSizeGridPosition)
                {

                    //print("Gameover");
                    state = State.Dead;
                }
            }

            transform.position = new Vector3(gridPosition.x, gridPosition.y);
            //move transform based on location of gridPosition

            transform.eulerAngles = new Vector3(0, 0, GetAngleFromVector(gridMoveDirectionVector) - 90);
            //modify transform to face the correct way

            UpdateCarSize();

        }
    }

    private void CreateCarSize()
    {
        carSizeList.Add(new Carsize(carSizeList.Count));
    }

    private void UpdateCarSize(){
        for (int i = 0; i < carSizeList.Count; i++) {
            carSizeList[i].SetCarMovePosition(carMovePositionList[i]);
            //carSizeList[i].SetGridPosition(carMovePositionList[i].GetGridPosition());
        }
    }

    private float GetAngleFromVector(Vector2Int dir)
    {
        float n = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
        if (n < 0) n += 360;
        return n;
    }

    public Vector2Int GetGridPosition()
    {
        return gridPosition;
    }

    //returns car list of positions full with body
    public List<Vector2Int> Getcargridpositionlist(){
        List<Vector2Int> gridPositionList = new List<Vector2Int>() { gridPosition };
        foreach (CarMovePosition carMovePosition in carMovePositionList)
        {
            gridPositionList.Add(carMovePosition.GetGridPosition());
        }
        return gridPositionList;
    }

    private class Carsize{

        private CarMovePosition carMovePosition;
        private Transform transform;

        public Carsize(int sizeIndex){
            GameObject carsGameObject = new GameObject("carBody", typeof(SpriteRenderer));
            carsGameObject.GetComponent<SpriteRenderer>().sprite = GameAssets.instance.carsSprite;
            carsGameObject.GetComponent<SpriteRenderer>().sortingOrder = -sizeIndex;
            transform = carsGameObject.transform;
        }

        public void SetCarMovePosition(CarMovePosition carMovePosition){
            this.carMovePosition = carMovePosition;

            transform.position = new Vector3(carMovePosition.GetGridPosition().x, carMovePosition.GetGridPosition().y);

            float angle;
            switch (carMovePosition.GetDirection()){
            default:
                case Direction.Up:// going up
                    switch (carMovePosition.GetPreviousDirection()){
                        default:
                            angle = 0; break;
                        case Direction.Left: // was going left
                            angle = 0 + 45; break;
                        case Direction.Right:// was going right
                            angle = 0 - 45; break;
                    }
                    break;
                case Direction.Down:
                    switch (carMovePosition.GetPreviousDirection()){
                        default:
                            angle = 180; break;
                        case Direction.Left:
                            angle = 180 + 45; break;
                        case Direction.Right:
                            angle = 180 - 45; break;
                    }
                    break;
                case Direction.Left:
                    switch (carMovePosition.GetPreviousDirection()){
                        default:
                            angle = -90; break;
                        case Direction.Down:
                            angle = -45; break;
                        case Direction.Up:
                            angle = 45; break;
                    }
                    break;
                case Direction.Right: // going right
                    switch (carMovePosition.GetPreviousDirection()){
                    default:
                        angle = 90; break;
                    case Direction.Down: // previously going down
                        angle = 45; break;
                    }
                    break;
            }
            transform.eulerAngles = new Vector3(0, 0, angle);
        }

        public Vector2Int GetGridPosition()
        {
            return carMovePosition.GetGridPosition();
        }
    }

    private class CarMovePosition{

        private CarMovePosition previousCarMovePosition;
        private Vector2Int gridPosition;
        private Direction direction;

        public CarMovePosition(CarMovePosition previousCarMovePosition, Vector2Int gridPosition, Direction direction){
            this.previousCarMovePosition = previousCarMovePosition;
            this.gridPosition = gridPosition;
            this.direction = direction;
        }

        public Vector2Int GetGridPosition(){
            return gridPosition;
        }

        public Direction GetDirection(){
            return direction;
        }

        public Direction GetPreviousDirection(){
            if (previousCarMovePosition == null){
                return Direction.Right;
            } else {
                return previousCarMovePosition.direction;
            }
        }

    }
    }

It may be the case of clicking/dragging something in unity2d itself which I had to do before. But I am so lost now.

Body:
It's telling you that

[SerializeField] private Car car;

is not initialized in code, but that's fine, because you're initializing it in the inspector. If you want to get rid of the warning, you can set it to null:

[SerializeField] private Car car = null;


问:
Slice an image into segments, is there any android libraries to do this?
Does android have any built-in features to slice an image into portions? For example, if I have an image loaded in my application (such as setting on in an ImageView), is it possible to slice that image up into 4 equal segments and display each one separately?

If there is nothing out of the box, which libraries would enable me to do this?

Thanks

答:
If you're working with bitmaps, you can use Bitmap.createBitmap to extract sub-images.

Hope this helps,

Phil Lello


问:
How to remove the site name from title in spree?
In Spree > Configuration the Site Name is what is set in the  tag of your website. It renders in your browser’s title bar on every page of the public-facing area of the site. I want to remove the site name from titles on my website. I tried to remove it but when I click update after deleting it from text area in Spree > Configuration (as shown in image) it shows up again after updating.

How can I remove it without going into coding from spree admin panel?

答:
I would suggest turning off the configuration parameter for that as such:

in your config/initializers/spree.rb

Spree.config do |config|
  ...
  config.always_put_site_name_in_title = false
end```