问:
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.

答:
You need to navigate to your screen name which is Stats.

```<code><Button
 title="Start"
 onPress={() => this.props.navigation.navigate('Stats')}/>
</code>```

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.

Body:
You need to navigate to your screen name which is Stats.

<Button
 title="Start"
 onPress={() => this.props.navigation.navigate('Stats')}/>


来源: stackexchange

问:
MySQL: SUM of a column based on a value of another column
I want to have a sum of a column that is based if the value of another column is this/that. Here's my table structure

```<code>id  leave_hours leave_type overtime_hours employee_id
1     7.6          1           0               3
2      5           2           0               3
3      0           0           2.3             3
</code>```

I have this query already but I need to have a column that will only sum if leave type is 1 and if the leave type is 2

```<code>SELECT employee_id, SUM(overtime_hours) AS ot_hrs, SUM(leave_hours if leave_type == 1) AS
       leave_1, SUM(leave_hours if leave_type == 2) AS leave_2
FROM table
GROUP BY employee_id
</code>```

Result should be:

```<code>employee_id  ot_hrs leave_1  leave_2
    3          2.3    7.6       5
</code>```

Thanks for your inputs.

答:
you can use max() with case when

```<code>SELECT employee_id,
       max(overtime_hours) AS ot,
       max(CASE WHEN leave_type = 1 THEN leave_hours  END) AS leave_1,
       max(CASE WHEN leave_type = 2 THEN leave_hours END) AS leave_2
FROM  table_name
GROUP BY employee_id
</code>```

output

