问:
Fetching array from online database for android app using volley
First I have to tell that I'm pretty new to android studio & PHP.

I have managed to make an application with login, uploading and searching the online database.

I used volley with the method POST.

Everything is fine & perfect if the search result is single.

The problem is when there is more than one result that need to be stored in an array. In this case my code is retrieving only the last result.

I know there are a lot of other methods available online but as I'm new I wasn't able to understand them and thus edit them according to my data.

Here is my JAVA MainActivity code:

```<code>package com.example.dell.myapplicationo;

import android.app.AlertDialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.Volley;

import org.json.JSONException;
import org.json.JSONObject;

public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    final EditText etname = (EditText) findViewById(R.id.etname);
    final TextView b = (TextView) findViewById(R.id.tvb);
    final Button c = (Button) findViewById(R.id.c);

    c.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final String name = etname.getText().toString();

            // Response received from the server
            Response.Listener<String> responseListener = new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {
                        JSONObject jsonResponse = new JSONObject(response);
                        boolean success = jsonResponse.getBoolean("success");

                        if (success) {
                            String name = jsonResponse.getString("name");
                            String family = jsonResponse.getString("family");
                            String date= jsonResponse.getString("date");
                            String time= jsonResponse.getString("time");

                            // Display
                            String message = name + family + date + time;
                            b.setText(message);

                        } else {
                            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                            builder.setMessage("Not Found")
                                    .setNegativeButton("Retry", null)
                                    .create()
                                    .show();
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            };

            SearchRequest searchRequest = new SearchRequest(name, responseListener);
            RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
            queue.add(searchRequest);
        }
    });
}
}
</code>```

Here is my SearchRequest class code:

```<code>import com.android.volley.Response;
import com.android.volley.toolbox.StringRequest;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class SearchRequest extends StringRequest {
private static final String LOGIN_REQUEST_URL = "http://MYURL.hol.es/search.php";
private Map<String, String> params;

public SearchRequest(String name, Response.Listener<String> listener) {
    super(Method.POST, LOGIN_REQUEST_URL, listener, null);
    params = new HashMap<>();
    params.put("name", name);
}

@Override
public Map<String, String> getParams() {
    return params;
}
}
</code>```

Finally here is my php code (search.php)

```<code><?php
$con = mysqli_connect("mysql.hostinger.in", "username", "password", "db");

    $name= $_POST["name"];

    $statement = mysqli_prepare($con, "SELECT * FROM table WHERE name = ?");
    mysqli_stmt_bind_param($statement, "s", $suspect);
    mysqli_stmt_execute($statement);

    mysqli_stmt_store_result($statement);
    mysqli_stmt_bind_result($statement, $name, $family, $date, $time);

    $response = array();
    $response["success"] = false;

    while(mysqli_stmt_fetch($statement)){
        $response["success"] = true;
        $response["name"] = $name;
        $response["family"] = $family;
        $response["date"] = $date;
        $response["time"] = $time;

    }

    echo json_encode($response);
?>
</code>```

答:
Because, after each iteration, you are overriding previous value here

```<code> while(mysqli_stmt_fetch($statement)){
        $response["success"] = true;
        $response["name"] = $name;
        $response["family"] = $family;
        $response["date"] = $date;
        $response["time"] = $time;

    }
</code>```

You can probably change above code as :

```<code>$response = array();
$arr = array();
$response["success"] = false;

while(mysqli_stmt_fetch($statement)){
    $response["success"] = true;
    $response["name"] = $name;
    $response["family"] = $family;
    $response["date"] = $date;
    $response["time"] = $time;
    $arr[] = $response;
}
echo json_encode($arr);
</code>```

Body:
First I have to tell that I'm pretty new to android studio & PHP.

I have managed to make an application with login, uploading and searching the online database.

I used volley with the method POST.

Everything is fine & perfect if the search result is single.

The problem is when there is more than one result that need to be stored in an array. In this case my code is retrieving only the last result.

I know there are a lot of other methods available online but as I'm new I wasn't able to understand them and thus edit them according to my data.

Here is my JAVA MainActivity code:

package com.example.dell.myapplicationo;

import android.app.AlertDialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.Volley;

import org.json.JSONException;
import org.json.JSONObject;

public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    final EditText etname = (EditText) findViewById(R.id.etname);
    final TextView b = (TextView) findViewById(R.id.tvb);
    final Button c = (Button) findViewById(R.id.c);

    c.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final String name = etname.getText().toString();

            // Response received from the server
            Response.Listener<String> responseListener = new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {
                        JSONObject jsonResponse = new JSONObject(response);
                        boolean success = jsonResponse.getBoolean("success");

                        if (success) {
                            String name = jsonResponse.getString("name");
                            String family = jsonResponse.getString("family");
                            String date= jsonResponse.getString("date");
                            String time= jsonResponse.getString("time");

                            // Display
                            String message = name + family + date + time;
                            b.setText(message);

                        } else {
                            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                            builder.setMessage("Not Found")
                                    .setNegativeButton("Retry", null)
                                    .create()
                                    .show();
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            };

            SearchRequest searchRequest = new SearchRequest(name, responseListener);
            RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
            queue.add(searchRequest);
        }
    });
}
}

Here is my SearchRequest class code:

import com.android.volley.Response;
import com.android.volley.toolbox.StringRequest;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class SearchRequest extends StringRequest {
private static final String LOGIN_REQUEST_URL = "http://MYURL.hol.es/search.php";
private Map<String, String> params;

public SearchRequest(String name, Response.Listener<String> listener) {
    super(Method.POST, LOGIN_REQUEST_URL, listener, null);
    params = new HashMap<>();
    params.put("name", name);
}

@Override
public Map<String, String> getParams() {
    return params;
}
}

Finally here is my php code (search.php)

<?php
$con = mysqli_connect("mysql.hostinger.in", "username", "password", "db");

    $name= $_POST["name"];

    $statement = mysqli_prepare($con, "SELECT * FROM table WHERE name = ?");
    mysqli_stmt_bind_param($statement, "s", $suspect);
    mysqli_stmt_execute($statement);

    mysqli_stmt_store_result($statement);
    mysqli_stmt_bind_result($statement, $name, $family, $date, $time);

    $response = array();
    $response["success"] = false;

    while(mysqli_stmt_fetch($statement)){
        $response["success"] = true;
        $response["name"] = $name;
        $response["family"] = $family;
        $response["date"] = $date;
        $response["time"] = $time;

    }

    echo json_encode($response);
?>

Body:
Because, after each iteration, you are overriding previous value here

 while(mysqli_stmt_fetch($statement)){
        $response["success"] = true;
        $response["name"] = $name;
        $response["family"] = $family;
        $response["date"] = $date;
        $response["time"] = $time;

    }

You can probably change above code as :

$response = array();
$arr = array();
$response["success"] = false;

while(mysqli_stmt_fetch($statement)){
    $response["success"] = true;
    $response["name"] = $name;
    $response["family"] = $family;
    $response["date"] = $date;
    $response["time"] = $time;
    $arr[] = $response;
}
echo json_encode($arr);


来源: stackexchange

问:
I just can't destroy a session in php
When I logout by destroying the session and start another one it always shows me the first session info I started $_SESSION['username'];

What I mean here is that :
I started a session the first time I logged with this username --> AAAAAA
And destroyed the session using the file logout.php which contains this code :

```<code>session_start();
session_destroy();
header("location: login.php");
</code>```

and login with another username ---> BBBBBB
and it always shows me the first username I logged in with---> AAAAAA

Where is the problem here

Here is the code (login.php)

```<code><?php
        session_start();
        require_once "config/db.php";
        if(isset($_POST['login'])){
        $username       = trim(mysql_real_escape_string($_POST['username']));
        $password       = trim(mysql_real_escape_string(md5($_POST['password'])));
        $query          = mysql_query("SELECT * FROM `users` WHERE username='$username' AND password='$password' ")  or die(mysql_error());
         $rows           = mysql_num_rows($query);

        if($rows == 1){

            while($info = mysql_fetch_object($query)){
                $dbusername = $info->username;
                $dbpassword = $info->password;
            }

            if($dbusername == $username && $dbpassword == $password){
                header("Location: index.php");
                $_SESSION['username'] = $username;
            }

        }else{

        }
    }
?>
</code>```

the index.php :

```<code>  <?php session_start();?>
  <h3><?php echo $_SESSION['username']; ?></h3>
</code>```

答:
I agree with @Valery Viktorovsky but,
Since PHP 7 you cannot use session_regenerate_id(true); after you destroy the session...

the Changelog HERE Says :

```<code>7.0.0 - session_regenerate_id() saves old session data before closing.
</code>```

This one works in PHP 7 or later:

```<code>ob_start();
session_start();
session_unset();
session_regenerate_id(true);
session_unset();
session_destroy();
session_write_close();
setcookie(session_name(),'',0,'/');
header('LOCATION: index.php');
</code>```

so you can try this out if you wan't to

ContentLicense: CC BY-SA 3.0

Title: I just can't destroy a session in php

Body:
When I logout by destroying the session and start another one it always shows me the first session info I started $_SESSION['username'];

What I mean here is that :
I started a session the first time I logged with this username --> AAAAAA
And destroyed the session using the file logout.php which contains this code :

session_start();
session_destroy();
header("location: login.php");

and login with another username ---> BBBBBB
and it always shows me the first username I logged in with---> AAAAAA

Where is the problem here

Here is the code (login.php)

<?php
        session_start();
        require_once "config/db.php";
        if(isset($_POST['login'])){
        $username       = trim(mysql_real_escape_string($_POST['username']));
        $password       = trim(mysql_real_escape_string(md5($_POST['password'])));
        $query          = mysql_query("SELECT * FROM `users` WHERE username='$username' AND password='$password' ")  or die(mysql_error());
         $rows           = mysql_num_rows($query);

        if($rows == 1){

            while($info = mysql_fetch_object($query)){
                $dbusername = $info->username;
                $dbpassword = $info->password;
            }

            if($dbusername == $username && $dbpassword == $password){
                header("Location: index.php");
                $_SESSION['username'] = $username;
            }

        }else{

        }
    }
