问:
Simple Vue.js with webpack
I know basically nothing about javascript/webpack/npm/whatever but I am trying a simple Vue.js app.

It looks like this:

index.html

```<code><!DOCTYPE html>

<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Vue Test</title>
  </head>
  <body>
    <div class="vue-app">
      {{ message }}
    </div>
    <script src="/static/testvue.bundle.js"></script>
  </body>
</html>
</code>```

main.js

```<code>import Vue from 'vue';

new Vue({
    data: {
        message: 'Testing Vue'
    },
    el: '.vue-app'
});
</code>```

webpack.config.js

```<code>var path = require('path');

module.exports = {
    entry: './main.js',
    output: {
        filename: 'testvue.bundle.js',
        path: path.join(__dirname, '')
    },
    devServer: {
        inline: true,
        port: 8080
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                exclude: /node_modules/,
                loader: 'babel-loader',

                query: {
                    presets: ['es2015']
                }
            }
        ]
    }
};
</code>```

When I go to the webpage, it is blank and I see this in the "elements" in the console:

```<code><!--function (e,n,r,o){return Ce(t,e,n,r,o,!0)}-->
</code>```

Any idea what's going on and how to make it work? It's like it's trying to do something, but something doesn't line up. I've tried changing a few things that I have seen differently like using #vue-app instead of .vue-app or changing it to be under 'body' and then putting the {{message}} directly into the body but that doesn't help and I dont know what the difference is.

答:
So, looks like the issue is that webpack wants the "ESM" version of Vue.

You can add some stuff to the webpack.config.js as per: https://v2.vuejs.org/v2/guide/installation.html

And then it seems to start working.

Code snippet

```<code>resolve: {
    alias: {
        'vue$': 'vue/dist/vue.esm.js'
    }
}
</code>```

I am not sure what the difference is or why this matters though.

Title: Simple Vue.js with webpack

Body:
I know basically nothing about javascript/webpack/npm/whatever but I am trying a simple Vue.js app.

It looks like this:

index.html

<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Vue Test</title>

      {{ message }}

main.js

import Vue from 'vue';

new Vue({
    data: {
        message: 'Testing Vue'
    },
    el: '.vue-app'
});

webpack.config.js

var path = require('path');

module.exports = {
    entry: './main.js',
    output: {
        filename: 'testvue.bundle.js',
        path: path.join(__dirname, '')
    },
    devServer: {
        inline: true,
        port: 8080
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                exclude: /node_modules/,
                loader: 'babel-loader',

                query: {
                    presets: ['es2015']
                }
            }
        ]
    }
};

When I go to the webpage, it is blank and I see this in the "elements" in the console:

Any idea what's going on and how to make it work? It's like it's trying to do something, but something doesn't line up. I've tried changing a few things that I have seen differently like using #vue-app instead of .vue-app or changing it to be under 'body' and then putting the {{message}} directly into the body but that doesn't help and I dont know what the difference is.

Body:
So, looks like the issue is that webpack wants the "ESM" version of Vue.

You can add some stuff to the webpack.config.js as per: https://v2.vuejs.org/v2/guide/installation.html

And then it seems to start working.

Code snippet

resolve: {
    alias: {
        'vue$': 'vue/dist/vue.esm.js'
    }
}

I am not sure what the difference is or why this matters though.


来源: stackexchange

问:
Can't display values for a user profile in CodeIgniter?
I am making a simple twitter clone for practice with CodeIgniter and am having difficulty echoing the first_name and last_name and date_joined value from my users table in my user.php view. I just want to show the values for the user that is currently logged in.

I would want the values to echo below the session username in my view. My controller, view, and models are below. Right now I get the following error:

Message: Cannot use object of type stdClass as array