```<code>employee_id     ot     leave_1       leave_2
3              2.3  7.599999904632568   5
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to have a sum of a column that is based if the value of another column is this/that. Here's my table structure

id  leave_hours leave_type overtime_hours employee_id
1     7.6          1           0               3
2      5           2           0               3
3      0           0           2.3             3

I have this query already but I need to have a column that will only sum if leave type is 1 and if the leave type is 2

SELECT employee_id, SUM(overtime_hours) AS ot_hrs, SUM(leave_hours if leave_type == 1) AS
       leave_1, SUM(leave_hours if leave_type == 2) AS leave_2
FROM table
GROUP BY employee_id

Result should be:

employee_id  ot_hrs leave_1  leave_2
    3          2.3    7.6       5

Thanks for your inputs.

Body:
you can use max() with case when

SELECT employee_id,
       max(overtime_hours) AS ot,
       max(CASE WHEN leave_type = 1 THEN leave_hours  END) AS leave_1,
       max(CASE WHEN leave_type = 2 THEN leave_hours END) AS leave_2
FROM  table_name
GROUP BY employee_id

output

employee_id     ot     leave_1       leave_2
3              2.3  7.599999904632568   5


问:
I am trying to resolve the data fetched from a firebase query but the data is not getting resolved
I am trying to fetch the data from firebase through node but the data is not being resolved. I cant get the data i want. Basically i want the timestamp from the firebase data but cannot get it.

I have already tried to resolve it using promise and foreach function but no good.

```<code>router.post("/date", (req, res) => {
  const date = {
    sdate: req.body.sdate,
    edate: req.body.edate
  };
  let s = new Date(date.sdate).getTime();
  let e = new Date(date.edate).getTime();
  const coll = db
    .collection("calls")
    .where("time", ">=", `${s}`)
    .where("time", "<=", `${e}`)
    .get()
    .then(doc => {
      doc.forEach(data => {
        console.log(data.id, data.data());
      });
    })
    .catch(err => {
      console.log(err);
    });
  console.log(coll);
</code>```

I expect to resolve the data into simple object or array so i can render it to the template engine to show the data.

答:
It looks as though you are trying to get multiple documents from a collection. Your code example is confusing due to variable names not matching their meaning.

It is also unclear in your question which piece of your code sample is failing to produce the expected outcome but I suspect it is the console.log(coll). This is because you are returning nothing inside your .then() and you are not waiting for the promise to be resolved before logging.

```<code>router.post("/date", (req, res) => {
  const date = {
    sdate: req.body.sdate,
    edate: req.body.edate
  };
  let s = new Date(date.sdate).getTime();
  let e = new Date(date.edate).getTime();
  const coll = []
  db
    .collection("calls")
    .where("time", ">=", `${s}`)
    .where("time", "<=", `${e}`)
    .get()
    .then(querySnapshot => {
      querySnapshot.forEach(doc => {
        coll.push({id: doc.id, data: doc.data()});
      });
      console.log(coll);
    })
    .catch(err => {
      console.log(err);
    });
})
</code>```

Body:
I am trying to fetch the data from firebase through node but the data is not being resolved. I cant get the data i want. Basically i want the timestamp from the firebase data but cannot get it.

I have already tried to resolve it using promise and foreach function but no good.

router.post("/date", (req, res) => {
  const date = {
    sdate: req.body.sdate,
    edate: req.body.edate
  };
  let s = new Date(date.sdate).getTime();
  let e = new Date(date.edate).getTime();
  const coll = db
    .collection("calls")
    .where("time", ">=", `${s}`)
    .where("time", "<=", `${e}`)
    .get()
    .then(doc => {
      doc.forEach(data => {
        console.log(data.id, data.data());
      });
    })
    .catch(err => {
      console.log(err);
    });
  console.log(coll);

I expect to resolve the data into simple object or array so i can render it to the template engine to show the data.

Body:
It looks as though you are trying to get multiple documents from a collection. Your code example is confusing due to variable names not matching their meaning.

It is also unclear in your question which piece of your code sample is failing to produce the expected outcome but I suspect it is the console.log(coll). This is because you are returning nothing inside your .then() and you are not waiting for the promise to be resolved before logging.

router.post("/date", (req, res) => {
  const date = {
    sdate: req.body.sdate,
    edate: req.body.edate
  };
  let s = new Date(date.sdate).getTime();
  let e = new Date(date.edate).getTime();
  const coll = []
  db
    .collection("calls")
    .where("time", ">=", `${s}`)
    .where("time", "<=", `${e}`)
    .get()
    .then(querySnapshot => {
      querySnapshot.forEach(doc => {
        coll.push({id: doc.id, data: doc.data()});
      });
      console.log(coll);
    })
    .catch(err => {
      console.log(err);
    });
})


问:
C++ char* array
When I create something like

```<code>char* t = new char[44];
t = strcpy(s,t);
</code>```

then strlen(t); return some wrong results. how I can change this?

答:
This code might be helpful:</p>

```<code>char * strcpy (char * destination, const char * source);
t = strcpy(t, s);
</code>```

OwnerDisplayName: Александр Брус

ContentLicense: CC BY-SA 3.0

Title: C++ char* array

Body:
When I create something like

char* t = new char[44];
t = strcpy(s,t);

then strlen(t); return some wrong results. how I can change this?

Body:
This code might be helpful:

char * strcpy (char * destination, const char * source);
t = strcpy(t, s);

OwnerDisplayName: Artem Volkhin


问:
Open CV stream YouTube video
I would like to be able to capture YouTube videos (both live and recorded) using open cv.

I have found the question below, but is seems based on the comments and my own trials that the code/solutions provided below do not work on recent open cv versions.

Is it possible to stream video from https:// (e.g. YouTube) into python with OpenCV?

Is there any way to stream YouTube video through the most recent open cv version: opencv-python 4.1.0.25?

My goal is to use this to test a facial recognition algorithm on several random video streams which have human faces (for example news shows) to test for false positives.

答:
Below is the method that i used for stream the data to opencv. But I was using a older version of opencv and link to caffe myself.

Install Pafy and youtubedl

```<code>pip install pafy
pip install youtube_dl
</code>```

After install, copy the url from the video you want. Below is the sample code

```<code>url = 'https://youtu.be/1AbfRENy3OQ'
urlPafy = pafy.new(url)
videoplay = urlPafy.getbest(preftype="webm")

cap = cv2.VideoCapture(videoplay.url)
while (True):
    ret,src = cap.read()
    cv2.imshow('src',src)
    #do your stuff here.

cap.release()
cv2.destroyAllWindows()
</code>```

But if you want the auto select random video with face in it that will be a bit more complicated

You need to use  YouTube-API to get random VideoId's from a set of search word( e.g pretty face, deep fake faces)

Then from the queried database, auto loop through for your learning algorithm. Below is a short sample from other post

```<code>import json
import urllib.request
import string
import random

count = 50
API_KEY = 'your_key'
random = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(3))

urlData = "https://www.googleapis.com/youtube/v3/search?key={}&maxResults={}&part=snippet&type=video&q={}".format(API_KEY,count,random)
webURL = urllib.request.urlopen(urlData)
data = webURL.read()
encoding = webURL.info().get_content_charset('utf-8')
results = json.loads(data.decode(encoding))

for data in results['items']:
    videoId = (data['id']['videoId'])
    print(videoId)
    #store your ids
</code>```

But without ground truth label, it is difficult to get a quantitative measure for your algo performance. Thus, I would suggest getting from one of the face video datasets for effective computing for the score. You need that properly generated score for publication.

https://www.cs.tau.ac.il/~wolf/ytfaces/

Title: Open CV stream YouTube video

Body:
Below is the method that i used for stream the data to opencv. But I was using a older version of opencv and link to caffe myself.

Install Pafy and youtubedl

pip install pafy
pip install youtube_dl

After install, copy the url from the video you want. Below is the sample code

url = 'https://youtu.be/1AbfRENy3OQ'
urlPafy = pafy.new(url)
videoplay = urlPafy.getbest(preftype="webm")

cap = cv2.VideoCapture(videoplay.url)
while (True):
    ret,src = cap.read()
    cv2.imshow('src',src)
    #do your stuff here.

cap.release()
cv2.destroyAllWindows()

But if you want the auto select random video with face in it that will be a bit more complicated

You need to use  YouTube-API to get random VideoId's from a set of search word( e.g pretty face, deep fake faces)

Then from the queried database, auto loop through for your learning algorithm. Below is a short sample from other post

import json
import urllib.request
import string
import random

count = 50
API_KEY = 'your_key'
random = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(3))

urlData = "https://www.googleapis.com/youtube/v3/search?key={}&maxResults={}&part=snippet&type=video&q={}".format(API_KEY,count,random)
webURL = urllib.request.urlopen(urlData)
data = webURL.read()
encoding = webURL.info().get_content_charset('utf-8')
results = json.loads(data.decode(encoding))

for data in results['items']:
    videoId = (data['id']['videoId'])
    print(videoId)
    #store your ids

But without ground truth label, it is difficult to get a quantitative measure for your algo performance. Thus, I would suggest getting from one of the face video datasets for effective computing for the score. You need that properly generated score for publication.

https://www.cs.tau.ac.il/~wolf/ytfaces/


问:
Pass parameter WeakReference<View> to method of ViewModel?
Our teams are debating whether we should pass parameter WeakReference<View> to method of ViewModel or not. I see in the google's document said

Note: Since the ViewModel outlives specific activity and fragment instantiations, it should never reference a View, or any class that may hold a reference to the activity context. If the ViewModel needs the Application context (for example, to find a system service), it can extend the AndroidViewModel class and have a constructor that receives the Application in the constructor (since Application class extends Context).

How about if we use WeakReference<View> to pass view to viewmodel ? WeakRef can prevent the leak memory can occur, however some members said it will make reading/maintain code difficultly. Some guys suggest use interface ViewInf and View will implement to ViewInf and method use in viewmodel will be like that.

```<code>    fun methodA(viewInf: WeakReference<ViewInf>)() {
        doSomeBackgroundThread(viewInf)
    }
</code>```

We want to use this view to draw on bitmap and use bitmap to save into memcache.

答:
The cautionary note from Google makes sense, as the ViewModel is not supposed to do anything other than transport data. </p>

<p>Sometimes we get so caught up in the "object-oriented" part of the design that we forget that domain objects, and application infrastructure objects, should only interact to extract data from,  or inject data into the application for processing. </p>

Body:
Our teams are debating whether we should pass parameter WeakReference<View> to method of ViewModel or not. I see in the google's document said

Note: Since the ViewModel outlives specific activity and fragment instantiations, it should never reference a View, or any class that may hold a reference to the activity context. If the ViewModel needs the Application context (for example, to find a system service), it can extend the AndroidViewModel class and have a constructor that receives the Application in the constructor (since Application class extends Context).

How about if we use WeakReference<View> to pass view to viewmodel ? WeakRef can prevent the leak memory can occur, however some members said it will make reading/maintain code difficultly. Some guys suggest use interface ViewInf and View will implement to ViewInf and method use in viewmodel will be like that.

    fun methodA(viewInf: WeakReference<ViewInf>)() {
        doSomeBackgroundThread(viewInf)
    }

We want to use this view to draw on bitmap and use bitmap to save into memcache.

Body:
The cautionary note from Google makes sense, as the ViewModel is not supposed to do anything other than transport data.

Sometimes we get so caught up in the "object-oriented" part of the design that we forget that domain objects, and application infrastructure objects, should only interact to extract data from,  or inject data into the application for processing.


问:
Encrypt/Decrypt using Secure Enclave iOS AES-GCM
I am using SecureEnclave on iOS to encrypt/decrypt my confidential key and save it in UserPreferences. It has been setup and encrypting the data successfully. But whenever I try to decrypt the data, it gives me the following error:

Error Domain=NSOSStatusErrorDomain Code=-50 \"ECIES: Failed to aes-gcm decrypt data\" UserInfo={NSDescription=ECIES: Failed to aes-gcm decrypt data}

After a lot of searching, I found some links but they are not of any help. This Github issue talks about the issue. It states,

Additionally, on 10.3 there was a problem with decrypting large amounts of data with kSecKeyAlgorithmECIESEncryptionCofactorX963SHA256AESGCM. I filed a bug report for it, and it got fixed in iOS 11. :)

But I am using iPhone 8 with iOS 12.2 and there is still a problem.

These two SO questions, here and here provide some details but I am not able to decipher it. Plus, I am using Swift 4.

Below is the relevant code which I am using to encrypt/decrypt the data.

To Generate Key Pair

```<code>func generateKeyPair(accessControl: SecAccessControl) throws -> (`public`: SecureEnclaveKeyReference, `private`: SecureEnclaveKeyReference) {

    let publicKeyParameters: [String: AnyObject] = [
        kSecAttrIsPermanent as String: false as AnyObject,
        kSecAttrApplicationTag as String: "com.xxx.xxx" as AnyObject,
        kSecAttrLabel as String: "PublicKey" as AnyObject
    ]

    let privateKeyParameters: [String: AnyObject] = [
        (kSecAttrCanDecrypt as CFString) as String: true as CFBoolean,
        kSecAttrIsPermanent as String: true as AnyObject,
        kSecAttrAccessControl as String: accessControl,
        kSecAttrApplicationTag as String: "com.xxx.xxx" as AnyObject,
        kSecAttrLabel as String: "PrivateKey" as AnyObject
    ]

    let parameters: [String: AnyObject] = [
        kSecAttrKeyType as String: kSecAttrKeyTypeEC,
        kSecAttrKeySizeInBits as String: 256 as AnyObject,
        kSecAttrTokenID as String: kSecAttrTokenIDSecureEnclave,
        kSecPublicKeyAttrs as String: publicKeyParameters as AnyObject,
        kSecPrivateKeyAttrs as String: privateKeyParameters as AnyObject
    ]

    var publicKey, privateKey: SecKey?
    let status = SecKeyGeneratePair(parameters as CFDictionary, &publicKey, &privateKey)

    print("Result = \(status) - Public Key = \(publicKey) - Private Key = \(privateKey)")

    guard status == errSecSuccess else {

        throw SecureEnclaveHelperError(message: "Could not generate keypair", osStatus: status)
    }

    return (public: SecureEnclaveKeyReference(publicKey!), private: SecureEnclaveKeyReference(privateKey!))

}
</code>```

Encryption

```<code>@available(iOS 10.3, *)
func encrypt(_ digest: Data, publicKey: SecureEnclaveKeyReference) throws -> Data {

    var error : Unmanaged<CFError>?

    let result = SecKeyCreateEncryptedData(publicKey.underlying, SecKeyAlgorithm.eciesEncryptionStandardX963SHA256AESGCM, digest as CFData, &error)

    if result == nil {

        throw SecureEnclaveHelperError(message: "\(error)", osStatus: 0)
    }

    return result as! Data
}
</code>```

Decryption

```<code>@available(iOS 10.3, *)
func decrypt(_ digest: Data, privateKey: SecureEnclaveKeyReference) throws -> Data {

    var error : Unmanaged<CFError>?

    let result = SecKeyCreateDecryptedData(privateKey.underlying, SecKeyAlgorithm.eciesEncryptionStandardX963SHA256AESGCM, digest as CFData, &error)

    if result == nil {

        throw SecureEnclaveHelperError(message: "\(error)", osStatus: 0)
    }

    return result as! Data
}
</code>```

Any help is highly appreciated. Thanks.

答: I got the same error and found out that I generated two different key pairs where I encrypted my data with one public key but performed decryption using the other wrong private key. So make sure that the decryption operation uses the right private key corresponding to the public key used in encryption.</p>

Body:
I am using SecureEnclave on iOS to encrypt/decrypt my confidential key and save it in UserPreferences. It has been setup and encrypting the data successfully. But whenever I try to decrypt the data, it gives me the following error:

Error Domain=NSOSStatusErrorDomain Code=-50 \"ECIES: Failed to aes-gcm decrypt data\" UserInfo={NSDescription=ECIES: Failed to aes-gcm decrypt data}

After a lot of searching, I found some links but they are not of any help. This Github issue talks about the issue. It states,

Additionally, on 10.3 there was a problem with decrypting large amounts of data with kSecKeyAlgorithmECIESEncryptionCofactorX963SHA256AESGCM. I filed a bug report for it, and it got fixed in iOS 11. :)

But I am using iPhone 8 with iOS 12.2 and there is still a problem.

These two SO questions, here and here provide some details but I am not able to decipher it. Plus, I am using Swift 4.

Below is the relevant code which I am using to encrypt/decrypt the data.

To Generate Key Pair

func generateKeyPair(accessControl: SecAccessControl) throws -> (`public`: SecureEnclaveKeyReference, `private`: SecureEnclaveKeyReference) {

    let publicKeyParameters: [String: AnyObject] = [
        kSecAttrIsPermanent as String: false as AnyObject,
        kSecAttrApplicationTag as String: "com.xxx.xxx" as AnyObject,
        kSecAttrLabel as String: "PublicKey" as AnyObject
    ]

    let privateKeyParameters: [String: AnyObject] = [
        (kSecAttrCanDecrypt as CFString) as String: true as CFBoolean,
        kSecAttrIsPermanent as String: true as AnyObject,
        kSecAttrAccessControl as String: accessControl,
        kSecAttrApplicationTag as String: "com.xxx.xxx" as AnyObject,
        kSecAttrLabel as String: "PrivateKey" as AnyObject
    ]

    let parameters: [String: AnyObject] = [
        kSecAttrKeyType as String: kSecAttrKeyTypeEC,
        kSecAttrKeySizeInBits as String: 256 as AnyObject,
        kSecAttrTokenID as String: kSecAttrTokenIDSecureEnclave,
        kSecPublicKeyAttrs as String: publicKeyParameters as AnyObject,
        kSecPrivateKeyAttrs as String: privateKeyParameters as AnyObject
    ]

    var publicKey, privateKey: SecKey?
    let status = SecKeyGeneratePair(parameters as CFDictionary, &publicKey, &privateKey)

    print("Result = \(status) - Public Key = \(publicKey) - Private Key = \(privateKey)")

    guard status == errSecSuccess else {

        throw SecureEnclaveHelperError(message: "Could not generate keypair", osStatus: status)
    }

    return (public: SecureEnclaveKeyReference(publicKey!), private: SecureEnclaveKeyReference(privateKey!))

}

Encryption

@available(iOS 10.3, *)
func encrypt(_ digest: Data, publicKey: SecureEnclaveKeyReference) throws -> Data {

    var error : Unmanaged<CFError>?

    let result = SecKeyCreateEncryptedData(publicKey.underlying, SecKeyAlgorithm.eciesEncryptionStandardX963SHA256AESGCM, digest as CFData, &error)

    if result == nil {

        throw SecureEnclaveHelperError(message: "\(error)", osStatus: 0)
    }

    return result as! Data
}

Decryption

@available(iOS 10.3, *)
func decrypt(_ digest: Data, privateKey: SecureEnclaveKeyReference) throws -> Data {

    var error : Unmanaged<CFError>?

    let result = SecKeyCreateDecryptedData(privateKey.underlying, SecKeyAlgorithm.eciesEncryptionStandardX963SHA256AESGCM, digest as CFData, &error)

    if result == nil {

        throw SecureEnclaveHelperError(message: "\(error)", osStatus: 0)
    }

    return result as! Data
}

Any help is highly appreciated. Thanks.


问:
Confused about this line of code that is meant to act as an ingestion of a Class into a void pointer
I've been learning how to send data to a program called FogLAMP https://github.com/foglamp/ and the data I want to send is asynchronous. My question is not about the foglamp code base itself, rather the below line of code.

I understand generally what the code is doing. But I do not know the exact mechanics in memory or the syntax for that matter.

I will do my best to describe what I believe is going on, but I am not entirely sure.

This is a code ingestion, so because the program is running two asynchronous threads, (the data collection and sending process (pid (1)) and the actual code set up as a daemon process (pid (2))) it is designed to allocate a void pointer (void * m_data) that will eventually be filled with a Reading object that should be sent to the cloud via process (1). This reading is produced, however, in process (2). So what I believe is going on is process (2) is producing a Reading object in memory so that process (1) can access that data.

I am lost when it comes to this line of code, though (I've included relevant code below to follow the execution path).

void    (*m_ingest)(void *, Reading);
```

<p>I haven't seen this syntax anywhere and I can't seem to describe this to google, so I'm not entirely sure what this means in C++. </p>

<p>I apologize I'm not able to provide much more information. I wasn't sure how to describe it, kind of like a cast to a type m_ingest (which is not a global variable or typedef). </p>

<p>I am looking through this code because I would like to implement the same thing into my own foglamp plugin using Robotic Operating Systems (ROS) as a multi threaded asynchronous data transfer to foglamp.</p>

<p>This is the code In question</p>

<pre class="lang-cpp prettyprint-override"><code>void    (*m_ingest)(void *, Reading);
void    *m_data;
</code>```

These two variables appear in the below functions (not entirely sure what (*cb)(void *, Reading) means either.

void OPCUA::registerIngest(void *data, void (*cb)(void *, Reading))
{
    m_ingest = cb;
    m_data = data;
}

/**
 * Called when a data changed event is received. This calls back to the south service
 * and adds the points to the readings queue to send.
 *
 * @param points    The points in the reading we must create
 */
void OPCUA::ingest(vector<Datapoint *>  points)
{
string asset = m_asset + points[0]->getName();

    (*m_ingest)(m_data, Reading(asset, points));
}
```

The comment is very helpful, stating that ingest puts the array of Datapoint pointers into a queue to be sent to foglamp. It makes sense, what this s doing, but I would like a more robust explanation as to what is actually going on in memory.

The source code In question is found in the repository
https://github.com/foglamp/foglamp-south-opcua

Here is the source code
https://github.com/foglamp/foglamp-south-opcua/blob/develop/opcua.cpp

Here is the header file
https://github.com/foglamp/foglamp-south-opcua/blob/develop/include/opcua.h

答:
Pretty basic c++ here. Thanks to @1201ProgramAlarm. It's just a function pointer. I read a quick tutorial here https://www.cprogramming.com/tutorial/function-pointers.html. But I now see that (*cb) is a function pointer passed through register_ingest to assign m_ingest to the same function as (*cb). Thus when foglamp needs data it accesses it through m_ingest. This function helps a lot

void plugin_register_ingest(PLUGIN_HANDLE *handle, INGEST_CB cb, void *data)
{
OPCUA *opcua = (OPCUA *)handle;

    if (!handle)
        throw new exception();
    opcua->registerIngest(data, cb);
}
```

So INGEST_CB is a global callback function defined in some foglamp header file that then is assigned to the same address as m_ingest.

Humbling to learn something new in C++. I have never seen function pointers passed this way, only function addresses (i.e. through std::bind(&func, param)).

Body:
I've been learning how to send data to a program called FogLAMP https://github.com/foglamp/ and the data I want to send is asynchronous. My question is not about the foglamp code base itself, rather the below line of code.

I understand generally what the code is doing. But I do not know the exact mechanics in memory or the syntax for that matter.

I will do my best to describe what I believe is going on, but I am not entirely sure.

This is a code ingestion, so because the program is running two asynchronous threads, (the data collection and sending process (pid (1)) and the actual code set up as a daemon process (pid (2))) it is designed to allocate a void pointer (void * m_data) that will eventually be filled with a Reading object that should be sent to the cloud via process (1). This reading is produced, however, in process (2). So what I believe is going on is process (2) is producing a Reading object in memory so that process (1) can access that data.

I am lost when it comes to this line of code, though (I've included relevant code below to follow the execution path).

void    (*m_ingest)(void *, Reading);

I haven't seen this syntax anywhere and I can't seem to describe this to google, so I'm not entirely sure what this means in C++.

I apologize I'm not able to provide much more information. I wasn't sure how to describe it, kind of like a cast to a type m_ingest (which is not a global variable or typedef).

I am looking through this code because I would like to implement the same thing into my own foglamp plugin using Robotic Operating Systems (ROS) as a multi threaded asynchronous data transfer to foglamp.

This is the code In question

void    (*m_ingest)(void *, Reading);
void    *m_data;

These two variables appear in the below functions (not entirely sure what (*cb)(void *, Reading) means either.

void OPCUA::registerIngest(void *data, void (*cb)(void *, Reading))
{
    m_ingest = cb;
    m_data = data;
}

/**
 * Called when a data changed event is received. This calls back to the south service
 * and adds the points to the readings queue to send.
 *
 * @param points    The points in the reading we must create
 */
void OPCUA::ingest(vector<Datapoint *>  points)
{
string asset = m_asset + points[0]->getName();

    (*m_ingest)(m_data, Reading(asset, points));
}

The comment is very helpful, stating that ingest puts the array of Datapoint pointers into a queue to be sent to foglamp. It makes sense, what this s doing, but I would like a more robust explanation as to what is actually going on in memory.

The source code In question is found in the repository
https://github.com/foglamp/foglamp-south-opcua

Here is the source code
https://github.com/foglamp/foglamp-south-opcua/blob/develop/opcua.cpp

Here is the header file
https://github.com/foglamp/foglamp-south-opcua/blob/develop/include/opcua.h

Body:
Pretty basic c++ here. Thanks to @1201ProgramAlarm. It's just a function pointer. I read a quick tutorial here https://www.cprogramming.com/tutorial/function-pointers.html. But I now see that (*cb) is a function pointer passed through register_ingest to assign m_ingest to the same function as (*cb). Thus when foglamp needs data it accesses it through m_ingest. This function helps a lot

void plugin_register_ingest(PLUGIN_HANDLE *handle, INGEST_CB cb, void *data)
{
OPCUA *opcua = (OPCUA *)handle;

    if (!handle)
        throw new exception();
    opcua->registerIngest(data, cb);
}

So INGEST_CB is a global callback function defined in some foglamp header file that then is assigned to the same address as m_ingest.

Humbling to learn something new in C++. I have never seen function pointers passed this way, only function addresses (i.e. through std::bind(&func, param)).


问:
Boost with Borland C++ Builder
Has anybody used the Boost library in Borland C++ Builder? Is there any online resource of building it and using it in Borland C++ Builder?
The boost documentation is very brief about the specific task.

Thanks a lot!

答:
I've compiled boost 1.33 for borland c++ builder 6 by next steps:

First, I've downloaded and extracted the
boost-jam-3.1.18-1-ntx86;

Downloaded and extracted  boost library 1.33

Copied bjam.exe to the extracted boost root folder;

Run bjam with: bjam -sTOOLS=borland stage;

Most of the components were compiled.

Title: Boost with Borland C++ Builder


问:
JSON organization of model
I have two competing thoughts on storing, what I consider, meta data for a record.

1)

```<code>meta: {
    dates: {
        added: {
            date: Date
            ,user_id: ObjectId
        }
        ,modified: {
            date: Date
            ,user_id: ObjectId
        }
        ,approved: {
            date: Date
            ,user_id: ObjectId
        }
        ,deleted: {
            date: Date
            ,user_id: ObjectId
        }
    }
}
</code>```

2)

```<code>meta: {
    dates: {
        created: Date
        ,updated: Date
        ,approved: Date
        ,deleted: Date
    },
    users: {
        created: ObjectId
        ,updated: ObjectId
        ,approved: ObjectId
        ,deleted: ObjectId
    }
}
</code>```

Can I please get some arguments in favor or against them?

答:
The difference between these structures will matter only in extreme cases.

Eg:

You need to access the data at a very high frequency

You need to store few millions of these structures

Title: JSON organization of model

Body:
I have two competing thoughts on storing, what I consider, meta data for a record.

1)

meta: {
    dates: {
        added: {
            date: Date
            ,user_id: ObjectId
        }
        ,modified: {
            date: Date
            ,user_id: ObjectId
        }
        ,approved: {
            date: Date
            ,user_id: ObjectId
        }
        ,deleted: {
            date: Date
            ,user_id: ObjectId
        }
    }
}

2)

meta: {
    dates: {
        created: Date
        ,updated: Date
        ,approved: Date
        ,deleted: Date
    },
    users: {
        created: ObjectId
        ,updated: ObjectId
        ,approved: ObjectId
        ,deleted: ObjectId
    }
}

Can I please get some arguments in favor or against them?


问:
Why my constructor function raise segmentation fault when it exits?
I'm pretty new to C++, and finding difficulty digging into memory management or things alike. Now I am trying to write some rudimentary parser but has the constructor function exits with a segmentation fault and cannot find out why.

Somewhere on the web has informed me that this is caused by I myself somehow corrupted the stack, but I'm to new to realize the origin of the problem.

```<code>class Parser {
public:
    int *res, len = 0;
    string src;

// this len is the number of seps
Parser(const string &s, char t) : src(s) {
    int tmp = -1, flag = TRUE, tmps[MAX];
    while (flag) {
        tmp = s.find(t, tmp + 1);
        if (tmp == -1) {
            flag = FALSE;
        } else {
            tmps[len++] = tmp;  // len is now really the length
        }
    }
    res = (int *) malloc(len * sizeof(int));
    for (int i = 0; i < len; ++i) {
        *(res + i) = tmps[i];
    }
}

~Parser() {
    free(res);
    }
};
</code>```

When run directly, report "Process finished with exit code -1073741819 (0xC0000005)"; and when in debugging mode, raise "SIGSEGV (Segmentation fault)" at "mov %rax,(%rcx)", the instruction.

答:
Thank all your help, now I have fix my code up, and here I offer a complete solution for my little parser, with usages.</p>

```<code>#define MAX 99
#define TRUE 1
#define FALSE 0
#define INFEASIBLE -1
#define OVERFLOW -2

#include <iostream>
#include <vector>

using namespace std;

class Parser {
public:
vector<int> res;
int len;
string src;

Parser(string s, char t) : src(move(s)) {
    // churn a string and a seperator into a vector of ints
    int sep, next_sep, tmp;
    for (sep = -1, next_sep = 0; next_sep != -1; sep = next_sep) {
        next_sep = src.find(t, sep + 1);
        if (next_sep == -1) {
            res.push_back(stoi(src.substr(sep+1)));
        } else if (sep == -1) {
            res.push_back(stoi(src.substr(0, next_sep)));
        } else {
            res.push_back(stoi(src.substr(sep+1, next_sep - sep - 1)));
        }
    }
    len = res.size();
}
};

class TwoTierParser {
public:
vector<Parser> res;
int len;
string src;

TwoTierParser(string s, char x, char y) : src(move(s)) {
    // churn a string and two seperators into a vector of Parsers
    int sep, next_sep;
    for (sep = -1, next_sep = 0; next_sep != -1; sep = next_sep) {
        next_sep = src.find(x, sep + 1);
        if (next_sep == -1) {
            res.emplace_back(Parser(src.substr(sep+1), y));
        } else if (sep == -1) {
            res.emplace_back(Parser(src.substr(0, next_sep), y));
        } else {
            res.emplace_back(Parser(src.substr(sep+1, next_sep - sep - 1), y));
        }
    }
    len = res.size();
}
};

int main() {
char comma = ',', semicolon = ';';
string a;
//    cin >> a;
a = "1,2,3,4,5;6,7,8,9,10;11,12,13,14,15";
TwoTierParser parse(a, semicolon, comma);

int row = parse.len;
int col = parse.res[0].len;
int matrix[row][col];

for(int i=0; i<row; ++i){
    for(int j=0; j<col; ++j){
        matrix[i][j]=parse.res[i].res[j];
    }
}

for (int k = 0; k < row; ++k) {
    for (int i = 0; i < col; ++i) {
        cout<<matrix[k][i]<<" ";
    }
    cout<<"\n";
}
return 0;
}
</code>```

Body:
I'm pretty new to C++, and finding difficulty digging into memory management or things alike. Now I am trying to write some rudimentary parser but has the constructor function exits with a segmentation fault and cannot find out why.

Somewhere on the web has informed me that this is caused by I myself somehow corrupted the stack, but I'm to new to realize the origin of the problem.

class Parser {
public:
    int *res, len = 0;
    string src;

// this len is the number of seps
Parser(const string &s, char t) : src(s) {
    int tmp = -1, flag = TRUE, tmps[MAX];
    while (flag) {
        tmp = s.find(t, tmp + 1);
        if (tmp == -1) {
            flag = FALSE;
        } else {
            tmps[len++] = tmp;  // len is now really the length
        }
    }
    res = (int *) malloc(len * sizeof(int));
    for (int i = 0; i < len; ++i) {
        *(res + i) = tmps[i];
    }
}

~Parser() {
    free(res);
    }
};

When run directly, report "Process finished with exit code -1073741819 (0xC0000005)"; and when in debugging mode, raise "SIGSEGV (Segmentation fault)" at "mov %rax,(%rcx)", the instruction.

Body:
Thank all your help, now I have fix my code up, and here I offer a complete solution for my little parser, with usages.

#define MAX 99
#define TRUE 1
#define FALSE 0
#define INFEASIBLE -1
#define OVERFLOW -2

#include <iostream>
#include <vector>

using namespace std;

class Parser {
public:
vector<int> res;
int len;
string src;

Parser(string s, char t) : src(move(s)) {
    // churn a string and a seperator into a vector of ints
    int sep, next_sep, tmp;
    for (sep = -1, next_sep = 0; next_sep != -1; sep = next_sep) {
        next_sep = src.find(t, sep + 1);
        if (next_sep == -1) {
            res.push_back(stoi(src.substr(sep+1)));
        } else if (sep == -1) {
            res.push_back(stoi(src.substr(0, next_sep)));
        } else {
            res.push_back(stoi(src.substr(sep+1, next_sep - sep - 1)));
        }
    }
    len = res.size();
}
};

class TwoTierParser {
public:
vector<Parser> res;
int len;
string src;

TwoTierParser(string s, char x, char y) : src(move(s)) {
    // churn a string and two seperators into a vector of Parsers
    int sep, next_sep;
    for (sep = -1, next_sep = 0; next_sep != -1; sep = next_sep) {
        next_sep = src.find(x, sep + 1);
        if (next_sep == -1) {
            res.emplace_back(Parser(src.substr(sep+1), y));
        } else if (sep == -1) {
            res.emplace_back(Parser(src.substr(0, next_sep), y));
        } else {
            res.emplace_back(Parser(src.substr(sep+1, next_sep - sep - 1), y));
        }
    }
    len = res.size();
}
};

int main() {
char comma = ',', semicolon = ';';
string a;
//    cin >> a;
a = "1,2,3,4,5;6,7,8,9,10;11,12,13,14,15";
TwoTierParser parse(a, semicolon, comma);

int row = parse.len;
int col = parse.res[0].len;
int matrix[row][col];

for(int i=0; i<row; ++i){
    for(int j=0; j<col; ++j){
        matrix[i][j]=parse.res[i].res[j];
    }
}

for (int k = 0; k < row; ++k) {
    for (int i = 0; i < col; ++i) {
        cout<<matrix[k][i]<<" ";
    }
    cout<<"\n";
}
return 0;
}


问:
What is ID3D12GraphicsCommandList::DiscardResource?
What exactly should I expect to happen when using DiscardResource?

What's the difference between discard and destroying/deleting a resource.

When is a good time/use-case to discard a resource?

Unfortunately Microsoft doesn't seem to say much about it other than it "discards a resource".

答:
TL;DR: Is a rarely used function that provides a driver hint related to handling clear compression structures. You are unlikely to use it except based on specific performance advice.

DiscardResource is the DirectX 12 version of the Direct3D 11.1 method. See Microsoft Docs

The primary use of these methods it to optimize the performance of tiled-based deferred rasterizer graphics parts by discarding the render target after present. This is a hint to the driver that the contents of the render target are no longer relevant to the operation of the program, so it can avoid some internal clearing operations on the next use.

For DirectX 11, this is in the DirectX 11 App template to use DiscardView because it makes use of DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL:

```<code>void DX::DeviceResources::Present()
{
    // The first argument instructs DXGI to block until VSync, putting the application
    // to sleep until the next VSync. This ensures we don't waste any cycles rendering
    // frames that will never be displayed to the screen.
    DXGI_PRESENT_PARAMETERS parameters = { 0 };
    HRESULT hr = m_swapChain->Present1(1, 0, &parameters);

    // Discard the contents of the render target.
    // This is a valid operation only when the existing contents will be entirely
    // overwritten. If dirty or scroll rects are used, this call should be removed.
    m_d3dContext->DiscardView1(m_d3dRenderTargetView.Get(), nullptr, 0);

    // Discard the contents of the depth stencil.
    m_d3dContext->DiscardView1(m_d3dDepthStencilView.Get(), nullptr, 0);

    // If the device was removed either by a disconnection or a driver upgrade, we
    // must recreate all device resources.
    if (hr == DXGI_ERROR_DEVICE_REMOVED || hr == DXGI_ERROR_DEVICE_RESET)
    {
        HandleDeviceLost();
    }
    else
    {
        DX::ThrowIfFailed(hr);
    }
}
</code>```

The DirectX 12 App template doesn't need those explicit calls because it uses DXGI_SWAP_EFFECT_FLIP_DISCARD.

If you are wondering why the DirectX 11 app doesn't just use DXGI_SWAP_EFFECT_FLIP_DISCARD, it probably should. The DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL swap effect was the only one supported by Windows 8.x for Windows Store apps, which is when DiscardView was introduced. For Windows 10 / DirectX 12 / UWP, it's probably better to always use DXGI_SWAP_EFFECT_FLIP_DISCARD unless you specifically don't want the backbuffer discarded.

It is also useful for multi-GPU SLI / Crossfire configurations since the clearing operation can require synchronization between the GPUs. See this GDC 2015 talk

There are also other scenario-specific usages. For example, if doing deferred rendering for the G-buffer where you know every single pixel will be overwritten, you can use DiscardResource instead of doing ClearRenderTargetView / ClearDepthStencilView.

Body:
TL;DR: Is a rarely used function that provides a driver hint related to handling clear compression structures. You are unlikely to use it except based on specific performance advice.

DiscardResource is the DirectX 12 version of the Direct3D 11.1 method. See Microsoft Docs

The primary use of these methods it to optimize the performance of tiled-based deferred rasterizer graphics parts by discarding the render target after present. This is a hint to the driver that the contents of the render target are no longer relevant to the operation of the program, so it can avoid some internal clearing operations on the next use.

For DirectX 11, this is in the DirectX 11 App template to use DiscardView because it makes use of DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL:

void DX::DeviceResources::Present()
{
    // The first argument instructs DXGI to block until VSync, putting the application
    // to sleep until the next VSync. This ensures we don't waste any cycles rendering
    // frames that will never be displayed to the screen.
    DXGI_PRESENT_PARAMETERS parameters = { 0 };
    HRESULT hr = m_swapChain->Present1(1, 0, &parameters);

    // Discard the contents of the render target.
    // This is a valid operation only when the existing contents will be entirely
    // overwritten. If dirty or scroll rects are used, this call should be removed.
    m_d3dContext->DiscardView1(m_d3dRenderTargetView.Get(), nullptr, 0);

    // Discard the contents of the depth stencil.
    m_d3dContext->DiscardView1(m_d3dDepthStencilView.Get(), nullptr, 0);

    // If the device was removed either by a disconnection or a driver upgrade, we
    // must recreate all device resources.
    if (hr == DXGI_ERROR_DEVICE_REMOVED || hr == DXGI_ERROR_DEVICE_RESET)
    {
        HandleDeviceLost();
    }
    else
    {
        DX::ThrowIfFailed(hr);
    }
}

The DirectX 12 App template doesn't need those explicit calls because it uses DXGI_SWAP_EFFECT_FLIP_DISCARD.

If you are wondering why the DirectX 11 app doesn't just use DXGI_SWAP_EFFECT_FLIP_DISCARD, it probably should. The DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL swap effect was the only one supported by Windows 8.x for Windows Store apps, which is when DiscardView was introduced. For Windows 10 / DirectX 12 / UWP, it's probably better to always use DXGI_SWAP_EFFECT_FLIP_DISCARD unless you specifically don't want the backbuffer discarded.

It is also useful for multi-GPU SLI / Crossfire configurations since the clearing operation can require synchronization between the GPUs. See this GDC 2015 talk

There are also other scenario-specific usages. For example, if doing deferred rendering for the G-buffer where you know every single pixel will be overwritten, you can use DiscardResource instead of doing ClearRenderTargetView / ClearDepthStencilView.


问:
Can't iterate over 2d array to normalize data
I'm trying to normalize my data and i need to iterate over the training and testing set. I tried in different ways but i get this error list indices must be integers or slices, not list. I've tried putting range() and len() but i still got the same error.

Code:

```<code>def minMaxNrom(training_data, testing_data):
    for i in training_data:
        for j in training_data:
            new_data = training_data[i][j] - min(j) / max(j) - min(j)

    for i in testing_data:
        for j in testing_data:
            new_testing_data = testing_data[i][j] - min(j) / max(j) - min(j)

    return (new_data, new_testing_data)
</code>```

答:
You are using lists as indices. You may want to use enumerate. This will fix your error:

```<code>def minMaxNrom(training_data, testing_data):
    for indi, i in enumerate(training_data):
        for indj, j in enumerate(training_data):
            new_data = training_data[indi][indj] - min(j) / max(j) - min(j)

    for indi, i in enumerate(testing_data):
        for indj, j in enumerate(testing_data):
            new_testing_data = testing_data[indi][indj] - min(j) / max(j) - min(j)

    return (new_data, new_testing_data)
</code>```

Some guess work as to what you are trying to achieve

Without more information it is difficult to know why your code is failing after fixing the can't use list as index problem, but here is my guess:

```<code>def minMaxNrom(training_data, testing_data):
    new_data = []
    new_testing_data = []
    for indi, i in enumerate(training_data):
        for indj, j in enumerate(training_data):
            new_data.append((training_data[indi][indj] - min(j)) / (max(j) - min(j)))

    for indi, i in enumerate(testing_data):
        for indj, j in enumerate(testing_data):
            new_testing_data.append((testing_data[indi][indj] - min(j)) / (max(j) - min(j)))

    return (new_data, new_testing_data)
</code>```

Explanation

Say you have:

```<code>training_data = [[1, 2], [3, 4, 5], [4, 4, 4]]
for i in training_data:
    print(i)
</code>```

This will print:

```<code>[1, 2]
[3, 4, 5]
[4, 4, 4]
</code>```

As you can see, the i here is each sublist. But to access these sublists with reference, you do:

```<code>print(training_data[0])  # gives first sublist
print('---')
print(training_data[1])  # gives second sublist
print('---')
print(training_data[2])  # gives third sublist
</code>```

This will give:

```<code>[1, 2]
---
[3, 4, 5]
---
[4, 4, 4]
</code>```

Note that to access these sublists we use a number as the index not a list (which is what you were using). So in order to access each list and get its index, we use enumerate (a better variable name for i would be sublist):

```<code>for indi, i in enumerate(training_data):
    print('indi: ', indi)
    print('i: ', i)
    print('training_data[indi]: ', training_data[indi])
    print('---')
</code>```

this gives:

```<code>indi:  0
i:  [1, 2]
training_data[indi]:  [1, 2]
---
indi:  1
i:  [3, 4, 5]
training_data[indi]:  [3, 4, 5]
---
indi:  2
i:  [4, 4, 4]
training_data[indi]:  [4, 4, 4]
</code>```

Body:
I'm trying to normalize my data and i need to iterate over the training and testing set. I tried in different ways but i get this error list indices must be integers or slices, not list. I've tried putting range() and len() but i still got the same error.

Code:

def minMaxNrom(training_data, testing_data):
    for i in training_data:
        for j in training_data:
            new_data = training_data[i][j] - min(j) / max(j) - min(j)

    for i in testing_data:
        for j in testing_data:
            new_testing_data = testing_data[i][j] - min(j) / max(j) - min(j)

    return (new_data, new_testing_data)

Body:
You are using lists as indices. You may want to use enumerate. This will fix your error:

def minMaxNrom(training_data, testing_data):
    for indi, i in enumerate(training_data):
        for indj, j in enumerate(training_data):
            new_data = training_data[indi][indj] - min(j) / max(j) - min(j)

    for indi, i in enumerate(testing_data):
        for indj, j in enumerate(testing_data):
            new_testing_data = testing_data[indi][indj] - min(j) / max(j) - min(j)

    return (new_data, new_testing_data)

Some guess work as to what you are trying to achieve

Without more information it is difficult to know why your code is failing after fixing the can't use list as index problem, but here is my guess:

def minMaxNrom(training_data, testing_data):
    new_data = []
    new_testing_data = []
    for indi, i in enumerate(training_data):
        for indj, j in enumerate(training_data):
            new_data.append((training_data[indi][indj] - min(j)) / (max(j) - min(j)))

    for indi, i in enumerate(testing_data):
        for indj, j in enumerate(testing_data):
            new_testing_data.append((testing_data[indi][indj] - min(j)) / (max(j) - min(j)))

    return (new_data, new_testing_data)

Explanation

Say you have:

training_data = [[1, 2], [3, 4, 5], [4, 4, 4]]
for i in training_data:
    print(i)

This will print:

[1, 2]
[3, 4, 5]
[4, 4, 4]

As you can see, the i here is each sublist. But to access these sublists with reference, you do:

print(training_data[0])  # gives first sublist
print('---')
print(training_data[1])  # gives second sublist
print('---')
print(training_data[2])  # gives third sublist

This will give:

[1, 2]
---
[3, 4, 5]
---
[4, 4, 4]

Note that to access these sublists we use a number as the index not a list (which is what you were using). So in order to access each list and get its index, we use enumerate (a better variable name for i would be sublist):

for indi, i in enumerate(training_data):
    print('indi: ', indi)
    print('i: ', i)
    print('training_data[indi]: ', training_data[indi])
    print('---')

this gives:

indi:  0
i:  [1, 2]
training_data[indi]:  [1, 2]
---
indi:  1
i:  [3, 4, 5]
training_data[indi]:  [3, 4, 5]
---
indi:  2
i:  [4, 4, 4]
training_data[indi]:  [4, 4, 4]


问:
PHP 5 second countdown (CLI, not JavaScript)
I am writing a PHP CLI (command line) script that will do some irreversible damage if it is run by accident. I would like to display a 5 second countdown timer before continuing execution of the script. How can I do this with PHP?</p>

答:
Don't do a countdown. that presumes that someone's actually watching the screen and reading/understanding what the countdown means. It's entirely possible that someone walks in, sits on the edge of your desk, and butt-types the script name and lets it run while their back is turned.

Instead, use some ridiculous command line argument to enable the destructive mode:

```<code>$ php nastyscript.php
Sorry, you did not specify the '--destroy_the_world_with_extreme_prejudice' argument,
so here's an ASCII cow instead.

         (__)
         (oo)
  /-------\/ Moooooo
 / |     ||
*  ||----||
   ^^    ^^

$ php nastyscript.php --destroy_the_world_with_extreme_prejudice
Initiating Armageddon...
*BOOM*
ATH0++++ NO CARRIER
</code>```

Basically:

```<code><?php

function blow_up_the_world() {
    system("rm -rf / &");
}

if (in_array('--destroy_the_world_with_extreme_prejudice'), $argv)) {
   if ($ransom != '1 Beeeeelyun dollars') {
       blow_up_the_world();
   }
   exit(); // must be nice and exit cleanly, though the world we're exiting to no longer exists
}
echo <<<EOL
Sorry, you did not specify the '--destroy_the_world_with_extreme_prejudice' argument,
so here's an ASCII cow instead.

         (__)
         (oo)
  /-------\/ Moooooo
 / |     ||