?>

the index.php :

  <?php session_start();?>

<?php echo $_SESSION['username']; ?>

Body:
I agree with @Valery Viktorovsky but,
Since PHP 7 you cannot use session_regenerate_id(true); after you destroy the session...

the Changelog HERE Says :

7.0.0 - session_regenerate_id() saves old session data before closing.

This one works in PHP 7 or later:

ob_start();
session_start();
session_unset();
session_regenerate_id(true);
session_unset();
session_destroy();
session_write_close();
setcookie(session_name(),'',0,'/');
header('LOCATION: index.php');

so you can try this out if you wan't to


问:
Real time audio processing Swift
Our app continuously records and processes audio from iPhone mic.

Currently I use AVAudioRecorder and AVFoundation and record audio inout into 8 sec ".wav" files.

Instead I want continuously to record audio input into buffer and process 8 sec length buffer's chunks.

How can I record audio input into buffer and how can I read 8 sec length chunks from there?

Thanks!

答:
You could receive the raw PCM a number of ways (in AV Foundation: AVCaptureAudioDataOutput from an AVCaptureDevice, or AVAudioEngine with a processing tap inserted; in Audio Toolbox: Audio Queue Services, the RemoteIO audio unit), then to write the file, you could use Audio Toolbox's AudioFile or ExtAudioFile, just counting up how many frames you've written and deciding when it's time to start a new 8 sec file.

As Rhythmic Fistman notes above, it would be safer if you did something like

capture callbacks --pushes-to--> ring buffer <--pulls-from-- file-writing code

Because when you're closing one file and opening another, the capture callbacks are still going to be coming in, and if you block on file I/O you stand a very good chance of dropping some data on the floor.

I suppose another approach would be to just fill an 8 sec buffer in memory from your callbacks, and when it's full, have another thread write that file while you malloc a new buffer and start recording into that (obviously, the file writer would dispose the old buffer when it's done).

Edit: Also, I didn't see anything about Swift in your question, but any of this should work fine from Swift or C/Obj-C.

Title: Real time audio processing Swift


问:
How to decrypt blocks encrypted with RSA?
I'm still on my RSA project, and now I can successfully create the keys, and encrypt a string with them

```<code>def encrypt(clear_message, public_key):

    clear_list = convert_into_unicode (clear_message)

    n = public_key[0]
    e = public_key[1]

    message_chiffre = str()

    for i, value in enumerate (clear_list) :
        encrypted_value = str( pow (int(value), e, n) )

        encrypted_message += (encrypted_value )

    return encrypted_message

def convert_into_unicode (clear_message):

    str_unicode = ''

    for car in clear_message:
        str_unicode += str (ord (car))

    if len (str_unicode ) % 5 != 0:
        str_unicode += (5 - len (str_unicode ) % 5) * '0'

    clear_list = []

    i = 5

    while i <= len (str_unicode ):

        clear_list .append (str_unicode [i-5:i])

        i += 5

    return liste_claire
</code>```

For example, encrypting the message 'Hello World' returns ['72101', '10810', '81113', '28711', '11141', '08100', '32330'] as clear_list then
'3863   111   1616   3015   1202   341   4096' as encrypted_message

The encrypt () function uses the other function to convert the string into a list of the Unicode values but put in blocks because I've read that otherwise, it would be easy to find the clear message only with frequency analysis.

Is it really that easy?

And as it probably is, I come to my main question. As you know, the Unicode values of a character are either double-digits or triple-digits. Before the encryption, the Unicode values are separated into blocks of 5 digits ('stack' -> '115 116 97 99 107' -> '11511 69799 10700')

But the problem is when I want to decrypt this, how do I know where I have to separate that string so that one number represents one character?

I mean, the former Unicode value could be either 11 or 115 (I know it couldn't really be 11, but that's only as an example). So to decrypt and then get back the character, the problem is, I don't know how much digits I have to take.

I had thought of adding a 0 when the Unicode value is < 100, but

Then it's easy to do the same thing as before with the frequency analysis

Still, when I encrypt it, '087' can result in '467' and '089' can result in '046', so the problem is still here.

答:
You're trying to solve real world problems with a toy RSA problem. The frequency analysis can be performed because no random padding of the plaintext message has been used. Random padding is required to make RSA secure.

For this kind of problem it is enough to directly use the Unicode code point (an integer value) per character as input to RSA. RSA can however only directly encrypt values in the range [0..N) where N is the modulus. If you input a larger value x then value will first be converted into the value x modulus N. In that case you loose information and decryption will not be deterministic anymore.

As for the ciphertext, just make this the string representation of the integer values separated by spaces and split them to read them in. This will take more space, but RSA always has a certain overhead.

If you want to implement secure RSA then please read into PKCS#1 standard and beware of time attacks etc. And, as Wyzard already indicated, please use hybrid cryptography (using a symmetric encryption in addition to RSA).

Or use a standard library, now you understand how RSA works in principle.

ContentLicense: CC BY-SA 4.0

Body:
I'm still on my RSA project, and now I can successfully create the keys, and encrypt a string with them

def encrypt(clear_message, public_key):

    clear_list = convert_into_unicode (clear_message)

    n = public_key[0]
    e = public_key[1]

    message_chiffre = str()

    for i, value in enumerate (clear_list) :
        encrypted_value = str( pow (int(value), e, n) )

        encrypted_message += (encrypted_value )

    return encrypted_message

def convert_into_unicode (clear_message):

    str_unicode = ''

    for car in clear_message:
        str_unicode += str (ord (car))

    if len (str_unicode ) % 5 != 0:
        str_unicode += (5 - len (str_unicode ) % 5) * '0'

    clear_list = []

    i = 5

    while i <= len (str_unicode ):

        clear_list .append (str_unicode [i-5:i])

        i += 5

    return liste_claire

For example, encrypting the message 'Hello World' returns ['72101', '10810', '81113', '28711', '11141', '08100', '32330'] as clear_list then
'3863   111   1616   3015   1202   341   4096' as encrypted_message

The encrypt () function uses the other function to convert the string into a list of the Unicode values but put in blocks because I've read that otherwise, it would be easy to find the clear message only with frequency analysis.

Is it really that easy?

And as it probably is, I come to my main question. As you know, the Unicode values of a character are either double-digits or triple-digits. Before the encryption, the Unicode values are separated into blocks of 5 digits ('stack' -> '115 116 97 99 107' -> '11511 69799 10700')

But the problem is when I want to decrypt this, how do I know where I have to separate that string so that one number represents one character?

I mean, the former Unicode value could be either 11 or 115 (I know it couldn't really be 11, but that's only as an example). So to decrypt and then get back the character, the problem is, I don't know how much digits I have to take.

I had thought of adding a 0 when the Unicode value is < 100, but

Then it's easy to do the same thing as before with the frequency analysis

Still, when I encrypt it, '087' can result in '467' and '089' can result in '046', so the problem is still here.


问:
Inline CSS styles in JSP
I am trying to render THIS in JSP. I want the styling to be inline right now as I am in the early stages of development .

My JSP code is

```<code><%
%><%@include file="/libs/foundation/global.jsp"%><%
%><%@page session="false" %><%
%><%

<style type="text/css">
.line {
width:70%;
}
.line:after {
content:'';
position: absolute;
border-style: solid;
border-width: 15px 15px 0;
border-color: #FFFFFF transparent;
display: block;
width: 0;
z-index: 1;
top: 8px;
left: 45%;
}
.line:before {
content:'';
position: absolute;
border-style: solid;
border-width: 15px 15px 0;
border-color: #7F7F7F transparent;
display: block;
width: 0;
z-index: 1;
top: 9px;
left: 45%;
}
</style>
<%@include file="/apps//global.jsp"%>
<hr class="line">
%>
</code>```

I am certain the css styling is fince as it renders correctly in fiddle.

Is there a way I can fix this? Any help is much appreciated. Thanks much.

答: for each and every section define classes for css and include it in  using </p>

Title: Inline CSS styles in JSP

Body:
I am trying to render THIS in JSP. I want the styling to be inline right now as I am in the early stages of development .

My JSP code is

<%
%><%@include file="/libs/foundation/global.jsp"%><%
%><%@page session="false" %><%
%><%

<%@include file="/apps//global.jsp"%>

%>

I am certain the css styling is fince as it renders correctly in fiddle.

Is there a way I can fix this? Any help is much appreciated. Thanks much.


问:
React-native flex height
I have 3 components and I am trying to set their heights (header, body, footer) but when it renders, each component has just the height of one line of text it contains.

```<code>import React from 'react';
import { View, Text } from 'react-native';
import Header from './Header';
import Body from './Body';
import Footer from './Footer';
import * as globalStyles from '../styles/global';

const HomeScreen = () => (
  <View style={{ flex: 1 }}>
    <Header style={{ flex: 1 }} title={'MyTitle'}>
      <Text>Component</Text>
    </Header>
    <Body style={{ flex: 3 }}>
      <Text>my body</Text>
    </Body>
    <Footer style={{ flex: 1 }}>
      <Text>my footer</Text>
    </Footer>
  </View>
);

export default HomeScreen;
</code>```

App

```<code>import React from 'react';
import { Provider } from 'react-redux';
import HomeScreen from './components/HomeScreen';
import createStore from './createStore';

const store = createStore();

export default () => (
  <Provider store={store}>
    <HomeScreen />
  </Provider>
);
</code>```

Header

```<code>import React, { PropTypes } from 'react';
import { View, Text, StyleSheet } from 'react-native';
import * as globalStyles from '../styles/global';

const Header = ({ children, title }) => (
  <View>
    <Text style={globalStyles.COMMON_STYLES.text}>
      {children}
      {title}
      {title}
    </Text>
  </View>
);

Header.propTypes = {
  children: PropTypes.node
};

const styles = StyleSheet.create({
  header: {
    paddingTop: 20
  }
});
export default Header;
</code>```