This is when I just try to echo $user['first_name'], $user['last_name], etc. I had it working before simply echoing out like this but now I can't.
If I do a var_dump of $user I just get the following:

/app/www/application/views/user.php:5: class stdClass#22 (1) { public $user_id => string(1) "1" }

Controller: User.php

```<code>class User extends CI_Controller
{
 function index()
 {
  $this->load->model('login_model');
  $data['user'] = $this->login_model->get_user();
  $data['tweets'] = $this->tweet_model->usertweets();
  $this->load->view('templates/header');
  $this->load->view('user', $data);
  $this->load->view('templates/footer');
 }
}
</code>```

Model: Login_model.php

```<code>class Login_model extends CI_Model
{
 function can_login($username, $password)
{
 $this->db->where('username', $username);
 $this->db->where('password', $password);
 $query = $this->db->get('users');

 //SELECT * FROM users WHERE username = '$username' AND password = '$password'

 if($query->num_rows() > 0)
 {
  return true;
 }
 else {
  return false;
 }
}

 function get_user()
 {
  $query = $this->db->get('users');

  $username = $_SESSION['username'];
  $this->db->select('user_id', 'first_name', 'last_name', 'date_joined');
  $this->db->from('users');
  $this->db->where('username', $username);
  $query = $this->db->get();
  return $query->row();
 }
}
</code>```

Model: Tweet_model.php

```<code>class Tweet_model extends CI_Model
{
public function __construct()
{
    $this->load->database();
}

public function get_tweets($tweet_id = false)
{
    if ($tweet_id === false) {
        $this->db->join('users', 'tweets.user_id = users.user_id');
        $query = $this->db->get('tweets');
        return $query->result_array();
    }

    $query = $this->db->get_where('tweets', array('tweet_id' => $tweet_id));
    return $query->row_array();
}

public function set_tweet()
{
    $tweet = url_title($this->input->post('tweet'), 'dash', true);

    $query = $this->db->get('users');

    $username = $_SESSION['username'];
    $this->db->select('user_id');
    $this->db->from('users');
    $this->db->where('username', $username);

    if ($this->db->affected_rows())
    {
        $user = $query->row();
        var_dump($user_id);
    }

    $data = array(
      'tweet' => $this->input->post('tweet'),
      'user_id' => $user->user_id
    );

    return $this->db->insert('tweets', $data);
}

function Usertweets() {
  $this->db->flush_cache();

  $username = $_SESSION['username'];
  $this->db->select('user_id');
  $this->db->from('users');
  $this->db->where('username', $username);

  $query = $this->db->get();
  $user = $query->row();

  $this->db->flush_cache();

  $this->db->select('*');
  $this->db->from('tweets');
  $this->db->where('user_id', $user->user_id);

  return $this->db->get()->result();

}
}
</code>```

View: user.php

```<code><div class="container">
 <div class="row">
  <div class="col-md-4">
   <h4><?php echo $_SESSION['username']; ?></h4>
  </div>
  <div class="col-md-8">
   <?php foreach ($tweets as $tweet): ?>
    <div class="user-tweet">
     <h4><?php echo $_SESSION['username']; ?></h4>
     <h6><?php echo $tweet->tweet_date; ?></h6>
     <p><?php echo $tweet->tweet; ?></p>
    </div>
   <?php endforeach; ?>
  </div>
 </div>
</div>
</code>```

答:
Generally any CI db function call that doesn't contain array somwhere in the name returns an object such as row() or result() with their array counterparts being row_array() and result_array().

Arrays are accessed like $arr['somevalue'] in the view and objects are accessed like $obj->somevalue. I can't track down your error because everything looks ok, but I suspect you might be getting no rows and thus foreach fails. Before foreach it is always a good idea to check if you have anything to print!

```<code><div class="col-md-8">
    <?php if (count($tweets) > 0): ?>
    <?php foreach ($tweets as $tweet): ?>
        <div class="user-tweet">
            <h4><?php echo $_SESSION['username']; ?></h4>
            <h6><?php echo $tweet->tweet_date; ?></h6>
            <p><?php echo $tweet->tweet; ?></p>
        </div>
    <?php endforeach; ?>
    <?php else: ?>
    No tweets!
    <?php endif; ?>
</div>
</code>```

Code Review

First off, in your get_users function remove the first $query = $this->db->get('users'); as it is unnecessary.

Refactor can_login to:

```<code>function can_login($username, $password) {
    $this->db->where('username', $username);
    $this->db->where('password', $password);
    return $this->db->count_all_results('users') > 0; // or == 1
}
</code>```

Refactor set_tweet following the DRY principle:

```<code>public function set_tweet() {
    $this->load->model('login_model');
    $tweet = url_title($this->input->post('tweet'), 'dash', true);
    $data = array(
        'tweet' => $this->input->post('tweet'),
        'user_id' => $this->login_model->get_user()->user_id
    );
    return $this->db->insert('tweets', $data);
}
</code>```

Should note as a general good practice that you should probably store the user_id in a session at login if you are using this that much; it will reduce database strain. Further, I assume that you don't let any of these actions happen if the user isn't logged in as$user_id or any of the user related row fields won't be accessible and will throw a notice if you try and access them. Redirect the user to login somewhere if (in your case) $_SESSION['username'] isn't set.

Following the previous refactor you can refactor Usertweets to:

```<code>function Usertweets() {
    $this->load->model('login_model');
    //$this->db->select('*'); * is done for you by default
    $this->db->where('user_id', $this->login_model->get_user()->user_id);
    return $this->db->get('tweets')->result(); // object returned
}
</code>```

You might want to consider returning an object to keep everything the same in get_tweets as well.

ContentLicense: CC BY-SA 3.0

Body:
I am making a simple twitter clone for practice with CodeIgniter and am having difficulty echoing the first_name and last_name and date_joined value from my users table in my user.php view. I just want to show the values for the user that is currently logged in.

I would want the values to echo below the session username in my view. My controller, view, and models are below. Right now I get the following error:

Message: Cannot use object of type stdClass as array

This is when I just try to echo $user['first_name'], $user['last_name], etc. I had it working before simply echoing out like this but now I can't.
If I do a var_dump of $user I just get the following:

/app/www/application/views/user.php:5: class stdClass#22 (1) { public $user_id => string(1) "1" }

Controller: User.php

class User extends CI_Controller
{
 function index()
 {
  $this->load->model('login_model');
  $data['user'] = $this->login_model->get_user();
  $data['tweets'] = $this->tweet_model->usertweets();
  $this->load->view('templates/header');
  $this->load->view('user', $data);
  $this->load->view('templates/footer');
 }
}

Model: Login_model.php

class Login_model extends CI_Model
{
 function can_login($username, $password)
{
 $this->db->where('username', $username);
 $this->db->where('password', $password);
 $query = $this->db->get('users');

 //SELECT * FROM users WHERE username = '$username' AND password = '$password'

 if($query->num_rows() > 0)
 {
  return true;
 }
 else {
  return false;
 }
}

 function get_user()
 {
  $query = $this->db->get('users');

  $username = $_SESSION['username'];
  $this->db->select('user_id', 'first_name', 'last_name', 'date_joined');
  $this->db->from('users');
  $this->db->where('username', $username);
  $query = $this->db->get();
  return $query->row();
 }
}

Model: Tweet_model.php

class Tweet_model extends CI_Model
{
public function __construct()
{
    $this->load->database();
}

public function get_tweets($tweet_id = false)
{
    if ($tweet_id === false) {
        $this->db->join('users', 'tweets.user_id = users.user_id');
        $query = $this->db->get('tweets');
        return $query->result_array();
    }

    $query = $this->db->get_where('tweets', array('tweet_id' => $tweet_id));
    return $query->row_array();
}

public function set_tweet()
{
    $tweet = url_title($this->input->post('tweet'), 'dash', true);

    $query = $this->db->get('users');

    $username = $_SESSION['username'];
    $this->db->select('user_id');
    $this->db->from('users');
    $this->db->where('username', $username);

    if ($this->db->affected_rows())
    {
        $user = $query->row();
        var_dump($user_id);
    }

    $data = array(
      'tweet' => $this->input->post('tweet'),
      'user_id' => $user->user_id
    );

    return $this->db->insert('tweets', $data);
}

function Usertweets() {
  $this->db->flush_cache();

  $username = $_SESSION['username'];
  $this->db->select('user_id');
  $this->db->from('users');
  $this->db->where('username', $username);

  $query = $this->db->get();
  $user = $query->row();

  $this->db->flush_cache();

  $this->db->select('*');
  $this->db->from('tweets');
  $this->db->where('user_id', $user->user_id);

  return $this->db->get()->result();

}
}

View: user.php

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

   <?php foreach ($tweets as $tweet): ?>

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

<?php echo $tweet->tweet_date; ?>

<?php echo $tweet->tweet; ?>

   <?php endforeach; ?>

Body:
Generally any CI db function call that doesn't contain array somwhere in the name returns an object such as row() or result() with their array counterparts being row_array() and result_array().

Arrays are accessed like $arr['somevalue'] in the view and objects are accessed like $obj->somevalue. I can't track down your error because everything looks ok, but I suspect you might be getting no rows and thus foreach fails. Before foreach it is always a good idea to check if you have anything to print!

<div class="col-md-8">
    <?php if (count($tweets) > 0): ?>
    <?php foreach ($tweets as $tweet): ?>
        <div class="user-tweet">
            <h4><?php echo $_SESSION['username']; ?></h4>
            <h6><?php echo $tweet->tweet_date; ?></h6>
            <p><?php echo $tweet->tweet; ?></p>
        </div>
    <?php endforeach; ?>
    <?php else: ?>
    No tweets!
    <?php endif; ?>
</div>

Code Review

First off, in your get_users function remove the first $query = $this->db->get('users'); as it is unnecessary.

Refactor can_login to:

function can_login($username, $password) {
    $this->db->where('username', $username);
    $this->db->where('password', $password);
    return $this->db->count_all_results('users') > 0; // or == 1
}

Refactor set_tweet following the DRY principle:

public function set_tweet() {
    $this->load->model('login_model');
    $tweet = url_title($this->input->post('tweet'), 'dash', true);
    $data = array(
        'tweet' => $this->input->post('tweet'),
        'user_id' => $this->login_model->get_user()->user_id
    );
    return $this->db->insert('tweets', $data);
}

Should note as a general good practice that you should probably store the user_id in a session at login if you are using this that much; it will reduce database strain. Further, I assume that you don't let any of these actions happen if the user isn't logged in as$user_id or any of the user related row fields won't be accessible and will throw a notice if you try and access them. Redirect the user to login somewhere if (in your case) $_SESSION['username'] isn't set.

Following the previous refactor you can refactor Usertweets to:

function Usertweets() {
    $this->load->model('login_model');
    //$this->db->select('*'); * is done for you by default
    $this->db->where('user_id', $this->login_model->get_user()->user_id);
    return $this->db->get('tweets')->result(); // object returned
}

You might want to consider returning an object to keep everything the same in get_tweets as well.


问:
React native initalRouteName not working with Stack Navigation
I am new to react-native and I am trying to implement a simple application using StackNavigation and react-redux with welcome and signup screens. I have configured both the screens using StackNavigation but for some reasons , only the SignUp screen pops up when the app starts. Below are my files :

Index.js

```<code>import { AppRegistry } from 'react-native';
import App from './App';
AppRegistry.registerComponent('MyApp', () => App);
</code>```

App.js

```<code>import React, { Component } from 'react';
import { Provider, connect } from "react-redux";
import { addNavigationHelpers } from "react-navigation";
import StackNavConfig from "./js/config/routes";
import getStore from "./js/store";

const AppNavigator = StackNavConfig;

const initialState = AppNavigator.router.getActionForPathAndParams('Welcome');

const navReducer = (state = initialState, action) => {
    const newState = AppNavigator.router.getStateForAction(action, state);
    return newState || state;
};

const AppWithNavigationState = connect(state => ({
    nav: state.nav,
}))(({ dispatch, nav }) => (
    <AppNavigator navigation={addNavigationHelpers({ dispatch, state: nav })} />
));

const store = getStore(navReducer);

class App extends React.Component {
  render() {
    return (
      <Provider store={store}>
        <AppWithNavigationState />
      </Provider>
    );
  }
}

export default App;
</code>```

js/config/routes.js

```<code>import Welcome from "../components/Welcome/view/Welcome";
import SignUp from "../components/SignUp/view/SignUp";
import { StackNavigator } from "react-navigation";

const Routes = {
    Welcome: { screen: Welcome , path: ''},
    SignUp: { screen: SignUp , path : '/signup'},
};

const RoutesConfig = {
    initialRouteName: 'Welcome',
    headerMode: 'none',
};

export default StackNavConfig = StackNavigator(Routes, RoutesConfig);
</code>```

store.js

```<code>import { createStore, applyMiddleware } from "redux";

import thunk from "redux-thunk";
import getRootReducer from "./reducers/index";

export default function getStore(navReducer) {
    const store = createStore(
        getRootReducer(navReducer),
        undefined,
        applyMiddleware(thunk)
    );

    return store;
}
</code>```

Below are my components
Welcome.js

```<code>import React from 'react';
import {
  View,
  Image} from 'react-native';
import { connect } from "react-redux";
import { bindActionCreators } from "redux";
import * as welcomeActions from "../actions/WelcomeActions";
import { welcomeStyles } from '../styles/WelcomeStyles';

class Welcome extends React.Component {

  constructor(){
    super();
    this.state = {  };
  }

  render(){
    return (
      <View style = {welcomeStyles.mainContainer}>
         <Text>Welcome</Text>
      </View>
    );
  }
}

export default connect(
  state => ({

  }),
  dispatch => bindActionCreators(welcomeActions, dispatch)
)(Welcome);
</code>```

SignUp.js

```<code>import React from 'react';
import {
  View,
  Image} from 'react-native';
import { connect } from "react-redux";
import { bindActionCreators } from "redux";
import * as welcomeActions from "../actions/SignUpActions";
import { signUpStyles } from '../styles/SignUpStyles';

class Welcome extends React.Component {

  constructor(){
    super();
    this.state = {  };
  }

  render(){
    return (
      <View style = {signUpStyles.mainContainer}>
         <Text>SignUp</Text>
      </View>
    );
  }
}

export default connect(
  state => ({

  }),
  dispatch => bindActionCreators(signUpActions, dispatch)
)(SignUp);
</code>```

I also have action and reducer files for each of my component.But they are blank as of now , since I haven't yet implemented the redux part.I am combining the reducers as below.

```<code>import { combineReducers } from "redux";
import welcomeReducer from "../components/Welcome/reducers/WelcomeReducer";
import signUpReducer from "../components/SignUp/reducers/SignUpReducer";

export default function getRootReducer(navReducer) {
    return combineReducers({
        nav: navReducer,
        welcomeReducer : welcomeReducer,
        signUpReducer : signUpReducer,
    });
}
</code>```

As mentioned before , even after setting the initialRouteName to Welcome in my routes.js , the SignUp screen appears first everytime I launch the app. Please help

答: I found out what was the issue. I was calling this.props.navigate inside the render function by mistake which was causing the navigation to different screen.</p>

Body:
I am new to react-native and I am trying to implement a simple application using StackNavigation and react-redux with welcome and signup screens. I have configured both the screens using StackNavigation but for some reasons , only the SignUp screen pops up when the app starts. Below are my files :

Index.js

import { AppRegistry } from 'react-native';
import App from './App';
AppRegistry.registerComponent('MyApp', () => App);

App.js

import React, { Component } from 'react';
import { Provider, connect } from "react-redux";
import { addNavigationHelpers } from "react-navigation";
import StackNavConfig from "./js/config/routes";
import getStore from "./js/store";

const AppNavigator = StackNavConfig;

const initialState = AppNavigator.router.getActionForPathAndParams('Welcome');

const navReducer = (state = initialState, action) => {
    const newState = AppNavigator.router.getStateForAction(action, state);
    return newState || state;
};

const AppWithNavigationState = connect(state => ({
    nav: state.nav,
}))(({ dispatch, nav }) => (
    <AppNavigator navigation={addNavigationHelpers({ dispatch, state: nav })} />
));

const store = getStore(navReducer);

class App extends React.Component {
  render() {
    return (
      <Provider store={store}>
        <AppWithNavigationState />
      </Provider>
    );
  }
}

export default App;

js/config/routes.js

import Welcome from "../components/Welcome/view/Welcome";
import SignUp from "../components/SignUp/view/SignUp";
import { StackNavigator } from "react-navigation";

const Routes = {
    Welcome: { screen: Welcome , path: ''},
    SignUp: { screen: SignUp , path : '/signup'},
};

const RoutesConfig = {
    initialRouteName: 'Welcome',
    headerMode: 'none',
};

export default StackNavConfig = StackNavigator(Routes, RoutesConfig);

store.js

import { createStore, applyMiddleware } from "redux";

import thunk from "redux-thunk";
import getRootReducer from "./reducers/index";

export default function getStore(navReducer) {
    const store = createStore(
        getRootReducer(navReducer),
        undefined,
        applyMiddleware(thunk)
    );

    return store;
}

Below are my components
Welcome.js

import React from 'react';
import {
  View,
  Image} from 'react-native';
import { connect } from "react-redux";
import { bindActionCreators } from "redux";
import * as welcomeActions from "../actions/WelcomeActions";
import { welcomeStyles } from '../styles/WelcomeStyles';

class Welcome extends React.Component {

  constructor(){
    super();
    this.state = {  };
  }

  render(){
    return (
      <View style = {welcomeStyles.mainContainer}>
         <Text>Welcome</Text>
      </View>
    );
  }
}

export default connect(
  state => ({

  }),
  dispatch => bindActionCreators(welcomeActions, dispatch)
)(Welcome);

SignUp.js

import React from 'react';
import {
  View,
  Image} from 'react-native';
import { connect } from "react-redux";
import { bindActionCreators } from "redux";
import * as welcomeActions from "../actions/SignUpActions";
import { signUpStyles } from '../styles/SignUpStyles';

class Welcome extends React.Component {

  constructor(){
    super();
    this.state = {  };
  }

  render(){
    return (
      <View style = {signUpStyles.mainContainer}>
         <Text>SignUp</Text>
      </View>
    );
  }
}

export default connect(
  state => ({

  }),
  dispatch => bindActionCreators(signUpActions, dispatch)
)(SignUp);

I also have action and reducer files for each of my component.But they are blank as of now , since I haven't yet implemented the redux part.I am combining the reducers as below.

import { combineReducers } from "redux";
import welcomeReducer from "../components/Welcome/reducers/WelcomeReducer";
import signUpReducer from "../components/SignUp/reducers/SignUpReducer";

export default function getRootReducer(navReducer) {
    return combineReducers({
        nav: navReducer,
        welcomeReducer : welcomeReducer,
        signUpReducer : signUpReducer,
    });
}

As mentioned before , even after setting the initialRouteName to Welcome in my routes.js , the SignUp screen appears first everytime I launch the app. Please help


问:
How do I strip malicious HTML (XXS etc.) from content submissions?
I have a content submission form that contains multiple fields for input, all of which, when submitted, are entered directly into the database. When this content is requested, it is printed.

I have realized this is a security issue.

How can I strip malicious HTML (XSS) only, while still allowing formatting tags (b, i etc.)?

答:
I think encoding the input would help...

For PHP I believe it is:

```<code>htmlspecialchars
</code>```

Body:
I think encoding the input would help...

For PHP I believe it is:

htmlspecialchars

ContentLicense: CC BY-SA 2.5


问:
How to continuously delete old fluentd logs from elasticsearch?
A Fluentd log collector writes to Elasticsearch which eventually fills up the disk. How to limit them to a month, for example?

Part of the Fluentd config (using Kubernetes):

```<code><match kubernetes.**>
  @type elasticsearch_dynamic
  host elasticsearch.default.svc.cluster.local
  port 9200
  include_tag_key true
  logstash_format true
  logstash_prefix kubernetes-${record['kubernetes']['pod_name']}
</match>
</code>```

"Curator" for Elasticsearch, can delete "indexes", but I don't know what indexes Fluentd creates, when it stops using them and what does it mean to delete an index when there are still useful new logs in it?

答:
Curator will delete indices for you, regardless of whether Logstash, fluentd, or some other app made them.  This example will work with the index pattern you provided in the above comments.</p>

```<code>---
actions:
  1:
    action: delete_indices
    description: >-
      Delete indices older than 30 days (based on index name), for kubernetes-elasticsearch-
      prefixed indices. Ignore the error if the filter does not result in an
      actionable list of indices (ignore_empty_list) and exit cleanly.
    options:
      ignore_empty_list: true
      disable_action: true
    filters:
      - filtertype: pattern
        kind: prefix
        value: kubernetes-elasticsearch-
      - filtertype: age
        source: name
        direction: older
        timestring: '%Y.%m.%d'
        unit: days
        unit_count: 30
</code>```

Body:
A Fluentd log collector writes to Elasticsearch which eventually fills up the disk. How to limit them to a month, for example?

Part of the Fluentd config (using Kubernetes):

<match kubernetes.**>
  @type elasticsearch_dynamic
  host elasticsearch.default.svc.cluster.local
  port 9200
  include_tag_key true
  logstash_format true
  logstash_prefix kubernetes-${record['kubernetes']['pod_name']}
</match>

"Curator" for Elasticsearch, can delete "indexes", but I don't know what indexes Fluentd creates, when it stops using them and what does it mean to delete an index when there are still useful new logs in it?

Body:
Curator will delete indices for you, regardless of whether Logstash, fluentd, or some other app made them.  This example will work with the index pattern you provided in the above comments.

---
actions:
  1:
    action: delete_indices
    description: >-
      Delete indices older than 30 days (based on index name), for kubernetes-elasticsearch-
      prefixed indices. Ignore the error if the filter does not result in an
      actionable list of indices (ignore_empty_list) and exit cleanly.
    options:
      ignore_empty_list: true
      disable_action: true
    filters:
      - filtertype: pattern
        kind: prefix
        value: kubernetes-elasticsearch-
      - filtertype: age
        source: name
        direction: older
        timestring: '%Y.%m.%d'
        unit: days
        unit_count: 30


问:
AddClass to match statements
I am trying to allocate tbody into 1 of 2 different class. I can't seem to get the if statement running, perhaps I have not used the syntax correctly?

condition 1: If tbody id = today (yyyymm), then add class "current"

condition 2: If tbody id < today (yyyymm), then add class "past"

condition 3: If tbody id > today (yyyymm), then add do nothing

$(function(){
var d = new Date();
var month = d.getMonth()+1;
var day = d.getDate();
var output = d.getFullYear() + (month<10 ? '0' : '') + month;
var checktbody = $('tbody').attr('id');
//alert(output);

if(checktbody == output) {
$(this).addclass("current");
}

//$("table#ttrate").find("tbody".attr("id") == output).addclass("current");

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>table#ttx{margin-left:40px; border-collapse:collapse;}
#ttx th {padding-top: 18px; text-align:left;}
#ttx td {padding-left: 18px;}
#ttx tbody.current {background-color: #FFFF99;}
#ttx tbody.past {color: #B8B8B8;}</code>```

Jan-2018

Buy	23,000

Sell	10,250

Dec-2017

Buy	20,000

Sell	12,500

Nov-2017

Buy	10,000

Sell	8,750

```

答:
What you need to do is to check whether each tbody has matching id.

Your original syntax var checktbody = $('tbody').attr('id'); only gets  one tbody from all the tbodies.

So, what you need to do is to use for loop in pure JavaScript, or if in jQuery, a jQuery.each().

```<code>$('tbody').each(function(index, tb){

    // Do all your if-else logic here
    if (tb.id == output)
        $(tb).addClass(...);

    /* more logic here */

});
</code>```

$(function(){
var d = new Date();
var month = d.getMonth()+1;
var day = d.getDate();
var output = d.getFullYear() + (month<10 ? '0' : '') + month;

/* DELETE THIS
var checktbody = $('tbody').attr('id');
//alert(output);

if(checktbody == output) {
$(this).addclass("current");
}
*/

// ADD THIS
$('tbody').each(function(i, v){

  if (v.id == output)
    $(this).addClass('current');

  /* more logic here */

});

//$("table#ttrate").find("tbody".attr("id") == output).addclass("current");

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>table#ttx{margin-left:40px; border-collapse:collapse;}
#ttx th {padding-top: 18px; text-align:left;}
#ttx td {padding-left: 18px;}
#ttx tbody.current {background-color: #FFFF99;}
#ttx tbody.past {color: #B8B8B8;}</code>```

Jan-2018

Buy	23,000

Sell	10,250

Dec-2017

Buy	20,000

Sell	12,500

Nov-2017

Buy	10,000

Sell	8,750

```

Title: AddClass to match statements

Body:
I am trying to allocate tbody into 1 of 2 different class. I can't seem to get the if statement running, perhaps I have not used the syntax correctly?

condition 1: If tbody id = today (yyyymm), then add class "current"

condition 2: If tbody id < today (yyyymm), then add class "past"

condition 3: If tbody id > today (yyyymm), then add do nothing

$(function(){
var d = new Date();
var month = d.getMonth()+1;
var day = d.getDate();
var output = d.getFullYear() + (month<10 ? '0' : '') + month;
var checktbody = $('tbody').attr('id');
//alert(output);

if(checktbody == output) {
$(this).addclass("current");
}

//$("table#ttrate").find("tbody".attr("id") == output).addclass("current");

});

table#ttx{margin-left:40px; border-collapse:collapse;}
#ttx th {padding-top: 18px; text-align:left;}
#ttx td {padding-left: 18px;}
#ttx tbody.current {background-color: #FFFF99;}
#ttx tbody.past {color: #B8B8B8;}

Jan-2018

Buy	23,000

Sell	10,250

Dec-2017

Buy	20,000

Sell	12,500

Nov-2017

Buy	10,000

Sell	8,750

Body:
What you need to do is to check whether each tbody has matching id.

Your original syntax var checktbody = $('tbody').attr('id'); only gets  one tbody from all the tbodies.

So, what you need to do is to use for loop in pure JavaScript, or if in jQuery, a jQuery.each().

$('tbody').each(function(index, tb){

    // Do all your if-else logic here
    if (tb.id == output)
        $(tb).addClass(...);

    /* more logic here */

});

$(function(){
var d = new Date();
var month = d.getMonth()+1;
var day = d.getDate();
var output = d.getFullYear() + (month<10 ? '0' : '') + month;

/* DELETE THIS
var checktbody = $('tbody').attr('id');
//alert(output);

if(checktbody == output) {
$(this).addclass("current");
}
*/

// ADD THIS
$('tbody').each(function(i, v){

  if (v.id == output)
    $(this).addClass('current');

  /* more logic here */

});

//$("table#ttrate").find("tbody".attr("id") == output).addclass("current");

});

table#ttx{margin-left:40px; border-collapse:collapse;}
#ttx th {padding-top: 18px; text-align:left;}
#ttx td {padding-left: 18px;}
#ttx tbody.current {background-color: #FFFF99;}
#ttx tbody.past {color: #B8B8B8;}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="ttx">
<tbody id="201801">
<tr><th colspan="2">Jan-2018</th></tr>
<tr><td>Buy</td><td>23,000</td></tr>
<tr><td>Sell</td><td>10,250</td></tr>
</tbody>

<tbody id="201712">
<tr><th colspan="2">Dec-2017</th></tr>
<tr><td>Buy</td><td>20,000</td></tr>
<tr><td>Sell</td><td>12,500</td></tr>
</tbody>

<tbody id="201711">
<tr><th colspan="2">Nov-2017</th></tr>
<tr><td>Buy</td><td>10,000</td></tr>
<tr><td>Sell</td><td>8,750</td></tr>
</tbody>

</table>


问:
API dialog flow assistant
Hello I’ve been searching around and found this community is good for asking about Dialogflow or Api.ai , my question was how would I be able to intergrate my assistant into a service that gives it a voice so it can speak back to the user because I was looking to make a google like assistant so I could put the assistant into a raspberry pi give it a mic and speaker and it can be an assistant thanks .</p>

答: You can add the Google Assistant to a Raspberry Pi using the Google Assistant SDK.  You could then create a app for the Google Assistant with Dialogflow and invoke it by saying "OK Google talk to name of your app".

Title: API dialog flow assistant


问:
How to insert multiple values to a node in a linked list
For my current assignment I have to insert data from a file(which I already have uploaded (I DO NOT NEED HELP WITH THAT PART), but what I do not fully understand is how to assign this data to separate nodes.

```<code> 411048 2015 1 9.58
 411048 2015 3 14.82
 411048 2016 4 20.51
 411048 2016 1 10.99
 411000 1973 1 0.54
 411048 2016 3 18.40
 411048 2016 5 -99.99
</code>```

That is the formatting of our information and corresponds to Location | Year | month | temperature
I understand how to input different nodes into a linked list using the head next and tail, but what I do not understand is how to assign each row of data to
a location, year, month and temperature to one node.

```<code>//skeletal function for this

void insert(std::string location, int year, int month, double temperature);
</code>```

Any help is very appreciated, and if anyone trying to help would like, I can uploaded to skeletal code for my linkedlist.h/.cpp and my node.h/cpp

ALSO if a part of my question is unclear please let me know so I can try to clarify what it is I am asking.
Thanks.

答:
Assuming you have some kind of input file stream (call it ifs), the easiest way to do what you're looking for is something like

```<code>std::string location;
int year;
int month;
double temperature;

while (ifs >> location >> year >> month >> temperature) {
  // actions
}
</code>```

Body:
For my current assignment I have to insert data from a file(which I already have uploaded (I DO NOT NEED HELP WITH THAT PART), but what I do not fully understand is how to assign this data to separate nodes.

 411048 2015 1 9.58
 411048 2015 3 14.82
 411048 2016 4 20.51
 411048 2016 1 10.99
 411000 1973 1 0.54
 411048 2016 3 18.40
 411048 2016 5 -99.99

That is the formatting of our information and corresponds to Location | Year | month | temperature
I understand how to input different nodes into a linked list using the head next and tail, but what I do not understand is how to assign each row of data to
a location, year, month and temperature to one node.

//skeletal function for this

void insert(std::string location, int year, int month, double temperature);

Any help is very appreciated, and if anyone trying to help would like, I can uploaded to skeletal code for my linkedlist.h/.cpp and my node.h/cpp

ALSO if a part of my question is unclear please let me know so I can try to clarify what it is I am asking.
Thanks.

Body:
Assuming you have some kind of input file stream (call it ifs), the easiest way to do what you're looking for is something like

std::string location;
int year;
int month;
double temperature;

while (ifs >> location >> year >> month >> temperature) {
  // actions
}


问:
Checking a password
I think I have the right idea of solving this function, but I'm not sure why
I don't get the desired results shown in the docstring. Can anyone please help me fix this?</p>

```<code>def check_password(s):
'''(str, bool)
>>> check_password('TopSecret')
False
>>> check_password('TopSecret15')
True
'''
for char in s:
    if char.isdigit():
        if  char.islower():
            if char.isupper():
                return True
else:
    return False
</code>```

答:
Your logic is flawed it should look like this:

```<code>def check_password(s):
    has_digit = False
    has_lower = False
    has_upper = False

    for char in s:
        if char.isdigit():
            has_digit = True
        if char.islower():
            has_lower = True
        if char.isupper():
            has_upper = True

    # if all three are true return true
    if has_digit and has_upper and has_lower:
        return True
    else:
        return False
</code>```

Now, let's talk about what's wrong with your code.

```<code>def check_password(s):
    for char in s:
        if char.isdigit():
            if char.islower(): # we only get to this check if char was a digit
                if char.isupper(): # we only get here if char was a digit and lower
                    # it is not possible to get here
                    # char would have to be a digit, lower, and upper
                    return True
    else:
        return False
</code>```

As an example let's look at TopSecret15, we start with T

isdigit = False so we immediately return false for 'T'

We will continue to immediately return false until we get to '1'

Let's say we were on 1, isdigit would be true, but islower would be false so again it returns false

Do you see how it is impossible for all three of these to be true for the same char?

Your code is equivalent to:

```<code>if char.isdigit and char.islower and char.isupper:
    # this will never happen
</code>```

Title: Checking a password

Body:
I think I have the right idea of solving this function, but I'm not sure why
I don't get the desired results shown in the docstring. Can anyone please help me fix this?

def check_password(s):
'''(str, bool)
>>> check_password('TopSecret')
False
>>> check_password('TopSecret15')
True
'''
for char in s:
    if char.isdigit():
        if  char.islower():
            if char.isupper():
                return True
else:
    return False

Body:
Your logic is flawed it should look like this:

def check_password(s):
    has_digit = False
    has_lower = False
    has_upper = False

    for char in s:
        if char.isdigit():
            has_digit = True
        if char.islower():
            has_lower = True
        if char.isupper():
            has_upper = True

    # if all three are true return true
    if has_digit and has_upper and has_lower:
        return True
    else:
        return False

Now, let's talk about what's wrong with your code.

def check_password(s):
    for char in s:
        if char.isdigit():
            if char.islower(): # we only get to this check if char was a digit
                if char.isupper(): # we only get here if char was a digit and lower
                    # it is not possible to get here
                    # char would have to be a digit, lower, and upper
                    return True
    else:
        return False

As an example let's look at TopSecret15, we start with T

isdigit = False so we immediately return false for 'T'

We will continue to immediately return false until we get to '1'

Let's say we were on 1, isdigit would be true, but islower would be false so again it returns false

Do you see how it is impossible for all three of these to be true for the same char?

Your code is equivalent to:

if char.isdigit and char.islower and char.isupper:
    # this will never happen


问:
use mapv(a map tool by baidu) in node?
I want to change following code into node environment. Help me!

code is from http://mapv.baidu.com/examples/

And the content is following:

```<code>    var map = new BMap.Map(slice.selector, {
        enableMapClick: false
    });    // 创建Map实例
    map.centerAndZoom(new BMap.Point(105.403119, 38.028658), 5);  // 初始化地图,设置中心点坐标和地图级别
    map.enableScrollWheelZoom(true); // 开启鼠标滚轮缩放

    map.setMapStyle({
        style: 'light'
    });

    var randomCount = 300;

    var data = [];

    var citys =
    ["北京","天津","上海","重庆","石家庄","太原","呼和浩特","哈尔滨",
     "长春","沈阳","济南","南京","合肥","杭州","南昌","福州","郑州","武汉",
     "长沙","广州","南宁","西安","银川","兰州","西宁","乌鲁木齐","成都",
     "贵阳","昆明","拉萨","海口"];

    // 构造数据
    while (randomCount--) {
        var cityCenter = mapv.utilCityCenter.getCenterByCityName(citys[parseInt(Math.random() * citys.length)]);
        data.push({
            geometry: {
                type: 'Point',
                coordinates: [cityCenter.lng - 2 + Math.random() * 4, cityCenter.lat - 2 + Math.random() * 4]
            },
            count: 30 * Math.random()
        });
    }
    //数据集
    var dataSet = new mapv.DataSet(data);

    var options = {
        fillStyle: 'rgba(255, 50, 50, 0.6)',
        shadowColor: 'rgba(255, 50, 50, 1)',
        shadowBlur: 30,
        globalCompositeOperation: 'lighter',
        methods: {
            click: function (item) {
                console.log(item);
            }
        },
        size: 5,
        draw: 'simple'
    }

    var mapvLayer = new mapv.baiduMapLayer(map, dataSet, options);
</code>```

I use "mapv = require('mapv');" to import module mapv. But I can not get module "BMap", how can I get it?

答:
add
in your index.html
and use var BMap = window.BMap in your js code</p>

Title: use mapv(a map tool by baidu) in node?

Body:
I want to change following code into node environment. Help me!

code is from http://mapv.baidu.com/examples/

And the content is following:

    var map = new BMap.Map(slice.selector, {
        enableMapClick: false
    });    // 创建Map实例
    map.centerAndZoom(new BMap.Point(105.403119, 38.028658), 5);  // 初始化地图,设置中心点坐标和地图级别
    map.enableScrollWheelZoom(true); // 开启鼠标滚轮缩放

    map.setMapStyle({
        style: 'light'
    });

    var randomCount = 300;

    var data = [];

    var citys =
    ["北京","天津","上海","重庆","石家庄","太原","呼和浩特","哈尔滨",
     "长春","沈阳","济南","南京","合肥","杭州","南昌","福州","郑州","武汉",
     "长沙","广州","南宁","西安","银川","兰州","西宁","乌鲁木齐","成都",
     "贵阳","昆明","拉萨","海口"];

    // 构造数据
    while (randomCount--) {
        var cityCenter = mapv.utilCityCenter.getCenterByCityName(citys[parseInt(Math.random() * citys.length)]);
        data.push({
            geometry: {
                type: 'Point',
                coordinates: [cityCenter.lng - 2 + Math.random() * 4, cityCenter.lat - 2 + Math.random() * 4]
            },
            count: 30 * Math.random()
        });
    }
    //数据集
    var dataSet = new mapv.DataSet(data);

    var options = {
        fillStyle: 'rgba(255, 50, 50, 0.6)',
        shadowColor: 'rgba(255, 50, 50, 1)',
        shadowBlur: 30,
        globalCompositeOperation: 'lighter',
        methods: {
            click: function (item) {
                console.log(item);
            }
        },
        size: 5,
        draw: 'simple'
    }

    var mapvLayer = new mapv.baiduMapLayer(map, dataSet, options);

I use "mapv = require('mapv');" to import module mapv. But I can not get module "BMap", how can I get it?


答: C# equivalent of char is byte. But in your case you need possibility of negative numbers, so you’ll need a multidimensional array of sbyte. </p>

Title: char stored as int array in C? How to I convert it to C#

Body:
I am trying to understand part of the C code and convert it to C# code. I have a hard time understanding this part, it seems like a char array, expressed with intergers. How do I convert it to C# code?

Thanks in advance!

static const char   gradient[32][4] =
{
    { 1,  1,  1,  0}, { 1,  1,  0,  1}, { 1,  0,  1,  1}, { 0,  1,  1,  1},
    { 1,  1, -1,  0}, { 1,  1,  0, -1}, { 1,  0,  1, -1}, { 0,  1,  1, -1},
    { 1, -1,  1,  0}, { 1, -1,  0,  1}, { 1,  0, -1,  1}, { 0,  1, -1,  1},
    { 1, -1, -1,  0}, { 1, -1,  0, -1}, { 1,  0, -1, -1}, { 0,  1, -1, -1},
    {-1,  1,  1,  0}, {-1,  1,  0,  1}, {-1,  0,  1,  1}, { 0, -1,  1,  1},
    {-1,  1, -1,  0}, {-1,  1,  0, -1}, {-1,  0,  1, -1}, { 0, -1,  1, -1},
    {-1, -1,  1,  0}, {-1, -1,  0,  1}, {-1,  0, -1,  1}, { 0, -1, -1,  1},
    {-1, -1, -1,  0}, {-1, -1,  0, -1}, {-1,  0, -1, -1}, { 0, -1, -1, -1},
};


问:
Why doesn't this templated function to zero-initialize an array compile?
I'm trying to write a simple templated function that will initialize all members of an array to zero (or to their default-constructed state, if the array is an array of objects).  Here's what I've got written:

```<code>template<typename T, int size> inline void ClearTheArray(T[size] theArray)
{
   for (size_t i=0; i<size; i++) theArray[i] = T();
}
</code>```

... the idea being that I could then reset any array to its default-constructed/all-zeroes state like this:

```<code>int myArray[6] = {1,2,3,4,5,6};
ClearTheArray(myArray);
// myArray now contains all zeroes

int * somePointer = myArray;
ClearTheArray(somePointer);  // compile error: somePointer doesn't contain array length info
</code>```

However, the above doesn't compile; instead I get a syntax error ("expected ')'") at the first instance of theArray in the formal arguments list.  What am I doing wrong here?  Is there a way to do this right?

答:
Well, T[size] theArray is simply not correct declaration syntax. Just like when declaring arrays in any other context, the name goes before the bounds. So T theArray[size] would be the right syntax.

But this will still not do what you want it to do because arrays can't be passed by value and trying to pass an array by value causes it to decay to a pointer. The compiler must rewrite your parameter declaration to simply T* theArray. This makes size impossible to deduce, and allows your function to accept arbitrary pointers.

To solve these issues, you have to pass the array by reference:

```<code>template<typename T, int size> inline void ClearTheArray(T (&theArray)[size])
{
   for (size_t i=0; i<size; i++) theArray[i] = T();
}
</code>```

Then your example usage will behave as you expect.

There's no sense re-inventing the wheel though. The standard way to do this is

```<code>using std::begin;
using std::end;
std::fill(begin(myArray), end(myArray), 0);
std::fill(begin(somePointer), end(somePointer), 0);  // compile error
</code>```

Body:
I'm trying to write a simple templated function that will initialize all members of an array to zero (or to their default-constructed state, if the array is an array of objects).  Here's what I've got written:

template<typename T, int size> inline void ClearTheArray(T[size] theArray)
{
   for (size_t i=0; i<size; i++) theArray[i] = T();
}

... the idea being that I could then reset any array to its default-constructed/all-zeroes state like this:

int myArray[6] = {1,2,3,4,5,6};
ClearTheArray(myArray);
// myArray now contains all zeroes

int * somePointer = myArray;
ClearTheArray(somePointer);  // compile error: somePointer doesn't contain array length info

However, the above doesn't compile; instead I get a syntax error ("expected ')'") at the first instance of theArray in the formal arguments list.  What am I doing wrong here?  Is there a way to do this right?

Body:
Well, T[size] theArray is simply not correct declaration syntax. Just like when declaring arrays in any other context, the name goes before the bounds. So T theArray[size] would be the right syntax.

But this will still not do what you want it to do because arrays can't be passed by value and trying to pass an array by value causes it to decay to a pointer. The compiler must rewrite your parameter declaration to simply T* theArray. This makes size impossible to deduce, and allows your function to accept arbitrary pointers.

To solve these issues, you have to pass the array by reference:

template<typename T, int size> inline void ClearTheArray(T (&theArray)[size])
{
   for (size_t i=0; i<size; i++) theArray[i] = T();
}

Then your example usage will behave as you expect.

There's no sense re-inventing the wheel though. The standard way to do this is

using std::begin;
using std::end;
std::fill(begin(myArray), end(myArray), 0);
std::fill(begin(somePointer), end(somePointer), 0);  // compile error


问:
What are the arrays that contain references to itself? What are circular references inside the array/object? How to serialize such entities in PHP?
While reading the manual page on the built-in function serialize() I came across the following quoted text :

You can even serialize() arrays that contain references to itself.
  Circular references inside the array/object you are serializing will
  also be stored. Any other reference will be lost.

I didn't understand what does mean by the array that contain references to itself?

I also didn't understand what are circular references inside the array/object?

The only thing I understood from the above text is I can generate a storable representation of such types of values using the built-in function serialize()

Also, there are no more code examples or explanation has been given with this regard.

I googled to understand the meaning of these types of entities specifically in PHP but I got nothing from Google.

Can someone please explain me these concepts with the help of easy to understand explanation accompanied with the suitable code examples. Examples would make things understand better.

答:
Examples are at the end of the answer.

In (a) we try insert an array into itself. But a mechanism called copy on write kicks in and we insert $a into a copy of $a and end up with an array that contains an empty array. (b) is a little tricky. First we create an array that contains a reference to itself, but that means $b will itself be a reference. Then we pass $b to serialize, but serialize accepts a value only and thus will create a copy of $b. The output shows an array that contains an array that contains a reference to itself. The R:2; in the output indicates a reference to the second array. For some internal reason the count starts with 1 and not 0. (If you're really interested, I could lookup the reason, but for this question you can just accept it).

Object act a little different. This is because objects in PHP are accessed by a an ID, and the copy on write only duplicates the ID structure and not the object itself. In the output of (c) you can see that this is by a small r. The number is just as above. But as seen in (d) you can also assign objects by reference and the small r will become a capital R. The output differs from (b), because while $d will be copied just like $b it again only affects the ID structure, and we see an object that contains a reference to itself. (e) utilizes the clone keyword to create an actual copy and serializes as such.

Further Reading about PHP refereces.

```<code><?php

$a = [];
$a[] = $a;
echo "\na: ".serialize($a);

$b = [];
$b[] =& $b;
echo "\nb: ".serialize($b);

$c = new stdClass();
$c->c = $c;
echo "\nc: ".serialize($c);

$d = new stdClass();
$d->d =& $d;
echo "\nd: ".serialize($d);

$e = new stdClass();
$e->e = clone $e;
echo "\ne: ".serialize($e);
</code>```

Output:

```<code>a: a:1:{i:0;a:0:{}}
b: a:1:{i:0;a:1:{i:0;R:2;}}
c: O:8:"stdClass":1:{s:1:"c";r:1;}
d: O:8:"stdClass":1:{s:1:"d";R:1;}
e: O:8:"stdClass":1:{s:1:"e";O:8:"stdClass":0:{}}
</code>```

Link to play around with.

Feel free to ask for clarification in comments the question is quite broad and I tried to keep it brief.

Body:
Examples are at the end of the answer.

In (a) we try insert an array into itself. But a mechanism called copy on write kicks in and we insert $a into a copy of $a and end up with an array that contains an empty array. (b) is a little tricky. First we create an array that contains a reference to itself, but that means $b will itself be a reference. Then we pass $b to serialize, but serialize accepts a value only and thus will create a copy of $b. The output shows an array that contains an array that contains a reference to itself. The R:2; in the output indicates a reference to the second array. For some internal reason the count starts with 1 and not 0. (If you're really interested, I could lookup the reason, but for this question you can just accept it).

Object act a little different. This is because objects in PHP are accessed by a an ID, and the copy on write only duplicates the ID structure and not the object itself. In the output of (c) you can see that this is by a small r. The number is just as above. But as seen in (d) you can also assign objects by reference and the small r will become a capital R. The output differs from (b), because while $d will be copied just like $b it again only affects the ID structure, and we see an object that contains a reference to itself. (e) utilizes the clone keyword to create an actual copy and serializes as such.

Further Reading about PHP refereces.

<?php

$a = [];
$a[] = $a;
echo "\na: ".serialize($a);

$b = [];
$b[] =& $b;
echo "\nb: ".serialize($b);

$c = new stdClass();
$c->c = $c;
echo "\nc: ".serialize($c);

$d = new stdClass();
$d->d =& $d;
echo "\nd: ".serialize($d);

$e = new stdClass();
$e->e = clone $e;
echo "\ne: ".serialize($e);

Output:

a: a:1:{i:0;a:0:{}}
b: a:1:{i:0;a:1:{i:0;R:2;}}
c: O:8:"stdClass":1:{s:1:"c";r:1;}
d: O:8:"stdClass":1:{s:1:"d";R:1;}
e: O:8:"stdClass":1:{s:1:"e";O:8:"stdClass":0:{}}

Link to play around with.

Feel free to ask for clarification in comments the question is quite broad and I tried to keep it brief.


问:
Creating a log file from command line
I'm using the csc command to build a dll

```<code>csc /out:Test.dll /target:library file1.cs file2.cs
</code>```

I tried adding the /fl and /flp parameters to the command to make it
the following :

```<code>csc /out:Test.dll /target:library file1.cs file2.cs /fl
/flp:logfile=MyProjectOutput.log;verbosity=normal
</code>```

. But it doesn't work as the /fl command is not recognized.
 Links-https://msdn.microsoft.com/en-us/library/ms171470.aspx

答:
As @virusstorm pointed out, you are using the csc and not msbuild, which means you need the /errorlog flag:

```<code>csc /out:Test.dll /target:library file1.cs file2.cs /errorlog:MyProjectOutput.log
</code>```

Title: Creating a log file from command line

Body:
I'm using the csc command to build a dll

csc /out:Test.dll /target:library file1.cs file2.cs

I tried adding the /fl and /flp parameters to the command to make it
the following :

csc /out:Test.dll /target:library file1.cs file2.cs /fl
/flp:logfile=MyProjectOutput.log;verbosity=normal

. But it doesn't work as the /fl command is not recognized.
 Links-https://msdn.microsoft.com/en-us/library/ms171470.aspx

Body:
As @virusstorm pointed out, you are using the csc and not msbuild, which means you need the /errorlog flag:

csc /out:Test.dll /target:library file1.cs file2.cs /errorlog:MyProjectOutput.log


问:
Syntax error when I add an additional field to select statement
SQL novice hoping to get some help with a select statement

I can run this successfully:

```<code>select distinct t.QUALIFIEDORGUNITCODE as DEALERNUMBER,
       count(distinct(t.TRANSACTIONID)) as TRANSACTION_VOLUME
  from adtdealers.transaction t
  where t.DATECREATED between '01-oct-17' and '01-nov-17'
  group by t.QUALIFIEDORGUNITCODE;
</code>```

but if I attempt to add another field to the select I receive the following error:

ORA-00936: missing expression 00936. 00000 - "missing expression" *Cause: *Action: Error at Line: 17 Column: 105

```<code>select to_char(t.DATECREATED, 'MON-DD') as DAY,
       count(distinct(t.TRANSACTIONID)) as TRANSACTION_VOLUME,
       distinct t.QUALIFIEDORGUNITCODE as DEALERNUMBER
  from adtdealers.transaction t
  where t.DATECREATED between '01-oct-17' and '01-nov-17'
  group by to_char(t.DATECREATED, 'MON-DD'), t.QUALIFIEDORGUNITCODE;
</code>```

I can also run this succesfully:

```<code>select distinct t.QUALIFIEDORGUNITCODE as DEALERNUMBER,
       to_char(t.DATECREATED, 'MON-DD') as DAY
  from adtdealers.transaction t
  where t.DATECREATED between '01-oct-17' and '01-nov-17'
  group by t.QUALIFIEDORGUNITCODE, t.DATECREATED;
</code>```

答:
You almost never need select distinct if you are using group by.  I think you simply intend:

```<code>select to_char(t.DATECREATED, 'MON-DD') as DAY,
       count(distinct t.TRANSACTIONID) as TRANSACTION_VOLUME,
       t.QUALIFIEDORGUNITCODE as DEALERNUMBER
from adtdealers.transaction t
where t.DATECREATED between date '2017-10-01' and date '2017-11-01'
group by to_char(t.DATECREATED, 'MON-DD'), t.QUALIFIEDORGUNITCODE;
</code>```

Notice that I changed the date literals to use ISO-standard formats at the date keyword.

Body:
SQL novice hoping to get some help with a select statement

I can run this successfully:

select distinct t.QUALIFIEDORGUNITCODE as DEALERNUMBER,
       count(distinct(t.TRANSACTIONID)) as TRANSACTION_VOLUME
  from adtdealers.transaction t
  where t.DATECREATED between '01-oct-17' and '01-nov-17'
  group by t.QUALIFIEDORGUNITCODE;

but if I attempt to add another field to the select I receive the following error:

ORA-00936: missing expression 00936. 00000 - "missing expression" *Cause: *Action: Error at Line: 17 Column: 105

select to_char(t.DATECREATED, 'MON-DD') as DAY,
       count(distinct(t.TRANSACTIONID)) as TRANSACTION_VOLUME,
       distinct t.QUALIFIEDORGUNITCODE as DEALERNUMBER
  from adtdealers.transaction t
  where t.DATECREATED between '01-oct-17' and '01-nov-17'
  group by to_char(t.DATECREATED, 'MON-DD'), t.QUALIFIEDORGUNITCODE;

I can also run this succesfully:

select distinct t.QUALIFIEDORGUNITCODE as DEALERNUMBER,
       to_char(t.DATECREATED, 'MON-DD') as DAY
  from adtdealers.transaction t
  where t.DATECREATED between '01-oct-17' and '01-nov-17'
  group by t.QUALIFIEDORGUNITCODE, t.DATECREATED;

Body:
You almost never need select distinct if you are using group by.  I think you simply intend:

select to_char(t.DATECREATED, 'MON-DD') as DAY,
       count(distinct t.TRANSACTIONID) as TRANSACTION_VOLUME,
       t.QUALIFIEDORGUNITCODE as DEALERNUMBER
from adtdealers.transaction t
where t.DATECREATED between date '2017-10-01' and date '2017-11-01'
group by to_char(t.DATECREATED, 'MON-DD'), t.QUALIFIEDORGUNITCODE;

Notice that I changed the date literals to use ISO-standard formats at the date keyword.


答:
I've gone way overboard here (because I'm bored I guess) and whipped up an extensible password-checking system. Perhaps it will help clarify why your version doesn't do what you want (or maybe it won't).

The essential problem with your code is that it checks for a single characteristic instead each of the required characteristics.

```<code>def check_password(password):
    # These are the characteristics we want a password to have:
    characteristics = [
        length(8),      # At least 8 characters
        lower_case(1),  # At least 1 lower case letter
        upper_case(1),  # At least 1 upper case letter
        number(1),      # At least 1 number
    ]
    # Check to see if the supplied password has *all* of the desired
    # characteristics:
    return all(
        characteristic(password)
        for characteristic in characteristics
    )

def length(n=10):
    # Ensure password has at least N characters
    def check(password):
        return len(password) >= n
    return check

def lower_case(n=1):
    # Ensure password has at least N lower case characters
    def check(password):
        count = 0
        for char in password:
            if char.islower():
                count += 1
            if count == n:
                return True
        return False
    return check

def upper_case(n=1):
    # Ensure password has at least N upper case characters
    def check(password):
        count = 0
        for char in password:
            if char.isupper():
                count += 1
            if count == n:
                return True
        return False
    return check

def number(n=1):
    # Ensure password has at least N numbers
    def check(password):
        count = 0
        for char in password:
            if char.isdigit():
                count += 1
            if count == n:
                return True
        return False
    return check

# Doesn't have any numbers:
>>> print(check_password('TopSecret'))
False

# Acceptable:
>>> print(check_password('TopSecret15'))
True

# Has lower case, upper case, and number, but it's not long enough:
>>> print(check_password('Ab1'))
False
</code>```

Notes:

Some parts of this are simplified in order to make it more clear what's going on (all of the check functions could be one-liners).

In a production system, password requirements will almost certainly change over time and you want to make sure that implementing additional requirements is easy.

A regular expression might not be as easy to understand or extend (although it might be a little faster, but that probably doesn't matter at all).

The approach above is somewhat similar to Django's password validation system.

Title: Checking a password

Body:
I've gone way overboard here (because I'm bored I guess) and whipped up an extensible password-checking system. Perhaps it will help clarify why your version doesn't do what you want (or maybe it won't).

The essential problem with your code is that it checks for a single characteristic instead each of the required characteristics.

def check_password(password):
    # These are the characteristics we want a password to have:
    characteristics = [
        length(8),      # At least 8 characters
        lower_case(1),  # At least 1 lower case letter
        upper_case(1),  # At least 1 upper case letter
        number(1),      # At least 1 number
    ]
    # Check to see if the supplied password has *all* of the desired
    # characteristics:
    return all(
        characteristic(password)
        for characteristic in characteristics
    )

def length(n=10):
    # Ensure password has at least N characters
    def check(password):
        return len(password) >= n
    return check

def lower_case(n=1):
    # Ensure password has at least N lower case characters
    def check(password):
        count = 0
        for char in password:
            if char.islower():
                count += 1
            if count == n:
                return True
        return False
    return check

def upper_case(n=1):
    # Ensure password has at least N upper case characters
    def check(password):
        count = 0
        for char in password:
            if char.isupper():
                count += 1
            if count == n:
                return True
        return False
    return check

def number(n=1):
    # Ensure password has at least N numbers
    def check(password):
        count = 0
        for char in password:
            if char.isdigit():
                count += 1
            if count == n:
                return True
        return False
    return check

# Doesn't have any numbers:
>>> print(check_password('TopSecret'))
False

# Acceptable:
>>> print(check_password('TopSecret15'))
True

# Has lower case, upper case, and number, but it's not long enough:
>>> print(check_password('Ab1'))
False

Notes:

Some parts of this are simplified in order to make it more clear what's going on (all of the check functions could be one-liners).

In a production system, password requirements will almost certainly change over time and you want to make sure that implementing additional requirements is easy.

A regular expression might not be as easy to understand or extend (although it might be a little faster, but that probably doesn't matter at all).

The approach above is somewhat similar to Django's password validation system.


问:
Repeat Python function call on exception?
Hey everybody I'm working on a data scraping project and I'm looking for a clean way to repeat a function call if an exception is raised.

Pseudo-code:

```<code>try:
    myfunc(x)
except myError:
    ###try to call myfunc(x) again Y number of times,
        until success(no exceptions raised) otherwise raise myError2
</code>```

I realize this isn't best practice at all but I'm working through a number of different code/network layers that aren't reliable and I can't realistically debug them.

Right now I'm accomplishing this with a huge set of try\except blocks and it's making my eyes bleed.

Elegant ideas anyone?

答:
To do precisely what you want, you could do something like the following:

```<code>import functools
def try_x_times(x, exceptions_to_catch, exception_to_raise, fn):
    @functools.wraps(fn) #keeps name and docstring of old function
    def new_fn(*args, **kwargs):
        for i in xrange(x):
            try:
                return fn(*args, **kwargs)
            except exceptions_to_catch:
                 pass
        raise exception_to_raise
    return new_fn
</code>```

Then you just wrap the old function in this new function:

```<code>#instead of
#risky_method(1,2,'x')
not_so_risky_method = try_x_times(3, (MyError,), myError2, risky_method)
not_so_risky_method(1,2,'x')

#or just
try_x_times(3, (MyError,), myError2, risky_method)(1,2,'x')
</code>```

Body:
Hey everybody I'm working on a data scraping project and I'm looking for a clean way to repeat a function call if an exception is raised.

Pseudo-code:

try:
    myfunc(x)
except myError:
    ###try to call myfunc(x) again Y number of times,
        until success(no exceptions raised) otherwise raise myError2

I realize this isn't best practice at all but I'm working through a number of different code/network layers that aren't reliable and I can't realistically debug them.

Right now I'm accomplishing this with a huge set of try\except blocks and it's making my eyes bleed.

Elegant ideas anyone?

Body:
To do precisely what you want, you could do something like the following:

import functools
def try_x_times(x, exceptions_to_catch, exception_to_raise, fn):
    @functools.wraps(fn) #keeps name and docstring of old function
    def new_fn(*args, **kwargs):
        for i in xrange(x):
            try:
                return fn(*args, **kwargs)
            except exceptions_to_catch:
                 pass
        raise exception_to_raise
    return new_fn

Then you just wrap the old function in this new function:

#instead of
#risky_method(1,2,'x')
not_so_risky_method = try_x_times(3, (MyError,), myError2, risky_method)
not_so_risky_method(1,2,'x')

#or just
try_x_times(3, (MyError,), myError2, risky_method)(1,2,'x')


问:
"Collapsing" state in a functional map?
This question is inspired by Software Foundations, but isn't about an exercise. That I know about, so far.

The Imp chapter ("Simple Imperative Programs") uses functional maps (from the Maps chapter ("Total and Partial Maps")) for the environment of the simpl.[1] programming language.

```<code>Inductive id : Type :=
  | Id : string -> id.

Definition total_map (A:Type) := id -> A.

Definition t_empty {A:Type} (v : A) : total_map A :=
  (fun _ => v).

Definition t_update {A:Type} (m : total_map A) (x : id) (v : A) :=
  fun x' => if beq_id x x' then v else m x'.
</code>```

Reasoning about programs in the Imp chapter requires manipulating program states of the form t_update (t_update (...) x 4) y 12), which becomes tedious because the state grows with every assignment, even if what the assignment is "implementing" is an update of an existing variable.

In theory, it should be possible to collapse program states down to single t_update's for each variable, and I've gone so far as to prove a couple of lemmas that go in the right direction.

```<code>Require Import Coq.Logic.FunctionalExtensionality.

Lemma swap_updates : forall A (m : total_map A) x vx y vy,
  x <> y -> t_update (t_update m x vx) y vy = t_update (t_update m y vy) x vx.
Proof.
  intros A m x vx y vy H. apply functional_extensionality. intros k.
  unfold t_update. destruct (beq_id y k) eqn:Eqyk.
  - destruct (beq_id x k) eqn:Eqxk.
    + apply beq_id_true_iff in Eqyk. apply beq_id_true_iff in Eqxk. subst.
      contradiction.
    + reflexivity.
  - destruct (beq_id x k) eqn:Eqxk; reflexivity.
Qed.

Lemma collapse_updates : forall A (m : total_map A) x v1 v2,
  t_update (t_update m x v1) x v2 = t_update m x v2.
Proof.
  intros A m x v1 v2. apply functional_extensionality. intros k.
  unfold t_update. destruct (beq_id x k); reflexivity.
Qed.
</code>```

But I don't know how to state (much less prove or use, for that matter) a theorem that t_update (... (t_update (...) x 4) ...) x 27 is equal to t_update (...) x 27; i.e. with the useless bindings for x removed.

Any ideas?

[1] I just saw this. I'm leaving it, but I'm considering taking a vacation from Coq soon.

答:
One way to do this is to proceed via an intermediate representation where we can more easily manipulate the updates. I did so by defining updates in terms of a list of (id, A) pairs (l_update), and then proved that we can add to the list of updates and replace any existing updates (add_update does this). The simplification is finally a tactic that first rewrites everything to use l_update, then computes the list of updates (which doesn't have duplicate IDs) by simplifying add_update, and then finally computes l_update down to t_updates (since it happens to be defined that way). In a real development it would be a bit easier since you'd be using strings for the IDs and the if string_dec "a" "b" then ... else ... calls should compute away, whereas I have to use a rewrite since the decision function is an axiom.

```<code>Require Import Coq.Logic.FunctionalExtensionality.
Require Import List.

Variable id:Type.
Axiom id_eq_dec : forall (x y:id), {x=y}+{x<>y}.

Variable A:Type.

Definition total_map := id -> A.

Definition t_update (m : total_map) (x : id) (v : A) : total_map :=
  fun x' => if id_eq_dec x x' then v else m x'.

Definition Updates := list (id*A).

Fixpoint l_update (m:total_map) (us:Updates) : total_map :=
  match us with
  | nil => m
  | (x,a)::us' => t_update (l_update m us') x a
  end.

Fixpoint add_update (us:Updates) x a : Updates :=
  match us with
  | nil => (x, a)::nil
  | (x',a')::us' => if id_eq_dec x x' then
                    add_update us' x a
                  else (x',a') :: add_update us' x a
  end.

Lemma t_update_neq : forall m x v x',
    x <> x' ->
    t_update m x v x' = m x'.
Proof.
  unfold t_update; intros.
  destruct (id_eq_dec x x'); congruence.
Qed.

Lemma t_update_eq : forall m x v,
    t_update m x v x = v.
Proof.
  unfold t_update; intros.
  destruct (id_eq_dec x x); congruence.
Qed.

Hint Rewrite t_update_neq using (solve [ auto ] ) : upd.
Hint Rewrite t_update_eq : upd.

Ltac cmp_id x x' := destruct (id_eq_dec x x'); subst; simpl;
                    try autorewrite with upd;
                    try congruence; auto.

Lemma l_update_add_other_update: forall us x a m a' x',
    x <> x' ->
    l_update m (add_update us x a) x' = l_update m (add_update us x a') x'.
Proof.
  induction us; simpl; intros.
  autorewrite with upd; auto.
  destruct a.
  cmp_id x i.
  cmp_id i x'.
Qed.

Hint Resolve l_update_add_other_update.

Lemma l_update_add_update : forall us m x a,
    l_update m (add_update us x a) x = a.
Proof.
  induction us; simpl; intros;
    autorewrite with upd;
    auto.
  destruct a; simpl.
  cmp_id x i.
Qed.

Hint Rewrite l_update_add_update : upd.

Lemma l_update_add_update_neq : forall us m x x' a,
    x <> x' ->
    l_update m (add_update us x a) x' = l_update m us x'.
Proof.
  induction us; intros.
  simpl; autorewrite with upd; auto.
  destruct a; simpl.
  cmp_id x i.
  cmp_id i x'.
Qed.

Hint Rewrite l_update_add_update_neq using solve [ auto ] : upd.

Theorem l_update_add : forall us m x a,
    t_update (l_update m us) x a =
    l_update m (add_update us x a).
Proof.
  induction us; intros; extensionality x'; simpl; auto.
  destruct a; simpl in *.
  rewrite IHus by auto.
  cmp_id x i.
  cmp_id i x'.
  cmp_id x x'.
  cmp_id i x'.
Qed.

Lemma if_id_eq_not : forall T (a b:T) i i',
    i <> i' ->
    (if id_eq_dec i i' then a else b) = b.
Proof.
  intros.
  destruct (id_eq_dec i i'); congruence.
Qed.

Lemma if_id_eq : forall T (a b:T) i,
    (if id_eq_dec i i then a else b) = a.
Proof.
  intros.
  destruct (id_eq_dec i i); congruence.
Qed.

Ltac simplify_updates m :=
  replace m with (l_update m nil) by auto;
  repeat rewrite l_update_add;
  repeat (simpl; rewrite ?if_id_eq_not, ?if_id_eq by auto).

Example update_chain1 : forall m x1 x2 x3 a1 a2 a3 a4 a5,
    x1 <> x2 ->
    x2 <> x3 ->
    x1 <> x3 ->
    t_update
      (t_update
        (t_update
            (t_update
              (t_update m x1 a1) x3 a2) x2 a3) x1 a4) x3 a5 =
    t_update
      (t_update
        (t_update m x3 a5) x1 a4) x2 a3.
Proof.
  intros.
  etransitivity.
  simplify_updates m.
  auto.
  auto.
Qed.
</code>```

Title: "Collapsing" state in a functional map?

Body:
This question is inspired by Software Foundations, but isn't about an exercise. That I know about, so far.

The Imp chapter ("Simple Imperative Programs") uses functional maps (from the Maps chapter ("Total and Partial Maps")) for the environment of the simpl.[1] programming language.

Inductive id : Type :=
  | Id : string -> id.

Definition total_map (A:Type) := id -> A.

Definition t_empty {A:Type} (v : A) : total_map A :=
  (fun _ => v).

Definition t_update {A:Type} (m : total_map A) (x : id) (v : A) :=
  fun x' => if beq_id x x' then v else m x'.

Reasoning about programs in the Imp chapter requires manipulating program states of the form t_update (t_update (...) x 4) y 12), which becomes tedious because the state grows with every assignment, even if what the assignment is "implementing" is an update of an existing variable.

In theory, it should be possible to collapse program states down to single t_update's for each variable, and I've gone so far as to prove a couple of lemmas that go in the right direction.

Require Import Coq.Logic.FunctionalExtensionality.

Lemma swap_updates : forall A (m : total_map A) x vx y vy,
  x <> y -> t_update (t_update m x vx) y vy = t_update (t_update m y vy) x vx.
Proof.
  intros A m x vx y vy H. apply functional_extensionality. intros k.
  unfold t_update. destruct (beq_id y k) eqn:Eqyk.
  - destruct (beq_id x k) eqn:Eqxk.
    + apply beq_id_true_iff in Eqyk. apply beq_id_true_iff in Eqxk. subst.
      contradiction.
    + reflexivity.
  - destruct (beq_id x k) eqn:Eqxk; reflexivity.
Qed.

Lemma collapse_updates : forall A (m : total_map A) x v1 v2,
  t_update (t_update m x v1) x v2 = t_update m x v2.
Proof.
  intros A m x v1 v2. apply functional_extensionality. intros k.
  unfold t_update. destruct (beq_id x k); reflexivity.
Qed.

But I don't know how to state (much less prove or use, for that matter) a theorem that t_update (... (t_update (...) x 4) ...) x 27 is equal to t_update (...) x 27; i.e. with the useless bindings for x removed.

Any ideas?

[1] I just saw this. I'm leaving it, but I'm considering taking a vacation from Coq soon.

Body:
One way to do this is to proceed via an intermediate representation where we can more easily manipulate the updates. I did so by defining updates in terms of a list of (id, A) pairs (l_update), and then proved that we can add to the list of updates and replace any existing updates (add_update does this). The simplification is finally a tactic that first rewrites everything to use l_update, then computes the list of updates (which doesn't have duplicate IDs) by simplifying add_update, and then finally computes l_update down to t_updates (since it happens to be defined that way). In a real development it would be a bit easier since you'd be using strings for the IDs and the if string_dec "a" "b" then ... else ... calls should compute away, whereas I have to use a rewrite since the decision function is an axiom.

Require Import Coq.Logic.FunctionalExtensionality.
Require Import List.

Variable id:Type.
Axiom id_eq_dec : forall (x y:id), {x=y}+{x<>y}.

Variable A:Type.

Definition total_map := id -> A.

Definition t_update (m : total_map) (x : id) (v : A) : total_map :=
  fun x' => if id_eq_dec x x' then v else m x'.

Definition Updates := list (id*A).

Fixpoint l_update (m:total_map) (us:Updates) : total_map :=
  match us with
  | nil => m
  | (x,a)::us' => t_update (l_update m us') x a
  end.

Fixpoint add_update (us:Updates) x a : Updates :=
  match us with
  | nil => (x, a)::nil
  | (x',a')::us' => if id_eq_dec x x' then
                    add_update us' x a
                  else (x',a') :: add_update us' x a
  end.

Lemma t_update_neq : forall m x v x',
    x <> x' ->
    t_update m x v x' = m x'.
Proof.
  unfold t_update; intros.
  destruct (id_eq_dec x x'); congruence.
Qed.

Lemma t_update_eq : forall m x v,
    t_update m x v x = v.
Proof.
  unfold t_update; intros.
  destruct (id_eq_dec x x); congruence.
Qed.

Hint Rewrite t_update_neq using (solve [ auto ] ) : upd.
Hint Rewrite t_update_eq : upd.

Ltac cmp_id x x' := destruct (id_eq_dec x x'); subst; simpl;
                    try autorewrite with upd;
                    try congruence; auto.

Lemma l_update_add_other_update: forall us x a m a' x',
    x <> x' ->
    l_update m (add_update us x a) x' = l_update m (add_update us x a') x'.
Proof.
  induction us; simpl; intros.
  autorewrite with upd; auto.
  destruct a.
  cmp_id x i.
  cmp_id i x'.
Qed.

Hint Resolve l_update_add_other_update.

Lemma l_update_add_update : forall us m x a,
    l_update m (add_update us x a) x = a.
Proof.
  induction us; simpl; intros;
    autorewrite with upd;
    auto.
  destruct a; simpl.
  cmp_id x i.
Qed.

Hint Rewrite l_update_add_update : upd.

Lemma l_update_add_update_neq : forall us m x x' a,
    x <> x' ->
    l_update m (add_update us x a) x' = l_update m us x'.
Proof.
  induction us; intros.
  simpl; autorewrite with upd; auto.
  destruct a; simpl.
  cmp_id x i.
  cmp_id i x'.
Qed.

Hint Rewrite l_update_add_update_neq using solve [ auto ] : upd.

Theorem l_update_add : forall us m x a,
    t_update (l_update m us) x a =
    l_update m (add_update us x a).
Proof.
  induction us; intros; extensionality x'; simpl; auto.
  destruct a; simpl in *.
  rewrite IHus by auto.
  cmp_id x i.
  cmp_id i x'.
  cmp_id x x'.
  cmp_id i x'.
Qed.

Lemma if_id_eq_not : forall T (a b:T) i i',
    i <> i' ->
    (if id_eq_dec i i' then a else b) = b.
Proof.
  intros.
  destruct (id_eq_dec i i'); congruence.
Qed.

Lemma if_id_eq : forall T (a b:T) i,
    (if id_eq_dec i i then a else b) = a.
Proof.
  intros.
  destruct (id_eq_dec i i); congruence.
Qed.

Ltac simplify_updates m :=
  replace m with (l_update m nil) by auto;
  repeat rewrite l_update_add;
  repeat (simpl; rewrite ?if_id_eq_not, ?if_id_eq by auto).

Example update_chain1 : forall m x1 x2 x3 a1 a2 a3 a4 a5,
    x1 <> x2 ->
    x2 <> x3 ->
    x1 <> x3 ->
    t_update
      (t_update
        (t_update
            (t_update
              (t_update m x1 a1) x3 a2) x2 a3) x1 a4) x3 a5 =
    t_update
      (t_update
        (t_update m x3 a5) x1 a4) x2 a3.
Proof.
  intros.
  etransitivity.
  simplify_updates m.
  auto.
  auto.
Qed.


问:
How do I check whether an unsigned int variable contains a negative number?
I have the following code:

```<code>int main()
{
    int i;
    unsigned int j;

    printf("Type a number:  ");
    scanf("%d", &i);

    j = i;

    if (________)
    {
        printf("Negative!\n");
    }

    return 0;
}
</code>```

What would I put in the if statement in order to check whether the unsigned variable "j" contains a negative number?

答:
```<code>int i;
unsigned int j;

// store a value in i

j = i;
</code>```

To test whether j contains a negative number:

```<code>if (0)
{
    printf("Negative!\n");
}
</code>```

An unsigned integer can never hold a negative value.

If the value of i is negative, then it will be converted to some positive value when you assign it to j. If you want to know whether the value of i is negative, you should test i, not j.

```<code>if (i < 0) {
    puts("i is negative");
}
else {
    puts("i is not negative");
}
puts("j is not negative");
</code>```

Note that converting the value of j back to int is not reliable. Conversion of a value exceeding INT_MAX to type int yields an implementation-defined result (or raises an implementation-defined signal). It's very likely you'll get back the original value of i, but why bother? If you want to test the value of i, test the value of i.

Body:
I have the following code:

int main()
{
    int i;
    unsigned int j;

    printf("Type a number:  ");
    scanf("%d", &i);

    j = i;

    if (________)
    {
        printf("Negative!\n");
    }

    return 0;
}

What would I put in the if statement in order to check whether the unsigned variable "j" contains a negative number?

Body:
int i;
unsigned int j;

// store a value in i

j = i;

To test whether j contains a negative number:

if (0)
{
    printf("Negative!\n");
}

An unsigned integer can never hold a negative value.

If the value of i is negative, then it will be converted to some positive value when you assign it to j. If you want to know whether the value of i is negative, you should test i, not j.

if (i < 0) {
    puts("i is negative");
}
else {
    puts("i is not negative");
}
puts("j is not negative");

Note that converting the value of j back to int is not reliable. Conversion of a value exceeding INT_MAX to type int yields an implementation-defined result (or raises an implementation-defined signal). It's very likely you'll get back the original value of i, but why bother? If you want to test the value of i, test the value of i.


问:
run python script from google home
I am trying to figure out if it is possible to trigger a python script to be run using google home? I would like to do something like saying "Hey Google run my python script." And from the Google home would execute running my python script. Anyone know if that is possible? </p>

答:
You could create a Dialogflow app that integrates with the Google Assistant so that when you invoke the app it sends a HTTP request to your server.  You could setup your server so that it runs your Python script when you receive that HTTP request.

Tutorial to create a Dialogflow app: https://dialogflow.com/docs/getting-started/building-your-first-agent

Title: run python script from google home


问:
Text and TouchableOpacity Style Type Annotations
I am trying to type annotate my React Native project using Flow, but I am having trouble finding the type definitions for the Text and TouchableOpacity elements so I can reference their style prop type definitions. How can I import and/or reference the type definitions for these elements?

Code below:

```<code>// @flow
import * as React from "react";
import { Text, TouchableOpacity } from "react-native";

type Props = {
    segmentIndex: number,
    segmentInfo: {
        title: string
    },
    segmentStyle: ???, // WHAT SHOULD I USE HERE?
    titleStyle: ???, // WHAT SHOULD I USE HERE?
    onSelection: (number) => void
}

export const SegmentButton = (props: Props) => {
    const _segmentPressed = () => {
        props.onSelection(props.segmentIndex)
    }

    return (
        <TouchableOpacity style={props.segmentStyle} onPress={_segmentPressed}>
            <Text style={props.titleStyle}>{props.segmentInfo.title.charAt(0).toUpperCase() + props.segmentInfo.title.substring(1)}</Text>
        </TouchableOpacity>
    )
}
</code>```

答:
There are many ways to define StyleSheet type.

1. react-native generic way

reference from react-native library,

SwipeableQuickActionButton.js

import { View } from 'react-native';

type Prop = {
    style?: ?View.propTypes.style,
}
```

<h2>2. <em>react-navigation</em> generic way</h2>

<p>reference from <em>react-navigation</em> library,</p>

<p><strong>TypeDefinition.js</strong></p>

<pre class="lang-is prettyprint-override"><code>export type Style =
  | { [key: string]: any }
  | number
  | false
  | null
  | void
  | Array<Style>;
</code>```

If you already installed react-navigation, import it from:

import type { Style } from 'react-navigation/src/TypeDefinition';

type Prop = {
    style?: Style,
}
```

<p>Or you can still use it by define in your own file.</p>

<h2>3. make <code>Style</code> type specific for <code><Text /></code> and <code><TouchableOpacity /></code></h2>

<p>It would be the hard way -- although doable, see if that worth the trouble.</p>

<p>take <code><Picker /></code> for reference, it defined <code>itemStyle</code> for <code><Text /></code> like below, which corresponding to text style for each picker item.</p>

<pre class="lang-is prettyprint-override"><code>var StyleSheetPropType = require('StyleSheetPropType');
var TextStylePropTypes = require('TextStylePropTypes');
var TextStyle = StyleSheetPropType(TextStylePropTypes);

type Prop = {
    itemStyle: TextStyle
}
</code>```

To use it in your own library, import them from:

import TextStylePropTypes from 'react-native/Libraries/Text/TextStylePropTypes';
import StyleSheetPropType from 'react-native/Libraries/StyleSheet/StyleSheetPropType';

let TextStyle = StyleSheetPropType(TextStylePropTypes);

type Prop = {
    style?: ?TextStyle,
}
```

Body:
I am trying to type annotate my React Native project using Flow, but I am having trouble finding the type definitions for the Text and TouchableOpacity elements so I can reference their style prop type definitions. How can I import and/or reference the type definitions for these elements?

Code below:

// @flow
import * as React from "react";
import { Text, TouchableOpacity } from "react-native";

type Props = {
    segmentIndex: number,
    segmentInfo: {
        title: string
    },
    segmentStyle: ???, // WHAT SHOULD I USE HERE?
    titleStyle: ???, // WHAT SHOULD I USE HERE?
    onSelection: (number) => void
}

export const SegmentButton = (props: Props) => {
    const _segmentPressed = () => {
        props.onSelection(props.segmentIndex)
    }

    return (
        <TouchableOpacity style={props.segmentStyle} onPress={_segmentPressed}>
            <Text style={props.titleStyle}>{props.segmentInfo.title.charAt(0).toUpperCase() + props.segmentInfo.title.substring(1)}</Text>
        </TouchableOpacity>
    )
}

Body:
There are many ways to define StyleSheet type.

1. react-native generic way

reference from react-native library,

SwipeableQuickActionButton.js

import { View } from 'react-native';

type Prop = {
    style?: ?View.propTypes.style,
}

2. react-navigation generic way

reference from react-navigation library,

TypeDefinition.js

export type Style =
  | { [key: string]: any }
  | number
  | false
  | null
  | void
  | Array<Style>;

If you already installed react-navigation, import it from:

import type { Style } from 'react-navigation/src/TypeDefinition';

type Prop = {
    style?: Style,
}

Or you can still use it by define in your own file.

3. make Style type specific for <Text /> and <TouchableOpacity />

It would be the hard way -- although doable, see if that worth the trouble.

take <Picker /> for reference, it defined itemStyle for <Text /> like below, which corresponding to text style for each picker item.

var StyleSheetPropType = require('StyleSheetPropType');
var TextStylePropTypes = require('TextStylePropTypes');
var TextStyle = StyleSheetPropType(TextStylePropTypes);

type Prop = {
    itemStyle: TextStyle
}

To use it in your own library, import them from:

import TextStylePropTypes from 'react-native/Libraries/Text/TextStylePropTypes';
import StyleSheetPropType from 'react-native/Libraries/StyleSheet/StyleSheetPropType';

let TextStyle = StyleSheetPropType(TextStylePropTypes);

type Prop = {
    style?: ?TextStyle,
}


问:
set navigationBar background image in swift
Code below is not working for me, can anyone help to figure it out what is wrong?</p>

```<code>var image = UIImage(named: "10384605_10152519403846670_5189785375955620548_n.jpg") as UIImage

self.navigationController.navigationBar.setBackgroundImage(image , forBarMetrics:UIBarMetrics)
</code>```

答:
@benLIVE asked for how to do a back button, which I was doing when I found the accepted answer, so I thought I'd leave this here too (if a bit late) b/c if you are going to replace a nav bar icon, you may as well replace all of them!</p>

```<code>    let cubeIcon = UIImageView(image: yourImage)
    cubeIcon.contentMode = .scaleAspectFit
    self.navigationItem.backBarButtonItem?.image = cubeIcon.image
</code>```

Body:
Code below is not working for me, can anyone help to figure it out what is wrong?

var image = UIImage(named: "10384605_10152519403846670_5189785375955620548_n.jpg") as UIImage

self.navigationController.navigationBar.setBackgroundImage(image , forBarMetrics:UIBarMetrics)

Body:
@benLIVE asked for how to do a back button, which I was doing when I found the accepted answer, so I thought I'd leave this here too (if a bit late) b/c if you are going to replace a nav bar icon, you may as well replace all of them!

    let cubeIcon = UIImageView(image: yourImage)
    cubeIcon.contentMode = .scaleAspectFit
    self.navigationItem.backBarButtonItem?.image = cubeIcon.image


问:
Fastest way to code up hitting a URL
I need to login to a site, then hit a certain URL about a thousand times (with different params, of course).

The URL is something this:

```<code>http://www.foo.com/bar.asp?id=x    ' where x is the ID
</code>```

Of course if I simply hit the URL without being logged, it will fail.
I am not very familiar with this type of work, but I would imagine that whatever the method I choose, it would have to support cookies.

I was thinking that I could create a winform app with a browser control and somehow drive it, but that seems like a massive overkill.

Is there a better way?

答: Using Python or PHP, you can use the libcURL library, I believe they both have bindings for these languages. If not, just use the urllib2 module (for Python).</p>

Title: Fastest way to code up hitting a URL

Body:
I need to login to a site, then hit a certain URL about a thousand times (with different params, of course).

The URL is something this:

http://www.foo.com/bar.asp?id=x    ' where x is the ID

Of course if I simply hit the URL without being logged, it will fail.
I am not very familiar with this type of work, but I would imagine that whatever the method I choose, it would have to support cookies.

I was thinking that I could create a winform app with a browser control and somehow drive it, but that seems like a massive overkill.

Is there a better way?


问:
How to organize mercurial repository / subrepositories in large team project
At work we need to regorganize our system of version control.

The structure of the project is the following:

2 teams: Team1 and Team2

a) Both Team1 and Team2 work on module A.

b) Team1 also works on B and C, which depend on A.

c) Team2 also works on D, which depends on A but not on B and C

We don't want Team2 to physically have on their local machines B and C (which belong to Team1) and at the same time we don't want Team1 to have D.

The aim is to have complete snapshots of the project in time, i.e. we would like to keep track and rollback to a given version of the whole project at any time.

We thought of using Mercurial subrepos, but it seems impossible (maybe) for a team to ignore the subrepos of the other team. Everyone has to pull every subrepo. Is this correct?

If so, how can we overcome this? Do we really need to have three completely independent repositories and manually track the compatible version of code A with that of both B+C and, separately, of D?

We are worried that such a manual tracking can be prone to errors over time.

答:
It's easy for a team to ignore the subrepos of another team.  They just need to use different branches in the parent repo, with .hgsub files that include only the subrepos needed for that branch.

I would suggest not having multiple master repos, but just one master repo with these three branches:

Branch "Team1" has in its .hgsub file only subrepos A, B, and C.

Branch "Team2" has only subrepos A and D in its .hgsub file.

Branch "All" (or default) has A, B, C, and D in its .hgsub file.

When team 1 checks out from branch team1, they get A, B, and C.  Team 2 checks out from branch team2, and they get just A and D.  The manager of the whole project uses branch "All" (or default), and updates all repos A, B, C, and D to appropriate versions, then commits, to tie all repo versions together and get the complete snapshot that you want.


问:
Issues with High Sierra 10.13.1 and Rails?
I've tried installing Rails on a high sierra but keep receiving a "Failed to build gem native extension" error.

checking for sys/epoll.h... no

^ This is what I need to be looking at. I'm not sure if this is an issue with the new OS...possibly an issue with nio4r-2.1.0?

Building native extensions. This could take a while...
ERROR:  Error installing rails:
 ERROR: Failed to build gem native extension.

    current directory: /Users/paulkim/.rvm/gems/ruby-2.4.2/gems/nio4r-2.1.0/ext/nio4r
/Users/paulkim/.rvm/rubies/ruby-2.4.2/bin/ruby -r ./siteconf20171203-22631-czj48g.rb extconf.rb
checking for unistd.h... yes
checking for sys/select.h... yes
checking for poll.h... yes
checking for sys/epoll.h... no
checking for sys/event.h... yes
checking for sys/queue.h... yes
checking for port.h... yes
checking for sys/resource.h... yes
creating Makefile

current directory: /Users/paulkim/.rvm/gems/ruby-2.4.2/gems/nio4r-2.1.0/ext/nio4r
make "DESTDIR=" clean

current directory: /Users/paulkim/.rvm/gems/ruby-2.4.2/gems/nio4r-2.1.0/ext/nio4r
make "DESTDIR="
compiling bytebuffer.c
compiling monitor.c
compiling nio4r_ext.c
In file included from nio4r_ext.c:7:
./../libev/ev.c:488:48: warning: '/*' within block comment [-Wcomment]
/*#define MIN_INTERVAL  0.00000095367431640625 /* 1/2**20, good till 2200 */
                                               ^
./../libev/ev.c:1068:26: warning: implicit conversion loses integer precision: 'uint64_t' (aka 'unsigned long long') to 'unsigned int' [-Wshorten-64-to-32]
  return ecb_popcount32 (x) + ecb_popcount32 (x >> 32);```

答:
It was an issue with High Sierra and xCode.I first reformatted my machine to El Capitan and had no issues installing Rails. Then on another machine with High Sierra I also had issues with Rails.

After updating to xCode 9.2, I successfully installed Rails 5.1.4.

Thanks everyone.