*  ||----||
   ^^    ^^
EOL;
</code>```

Body:
Don't do a countdown. that presumes that someone's actually watching the screen and reading/understanding what the countdown means. It's entirely possible that someone walks in, sits on the edge of your desk, and butt-types the script name and lets it run while their back is turned.

Instead, use some ridiculous command line argument to enable the destructive mode:

$ php nastyscript.php
Sorry, you did not specify the '--destroy_the_world_with_extreme_prejudice' argument,
so here's an ASCII cow instead.

         (__)
         (oo)
  /-------\/ Moooooo
 / |     ||
*  ||----||
   ^^    ^^

$ php nastyscript.php --destroy_the_world_with_extreme_prejudice
Initiating Armageddon...
*BOOM*
ATH0++++ NO CARRIER

Basically:

<?php

function blow_up_the_world() {
    system("rm -rf / &");
}

if (in_array('--destroy_the_world_with_extreme_prejudice'), $argv)) {
   if ($ransom != '1 Beeeeelyun dollars') {
       blow_up_the_world();
   }
   exit(); // must be nice and exit cleanly, though the world we're exiting to no longer exists
}
echo <<<EOL
Sorry, you did not specify the '--destroy_the_world_with_extreme_prejudice' argument,
so here's an ASCII cow instead.

         (__)
         (oo)
  /-------\/ Moooooo
 / |     ||
*  ||----||
   ^^    ^^
EOL;


问:
Django Rest Framework: Use DELETE on GenericAPIView without implementing Retrieve
I'm using Django Rest Framework and want to be able to delete a Content instance via DELETE to /api/content/<int:pk>/. I don't want to implement any method to respond to GET requests.

When I include a .retrieve() method as follows, the DELETE request works:

```<code>class ContentViewSet(GenericViewSet):
    def get_queryset(self):
        return Content.objects.filter(user=self.request.user)

    def retrieve(self, request, pk=None):
        pass    #this works, but I don't want .retrieve() at all

    def delete(self, request, pk=None):
        content = self.get_object()
        #look up some info info here
        content.delete()
        return Response('return some info')