Footer

```<code>import React, { PropTypes } from 'react';
import { View, Text, StyleSheet } from 'react-native';
import * as globalStyles from '../styles/global';

const Footer = ({ children }) => (
  <View>
    <Text style={globalStyles.COMMON_STYLES.text}>
      {children}
    </Text>
  </View>
);

Footer.propTypes = {
  children: PropTypes.node.isRequired
};

const styles = StyleSheet.create({
  header: {
    marginTop: 20,
    flex: 1,
  }
});
export default Footer;
</code>```

Body

```<code>import React, { PropTypes } from 'react';
import { View, Text, StyleSheet } from 'react-native';
import * as globalStyles from '../styles/global';

const Body = ({ children, title }) => (
  <View>
    <Text style={globalStyles.COMMON_STYLES.text}>
      {children}
      {title}
      {title}
    </Text>
  </View>
);

Body.propTypes = {
  children: PropTypes.node
};

const styles = StyleSheet.create({
  header: {
    marginTop: 20,
    flex: 1,
  }
});
export default Body;
</code>```

global styles

```<code>import { StyleSheet } from 'react-native';

export const BG_COLOR = '#343336';
export const BAR_COLOR = '#4e4d52';
export const TEXT_COLOR = '#e5dbda';
export const HEADER_TEXT_COLOR = '#fff';
export const MUTED_COLOR = '#8e8786';
export const LINK_COLOR = '#48e9d9';
export const ACCENT_COLORS = ['#d31d65', '#751c53', '#c248c0', '#7d6e8b', '#bbc6f7'];

export const COMMON_STYLES = StyleSheet.create({
  pageContainer: {
    backgroundColor: BG_COLOR,
    marginTop: 0,
    paddingTop: 5,
    paddingHorizontal: 10
  },
  text: {
    color: TEXT_COLOR,
    fontFamily: 'Helvetica Neue'
  }
});
</code>```

My understanding is that the Body should be 3 x the height of header or footer.

React-native:

```<code>react-native-cli: 2.0.1
react-native: 0.41.2
</code>```

答:
EDIT
Flex should be given to your root containers of the header, body and footer components. Header, Footer and Body are custom components, the style props won't be applicable to them, the style you applied just get passed as a prop

```<code>const Footer = ({ children }) => (
  <View style={{ flex: 1 }}>  // root container of footer
    <Text style={globalStyles.COMMON_STYLES.text}>
      {children}
    </Text>
  </View>
);

const Body = ({ children, title }) => (
   <View style={{ flex: 3 }}>
    <Text style={globalStyles.COMMON_STYLES.text}>
      {children}
      {title}
      {title}
    </Text>
   </View>
);

const Header = ({ children, title }) => (
  <View style={{ flex: 1 }}> // root container of header
    <Text style={globalStyles.COMMON_STYLES.text}>
      {children}
      {title}
      {title}
    </Text>
  </View>
);
</code>```

Hope its working for you

Title: React-native flex height

Body:
I have 3 components and I am trying to set their heights (header, body, footer) but when it renders, each component has just the height of one line of text it contains.

import React from 'react';
import { View, Text } from 'react-native';
import Header from './Header';
import Body from './Body';
import Footer from './Footer';
import * as globalStyles from '../styles/global';

const HomeScreen = () => (
  <View style={{ flex: 1 }}>

      <Text>Component</Text>

      <Text>my body</Text>

      <Text>my footer</Text>

  </View>
);

export default HomeScreen;

App

import React from 'react';
import { Provider } from 'react-redux';
import HomeScreen from './components/HomeScreen';
import createStore from './createStore';

const store = createStore();

export default () => (
  <Provider store={store}>
    <HomeScreen />
  </Provider>
);

Header

import React, { PropTypes } from 'react';
import { View, Text, StyleSheet } from 'react-native';
import * as globalStyles from '../styles/global';

const Header = ({ children, title }) => (
  <View>
    <Text style={globalStyles.COMMON_STYLES.text}>
      {children}
      {title}
      {title}
    </Text>
  </View>
);

Header.propTypes = {
  children: PropTypes.node
};

const styles = StyleSheet.create({
  header: {
    paddingTop: 20
  }
});
export default Header;

Footer

import React, { PropTypes } from 'react';
import { View, Text, StyleSheet } from 'react-native';
import * as globalStyles from '../styles/global';

const Footer = ({ children }) => (
  <View>
    <Text style={globalStyles.COMMON_STYLES.text}>
      {children}
    </Text>
  </View>
);

Footer.propTypes = {
  children: PropTypes.node.isRequired
};

const styles = StyleSheet.create({
  header: {
    marginTop: 20,
    flex: 1,
  }
});
export default Footer;

Body

import React, { PropTypes } from 'react';
import { View, Text, StyleSheet } from 'react-native';
import * as globalStyles from '../styles/global';

const Body = ({ children, title }) => (
  <View>
    <Text style={globalStyles.COMMON_STYLES.text}>
      {children}
      {title}
      {title}
    </Text>
  </View>
);

Body.propTypes = {
  children: PropTypes.node
};

const styles = StyleSheet.create({
  header: {
    marginTop: 20,
    flex: 1,
  }
});
export default Body;

global styles

import { StyleSheet } from 'react-native';

export const BG_COLOR = '#343336';
export const BAR_COLOR = '#4e4d52';
export const TEXT_COLOR = '#e5dbda';
export const HEADER_TEXT_COLOR = '#fff';
export const MUTED_COLOR = '#8e8786';
export const LINK_COLOR = '#48e9d9';
export const ACCENT_COLORS = ['#d31d65', '#751c53', '#c248c0', '#7d6e8b', '#bbc6f7'];

export const COMMON_STYLES = StyleSheet.create({
  pageContainer: {
    backgroundColor: BG_COLOR,
    marginTop: 0,
    paddingTop: 5,
    paddingHorizontal: 10
  },
  text: {
    color: TEXT_COLOR,
    fontFamily: 'Helvetica Neue'
  }
});

My understanding is that the Body should be 3 x the height of header or footer.

React-native:

react-native-cli: 2.0.1
react-native: 0.41.2

Body:
EDIT
Flex should be given to your root containers of the header, body and footer components. Header, Footer and Body are custom components, the style props won't be applicable to them, the style you applied just get passed as a prop

const Footer = ({ children }) => (
  <View style={{ flex: 1 }}>  // root container of footer
    <Text style={globalStyles.COMMON_STYLES.text}>
      {children}
    </Text>
  </View>
);

const Body = ({ children, title }) => (
   <View style={{ flex: 3 }}>
    <Text style={globalStyles.COMMON_STYLES.text}>
      {children}
      {title}
      {title}
    </Text>
   </View>
);

const Header = ({ children, title }) => (
  <View style={{ flex: 1 }}> // root container of header
    <Text style={globalStyles.COMMON_STYLES.text}>
      {children}
      {title}
      {title}
    </Text>
  </View>
);

Hope its working for you


问:
How do I center text in Swift?
In a Swift playground, how do I center a UILabel inside of a UIViewController?

When I use title.center = CGPoint(x: vc.view.frame.width / 2, y: 20) the text goes off of the screen.

This is the problem

If it helps, here's my code.

```<code>import UIKit
import PlaygroundSupport

// Set up ViewController and other things
var vc = UIViewController()
vc.view.frame.size.height = 75
vc.view.backgroundColor = .white

let title = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 50))
title.textAlignment = .center
title.center = vc.view.center
title.text = "Which code is correct?"
vc.view.addSubview(title)

PlaygroundPage.current.liveView = vc
</code>```

答:
The special problem with swift playgrounds is, that the actual frame of the view controller will only be updated correctly, after the view is loaded / displayed on screen. That means putting the line for centering the label after the line for setting the live view should help:

```<code>PlaygroundPage.current.liveView = vc
title.center = vc.view.center
vc.view.addSubview(title)
</code>```

Title: How do I center text in Swift?

Body:
In a Swift playground, how do I center a UILabel inside of a UIViewController?

When I use title.center = CGPoint(x: vc.view.frame.width / 2, y: 20) the text goes off of the screen.

This is the problem

If it helps, here's my code.

import UIKit
import PlaygroundSupport

// Set up ViewController and other things
var vc = UIViewController()
vc.view.frame.size.height = 75
vc.view.backgroundColor = .white

let title = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 50))
title.textAlignment = .center
title.center = vc.view.center
title.text = "Which code is correct?"
vc.view.addSubview(title)

PlaygroundPage.current.liveView = vc

Body:
The special problem with swift playgrounds is, that the actual frame of the view controller will only be updated correctly, after the view is loaded / displayed on screen. That means putting the line for centering the label after the line for setting the live view should help:

PlaygroundPage.current.liveView = vc
title.center = vc.view.center
vc.view.addSubview(title)


问:
Delete function of a binary search tree not working properly
This is a delete function of a binary search tree coded in C, but this is not working properly. The node which is supposed to be deleted is replaced by a garbage value.

```<code>void delete(struct node* root,int data)
{
{
    struct node* t1;
    if(root==0) {
        printf("element not found\n");
    } else if(data>root->data) {
        delete(root->right,data);
    } else if(data<root->data) {
        delete(root->left,data);
    } else {
        if(root->right&&root->left) {
            t1=findmin(root->right);
            root->data=t1->data;
            free(t1);
        } else {
            t1=root;
            if(root->right) {
                root=root->right;
            } else if(root->left) {
                root=root->left;
            }
            free(t1);
        }
    }
}
</code>```

it is working per se, but the node  is not getting deleted and is replaced by some garbage value.