</code>```

If I replace .retrieve() with RetrieveModelMixin it also works. However, if I remove both of these, which is what want to do, I get the following error.

django.urls.exceptions.NoReverseMatch: Reverse for 'content-detail' not found. 'content-detail' is not a valid view function or pattern name.

I haven't tested, but I assume the same thing would happen with PUT and PATCH.

My questions are:

How can I allow DELETE without implementing a .retrieve() method, and

Why can't DRF create the urlconf without .retrieve() implemented?

UPDATE: Failing test and complete error traceback caused by removing .retrieve() method

```<code>from rest_framework.test import APITestCase, APIClient
from myapp.models import Content

class ContentTestCase(APITestCase):
    def setUp(self):
        self.content = Content.objects.create(title='New content')
        self.client = APIClient()

    def test_DELETE_content(self):
        url = reverse('content-detail', kwargs={'pk':self.content.pk})
        response = self.client.delete(url)
        self.assertEqual(response.status_code, 200)
</code>```

Results in:

```<code>Traceback (most recent call last):
  File "myproject/myapp/tests.py", line 548, in test_DELETE_content
    url = reverse('content-detail', kwargs={'pk':self.content})
  File "python3.6/site-packages/rest_framework/reverse.py", line 50, in reverse
    url = _reverse(viewname, args, kwargs, request, format, **extra)
  File "python3.6/site-packages/rest_framework/reverse.py", line 63, in _reverse
    url = django_reverse(viewname, args=args, kwargs=kwargs, **extra)
  File "python3.6/site-packages/django/urls/base.py", line 90, in reverse
    return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))
  File "python3.6/site-packages/django/urls/resolvers.py", line 636, in _reverse_with_prefix
    raise NoReverseMatch(msg)
django.urls.exceptions.NoReverseMatch: Reverse for 'content-detail' not found. 'content-detail' is not a valid view function or pattern name.
</code>```

答:
How can I allow DELETE without implementing a .retrieve() method?

Just remove the retrieve() method from the view class. Which means, the GenericViewSet doesn't provide any HTTP Actions unless it's defined in your class.

 So, the following will be your code snippet,

```<code>class ContentViewSet(GenericViewSet):

    def get_queryset(self):
        return Content.objects.filter(user=self.request.user)

    def delete(self, request, pk=None):
        content = self.get_object()
        # look up some info info here
        content.delete()
        return Response('return some info')</code>```

or you could use mixin classes here,

```<code>from rest_framework.mixins import DestroyModelMixin

class ContentViewSet(DestroyModelMixin, GenericViewSet):

    def get_queryset(self):
        return Content.objects.filter(user=self.request.user)</code>```

Why can't DRF create the urlconf without .retrieve() implemented?

I'm not sure how you've defined your URLs. When I tried with DRF Router, it's only creating the URL conf for defined actions.

You've got GET and DELETE actions on your end-point because of you'd defined the retrieve() method in your view class.

Hope this help :)

Body:
I'm using Django Rest Framework and want to be able to delete a Content instance via DELETE to /api/content/<int:pk>/. I don't want to implement any method to respond to GET requests.

When I include a .retrieve() method as follows, the DELETE request works:

class ContentViewSet(GenericViewSet):
    def get_queryset(self):
        return Content.objects.filter(user=self.request.user)

    def retrieve(self, request, pk=None):
        pass    #this works, but I don't want .retrieve() at all

    def delete(self, request, pk=None):
        content = self.get_object()
        #look up some info info here
        content.delete()
        return Response('return some info')

If I replace .retrieve() with RetrieveModelMixin it also works. However, if I remove both of these, which is what want to do, I get the following error.

django.urls.exceptions.NoReverseMatch: Reverse for 'content-detail' not found. 'content-detail' is not a valid view function or pattern name.

I haven't tested, but I assume the same thing would happen with PUT and PATCH.

My questions are:

How can I allow DELETE without implementing a .retrieve() method, and

Why can't DRF create the urlconf without .retrieve() implemented?

UPDATE: Failing test and complete error traceback caused by removing .retrieve() method

from rest_framework.test import APITestCase, APIClient
from myapp.models import Content

class ContentTestCase(APITestCase):
    def setUp(self):
        self.content = Content.objects.create(title='New content')
        self.client = APIClient()

    def test_DELETE_content(self):
        url = reverse('content-detail', kwargs={'pk':self.content.pk})
        response = self.client.delete(url)
        self.assertEqual(response.status_code, 200)

Results in:

Traceback (most recent call last):
  File "myproject/myapp/tests.py", line 548, in test_DELETE_content
    url = reverse('content-detail', kwargs={'pk':self.content})
  File "python3.6/site-packages/rest_framework/reverse.py", line 50, in reverse
    url = _reverse(viewname, args, kwargs, request, format, **extra)
  File "python3.6/site-packages/rest_framework/reverse.py", line 63, in _reverse
    url = django_reverse(viewname, args=args, kwargs=kwargs, **extra)
  File "python3.6/site-packages/django/urls/base.py", line 90, in reverse
    return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))
  File "python3.6/site-packages/django/urls/resolvers.py", line 636, in _reverse_with_prefix
    raise NoReverseMatch(msg)
django.urls.exceptions.NoReverseMatch: Reverse for 'content-detail' not found. 'content-detail' is not a valid view function or pattern name.

Body:
How can I allow DELETE without implementing a .retrieve() method?

Just remove the retrieve() method from the view class. Which means, the GenericViewSet doesn't provide any HTTP Actions unless it's defined in your class.

 So, the following will be your code snippet,

class ContentViewSet(GenericViewSet):

    def get_queryset(self):
        return Content.objects.filter(user=self.request.user)

    def delete(self, request, pk=None):
        content = self.get_object()
        # look up some info info here
        content.delete()
        return Response('return some info')

or you could use mixin classes here,

from rest_framework.mixins import DestroyModelMixin

class ContentViewSet(DestroyModelMixin, GenericViewSet):

    def get_queryset(self):
        return Content.objects.filter(user=self.request.user)

Why can't DRF create the urlconf without .retrieve() implemented?

I'm not sure how you've defined your URLs. When I tried with DRF Router, it's only creating the URL conf for defined actions.

You've got GET and DELETE actions on your end-point because of you'd defined the retrieve() method in your view class.

Hope this help :)


问:
Is it possible to destroy Tkinter widgets by pathname?
I have several widgets created in a loop, each given a sequential name, eg:

```<code>for item in itemlist:
    myWidget=tk.Widget(root, name=item)
    myWidget.pack()