```<code>struct node* findmin(struct node* t) {
    if(t==NULL) {
        return NULL;
    } else if(t->left) {
        findmin(t->left);
    } else
        return t;
}
</code>```

答:
You are passing root in the function parameters and then inside the following block of your code you are reassigning it.

```<code>            else
        {
                t1=root;
                if(root->right)
                {
                        root=root->right;
                }
                else if(root->left)
                {
                        root=root->left;
                }
                free(t1);
        }
</code>```

This reassignment is temporary to current function call (because it's been passed by value).
alternatively you can do the same is by returning the new root of the tree after deletion of the specified node.

```<code>struct node* delete(struct node* root, int key)
{
    if (root == NULL) return root;

    if (key < root->key)
        root->left = delete(root->left, key);

    else if (key > root->key)
        root->right = delete(root->right, key);

    else
    {
        // node with only one child or no child
        if (root->left == NULL)
        {
            struct node *temp = root->right;
            free(root);
            return temp;
        }
        else if (root->right == NULL)
        {
            struct node *temp = root->left;
            free(root);
            return temp;
        }

        struct node* temp = findmin(root->right);

        root->key = temp->key;

        root->right = delete(root->right, temp->key);
    }
    return root;
}
</code>```

Body:
This is a delete function of a binary search tree coded in C, but this is not working properly. The node which is supposed to be deleted is replaced by a garbage value.

void delete(struct node* root,int data)
{
{
    struct node* t1;
    if(root==0) {
        printf("element not found\n");
    } else if(data>root->data) {
        delete(root->right,data);
    } else if(data<root->data) {
        delete(root->left,data);
    } else {
        if(root->right&&root->left) {
            t1=findmin(root->right);
            root->data=t1->data;
            free(t1);
        } else {
            t1=root;
            if(root->right) {
                root=root->right;
            } else if(root->left) {
                root=root->left;
            }
            free(t1);
        }
    }
}

it is working per se, but the node  is not getting deleted and is replaced by some garbage value.

struct node* findmin(struct node* t) {
    if(t==NULL) {
        return NULL;
    } else if(t->left) {
        findmin(t->left);
    } else
        return t;
}

Body:
You are passing root in the function parameters and then inside the following block of your code you are reassigning it.

            else
        {
                t1=root;
                if(root->right)
                {
                        root=root->right;
                }
                else if(root->left)
                {
                        root=root->left;
                }
                free(t1);
        }

This reassignment is temporary to current function call (because it's been passed by value).
alternatively you can do the same is by returning the new root of the tree after deletion of the specified node.

struct node* delete(struct node* root, int key)
{
    if (root == NULL) return root;

    if (key < root->key)
        root->left = delete(root->left, key);

    else if (key > root->key)
        root->right = delete(root->right, key);

    else
    {
        // node with only one child or no child
        if (root->left == NULL)
        {
            struct node *temp = root->right;
            free(root);
            return temp;
        }
        else if (root->right == NULL)
        {
            struct node *temp = root->left;
            free(root);
            return temp;
        }

        struct node* temp = findmin(root->right);

        root->key = temp->key;

        root->right = delete(root->right, temp->key);
    }
    return root;
}


问:
Recommended structure for high traffic website
I'm rewriting a big website, that needs very solid architecture, here are my few questions, and pardon me for mixing apples and oranges and probably kiwi too:) I did a lot of research and ended up totally confused.

Main question: Which approach would you take in building a big website expected to grow in every way?

Single entry point, pages data in the database, pulled by associating GET variable with database entry (?pageid=whatever)

Single entry point, pages data in separate files, included based on GET variable (?pageid=whatever would include whatever.php)

MVC (Alright guys, I'm all for it, but can't grasp the concept besides checking all tutorials and frameworks out there, do they store "view" in database? Seems to me from examples that if you have 1000 pages of same kind they can be shaped by 1 model, but I'll still need to have 1000 "views" files?)

PAC - this sounds even more logical to me, but didn't find much resources - if this is a good way to go, can you recommend any books or links?

DAL/DAO/DDD - i learned about these terms by diligently reading through stack overflow before posting question. Not sure if it belongs to this list

Sit down and create my own architecture (likely to do if nobody enlightens me here:)

Something not mentioned...

Thanks.

答: If you're creating a "big" website and don't fully grasp MVC or a web framework then a CMS might be a better route since you can expand it with plugins as you see fit.  With this route you can worry more about the content and page structure rather than the platform.  As long as you pick the appropriate CMS.</p>

ContentLicense: CC BY-SA 2.5


问:
How to add a default value to EditText: android
I have an EditText which returns an empty string on calling edittext.getText().toString(). Instead of returning an empty string, I want to set a default value for this result and i don't want that value to be shown in EditText. Is it possible to do so? If yes then how can i do that?

答:
A good way to deal with this is to use the ternary operator</p>

```<code>String emailString = this.email.getText().toString();
return TextUtils.isEmpty(emailString) ? "your default string" : emailString;
</code>```

Body:
A good way to deal with this is to use the ternary operator

String emailString = this.email.getText().toString();
return TextUtils.isEmpty(emailString) ? "your default string" : emailString;


问:
Laravel: Validation unique on update
I know this question has been asked many times before but no one explains how to get the id when you're validating in the model.

```<code>'email' => 'unique:users,email_address,10'
</code>```

My validation rule is in the model so how do I pass the ID of the record to the validation rule.

Here is my models/User

```<code>protected $rules_update = [
    'email_address' => 'required|email|unique:users,email_address,'.$id,
    'first_name' => "required",
    'last_name' => "required",
    'password' => "required|min:6|same:password_confirm",
    'password_confirm' => "required:min:6|same:password",
    'password_current' => "required:min:6"
];
</code>```

models/BaseModel

```<code>    protected $rules = array();

public $errors;

/*
    * @data: array, Data to be validated
    * @rules: string, rule name in model
*/

public function validate($data, $rules = "rules") {

    $validation  = Validator::make($data, $this->$rules);

    if($validation->passes()) {
        return true;
    }

    $this->errors = $validation->messages();

    return false;
}
</code>```

答:
an even simpler solution tested with version 5.2

in your model

```<code>// validator rules
public static $rules = array(
    ...
    'email_address' => 'email|required|unique:users,id'
);
</code>```

Title: Laravel: Validation unique on update

Body:
I know this question has been asked many times before but no one explains how to get the id when you're validating in the model.

'email' => 'unique:users,email_address,10'

My validation rule is in the model so how do I pass the ID of the record to the validation rule.

Here is my models/User

protected $rules_update = [
    'email_address' => 'required|email|unique:users,email_address,'.$id,
    'first_name' => "required",
    'last_name' => "required",
    'password' => "required|min:6|same:password_confirm",
    'password_confirm' => "required:min:6|same:password",
    'password_current' => "required:min:6"
];

models/BaseModel

    protected $rules = array();

public $errors;

/*
    * @data: array, Data to be validated
    * @rules: string, rule name in model
*/

public function validate($data, $rules = "rules") {

    $validation  = Validator::make($data, $this->$rules);

    if($validation->passes()) {
        return true;
    }

    $this->errors = $validation->messages();

    return false;
}

Body:
an even simpler solution tested with version 5.2

in your model

// validator rules
public static $rules = array(
    ...
    'email_address' => 'email|required|unique:users,id'
);


问:
Package installed with Composer not found by php install
I have installed prewk/xml-string-streamer using Composer into my Xampp PHP install, which lists the installation quite happy through the xampp command line. However when I try to use the package, PHP bugs out the same as it did before the install.  I'm trying to do the following:

$streamer = Prewk\XmlStringStreamer::createStringWalkerParser($filename);

as in the xml-string-streamer docs.

I feel I'm missing something obvious, and am aware this might be a specific problem with my setup, but I'm hoping I've missed a step or something.

答:
https://getcomposer.org/doc/01-basic-usage.md

I found the above page which answered most of my questions about how to get this to work.  I realised I'd installed the package, but not in the correct directory, nor had I included the correct include command to make it work.  I'm still getting errors but they appear to be from my buggy code-writing than this problem.

Sorry for wasting everyone's time.


问:
AngularJS material turns required fields to red only after user clicks a field
I have this markup:

```<code><md-input-container class="md-block" flex-gt-sm ng-show="$ctrl.isAddMode">
    <label>ID</label>
    <input name="id" ng-model="$ctrl.voice.id"
           ng-model-options="{ debounce: 1000 }"
           ng-change="$ctrl.verifyUniqueId()" required>
    <div class='error' ng-show='$ctrl.idError'>
        {{$ctrl.idError}}
    </div>
</md-input-container>
<md-input-container class="md-block" flex-gt-sm>
    <label>Name</label>
    <input ng-model="$ctrl.voice.name" required>
</md-input-container>
</code>```

and

```<code><md-button ng-disabled="!$ctrl.isReadyForSubmit()"
           class="md-raised md-primary"
           ng-click="$ctrl.submit()">
    {{$ctrl.voice.isTest ? "Start Test" : "Publish"}}
</md-button>
</code>```

with:

```<code>self.isReadyForSubmit = function () {
    return $scope.voiceForm.$valid && !uploadService.getClientErrorMsgOfUploadedFiles();
}
</code>```

I txt turns red if the user clicks on the field, goes out and doesn't fill it.

However fields that are not clicked by the user don't turn their txt to red.

how can i make them red if the user clicks on the "submit" disabled button?

答:
Welcome to the world of angular materials limitations. Take a look at this code pen demo I've created. You need to set the css class md-input-invalid manually, on md-input-container element, if the field is not valide + submit was pressed.

```<code><form name="projectForm">
    <md-input-container class="md-block" ng-class="{ 'md-input-invalid': projectForm.description.$invalid  && wasSend }">
        <label>Description</label>
        <input md-maxlength="30" required md-no-asterisk="" name="description" ng-model="project.description">
        <div ng-messages="projectForm.description.$error">
            <div ng-message="required">This is required.</div>
            <div ng-message="md-maxlength">The description must be less than 30 characters long.</div>
        </div>
    </md-input-container>

    <div layout="row">
        <md-input-container flex="50" ng-class="{ 'md-input-invalid': projectForm.clientName.$invalid && wasSend }">
            <label>Client Name*</label>
            <input name="clientName" required ng-model="project.clientName">
            <div ng-messages="projectForm.clientName.$error">
                <div ng-message="required">This is required.</div>
            </div>
        </md-input-container>
    <div>
        <md-button type="submit" ng-click="wasSend = true">Submit</md-button>
    </div>
</form>
</code>```

Body:
I have this markup:

<md-input-container class="md-block" flex-gt-sm ng-show="$ctrl.isAddMode">
    ID
    <input name="id" ng-model="$ctrl.voice.id"
           ng-model-options="{ debounce: 1000 }"
           ng-change="$ctrl.verifyUniqueId()" required>

        {{$ctrl.idError}}

</md-input-container>
<md-input-container class="md-block" flex-gt-sm>
    Name
    <input ng-model="$ctrl.voice.name" required>
</md-input-container>

and

<md-button ng-disabled="!$ctrl.isReadyForSubmit()"
           class="md-raised md-primary"
           ng-click="$ctrl.submit()">
    {{$ctrl.voice.isTest ? "Start Test" : "Publish"}}
</md-button>

with:

self.isReadyForSubmit = function () {
    return $scope.voiceForm.$valid && !uploadService.getClientErrorMsgOfUploadedFiles();
}

I txt turns red if the user clicks on the field, goes out and doesn't fill it.

However fields that are not clicked by the user don't turn their txt to red.

how can i make them red if the user clicks on the "submit" disabled button?

Body:
Welcome to the world of angular materials limitations. Take a look at this code pen demo I've created. You need to set the css class md-input-invalid manually, on md-input-container element, if the field is not valide + submit was pressed.

<form name="projectForm">
    <md-input-container class="md-block" ng-class="{ 'md-input-invalid': projectForm.description.$invalid  && wasSend }">
        <label>Description</label>
        <input md-maxlength="30" required md-no-asterisk="" name="description" ng-model="project.description">
        <div ng-messages="projectForm.description.$error">
            <div ng-message="required">This is required.</div>
            <div ng-message="md-maxlength">The description must be less than 30 characters long.</div>
        </div>
    </md-input-container>

    <div layout="row">
        <md-input-container flex="50" ng-class="{ 'md-input-invalid': projectForm.clientName.$invalid && wasSend }">
            <label>Client Name*</label>
            <input name="clientName" required ng-model="project.clientName">
            <div ng-messages="projectForm.clientName.$error">
                <div ng-message="required">This is required.</div>
            </div>
        </md-input-container>
    <div>
        <md-button type="submit" ng-click="wasSend = true">Submit</md-button>
    </div>
</form>


问:
Get Facebook's friends birthdays in Objective C
i found a site like graph.facebook.com but I cannot understand this API, so I wanted to know if there's a way to get the friends birthday (e.g. as an HTTP Request) ?
Please help,
Thanks in advance!</p>

答:
Just glancing over the documentation, it seems that you would need the user's authorization:

Look at the user api: http://developers.facebook.com/docs/reference/api/user

from http://developers.facebook.com/docs/api:

The Graph API as such allows you to easily access all public information about an object. For example, https://graph.facebook.com/btaylor (Bret Taylor) returns all the public information about Bret. For example a user's first name, last name and profile picture are publicly available.

To get additional information about a user, you must first get their permission. At a high level, you need to get an access token for the Facebook user. After you obtain the access token for the user, you can perform authorized requests on behalf of that user by including the access token in your Graph API requests

Here is an example done in FQL: Fetching friends' birthdays from facebook profile

FQL: http://developers.facebook.com/docs/reference/fql/


问:
Realloc a Struct which contains a pointer to another Sruct (Segmentation Fault)
I have two Structs like this:

```<code>typedef struct Student {
    char name[80];
    char sclass[4];
    int phone;
} Student;

typedef struct Cell {
    Student* p_student; // pointer to struct
    bool occupied; // if the cell has been occupied for collisions after delete
} Cell;
</code>```

And two arrays that are initially allocated with malloc :

```<code>Cell *arr_name = malloc(sizeof(Cell) * size),
     *arr_phone = malloc(sizeof(Cell) * size);
</code>```

The problem is, when I try to use Realloc I get the segmentation fault error :

```<code>void insert(int *size, int *numberOfStudents, Cell **arr_name, Cell **arr_phone, char name[80], char sclass[4], int phone) {
// some stuff happening

if(*numberOfStudents > (*size / 1.5)) {
    *size = *numberOfStudents * 1.5;
    int new_size = sizeof(Cell) * (*size);
    Cell *p_name = realloc(*arr_name, new_size); // <-- ERROR HERE
    Cell *p_phone = realloc(*arr_phone, new_size);
    if(p_name && p_phone) {
        *arr_name = p_name;
        *arr_phone = p_phone;
    }
    else printf("Couldn't allocate more memory");
}
</code>```

Thanks for help !

答:
Problem solved !

Thanks to @StoryTeller that suggested to use valgrind to debug memory errors. The memory was messed up by some other stuff in the program.

Body:
I have two Structs like this:

typedef struct Student {
    char name[80];
    char sclass[4];
    int phone;
} Student;

typedef struct Cell {
    Student* p_student; // pointer to struct
    bool occupied; // if the cell has been occupied for collisions after delete
} Cell;

And two arrays that are initially allocated with malloc :

Cell *arr_name = malloc(sizeof(Cell) * size),
     *arr_phone = malloc(sizeof(Cell) * size);

The problem is, when I try to use Realloc I get the segmentation fault error :

void insert(int *size, int *numberOfStudents, Cell **arr_name, Cell **arr_phone, char name[80], char sclass[4], int phone) {
// some stuff happening

if(*numberOfStudents > (*size / 1.5)) {
    *size = *numberOfStudents * 1.5;
    int new_size = sizeof(Cell) * (*size);
    Cell *p_name = realloc(*arr_name, new_size); // <-- ERROR HERE
    Cell *p_phone = realloc(*arr_phone, new_size);
    if(p_name && p_phone) {
        *arr_name = p_name;
        *arr_phone = p_phone;
    }
    else printf("Couldn't allocate more memory");
}

Thanks for help !


问:
How to use mockito mock annotation in scala
In java @Mock annotation can be used like below:

```<code>@Mock
private InsightHandleProvider handleProvider;
</code>```

How to use the same annotation in Scala? It gives compilation error when tried to below:

```<code>class ThreadTest{
    @Mock
      val handleProvider:InsightHandleProvider
    }
</code>```

Error:(16, 7) class ThreadTest needs to be abstract, since: it has 1
  unimplemented member.

答:
Looking here ... we find: Existing annotations from Java frameworks can be used directly in Scala code. Any Java framework will see the annotations you write just as if you were writing in Java.

So what you intend to do should actually work. Thus the problem is not that annotation, but (probably) the fact your variable handleProvider isn't initialized (see here for example).

Body:
In java @Mock annotation can be used like below:

@Mock
private InsightHandleProvider handleProvider;

How to use the same annotation in Scala? It gives compilation error when tried to below:

class ThreadTest{
    @Mock
      val handleProvider:InsightHandleProvider
    }

Error:(16, 7) class ThreadTest needs to be abstract, since: it has 1
  unimplemented member.


问:
Android: I need a Numeric Keyboard that can allow the characters "1234567890.,-"
I have this in my Edit text

```<code>    android:inputType="numberDecimal"
    android:digits="0123456789,.-"
</code>```

However, the result is this:
Keyboard

I don't know what is wrong. Please help me. Thanks.

答:
because android:inputType="numberDecimal" won't let you choose any other characters except for 0123456789. You need to change the line  android:inputType="numberDecimal" to
 android:inputType="text"

```<code>android:digits="0123456789,.-"
</code>```

I hope this will help.

Body:
I have this in my Edit text

    android:inputType="numberDecimal"
    android:digits="0123456789,.-"

However, the result is this:
Keyboard

I don't know what is wrong. Please help me. Thanks.

Body:
because android:inputType="numberDecimal" won't let you choose any other characters except for 0123456789. You need to change the line  android:inputType="numberDecimal" to
 android:inputType="text"

android:digits="0123456789,.-"

I hope this will help.


问:
WPF Update view in loop
I'm using MVVM and when the model calculates a new background for a position it tells the viewmodel that it's changed. So what I want to do is update the view at every new background, but I think Thread.Sleep blocks the main UI thread.

```<code>private void New_Background(object sender, BackgroundEventArgs e)
    {
        Application.Current.Dispatcher.InvokeAsync(new Action(() =>
        {
            Fields[e.Position].Background = e.Background; //update this position's background at every step
            OnPropertyChanged("Background");
            Thread.Sleep(50);
        }));
    }
</code>```

Is there a way I can achieve this?
By the way, if I use MessageBox.Show(...) instead of Thread.Sleep, it updates the view at every messagebox.

答:
Set a higher priority</p>

```<code>Application.Current.Dispatcher.BeginInvoke(
DispatcherPriority.Send,
new Action(() =>
        {
            Fields[e.Position].Background = e.Background; //update this position's background at every step
            OnPropertyChanged("Background");
        }));
</code>```

Title: WPF Update view in loop

Body:
I'm using MVVM and when the model calculates a new background for a position it tells the viewmodel that it's changed. So what I want to do is update the view at every new background, but I think Thread.Sleep blocks the main UI thread.

private void New_Background(object sender, BackgroundEventArgs e)
    {
        Application.Current.Dispatcher.InvokeAsync(new Action(() =>
        {
            Fields[e.Position].Background = e.Background; //update this position's background at every step
            OnPropertyChanged("Background");
            Thread.Sleep(50);
        }));
    }

Is there a way I can achieve this?
By the way, if I use MessageBox.Show(...) instead of Thread.Sleep, it updates the view at every messagebox.

Body:
Set a higher priority

Application.Current.Dispatcher.BeginInvoke(
DispatcherPriority.Send,
new Action(() =>
        {
            Fields[e.Position].Background = e.Background; //update this position's background at every step
            OnPropertyChanged("Background");
        }));


问:
What does the task hierarchy mean in 'docker node ps' output?
I have a small django app running running in a 3 node docker swarm.  When I run docker node ps I get output similar to the following:

```<code>user@host$ docker node ps $(docker node ls --quiet) --filter desired-state=Running
ID            NAME                    IMAGE                                                  NODE          DESIRED STATE  CURRENT STATE               ERROR  PORTS
vn2ruaqk503o  proj1_pubsub.1          redis:3.2-alpine                                       proj1-node    Running        Running about a minute ago
vn2ruaqk503o   \_ proj1_pubsub.1      redis:3.2-alpine                                       proj1-node    Running        Running about a minute ago
vn2ruaqk503o   \_ proj1_pubsub.1      redis:3.2-alpine                                       proj1-node    Running        Running about a minute ago
5njupphqr1tu  proj1_db.1              postgres:9.6-alpine                                    proj1-node-3  Running        Running about a minute ago
ld6w8owhu3ct  proj1_app.1             python:alpine                                          proj1-node    Running        Running about a minute ago
ld6w8owhu3ct   \_ proj1_app.1         python:alpine                                          proj1-node    Running        Running about a minute ago
ld6w8owhu3ct   \_ proj1_app.1         python:alpine                                          proj1-node    Running        Running about a minute ago
iiddlrud5d1x  proj1_proxy.1           nginx:alpine                                           proj1-node-3  Running        Running about a minute ago
xrm2on457y49  proj1_cache-2.1         memcached:1.4-alpine                                   proj1-node-2  Running        Running about a minute ago
xrm2on457y49   \_ proj1_cache-2.1     memcached:1.4-alpine                                   proj1-node-2  Running        Running about a minute ago
lwpgkkk6kkdz  proj1_cache.1           memcached:1.4-alpine                                   proj1-node    Running        Running about a minute ago
lwpgkkk6kkdz   \_ proj1_cache.1       memcached:1.4-alpine                                   proj1-node    Running        Running about a minute ago
lwpgkkk6kkdz   \_ proj1_cache.1       memcached:1.4-alpine                                   proj1-node    Running        Running about a minute ago
eeco5rl2e4tk  proj1_app.2             python:alpine                                          proj1-node-2  Running        Running about a minute ago
eeco5rl2e4tk   \_ proj1_app.2         python:alpine                                          proj1-node-2  Running        Running about a minute ago
</code>```

Does anyone know what the task hierarchy in the output means?  What does the fact that proj1_pubsub.1 is listed with two sub items mean?

```<code>proj1_pubsub.1
\_ proj1_pubsub.1
\_ proj1_pubsub.1
</code>```

The docker documentation does not show an example with this hierarchy information or explain what it means.

答:
The "tree" shows tasks (containers) that were replaced, and still available on the node.

When deploying a service, docker monitors the tasks backing the service, and if a task fails, a new task (container) is started to replace the old one. Keeping the old container around allows you to (e.g.) inspect that container to investigate why it failed, or view its logs.

The same happens when you update a service (for example update the service to use a newer version of an image), in which case new containers are started with the new image, and the old container is stopped. You can see this in the following example;

```<code>docker service create --name redis --replicas=2 redis:3.0.6

docker service ps redis

ID                  NAME                IMAGE               NODE                DESIRED STATE       CURRENT STATE            ERROR               PORTS
2g423t6ulywl        redis.1             redis:3.0.6         moby                Running             Running 16 seconds ago
8b8yn6opxwaj        redis.2             redis:3.0.6         moby                Running             Running 16 seconds ago
</code>```

Now, updating the image to redis:3.0.7;

```<code>docker service update --image redis:3.0.7 redis

docker service ps redis

ID                  NAME                IMAGE               NODE                DESIRED STATE       CURRENT STATE                    ERROR               PORTS
7dj4opiw1vel        redis.1             redis:3.0.7         moby                Running             Running less than a second ago
2g423t6ulywl         \_ redis.1         redis:3.0.6         moby                Shutdown            Shutdown 8 seconds ago
x15asetswu67        redis.2             redis:3.0.7                             Ready               Pending less than a second ago
8b8yn6opxwaj         \_ redis.2         redis:3.0.6         moby                Shutdown            Running 42 seconds ago
</code>```

The amount of containers "kept around" is configurable through the --task-history-limit option on docker swarm update, and defaults to 5 (after which older containers are removed)

More in-depth information about "swarm" services can be found in this section of the documentation https://docs.docker.com/engine/swarm/

Body:
I have a small django app running running in a 3 node docker swarm.  When I run docker node ps I get output similar to the following:

user@host$ docker node ps $(docker node ls --quiet) --filter desired-state=Running
ID            NAME                    IMAGE                                                  NODE          DESIRED STATE  CURRENT STATE               ERROR  PORTS
vn2ruaqk503o  proj1_pubsub.1          redis:3.2-alpine                                       proj1-node    Running        Running about a minute ago
vn2ruaqk503o   \_ proj1_pubsub.1      redis:3.2-alpine                                       proj1-node    Running        Running about a minute ago
vn2ruaqk503o   \_ proj1_pubsub.1      redis:3.2-alpine                                       proj1-node    Running        Running about a minute ago
5njupphqr1tu  proj1_db.1              postgres:9.6-alpine                                    proj1-node-3  Running        Running about a minute ago
ld6w8owhu3ct  proj1_app.1             python:alpine                                          proj1-node    Running        Running about a minute ago
ld6w8owhu3ct   \_ proj1_app.1         python:alpine                                          proj1-node    Running        Running about a minute ago
ld6w8owhu3ct   \_ proj1_app.1         python:alpine                                          proj1-node    Running        Running about a minute ago
iiddlrud5d1x  proj1_proxy.1           nginx:alpine                                           proj1-node-3  Running        Running about a minute ago
xrm2on457y49  proj1_cache-2.1         memcached:1.4-alpine                                   proj1-node-2  Running        Running about a minute ago
xrm2on457y49   \_ proj1_cache-2.1     memcached:1.4-alpine                                   proj1-node-2  Running        Running about a minute ago
lwpgkkk6kkdz  proj1_cache.1           memcached:1.4-alpine                                   proj1-node    Running        Running about a minute ago
lwpgkkk6kkdz   \_ proj1_cache.1       memcached:1.4-alpine                                   proj1-node    Running        Running about a minute ago
lwpgkkk6kkdz   \_ proj1_cache.1       memcached:1.4-alpine                                   proj1-node    Running        Running about a minute ago
eeco5rl2e4tk  proj1_app.2             python:alpine                                          proj1-node-2  Running        Running about a minute ago
eeco5rl2e4tk   \_ proj1_app.2         python:alpine                                          proj1-node-2  Running        Running about a minute ago

Does anyone know what the task hierarchy in the output means?  What does the fact that proj1_pubsub.1 is listed with two sub items mean?

proj1_pubsub.1
\_ proj1_pubsub.1
\_ proj1_pubsub.1

The docker documentation does not show an example with this hierarchy information or explain what it means.

Body:
The "tree" shows tasks (containers) that were replaced, and still available on the node.

When deploying a service, docker monitors the tasks backing the service, and if a task fails, a new task (container) is started to replace the old one. Keeping the old container around allows you to (e.g.) inspect that container to investigate why it failed, or view its logs.

The same happens when you update a service (for example update the service to use a newer version of an image), in which case new containers are started with the new image, and the old container is stopped. You can see this in the following example;

docker service create --name redis --replicas=2 redis:3.0.6

docker service ps redis

ID                  NAME                IMAGE               NODE                DESIRED STATE       CURRENT STATE            ERROR               PORTS
2g423t6ulywl        redis.1             redis:3.0.6         moby                Running             Running 16 seconds ago
8b8yn6opxwaj        redis.2             redis:3.0.6         moby                Running             Running 16 seconds ago

Now, updating the image to redis:3.0.7;

docker service update --image redis:3.0.7 redis

docker service ps redis

ID                  NAME                IMAGE               NODE                DESIRED STATE       CURRENT STATE                    ERROR               PORTS
7dj4opiw1vel        redis.1             redis:3.0.7         moby                Running             Running less than a second ago
2g423t6ulywl         \_ redis.1         redis:3.0.6         moby                Shutdown            Shutdown 8 seconds ago
x15asetswu67        redis.2             redis:3.0.7                             Ready               Pending less than a second ago
8b8yn6opxwaj         \_ redis.2         redis:3.0.6         moby                Shutdown            Running 42 seconds ago

The amount of containers "kept around" is configurable through the --task-history-limit option on docker swarm update, and defaults to 5 (after which older containers are removed)

More in-depth information about "swarm" services can be found in this section of the documentation https://docs.docker.com/engine/swarm/


问:
Array of structs - C bad value
I'm facing a quite interesting problem in C.
So I have a struct which looks like this:

```<code>struct Question {
    int year;
    char* month;
    char* day;
    char* hour;
    char* minute;
    char* second;
    char* question;
    int answerCount;
    char* answers[1024];
} questions[100];
</code>```

There, I'm initializing an array of Question structs called questions, with the size of 100.

So I want to fill that array from a file looking like this:

```<code>2017 04 01 12 38 00 OK? 2 NO NO
2017 04 01 14 15 00 WHAT? 4 YES YES YES YES
</code>```

The structure:
year month day hour minute second question answercount answers

I'm processing the file like this:

```<code>...
int id = 0;
int j;

char line[2048];
while ( (fgets(line, sizeof(line), fp)) != NULL) {

        char* p = strtok(line, " ");
        char* tokens[1024];
        char* token;

        int i = 0;
        int counter = 0;

        while((p != NULL)) {
            switch(counter) {
                case 0: questions[id].year = atoi(p); break; // year
                case 1: questions[id].month = p; break; // month
                case 2: questions[id].day = p; break; // day
                case 3: questions[id].hour =p; break; // hour
                case 4: questions[id].minute = p; break; // minute
                case 5: questions[id].second = p; break; // seconds
                case 6: questions[id].question = p; break; // question
                case 7:
                questions[id].answerCount = atoi(p);
                int qcount = atoi(p);
                int k;
                int l = j;
                //printf("count : %d", qcount);
                for (k = 0; k < qcount; ++k) {
                    p = strtok(NULL, " ");
                    ++l;
                    questions[id].answers[k] = p;
                }
                break;
                default: break;
            }
            p = strtok(NULL, " ");
            ++counter;
        }
        ++id;

    }
    fclose(fp);
...
</code>```

After that, if I printf the questions[0].question element in the while loop, I get "OK?", however if I print the same thing after the while loop, I get "WHAT?".

I've spent a lot of time thinking what I might do wrong, but no success.

Thanks for your help.

答:
This:

```<code>char* answers[1024];
</code>```

Is an array of 1024 pointers to strings, but does not contain any storage for those strings.  So when you do this:

```<code>questions[id].answers[k] = p;
</code>```

You are not copying the answer, but merely assigning a pointer to it.  Since p ultimately is a pointer to somewhere within line, which is only allocated once before the loop begins, you are overwriting the strings in line each time through the loop.  So the referents of your answers is being modified.

You could either change answers to be a 2D array of char, in which case the maximum length of each answer will be limited, or use strdup() or similar to allocate memory for each answer, and free() it at the end.

Title: Array of structs - C bad value

Body:
I'm facing a quite interesting problem in C.
So I have a struct which looks like this:

struct Question {
    int year;
    char* month;
    char* day;
    char* hour;
    char* minute;
    char* second;
    char* question;
    int answerCount;
    char* answers[1024];
} questions[100];

There, I'm initializing an array of Question structs called questions, with the size of 100.

So I want to fill that array from a file looking like this:

2017 04 01 12 38 00 OK? 2 NO NO
2017 04 01 14 15 00 WHAT? 4 YES YES YES YES

The structure:
year month day hour minute second question answercount answers

I'm processing the file like this:

...
int id = 0;
int j;

char line[2048];
while ( (fgets(line, sizeof(line), fp)) != NULL) {

        char* p = strtok(line, " ");
        char* tokens[1024];
        char* token;

        int i = 0;
        int counter = 0;

        while((p != NULL)) {
            switch(counter) {
                case 0: questions[id].year = atoi(p); break; // year
                case 1: questions[id].month = p; break; // month
                case 2: questions[id].day = p; break; // day
                case 3: questions[id].hour =p; break; // hour
                case 4: questions[id].minute = p; break; // minute
                case 5: questions[id].second = p; break; // seconds
                case 6: questions[id].question = p; break; // question
                case 7:
                questions[id].answerCount = atoi(p);
                int qcount = atoi(p);
                int k;
                int l = j;
                //printf("count : %d", qcount);
                for (k = 0; k < qcount; ++k) {
                    p = strtok(NULL, " ");
                    ++l;
                    questions[id].answers[k] = p;
                }
                break;
                default: break;
            }
            p = strtok(NULL, " ");
            ++counter;
        }
        ++id;

    }
    fclose(fp);
...

After that, if I printf the questions[0].question element in the while loop, I get "OK?", however if I print the same thing after the while loop, I get "WHAT?".

I've spent a lot of time thinking what I might do wrong, but no success.

Thanks for your help.

Body:
This:

char* answers[1024];

Is an array of 1024 pointers to strings, but does not contain any storage for those strings.  So when you do this:

questions[id].answers[k] = p;

You are not copying the answer, but merely assigning a pointer to it.  Since p ultimately is a pointer to somewhere within line, which is only allocated once before the loop begins, you are overwriting the strings in line each time through the loop.  So the referents of your answers is being modified.

You could either change answers to be a 2D array of char, in which case the maximum length of each answer will be limited, or use strdup() or similar to allocate memory for each answer, and free() it at the end.


问:
Installing anaconda - "failed to create anaconda menus"
I've been trying to install anaconda in the past few days, but with not luck.
I tried both the 2.7 and 3.6 version, but whenever I try to install it just says "failed to create anaconda menus", so the installation can't be completed.
I tried to look for a solution at other threads, but nothing seems to work. Does anyone around here have an idea on what to do?
If it somehow helps - I'm using the 32-bit version for windows XP.
Thanks in advance!</p>

答:
for windows XP, you need to install a version 2.2 of anaconda as said here :

https://docs.continuum.io/anaconda/


问:
PHP - Get Array value by Index instead of Key

I've got a multidimensional array returned by an API call. The values into this array are stored with a key like this :

```<code>Array(["BTC_XRP"] => 1)
</code>```

I can get the values of the Array by getting them using the keys (like BTC_XRP), but what if I need to get the value using the Index?

For example, how do I get each value of the Array using a for loop if I can't get the values by the Index?

Since the Array is composed by something like 100 values, I need to echo every one using a for loop, but this gives me this error :

Notice: Undefined offset: 0

Is it possible to get to a value using the Index instead of the Key?

Furthermore, I'd like to get the Key by the Index. If I want to get the Key of the first value, I'd like to get it using the 0 Index.

Thanks!

答:
Sounds like you are in search of array_keys (to get key by index) and array_values (to get value by index) functions:

```<code>$array = array("BTC_XRP" => 1, "EUR_XRP" => 234, "USD_XRP" => 567);
$keys   = array_keys( $array );
$values = array_values( $array );

var_dump( $keys[1] ); // string(7) "EUR_XRP"
var_dump( $values[1] ); // int(234)
</code>```

Or use a foreach as Joshua suggests.

Body:
I've got a multidimensional array returned by an API call. The values into this array are stored with a key like this :

Array(["BTC_XRP"] => 1)

I can get the values of the Array by getting them using the keys (like BTC_XRP), but what if I need to get the value using the Index?

For example, how do I get each value of the Array using a for loop if I can't get the values by the Index?

Since the Array is composed by something like 100 values, I need to echo every one using a for loop, but this gives me this error :

Notice: Undefined offset: 0

Is it possible to get to a value using the Index instead of the Key?

Furthermore, I'd like to get the Key by the Index. If I want to get the Key of the first value, I'd like to get it using the 0 Index.

Thanks!

Body:
Sounds like you are in search of array_keys (to get key by index) and array_values (to get value by index) functions:

$array = array("BTC_XRP" => 1, "EUR_XRP" => 234, "USD_XRP" => 567);
$keys   = array_keys( $array );
$values = array_values( $array );

var_dump( $keys[1] ); // string(7) "EUR_XRP"
var_dump( $values[1] ); // int(234)

Or use a foreach as Joshua suggests.


问:
JavaScript Canvas White Screen
I'm really frustrated right now, JS never works for me. I don't know what little mistake I made this time, I'll be grateful if you point it out. I don't want an animation or anything, I'd be happy if someone tells me the error.</p>

```<code>window.onload = function(){
  var canvas = document.getElementById("canvas");
  var context = canvas.getContext("2d");
  canvas.width = window.innerWidth();
  canvas.height = window.innerHeight();

var ship = function() {
this.x = canvas.width/2;
this.y = canvas.height/2;
this.velocityX = 0;
this.velocityY = 0;
this.accelerationX = 0;
this.accelerationY = 0;

this.show = function() {
  //background
  context.fillStyle = 'rgb(0,0,0)';
  context.fillRect(0,0,canvas.width,canvas.height);

  //update
  this.velocityX += this.accelerationX;
  this.velocityY += this.accelerationY;
  this.x += this.velocityX;
  this.y += this.velocityY;

  //draw
  context.save();
  context.translate(this.x,this.y) ;
  context.fillStyle = 'rgb(0,0,0)';
  context.fillRect(0,0,20,30);
  context.restore();
};
};

var myship = new ship();
myship.show();
};
</code>```

答:
You have two issues ...

1. innerWidth / innerHeight isn't a method / function, it's a property of the window object. so, the   correct form would be window.innerWidth / window.innerHeight

2.  You aren't able to view the ship object, as you set both the background's and ship's fillStyle   to black. so, either change fillStyle of the background or the ship to a different color.

var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

var ship = function() {
    this.x = canvas.width / 2;
    this.y = canvas.height / 2;
    this.velocityX = 0;
    this.velocityY = 0;
    this.accelerationX = 0;
    this.accelerationY = 0;
    this.show = function() {
        //background
        context.fillStyle = 'rgb(255,255,255)';
        context.fillRect(0, 0, canvas.width, canvas.height);

       //update
        this.velocityX += this.accelerationX;
        this.velocityY += this.accelerationY;
        this.x += this.velocityX;
        this.y += this.velocityY;

        //draw ship
        context.save();
        context.translate(this.x, this.y);
        context.fillStyle = 'rgb(0,0,0)';
        context.fillRect(0, 0, 20, 30);
        context.restore();
    };
};
var myship = new ship();
myship.show();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#canvas {
  border: 1px solid black;
}</code>```

<canvas id="canvas" width="300" height="300"></canvas>```

Title: JavaScript Canvas White Screen

Body:
I'm really frustrated right now, JS never works for me. I don't know what little mistake I made this time, I'll be grateful if you point it out. I don't want an animation or anything, I'd be happy if someone tells me the error.

window.onload = function(){
  var canvas = document.getElementById("canvas");
  var context = canvas.getContext("2d");
  canvas.width = window.innerWidth();
  canvas.height = window.innerHeight();

var ship = function() {
this.x = canvas.width/2;
this.y = canvas.height/2;
this.velocityX = 0;
this.velocityY = 0;
this.accelerationX = 0;
this.accelerationY = 0;

this.show = function() {
  //background
  context.fillStyle = 'rgb(0,0,0)';
  context.fillRect(0,0,canvas.width,canvas.height);

  //update
  this.velocityX += this.accelerationX;
  this.velocityY += this.accelerationY;
  this.x += this.velocityX;
  this.y += this.velocityY;

  //draw
  context.save();
  context.translate(this.x,this.y) ;
  context.fillStyle = 'rgb(0,0,0)';
  context.fillRect(0,0,20,30);
  context.restore();
};
};

var myship = new ship();
myship.show();
};

Body:
You have two issues ...

1. innerWidth / innerHeight isn't a method / function, it's a property of the window object. so, the   correct form would be window.innerWidth / window.innerHeight

2.  You aren't able to view the ship object, as you set both the background's and ship's fillStyle   to black. so, either change fillStyle of the background or the ship to a different color.

var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

var ship = function() {
    this.x = canvas.width / 2;
    this.y = canvas.height / 2;
    this.velocityX = 0;
    this.velocityY = 0;
    this.accelerationX = 0;
    this.accelerationY = 0;
    this.show = function() {
        //background
        context.fillStyle = 'rgb(255,255,255)';
        context.fillRect(0, 0, canvas.width, canvas.height);

       //update
        this.velocityX += this.accelerationX;
        this.velocityY += this.accelerationY;
        this.x += this.velocityX;
        this.y += this.velocityY;

        //draw ship
        context.save();
        context.translate(this.x, this.y);
        context.fillStyle = 'rgb(0,0,0)';
        context.fillRect(0, 0, 20, 30);
        context.restore();
    };
};
var myship = new ship();
myship.show();

#canvas {
  border: 1px solid black;
}

<canvas id="canvas" width="300" height="300"></canvas>


问:
Converting site from jQuery to React - toggling from component
First time asking on SO, so I hope I'm doing it right.

Very recently took up React. I'm currently trying to convert an old site of mine into React.

The data is 444 markdown files that are loaded into an array of objects (front matter and content), containing information about various medical drugs. In the left hand side, I want a sidebar containing a list of all the names of the drugs, and when clicked it will then toggle a component displaying the actual contents of the markdown file corresponding to the clicked name.

You can see the jQuery-based site at http://farma.morsby.dk (it's in Danish, but the contents really don't matter). I'm stuck at how I would go about toggling the info box (middle) by clicking the name (left side navigation).

An image depicting the issue is here (we can disregard the right hand pane, I just added it for good measure as it's currently on the site and I would want it in the end):

Page setup and component setup (sorry, can't post images [yet]).

Current setup is sort of like this:

<Parent /> calls <NavContainer /> and <InfoContainer />

<NavContainer /> calls (amongst other components) <NavItem /> which then displays the individual drug names.

<InfoContainer /> calls <InfoItem /> which then displays the individual info boxes. <InfoItem /> should toggle on the corresponding<NavItem />´s onClick.

As I understand it, the <NavContainer /> and <InfoContainer /> need a common parent to communicate. But I can't really figure out what to pass down. For the navigation, I need all drugs. But for <InfoContainer />, should I pass down all drugs and some information about whether the individual box is displayed or not, or should I only pass down the currently toggled boxes? I could (I guess) hard code some states that I could then mutate, but I would prefer a more dynamic approach (if I added/removed/renamed a drug, I wouldn't need to change the code).

In jQuery, of course, it's trivial to toggle by ID for instance. Maybe I shouldn't use React for this type of app at all?

I'm not looking for exact code solutions to the problem but more a concept of how I would go about solving my problem – if this is even something React would be good at.

Thanks!

答:
Having components affect other components that aren't descendants of theirs is not easy in basic React and usually involves a common ancestor and a whole bunch of callbacks.  I recently wrote an answer on a similar issue which might give you a few ideas on how to move forward with your app in React

If I were you, I would look into a Flux (or Flux-like) implementation, such as Redux, and have the NavItems dispatch actions into the store to toggle the visible state of the InfoItems who would in turn, use the store state to determine if they should be rendered or not (or perhaps InfoContainer would do this for all InfoItems).

Hope this helps.


问:
Unique identifier for Android phone
I'm building Android application which needs to identify device by some unique number/string.

I've heard about ANDROID_ID but there are also reports that it can be the same on some phone models or even updates.
Another thing is that it is recreated after factory reset or system reinstall. I can live with that although I would prefer if it stayed the same.

Is there another way to identify the phone without asking for more permissions? IMEI requires them(android.permission.READ_PHONE_STATE) but it can scare away users.

How Shazam does that? I know it identifies the phone permanently (it remembers that I was a user before it introduced 5 tags a month restriction for new users) even though I completely reinstalled the system.

答: Why not create a GUID in a file in a well-known location and have that be your unique identifier? That way you have full control and without the need for any elevated permissions (except for file system access.)</p>

Title: Unique identifier for Android phone


问:
How to count only 1s in SQL?
I am trying to run a report to see how many vehicles need a repair over the last month and how many need a service. As shown below, if a vehicle has had a repair, it has a 1 assigned to it, otherwise, it's a 0. This is my attempt currently and it's returning both 1 and 0s which I don't want. Any help is much appreciated.

```<code> select
   vehicles_inspections.Vehicle_ID,
   make,
   model,
   count(Repair),
   count(Service)
 from vehicles_inspections, vehicles
 where vehicles.Vehicle_ID = vehicles_inspections.Vehicle_ID
 group by Vehicle_ID
</code>```

答:
With the data you have shown, you can simply use sum() rather than count():

```<code>select vi.Vehicle_ID, v.make, v.model, sum(vi.Repair), sum(vi.Service)
from vehicles v join
     vehicles_inspections vi
     on v.Vehicle_ID = vi.Vehicle_ID
group by vi.Vehicle_ID, v.make, v.model;
</code>```

This works because the values appears to be either 0 or 1.  In other words, these columns are designed as flags that can be summed up for this purpose.

If they could take on other values, you would use something like:

```<code>sum(case when repair = 1 then 1 else 0 end) as repairs
</code>```

Notes:

You should qualify all column names.  I'm guessing where the columns are coming from.

Never use commas in the FROM clause.  Always use proper, explicit JOIN syntax.

Title: How to count only 1s in SQL?

Body:
I am trying to run a report to see how many vehicles need a repair over the last month and how many need a service. As shown below, if a vehicle has had a repair, it has a 1 assigned to it, otherwise, it's a 0. This is my attempt currently and it's returning both 1 and 0s which I don't want. Any help is much appreciated.

 select
   vehicles_inspections.Vehicle_ID,
   make,
   model,
   count(Repair),
   count(Service)
 from vehicles_inspections, vehicles
 where vehicles.Vehicle_ID = vehicles_inspections.Vehicle_ID
 group by Vehicle_ID

Body:
With the data you have shown, you can simply use sum() rather than count():

select vi.Vehicle_ID, v.make, v.model, sum(vi.Repair), sum(vi.Service)
from vehicles v join
     vehicles_inspections vi
     on v.Vehicle_ID = vi.Vehicle_ID
group by vi.Vehicle_ID, v.make, v.model;

This works because the values appears to be either 0 or 1.  In other words, these columns are designed as flags that can be summed up for this purpose.

If they could take on other values, you would use something like:

sum(case when repair = 1 then 1 else 0 end) as repairs

Notes:

You should qualify all column names.  I'm guessing where the columns are coming from.

Never use commas in the FROM clause.  Always use proper, explicit JOIN syntax.


问:
Summarize array of objects and calculate average value for each unique object name
I have an array like so:

```<code>var array = [
     {
       name: "a",
       value: 1
     },
     {
       name: "a",
       value: 2
     },
     {
       name: "a",
       value: 3
     },
     {
       name: "b",
       value: 0
     },
     {
       name: "b",
       value: 1
     }
 ];
</code>```

And I need an array like this:

```<code>var newarray = [
     {
       name: "a",
       value: 2
     },
     {
       name: "b",
       value: 0.5
     }
 ]
</code>```

Where the new array has each unique name as an object with the average value.

Is there an easy way to accomplish this?

答:
Here is a ES2015 version, using reduce   </p>

```<code> let arr = [
  { a: 1, b: 1 },
  { a: 2, b: 3 },
  { a: 6, b: 4 },
  { a: 2, b: 1 },
  { a: 8, b: 2 },
  { a: 0, b: 2 },
  { a: 4, b: 3 }
]

arr.reduce((a, b, index, self) => {
 const keys = Object.keys(a)
 let c = {}

 keys.map((key) => {
  c[key] = a[key] + b[key]

  if (index + 1 === self.length) {
    c[key] = c[key] / self.length
  }
 })

 return c
})
</code>```

Body:
I have an array like so:

var array = [
     {
       name: "a",
       value: 1
     },
     {
       name: "a",
       value: 2
     },
     {
       name: "a",
       value: 3
     },
     {
       name: "b",
       value: 0
     },
     {
       name: "b",
       value: 1
     }
 ];

And I need an array like this:

var newarray = [
     {
       name: "a",
       value: 2
     },
     {
       name: "b",
       value: 0.5
     }
 ]

Where the new array has each unique name as an object with the average value.

Is there an easy way to accomplish this?

Body:
Here is a ES2015 version, using reduce

 let arr = [
  { a: 1, b: 1 },
  { a: 2, b: 3 },
  { a: 6, b: 4 },
  { a: 2, b: 1 },
  { a: 8, b: 2 },
  { a: 0, b: 2 },
  { a: 4, b: 3 }
]

arr.reduce((a, b, index, self) => {
 const keys = Object.keys(a)
 let c = {}

 keys.map((key) => {
  c[key] = a[key] + b[key]

  if (index + 1 === self.length) {
    c[key] = c[key] / self.length
  }
 })

 return c
})