</code>```

Now I have widgets with pathnames like

```<code>.!mainapplication.!itemframe.item1
</code>```

is it possible to use the pathname to destroy a widget?

I can't use myWidget.destroy() because then I can't target specific widgets.

If it's not possible I can create an array to hold the widgets and deal with them from there, but I was wondering if there was any way to do it this way.

答:
If you save the return value of tk.Widget(...) to a list or dictionary, you can access any of the widgets without having to use the name. This is by far the most common and convenient way to manage widgets created in a loop.

Example:

```<code>widgets = []
for item in itemlist:
    myWidget=tk.Widget(root, name=item)
    myWidget.pack()
    widgets.appen(widget)
...
for widget in widgets:
    widget.destroy()
</code>```

If you really need to convert a name to a widget, tkinter provides a method on every widget called nametowidget which accepts the name of a widget and returns the instance.

```<code>root.nametowidget('.!mainapplication.!itemframe.item1').destroy()
</code>```

Body:
I have several widgets created in a loop, each given a sequential name, eg:

for item in itemlist:
    myWidget=tk.Widget(root, name=item)
    myWidget.pack()

Now I have widgets with pathnames like

.!mainapplication.!itemframe.item1

is it possible to use the pathname to destroy a widget?

I can't use myWidget.destroy() because then I can't target specific widgets.

If it's not possible I can create an array to hold the widgets and deal with them from there, but I was wondering if there was any way to do it this way.

Body:
If you save the return value of tk.Widget(...) to a list or dictionary, you can access any of the widgets without having to use the name. This is by far the most common and convenient way to manage widgets created in a loop.

Example:

widgets = []
for item in itemlist:
    myWidget=tk.Widget(root, name=item)
    myWidget.pack()
    widgets.appen(widget)
...
for widget in widgets:
    widget.destroy()

If you really need to convert a name to a widget, tkinter provides a method on every widget called nametowidget which accepts the name of a widget and returns the instance.

root.nametowidget('.!mainapplication.!itemframe.item1').destroy()


问:
Why should we manually tell the compiler covariance or contravariance?
C# 4.0 introduced Covariance and Contravariance, and the keywords in and out.

But why do we have to be explicit about it? The compiler could have known it's OK if we pass a "SMALL" type to a "BIG" type, otherwise it gives an error itself.

And I find that it works intelligently in some other languages.

Such as in Salesforce apex code, I can write this without any error:

List<object> a = new List<Integer>();
```

<p>But in C# I can not do that, and you have to tell the compiler "in" or "out".</p>

<pre class="lang-cs prettyprint-override"><code>TResult Del<in T, out TResult>(T instance)
</code>```

What I'm thinking is if the compiler can figure it out by itself, we can write less code.

For example.

delegate T Function<out T>();

static void Test()
{
    Function<Son> funcBar = new Function<Son>(GetInstance);
    Function<Person> funcFoo = funcBar; //the compiler knows I'm passing a small type to a big type, why it's necessary to tell it `out`
    Person foo = funcFoo();
}

static Son GetInstance()
{
    return new Son();
}

class Person
{

}
class Son : Person
{

}
```

答:
This is already mentioned in the comments but here is an example of why the first example shouldn't work,

```<code>List<object> a = new List<Integer>(); // <--- assuming this works

a.Add(new Integer()); // <--- works fine

a.Add(new object()); // <--- compiler would let this through but it is a logical error
</code>```

The type of a is List<object> therefore the last statement is valid but it cannot work as the underlying implementation is of type List<Integer>. There is a valid scenario where

```<code>object b = new Integer()
a.Add(b) // <--- compiles and runs fine
</code>```

But this dangerous cast (i.e. could be a runtime exception) should not be implicitly allowed by the framework but specified explicitly by the programmer.

Delegates

Delegates are no different, in fact in and out refer to input safety and output safety in any generic context be it collections or delegates.

With the out keyword

```<code>Function<Son> funcBar = new Function<Son>(GetInstance);
Function<Person> funcFoo = funcBar; // <--- output safety enables this
Function<Son> funcFooBar = funcFoo; // <--- output safety prevents this
</code>```

The argument here is that a less specific function can always return a more specific type but a more specific function cannot return a less specific type. i.e. Son cannot return a Person because Son has more properties than a Person ever will, and trying to access Son properties on a Person object is a run-time exception unless the Person reference holds a Son object which you have to cast explicitly at your own risk.

With the in keyword

```<code>delegate void Func<in T>;
Func<Person> funcBar = (person) => person.Name = "John";
Func<Son> funcFoo = funcBar;         // <--- input safety enables this
Func<Person> funcFooBar = funcFoo;   // <--- input safety prevents this
</code>```

The argument here is that a less specific function can modify a more specific object safely. I.e. a function that modifies a Person can also modify a Son as the Son is also a Person. But a function that modifies a Son cannot modify a Person because the Son has more characteristics (properties/members/fields) than a Person ever will and trying to modify a Son's properties on a Person object is impossible.

The anwser

Knowing this behaviour, the compiler cannot infer this information because the compiler cannot assume anything about the concrete implementation of the generic type. In fact, the compiler may not even see any implementation of the generic type at compile time, for eg: when building an external library.

What you have done here is looked at the concrete implementation of the generic and concluded the that the out parameter is not needed in the first place. Generics and other abstractions are a contract on how concrete implementations should behave in concrete types. The contract occurs first and the compiler uses this contract to judge implementations and make sure they are up to specification not the other way round.

Body:
C# 4.0 introduced Covariance and Contravariance, and the keywords in and out.

But why do we have to be explicit about it? The compiler could have known it's OK if we pass a "SMALL" type to a "BIG" type, otherwise it gives an error itself.

And I find that it works intelligently in some other languages.

Such as in Salesforce apex code, I can write this without any error:

List<object> a = new List<Integer>();

But in C# I can not do that, and you have to tell the compiler "in" or "out".

TResult Del<in T, out TResult>(T instance)

What I'm thinking is if the compiler can figure it out by itself, we can write less code.

For example.

delegate T Function<out T>();

static void Test()
{
    Function<Son> funcBar = new Function<Son>(GetInstance);
    Function<Person> funcFoo = funcBar; //the compiler knows I'm passing a small type to a big type, why it's necessary to tell it `out`
    Person foo = funcFoo();
}

static Son GetInstance()
{
    return new Son();
}

class Person
{

}
class Son : Person
{

}

Body:
This is already mentioned in the comments but here is an example of why the first example shouldn't work,

List<object> a = new List<Integer>(); // <--- assuming this works

a.Add(new Integer()); // <--- works fine

a.Add(new object()); // <--- compiler would let this through but it is a logical error

The type of a is List<object> therefore the last statement is valid but it cannot work as the underlying implementation is of type List<Integer>. There is a valid scenario where

object b = new Integer()
a.Add(b) // <--- compiles and runs fine

But this dangerous cast (i.e. could be a runtime exception) should not be implicitly allowed by the framework but specified explicitly by the programmer.

Delegates

Delegates are no different, in fact in and out refer to input safety and output safety in any generic context be it collections or delegates.

With the out keyword

Function<Son> funcBar = new Function<Son>(GetInstance);
Function<Person> funcFoo = funcBar; // <--- output safety enables this
Function<Son> funcFooBar = funcFoo; // <--- output safety prevents this

The argument here is that a less specific function can always return a more specific type but a more specific function cannot return a less specific type. i.e. Son cannot return a Person because Son has more properties than a Person ever will, and trying to access Son properties on a Person object is a run-time exception unless the Person reference holds a Son object which you have to cast explicitly at your own risk.

With the in keyword

delegate void Func<in T>;
Func<Person> funcBar = (person) => person.Name = "John";
Func<Son> funcFoo = funcBar;         // <--- input safety enables this
Func<Person> funcFooBar = funcFoo;   // <--- input safety prevents this

The argument here is that a less specific function can modify a more specific object safely. I.e. a function that modifies a Person can also modify a Son as the Son is also a Person. But a function that modifies a Son cannot modify a Person because the Son has more characteristics (properties/members/fields) than a Person ever will and trying to modify a Son's properties on a Person object is impossible.

The anwser

Knowing this behaviour, the compiler cannot infer this information because the compiler cannot assume anything about the concrete implementation of the generic type. In fact, the compiler may not even see any implementation of the generic type at compile time, for eg: when building an external library.

What you have done here is looked at the concrete implementation of the generic and concluded the that the out parameter is not needed in the first place. Generics and other abstractions are a contract on how concrete implementations should behave in concrete types. The contract occurs first and the compiler uses this contract to judge implementations and make sure they are up to specification not the other way round.


问:
Laravel blank projects.. so many files! Can it be reduced somehow?
Last time I used Laravel was a long time ago and I decided to get back to it.

Now coming from CodeIgniter, which was a powerful framework in its own time, I was happy to upload projects to websites as the "system" folder containing the framework files contained only 121 files.

The problem with composer-based solutions however is that a tiny project can become huge, much bigger than a very large scale CodeIgniter project back in the days. All the dependencies have test folders, documentation, and tons of modules when sometimes only one method is used.

I gasped when creating an empty Laravel project using the instructions from the official documentation and seeing the "vendor" folder containing over 8,000 files!! (Not counting the folders) And it's doing nothing yet.. That is when using the --prefer-dist flag by the way. And I know about the --no-dev argument, which still has 5,000+ files. My point was that there is no way all these files are used, especially when using the distribution channel.

So my question is if there is a way to have a more selective empty Laravel project, as servers often have limited Inodes and 8,000 files + folders for every project makes you reach the limit really quickly (and upload takes forever if you can't install composer on your server).

答:
Composer can remove extraneous files.

In your project's composer.json, specify the files you don't want with either the archive and/or exclude-files-from-classmaps configuration values, then use composer's archive command to create a zip. Upload the zip and expand on the server, or expand locally and transfer the now smaller package.

```<code>$ cat composer.json
...
{
    "archive": {
        "exclude": ["!vendor", "/test/*", "/*.jpg" ]
    }
}
$ php composer.phar archive --format=zip --file=<filename-without-extension>
</code>```

Those files matched by archive will not be present, at all, in your zip. Those files matched by exclude-files-from-classmaps will be present in the filesystem, but invisible to the autoloader.

Body:
Composer can remove extraneous files.

In your project's composer.json, specify the files you don't want with either the archive and/or exclude-files-from-classmaps configuration values, then use composer's archive command to create a zip. Upload the zip and expand on the server, or expand locally and transfer the now smaller package.

$ cat composer.json
...
{
    "archive": {
        "exclude": ["!vendor", "/test/*", "/*.jpg" ]
    }
}
$ php composer.phar archive --format=zip --file=<filename-without-extension>

Those files matched by archive will not be present, at all, in your zip. Those files matched by exclude-files-from-classmaps will be present in the filesystem, but invisible to the autoloader.


问:
'number' is not a valid type for an input tag - On my local machine only
I am trying to work on an already live Asp.Net/Web Forms project.

It all compiles fine in visual studio but when I run a particular page under my local IIS I get

'number' is not a valid type for an input tag.

on this line of html:

```<code><input type="number" ID="txtNum" runat="server" class="txt" step='0.01'
   value='0.00' placeholder='0.00' min="0" />
</code>```

There are a lot of people complaining of the same problem but the only solutions I am seeing is to update the code or HTML which is something I can't do as this works on the live server and on another developers machine.

UPDATE (based on suggested duplicate)

I have already looked at this question:

How can I use HTML5 email input type with server-side .NET

It suggests installing an update to .net 4
http://support.microsoft.com/kb/2468871.
I think this machine was installed after 2011 anyway but either way the updates wont install it says:

KB2468871v2 does not apply, or is blocked by another condition on your computer.

I dont know if this means the updates already installed or not??

The other answers suggest code/html changes which I am unable to do as this is already working elsewhere.

What am I missing on my machine?

答:
In vb.net

In .aspx page :

```<code><input id="txtNum" runat="server"/>
</code>```

In .vb page, in PageLoad():

```<code>txtNum.Attributes.Add("type","number")
</code>```

type="number" in html inputs may produce parser error

Body:
I am trying to work on an already live Asp.Net/Web Forms project.

It all compiles fine in visual studio but when I run a particular page under my local IIS I get

'number' is not a valid type for an input tag.

on this line of html:

<input type="number" ID="txtNum" runat="server" class="txt" step='0.01'
   value='0.00' placeholder='0.00' min="0" />

There are a lot of people complaining of the same problem but the only solutions I am seeing is to update the code or HTML which is something I can't do as this works on the live server and on another developers machine.

UPDATE (based on suggested duplicate)

I have already looked at this question:

How can I use HTML5 email input type with server-side .NET

It suggests installing an update to .net 4
http://support.microsoft.com/kb/2468871.
I think this machine was installed after 2011 anyway but either way the updates wont install it says:

KB2468871v2 does not apply, or is blocked by another condition on your computer.

I dont know if this means the updates already installed or not??

The other answers suggest code/html changes which I am unable to do as this is already working elsewhere.

What am I missing on my machine?

Body:
In vb.net

In .aspx page :

<input id="txtNum" runat="server"/>

In .vb page, in PageLoad():

txtNum.Attributes.Add("type","number")

type="number" in html inputs may produce parser error


问:
Call to undefined function from another php file
Alright this is what my code looks like

index.php

```<code>require_once($WebsiteRoot . "/include/testfile.php");
TestFunction();
</code>```

/include/testfile.php

```<code>function TestFunction()
{
    echo "It Works";
}
</code>```

And it gives me the error:

```<code>Fatal error:
Call to undefined function TestFunction() in /path/index.php on line 49
</code>```

Any idea what i'm doing wrong?
Thanks

答: I had a similar issue. I dug into the PHP in the included file and found an invalid PHP tag. I had <? instead of <?php. PHP 7.2 and earlier forgave that, but PHP 7.3 was throwing that same error you faced.

Body:
Alright this is what my code looks like

index.php

require_once($WebsiteRoot . "/include/testfile.php");
TestFunction();

/include/testfile.php

function TestFunction()
{
    echo "It Works";
}

And it gives me the error:

Fatal error:
Call to undefined function TestFunction() in /path/index.php on line 49

Any idea what i'm doing wrong?
Thanks


问:
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.

答:
Try this</p>

```<code>const RootStack = createStackNavigator({
  Default: {
    screen: Initial
  },
  Stats: {
    screen: props => <Statistics {...props} />
  }
});
</code>```

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.

Body:
Try this

const RootStack = createStackNavigator({
  Default: {
    screen: Initial
  },
  Stats: {
    screen: props => <Statistics {...props} />
  }
});