问:
State value `undefined` on state onChange
Writing a component named Member where I'm doing some calculations which I store in this.state before sending it somewhere else, but I got a problem, when firing one of onChange handlers some values of state are undefined , but should be filled some value.

Component Member

```<code>import React from "react";

import {calcSCR, difference, multiply} from "../../utils/Calculations";
import {SCR_COEFF} from "../../constants/calc";

class Member extends React.Component {

    constructor(props){
        super(props);

        this.state = {
            id: "1",
            full_name: 'Mocked member 1',
            role: 'Developer',
            salary: 1650,
            hourly_cost: 19.6, // SCR = (gross * coeff) / 100
            project_data: {
                project_id: '1',
                hourly_rate: 40,
                occupation: 50,
                estimate_hours: 70,
                revenue: 2800,// revenue = estimate_hours * hourly_rate
                cost: 1372,// cost = estimate_hours * hourly_cost
                profit: 1428// profit = revenue - cost
            }
        };

        this.onSalaryChange = this.onSalaryChange.bind(this);
        this.onHourlyCostChange = this.onHourlyCostChange.bind(this);
        this.onHourlyRateChange = this.onHourlyRateChange.bind(this);
        this.onEstimateHoursChange = this.onEstimateHoursChange.bind(this);
        this.onRevenueChange = this.onRevenueChange.bind(this);
        this.onCostChange = this.onCostChange.bind(this);
        this.onNameChange = this.onNameChange.bind(this);
        this.onOccupationChange = this.onOccupationChange.bind(this);

        this.save = this.save.bind(this);

    }

    save(){

    }

    onNameChange(e){
        this.setState({
            full_name: e.target.value
        })
    }

    onSalaryChange(e){
        let salary = e.target.value;

        this.setState({
            salary: salary,
            hourly_cost: calcSCR(salary, SCR_COEFF)
        })
    }

    onHourlyRateChange(e){
        let hourly_rate = e.target.value;
        let estimate_hours = this.state.project_data.estimate_hours;

        this.setState({
            project_data: {
                hourly_rate: hourly_rate,
                revenue: multiply(estimate_hours, hourly_rate)
            }
        })

    }

    onOccupationChange(e){
        this.setState({
            project_data: {
                occupation: e.target.value
            }
        })
    }

    onEstimateHoursChange(e){
        let estimate_hours = e.target.value;

        this.setState({
            project_data: {
                estimate_hours: estimate_hours,
                revenue: multiply(estimate_hours, this.state.project_data.hourly_rate),
                cost: multiply(estimate_hours,this.state.hourly_cost)
            }
        })

    }

    onHourlyCostChange(e){
        let hourly_cost = e.target.value;
        this.setState({
            hourly_cost: hourly_cost,
            project_data: {
                cost: multiply(this.state.project_data.estimate_hours, hourly_cost)
            }
        })
    }

    onRevenueChange(e){

        let revenue = e.target.value;

        this.setState({
            project_data: {
                revenue: revenue,
                profit: difference(revenue,this.state.project_data.cost)
            }
        })
    }

    onCostChange(e){

        let cost = e.target.value;

        this.setState({
            project_data: {
                cost: cost,
                profit: difference(this.state.project_data.revenue,cost)
            }
        })
    }

    render(){

        let {projectName} = this.props;
        let data = this.state;

        return (
            <div className="member">
                <a className="member__short_info" role="button" data-toggle="collapse" href={`#${data.id}`} aria-expanded="false" aria-controls={data.id}>
                    {data.full_name}
                </a>

                <div className="collapse member__member_full_info" id={data.id}>
                    <div className="member__full_info__row">
                        <div className="row">
                            <div className="col-sm-12 col-md-12 com-lg-12 member__full_info__header">
                                {projectName}
                            </div>

                            <div className="col-sm-12 col-md-12 col-lg-6 member__full_info__column">
                                <label htmlFor="full_name" className="member__full_info__label">Member full name:</label>
                                <input id="full_name" type="text" name="full_name" value={data.full_name} onChange={this.onNameChange}/>
                            </div>

                            <div className="col-sm-12 col-md-12 col-lg-6 member__full_info__column">
                                <label htmlFor="salary" className="member__full_info__label">Salary:</label>
                                <input id="salary" type="text" name="salary" value={data.salary} onChange={this.onSalaryChange}/>
                            </div>

                            <div className="col-sm-12 col-md-12 col-lg-6 member__full_info__column">
                                <label className="member__full_info__label">Hourly cost: </label>
                                <input id="hourly_cost" type="text" name="hourly_cost" value={data.hourly_cost} onChange={this.onHourlyCostChange}/>
                            </div>

                            <div className="col-sm-12 col-md-12 col-lg-6 member__full_info__column">
                                <label htmlFor="hourly_rate" className="member__full_info__label">Hourly rate</label>
                                <input id="hourly_rate" type="text" name="hourly_rate" value={data.project_data.hourly_rate} onChange={this.onHourlyRateChange}/>
                            </div>

                            <div className="col-sm-12 col-md-12 col-lg-6 member__full_info__column">
                                <label htmlFor="occupation" className="member__full_info__label">Occupation in project (%): </label>
                                <input id="occupation" type="text" name="occupation" value={data.project_data.occupation} onChange={this.onOccupationChange}/>
                            </div>

                            <div className="col-sm-12 col-md-12 col-lg-6 member__full_info__column">
                                <label htmlFor="estimate_hours" className="member__full_info__label">Estimate hours: </label>
                                <input id="estimate_hours" type="text" name="estimate_hours" value={data.project_data.estimate_hours} onChange={this.onEstimateHoursChange}/>
                            </div>

                            <div className="col-sm-12 col-md-12 col-lg-4 member__full_info__column">
                                <label className="member__full_info__label">Revenue: {data.project_data.revenue}</label>
                                {/*<input id="revenue" type="number" name="revenue" value={data.project_data.revenue} onChange={this.onRevenueChange}/>*/}
                            </div>

                            <div className="col-sm-12 col-md-12 col-lg-4 member__full_info__column">
                                <label className="member__full_info__label">Cost: {data.project_data.cost}</label>
                                {/*<input id="cost" type="number" name="cost" value={data.project_data.cost} onChange={this.onCostChange}/>*/}
                            </div>

                            <div className="col-sm-12 col-md-12 col-lg-4 member__full_info__column">
                                <label className="member__full_info__label">Profit: {data.project_data.profit}</label>
                            </div>

                            <div className="col-sm-12 member__full_info__save">
                                <button className="modal-component positive-btn no-margin" onClick={this.save}>Save</button>

                            </div>

                        </div>
                    </div>
                </div>
            </div>

        );
    }
}

export default Member;
</code>```

For example: inside onHourlyRateChange function estimate_hours becomes undefined after change.

Inside onEstimateHoursChange state variables this.state.project_data.hourly_rate and this.state.project_data.hourly_cost becomes undefined too. I have no Idea why it happens. Maybe you can give me some advices?

答:
You can partially update top-level properties of a state object, but nested updates won't work.

immutability-helper's update (replacement for react-addons-update) can be used to update nested properties:

```<code>import update from 'immutability-helper';

const newData = update(myData, {
  x: {y: {z: {$set: 7}}},
  a: {b: {$push: [9]}}
});
</code>```

Body:
Writing a component named Member where I'm doing some calculations which I store in this.state before sending it somewhere else, but I got a problem, when firing one of onChange handlers some values of state are undefined , but should be filled some value.

Component Member

import React from "react";

import {calcSCR, difference, multiply} from "../../utils/Calculations";
import {SCR_COEFF} from "../../constants/calc";

class Member extends React.Component {

    constructor(props){
        super(props);

        this.state = {
            id: "1",
            full_name: 'Mocked member 1',
            role: 'Developer',
            salary: 1650,
            hourly_cost: 19.6, // SCR = (gross * coeff) / 100
            project_data: {
                project_id: '1',
                hourly_rate: 40,
                occupation: 50,
                estimate_hours: 70,
                revenue: 2800,// revenue = estimate_hours * hourly_rate
                cost: 1372,// cost = estimate_hours * hourly_cost
                profit: 1428// profit = revenue - cost
            }
        };

        this.onSalaryChange = this.onSalaryChange.bind(this);
        this.onHourlyCostChange = this.onHourlyCostChange.bind(this);
        this.onHourlyRateChange = this.onHourlyRateChange.bind(this);
        this.onEstimateHoursChange = this.onEstimateHoursChange.bind(this);
        this.onRevenueChange = this.onRevenueChange.bind(this);
        this.onCostChange = this.onCostChange.bind(this);
        this.onNameChange = this.onNameChange.bind(this);
        this.onOccupationChange = this.onOccupationChange.bind(this);

        this.save = this.save.bind(this);

    }

    save(){

    }

    onNameChange(e){
        this.setState({
            full_name: e.target.value
        })
    }

    onSalaryChange(e){
        let salary = e.target.value;

        this.setState({
            salary: salary,
            hourly_cost: calcSCR(salary, SCR_COEFF)
        })
    }

    onHourlyRateChange(e){
        let hourly_rate = e.target.value;
        let estimate_hours = this.state.project_data.estimate_hours;

        this.setState({
            project_data: {
                hourly_rate: hourly_rate,
                revenue: multiply(estimate_hours, hourly_rate)
            }
        })

    }

    onOccupationChange(e){
        this.setState({
            project_data: {
                occupation: e.target.value
            }
        })
    }

    onEstimateHoursChange(e){
        let estimate_hours = e.target.value;

        this.setState({
            project_data: {
                estimate_hours: estimate_hours,
                revenue: multiply(estimate_hours, this.state.project_data.hourly_rate),
                cost: multiply(estimate_hours,this.state.hourly_cost)
            }
        })

    }

    onHourlyCostChange(e){
        let hourly_cost = e.target.value;
        this.setState({
            hourly_cost: hourly_cost,
            project_data: {
                cost: multiply(this.state.project_data.estimate_hours, hourly_cost)
            }
        })
    }

    onRevenueChange(e){

        let revenue = e.target.value;

        this.setState({
            project_data: {
                revenue: revenue,
                profit: difference(revenue,this.state.project_data.cost)
            }
        })
    }

    onCostChange(e){

        let cost = e.target.value;

        this.setState({
            project_data: {
                cost: cost,
                profit: difference(this.state.project_data.revenue,cost)
            }
        })
    }

    render(){

        let {projectName} = this.props;
        let data = this.state;

        return (

                <a className="member__short_info" role="button" data-toggle="collapse" href={`#${data.id}`} aria-expanded="false" aria-controls={data.id}>
                    {data.full_name}

                                {projectName}

                                Member full name:
                                <input id="full_name" type="text" name="full_name" value={data.full_name} onChange={this.onNameChange}/>

                                Salary:
                                <input id="salary" type="text" name="salary" value={data.salary} onChange={this.onSalaryChange}/>

                                Hourly cost:
                                <input id="hourly_cost" type="text" name="hourly_cost" value={data.hourly_cost} onChange={this.onHourlyCostChange}/>

                                Hourly rate
                                <input id="hourly_rate" type="text" name="hourly_rate" value={data.project_data.hourly_rate} onChange={this.onHourlyRateChange}/>

                                Occupation in project (%):
                                <input id="occupation" type="text" name="occupation" value={data.project_data.occupation} onChange={this.onOccupationChange}/>

                                Estimate hours:
                                <input id="estimate_hours" type="text" name="estimate_hours" value={data.project_data.estimate_hours} onChange={this.onEstimateHoursChange}/>

                                Revenue: {data.project_data.revenue}
                                {/*<input id="revenue" type="number" name="revenue" value={data.project_data.revenue} onChange={this.onRevenueChange}/>*/}

                                Cost: {data.project_data.cost}
                                {/*<input id="cost" type="number" name="cost" value={data.project_data.cost} onChange={this.onCostChange}/>*/}

                                Profit: {data.project_data.profit}

                                <button className="modal-component positive-btn no-margin" onClick={this.save}>Save</button>

        );
    }
}

export default Member;

For example: inside onHourlyRateChange function estimate_hours becomes undefined after change.

Inside onEstimateHoursChange state variables this.state.project_data.hourly_rate and this.state.project_data.hourly_cost becomes undefined too. I have no Idea why it happens. Maybe you can give me some advices?

Body:
You can partially update top-level properties of a state object, but nested updates won't work.

immutability-helper's update (replacement for react-addons-update) can be used to update nested properties:

import update from 'immutability-helper';

const newData = update(myData, {
  x: {y: {z: {$set: 7}}},
  a: {b: {$push: [9]}}
});


来源: stackexchange

问:
Memory error with numpy. array
I get a memory error when using numpy.arange with large numbers. My code is as follows:

```<code>import numpy as np

list = np.arange(0, 10**15, 10**3)
profit_list = []

for diff in list:
    x = do_some_calculation
    profit_list.append(x)
</code>```

What can be a replacement so I can avoid getting the memory error?

答:
If you replace list¹ with a generator, that is, you do

```<code>for diff in range(10**15, 10**3):
    x = do_some_calculation
    profit_list.append(x)
</code>```

then that will no longer cause MemoryErrors as you no longer initiate the full list. In this world, though, profit_list will probably by causing issues instead, as you are trying to add 10^12 items to that. Again, you can probably get around that by not storing the values explicitly, but rather yield them as you need them, using generators.

¹: Side note: Don't use list as a variable name as it shadows a built-in.

ContentLicense: CC BY-SA 3.0

Title: Memory error with numpy. array

Body:
I get a memory error when using numpy.arange with large numbers. My code is as follows:

import numpy as np

list = np.arange(0, 10**15, 10**3)
profit_list = []

for diff in list:
    x = do_some_calculation
    profit_list.append(x)

What can be a replacement so I can avoid getting the memory error?

Body:
If you replace list¹ with a generator, that is, you do

for diff in range(10**15, 10**3):
    x = do_some_calculation
    profit_list.append(x)

then that will no longer cause MemoryErrors as you no longer initiate the full list. In this world, though, profit_list will probably by causing issues instead, as you are trying to add 10^12 items to that. Again, you can probably get around that by not storing the values explicitly, but rather yield them as you need them, using generators.

¹: Side note: Don't use list as a variable name as it shadows a built-in.


问:
SQL Data won't show up in JTable
I have a program that when the user clicks on a button that the SQL data from the database shows in the JTable. Problem is when i click the button nothing shows up. But when i print the variables, it does show the correct value. So why won't anything show up in my JTable?

Note: JTable/Button was added with GUI design.

Code:

```<code>import connection.connection;
import java.awt.BorderLayout;
import java.awt.Font;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author peter
 */
public class Tabel extends javax.swing.JFrame {

    /**
     * Creates new form Tabel
     */
    public Tabel() {
        initComponents();
    }

    private void showBtnActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
        String[] columns = {"Nummer", "Adres", "Postcode", "Plaats",
                            "capaciteit"};

        String sql = "SELECT * FROM uitgiftepunt";

        try (
                Connection conn = connection.getConnection();
                Statement stmt = conn.createStatement();
                ResultSet rs = stmt.executeQuery(sql);
            ){
               DefaultTableModel model = new DefaultTableModel(columns, 0);
                while (rs.next()) {
                    int nummer = rs.getObject("nummer", Integer.class);
                    String adres = rs.getObject("adres", String.class);
                    String postcode = rs.getObject("postcode", String.class);
                    String plaats = rs.getObject("plaats", String.class);
                    int cap = rs.getObject("capaciteit", Integer.class);
                    model.addRow(new Object[]{nummer,adres,postcode,plaats,cap});
                    System.out.printf("%d, %s, %s, %s, %d", nummer,adres,postcode,plaats,cap);

                }

                jTable1.setModel(model);
                jScrollPane1 = new JScrollPane(jTable1);
                jTable1.setFillsViewportHeight(true);

            } catch (SQLException ex) {
            Logger.getLogger(Tabel.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Tabel().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JButton showBtn;
    // End of variables declaration
}
</code>```

答:
This is a guaranteed solution unless you have SQL exception which would have show up in your logs
Reuse this code snippet specifically the createView() and buildtabalemodel functions.

```<code>public class JTableSQLProblem extends JFrame{
JScrollPane scrollPane;

public JTableSQLProblem(){
    setSize(1000,500);
    setLayout( new FlowLayout());

    scrollPane = new JScrollPane();
    scrollPane.getViewport().add(createView());

    add(scrollPane);
    repaint();
    setVisible(true);
}
  public static DefaultTableModel buildtableModel(ResultSet resultSet) throws SQLException {

    ResultSetMetaData metaData = resultSet.getMetaData();

    Vector<String> columnNames = new Vector<>();
    int columnCount = metaData.getColumnCount();
    for (int column = 1; column <= columnCount; column++) {
        columnNames.add(metaData.getColumnName(column));

    }

    Vector<Vector<Object>> data = new Vector<>();
    while (resultSet.next()) {
        Vector<Object> vector = new Vector<Object>();
        for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) {
            vector.add(resultSet.getObject(columnIndex));
        }
        data.add(vector);
    }

    return new DefaultTableModel(data, columnNames);

}
 private static JTable createView() {
    try {
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/youtdatabasename","root","");
        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery(
                "SELECT * FROM yourtablename");

        JTable table = new JTable(buildtableModel(rs));
        UIDefaults defaults = UIManager.getLookAndFeelDefaults();
        defaults.put("Table.alternateRowColor", Color.decode("#f5f5f5"));
        table.setSelectionBackground(Color.decode("#1e90ff"));
        table.setSelectionForeground(Color.WHITE);
        table.setRowHeight(30);
        table.setBackground(Color.WHITE);
        table.setShowGrid(false);
        table.setFont(new Font("calibri", Font.PLAIN, 16));

        JTableHeader tableHeader = table.getTableHeader();
        tableHeader.setBackground(Color.decode("#B0E0E6"));
        tableHeader.setForeground(Color.black);
        tableHeader.setFont(new Font("Calibri Bold", Font.BOLD, 14));
        tableHeader.setBorder(new LineBorder(Color.WHITE));

        rs.close();
        return table;
    } catch (SQLException | HeadlessException exc) {
        JOptionPane.showMessageDialog(null, exc);
        return new JTable();
    }
}
public static void main(String[]args){
    new JTableSQLProblem();
}}
</code>```

Title: SQL Data won't show up in JTable

Body:
I have a program that when the user clicks on a button that the SQL data from the database shows in the JTable. Problem is when i click the button nothing shows up. But when i print the variables, it does show the correct value. So why won't anything show up in my JTable?

Note: JTable/Button was added with GUI design.

Code:

import connection.connection;
import java.awt.BorderLayout;
import java.awt.Font;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author peter
 */
public class Tabel extends javax.swing.JFrame {

    /**
     * Creates new form Tabel
     */
    public Tabel() {
        initComponents();
    }

    private void showBtnActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
        String[] columns = {"Nummer", "Adres", "Postcode", "Plaats",
                            "capaciteit"};

        String sql = "SELECT * FROM uitgiftepunt";

        try (
                Connection conn = connection.getConnection();
                Statement stmt = conn.createStatement();
                ResultSet rs = stmt.executeQuery(sql);
            ){
               DefaultTableModel model = new DefaultTableModel(columns, 0);
                while (rs.next()) {
                    int nummer = rs.getObject("nummer", Integer.class);
                    String adres = rs.getObject("adres", String.class);
                    String postcode = rs.getObject("postcode", String.class);
                    String plaats = rs.getObject("plaats", String.class);
                    int cap = rs.getObject("capaciteit", Integer.class);
                    model.addRow(new Object[]{nummer,adres,postcode,plaats,cap});
                    System.out.printf("%d, %s, %s, %s, %d", nummer,adres,postcode,plaats,cap);

                }

                jTable1.setModel(model);
                jScrollPane1 = new JScrollPane(jTable1);
                jTable1.setFillsViewportHeight(true);

            } catch (SQLException ex) {
            Logger.getLogger(Tabel.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Tabel().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JButton showBtn;
    // End of variables declaration
}

Body:
This is a guaranteed solution unless you have SQL exception which would have show up in your logs
Reuse this code snippet specifically the createView() and buildtabalemodel functions.

public class JTableSQLProblem extends JFrame{
JScrollPane scrollPane;

public JTableSQLProblem(){
    setSize(1000,500);
    setLayout( new FlowLayout());

    scrollPane = new JScrollPane();
    scrollPane.getViewport().add(createView());

    add(scrollPane);
    repaint();
    setVisible(true);
}
  public static DefaultTableModel buildtableModel(ResultSet resultSet) throws SQLException {

    ResultSetMetaData metaData = resultSet.getMetaData();

    Vector<String> columnNames = new Vector<>();
    int columnCount = metaData.getColumnCount();
    for (int column = 1; column <= columnCount; column++) {
        columnNames.add(metaData.getColumnName(column));

    }

    Vector<Vector<Object>> data = new Vector<>();
    while (resultSet.next()) {
        Vector<Object> vector = new Vector<Object>();
        for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) {
            vector.add(resultSet.getObject(columnIndex));
        }
        data.add(vector);
    }

    return new DefaultTableModel(data, columnNames);

}
 private static JTable createView() {
    try {
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/youtdatabasename","root","");
        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery(
                "SELECT * FROM yourtablename");

        JTable table = new JTable(buildtableModel(rs));
        UIDefaults defaults = UIManager.getLookAndFeelDefaults();
        defaults.put("Table.alternateRowColor", Color.decode("#f5f5f5"));
        table.setSelectionBackground(Color.decode("#1e90ff"));
        table.setSelectionForeground(Color.WHITE);
        table.setRowHeight(30);
        table.setBackground(Color.WHITE);
        table.setShowGrid(false);
        table.setFont(new Font("calibri", Font.PLAIN, 16));

        JTableHeader tableHeader = table.getTableHeader();
        tableHeader.setBackground(Color.decode("#B0E0E6"));
        tableHeader.setForeground(Color.black);
        tableHeader.setFont(new Font("Calibri Bold", Font.BOLD, 14));
        tableHeader.setBorder(new LineBorder(Color.WHITE));

        rs.close();
        return table;
    } catch (SQLException | HeadlessException exc) {
        JOptionPane.showMessageDialog(null, exc);
        return new JTable();
    }
}
public static void main(String[]args){
    new JTableSQLProblem();
}}


问:
Xamarin Resource.Designer.cs not refreshing new id's or events
So im working in Xamarin and i had a problem with my events and layouts because i added new stuff but the layouts didn't refresh they just kept displaying the old layouts and the new events i added had the same problem they are just ignoring my new code i already saw a few links and they said this happens because the Resource.Designer.cs is not refreshing but never gave any solutions any ideas?
.

UPDATE:
There are no build errors but still the layouts won't refresh.

答:
I'm having the same issue: this is the official Xamarin answer (which isn't particularly great for people unable to update to version 5.0 +):

https://developer.xamarin.com/guides/android/troubleshooting/questions/resource-designer-wont-update/

Options:

1) Manually edit your .csproj file (eww)

2) Create a brand new project and copy your resources (disgusting)

3) Update.

I wish I could be more helpful...


问:
Query Ignite Cache based on Spark RDD elements
Im trying to retrieve the cached value for every element in the JavaPairRDD. Im using the LOCAL cache mode as i want to minimize data shuffling of cached data. The ignite nodes are started in embedded mode within a spark job. The following code works fine if i run it on a single node. However, when i run it on a cluster of 5 machines, i get zero results.

The first attempt i had was using the IgniteRDD sql method:

```<code> dataRDD.sql("SELECT v.id,v.sub,v.obj FROM VPRow v JOIN table(id bigint = ?) i ON v.id = i.id",new Object[] {objKeyEntries.toArray()});
</code>```

where objKeyEntries is a collected set of entries in an RDD. The second attempt was using AffinityRun:

```<code>JavaPairRDD<Long, VPRow> objEntries = objKeyEntries.mapPartitionsToPair(new PairFlatMapFunction<Iterator<Tuple2<Long, Boolean>>, Long, VPRow>() {
    @Override
    public Iterator<Tuple2<Long, VPRow>> call(Iterator<Tuple2<Long, Boolean>> tuple2Iterator) throws Exception {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("ignite-rdd.xml");
        IgniteConfiguration igniteConfiguration = (IgniteConfiguration) ctx.getBean("ignite.cfg");
        Ignite ignite = Ignition.getOrStart(igniteConfiguration);
        IgniteCache<Long, VPRow> cache = ignite.getOrCreateCache("dataRDD");

        ArrayList<Tuple2<Long,VPRow>> lst = new ArrayList<>();
        while(tuple2Iterator.hasNext()) {
            Tuple2<Long, Boolean> val = tuple2Iterator.next();
            ignite.compute().affinityRun("dataRDD", val._1(),()->{
                lst.add(new Tuple2<>(val._1(),cache.get(val._1())));
            });
        }
        return lst.iterator();
    }
});
</code>```

The following is the ignite-rdd.xml configuration file:

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="ignite.cfg" class="org.apache.ignite.configuration.IgniteConfiguration">
        <property name="memoryConfiguration">
            <bean class="org.apache.ignite.configuration.MemoryConfiguration">
                <property name="systemCacheInitialSize" value="#{100 * 1024 * 1024}"/>
                <property name="defaultMemoryPolicyName" value="default_mem_plc"/>
                <property name="memoryPolicies">
                    <list>
                        <bean class="org.apache.ignite.configuration.MemoryPolicyConfiguration">
                            <property name="name" value="default_mem_plc"/>
                            <property name="initialSize" value="#{5 * 1024 * 1024 * 1024}"/>
                        </bean>
                    </list>
                </property>
            </bean>
        </property>
        <property name="cacheConfiguration">
            <list>
                <bean class="org.apache.ignite.configuration.CacheConfiguration">
                    <!-- Set a cache name. -->
                    <property name="name" value="dataRDD"/>
                    <!-- Set a cache mode. -->
                    <property name="cacheMode" value="LOCAL"/>
                    <!-- Index Integer pairs used in the example. -->
                    <property name="indexedTypes">
                        <list>
                            <value>java.lang.Long</value>
                            <value>edu.code.VPRow</value>
                        </list>
                    </property>
                    <property name="affinity">
                        <bean class="org.apache.ignite.cache.affinity.rendezvous.RendezvousAffinityFunction">
                            <property name="partitions" value="50"/>
                        </bean>
                    </property>
                </bean>
            </list>
        </property>
        <!-- Explicitly configure TCP discovery SPI to provide list of initial nodes. -->
        <property name="discoverySpi">
            <bean class="org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi">
                <property name="ipFinder">
                    <bean class="org.apache.ignite.spi.discovery.tcp.ipfinder.multicast.TcpDiscoveryMulticastIpFinder">
                        <property name="addresses">
                            <list>
                                <value>[IP5]</value>
                                <value>[IP4]</value>
                                <value>[IP3]</value>
                                <value>[IP2]</value>
                                <value>[IP1]</value>
                            </list>
                        </property>
                    </bean>
                </property>
            </bean>
        </property>
    </bean>
</beans>
</code>```

答:
Are you sure that you need to use LOCAL cache mode?

Most likely you filled cache only on one node and local caches on other nodes still empty.

affinityRun doesn't work because you have LOCAL cache, not PARTITIONED, so, it's not possible to determine owner node for key with AffinityFunction.

Body:
Im trying to retrieve the cached value for every element in the JavaPairRDD. Im using the LOCAL cache mode as i want to minimize data shuffling of cached data. The ignite nodes are started in embedded mode within a spark job. The following code works fine if i run it on a single node. However, when i run it on a cluster of 5 machines, i get zero results.

The first attempt i had was using the IgniteRDD sql method:

 dataRDD.sql("SELECT v.id,v.sub,v.obj FROM VPRow v JOIN table(id bigint = ?) i ON v.id = i.id",new Object[] {objKeyEntries.toArray()});

where objKeyEntries is a collected set of entries in an RDD. The second attempt was using AffinityRun:

JavaPairRDD<Long, VPRow> objEntries = objKeyEntries.mapPartitionsToPair(new PairFlatMapFunction<Iterator<Tuple2<Long, Boolean>>, Long, VPRow>() {
    @Override
    public Iterator<Tuple2<Long, VPRow>> call(Iterator<Tuple2<Long, Boolean>> tuple2Iterator) throws Exception {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("ignite-rdd.xml");
        IgniteConfiguration igniteConfiguration = (IgniteConfiguration) ctx.getBean("ignite.cfg");
        Ignite ignite = Ignition.getOrStart(igniteConfiguration);
        IgniteCache<Long, VPRow> cache = ignite.getOrCreateCache("dataRDD");

        ArrayList<Tuple2<Long,VPRow>> lst = new ArrayList<>();
        while(tuple2Iterator.hasNext()) {
            Tuple2<Long, Boolean> val = tuple2Iterator.next();
            ignite.compute().affinityRun("dataRDD", val._1(),()->{
                lst.add(new Tuple2<>(val._1(),cache.get(val._1())));
            });
        }
        return lst.iterator();
    }
});

The following is the ignite-rdd.xml configuration file:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="ignite.cfg" class="org.apache.ignite.configuration.IgniteConfiguration">
        <property name="memoryConfiguration">
            <bean class="org.apache.ignite.configuration.MemoryConfiguration">
                <property name="systemCacheInitialSize" value="#{100 * 1024 * 1024}"/>
                <property name="defaultMemoryPolicyName" value="default_mem_plc"/>
                <property name="memoryPolicies">
                    <list>
                        <bean class="org.apache.ignite.configuration.MemoryPolicyConfiguration">
                            <property name="name" value="default_mem_plc"/>
                            <property name="initialSize" value="#{5 * 1024 * 1024 * 1024}"/>
                        </bean>
                    </list>
                </property>
            </bean>
        </property>
        <property name="cacheConfiguration">
            <list>
                <bean class="org.apache.ignite.configuration.CacheConfiguration">

                    <property name="name" value="dataRDD"/>

                    <property name="cacheMode" value="LOCAL"/>

                    <property name="indexedTypes">
                        <list>
                            <value>java.lang.Long</value>
                            <value>edu.code.VPRow</value>
                        </list>
                    </property>
                    <property name="affinity">
                        <bean class="org.apache.ignite.cache.affinity.rendezvous.RendezvousAffinityFunction">
                            <property name="partitions" value="50"/>
                        </bean>
                    </property>
                </bean>
            </list>
        </property>

        <property name="discoverySpi">
            <bean class="org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi">
                <property name="ipFinder">
                    <bean class="org.apache.ignite.spi.discovery.tcp.ipfinder.multicast.TcpDiscoveryMulticastIpFinder">
                        <property name="addresses">
                            <list>
                                <value>[IP5]</value>
                                <value>[IP4]</value>
                                <value>[IP3]</value>
                                <value>[IP2]</value>
                                <value>[IP1]</value>
                            </list>
                        </property>
                    </bean>
                </property>
            </bean>
        </property>
    </bean>
</beans>


问:
Remove the last color form bitmap Undo
Please I need the help regarding Undo method , I tried to implement it like the code below but it is not remove the last color,
Kindly help me to resolve it.

awaiting your kind response.

Thanks in Advance.

MainActivity

```<code> public class MainActivity extends AppCompatActivity implements
 View.OnTouchListener {
Button red, blue, yellow, undo;
Paint paint;
private RelativeLayout drawingLayout;
private MyView myView;
private ArrayList<Path> paths = new ArrayList<Path>();
private ArrayList<Path> undonePaths = new ArrayList<Path>();

/**
 * Called when the activity is first created.
 */
  /*
  *
  * private ImageView imageView; private Canvas cv; private Bitmap mask,
  * original, colored; private int r,g,b; private int sG, sR, sB;
  */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    myView = new MyView(this);
    drawingLayout = (RelativeLayout) findViewById(R.id.relative_layout);
    drawingLayout.addView(myView);

    red = (Button) findViewById(R.id.btn_red);
    blue = (Button) findViewById(R.id.btn_blue);
    yellow = (Button) findViewById(R.id.btn_yellow);
    undo = (Button) findViewById(R.id.undo);

    red.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            paint.setColor(Color.RED);
        }
    });

    yellow.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            paint.setColor(Color.YELLOW);
        }
    });
    blue.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            paint.setColor(Color.BLUE);
        }
    });
    undo.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            myView.onClickUndo();
        }
    });
}

@Override
public boolean onTouch(View v, MotionEvent event) {
    // TODO Auto-generated method stub
    return false;
}

// flood fill
public class MyView extends View {

    final Point p1 = new Point();
    Bitmap mBitmap;
    ProgressDialog pd;
    Canvas canvas;
    private Path path;

    // Bitmap mutableBitmap ;
    public MyView(Context context) {
        super(context);

        paint = new Paint();
        paint.setAntiAlias(true);
        pd = new ProgressDialog(context);
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeJoin(Paint.Join.ROUND);
        paint.setStrokeWidth(5f);
        mBitmap = BitmapFactory.decodeResource(getResources(),
                R.drawable.gp1_1).copy(Bitmap.Config.ARGB_8888, true);

        this.path = new Path();

    }

    public void onClickUndo() {
        if (paths.size() > 0) {
            undonePaths.add(paths.remove(paths.size() - 1));
            invalidate();
        } else {
            Toast.makeText(getContext(), getString(R.string.nomore), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        this.canvas = canvas;
        paint.setColor(Color.GREEN);
      //   int width = drawingLayout.getWidth();
     // int height = drawingLayout.getHeight();
    // float centerX = (width - mBitmap.getWidth()) * 0.5f;
    //float centerY = (height - mBitmap.getHeight()) * 0.5f;
        canvas.drawBitmap(mBitmap, 0, 0, paint);
        ///////////////////////////////
        for (Path p : paths) {
            canvas.drawPath(p, paint);
            //////////////////////////
        }

    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        float x = event.getX();
        float y = event.getY();
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:

                p1.x = (int) x;
                p1.y = (int) y;
                final int sourceColor = mBitmap.getPixel((int) x, (int) y);
                final int targetColor = paint.getColor();
                new TheTask(mBitmap, p1, sourceColor, targetColor).execute();
                paths.add(path);

                invalidate();
        }
        return true;
    }

    public void clear() {
        path.reset();
        invalidate();
    }

    public int getCurrentPaintColor() {
        return paint.getColor();
    }

    class TheTask extends AsyncTask<Void, Integer, Void> {

        Bitmap bmp;
        Point pt;
        int replacementColor, targetColor;

        public TheTask(Bitmap bm, Point p, int sc, int tc) {
            this.bmp = bm;
            this.pt = p;
            this.replacementColor = tc;
            this.targetColor = sc;
            pd.setMessage(getString(R.string.wait));
            pd.show();
        }

        @Override
        protected void onPreExecute() {
            pd.show();

        }

        @Override
        protected void onProgressUpdate(Integer... values) {

        }

        @Override
        protected Void doInBackground(Void... params) {
            FloodFill f = new FloodFill();
            f.floodFill(bmp, pt, targetColor, replacementColor);
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            pd.dismiss();
            invalidate();
        }
    }
}

public class FloodFill {
    public void floodFill(Bitmap image, Point node, int targetColor,
                          int replacementColor) {
        int width = image.getWidth();
        int height = image.getHeight();
        int target = targetColor;
        int replacement = replacementColor;
        if (target != replacement) {
            Queue<Point> queue = new LinkedList<Point>();
            do {

                int x = node.x;
                int y = node.y;
                while (x > 0 && image.getPixel(x - 1, y) == target) {
                    x--;

                }
                boolean spanUp = false;
                boolean spanDown = false;
                while (x < width && image.getPixel(x, y) == target) {
                    image.setPixel(x, y, replacement);
                    if (!spanUp && y > 0
                            && image.getPixel(x, y - 1) == target) {
                        queue.add(new Point(x, y - 1));
                        spanUp = true;
                    } else if (spanUp && y > 0
                            && image.getPixel(x, y - 1) != target) {
                        spanUp = false;
                    }
                    if (!spanDown && y < height - 1
                            && image.getPixel(x, y + 1) == target) {
                        queue.add(new Point(x, y + 1));
                        spanDown = true;
                    } else if (spanDown && y < height - 1
                            && image.getPixel(x, y + 1) != target) {
                        spanDown = false;
                    }
                    x++;
                }
            } while ((node = queue.poll()) != null);
        }
    }
}
  }
</code>```

答:
I guess you mean the undo method doesn't work. The possible reason is the previous drawing on the canvas is not removed. Try clearing the canvas before drawing in the onDraw() method.

```<code> @Override protected void onDraw(Canvas canvas) {
 this.canvas = canvas;
canvas. drawColor(0,PorterDuff.Mode.CLEAR); //This clears the canvas.
 paint.setColor(Color.GREEN);
 //rest of the code
 }
</code>```

Title: Remove the last color form bitmap Undo

Body:
Please I need the help regarding Undo method , I tried to implement it like the code below but it is not remove the last color,
Kindly help me to resolve it.

awaiting your kind response.

Thanks in Advance.

MainActivity

 public class MainActivity extends AppCompatActivity implements
 View.OnTouchListener {
Button red, blue, yellow, undo;
Paint paint;
private RelativeLayout drawingLayout;
private MyView myView;
private ArrayList<Path> paths = new ArrayList<Path>();
private ArrayList<Path> undonePaths = new ArrayList<Path>();

/**
 * Called when the activity is first created.
 */
  /*
  *
  * private ImageView imageView; private Canvas cv; private Bitmap mask,
  * original, colored; private int r,g,b; private int sG, sR, sB;
  */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    myView = new MyView(this);
    drawingLayout = (RelativeLayout) findViewById(R.id.relative_layout);
    drawingLayout.addView(myView);

    red = (Button) findViewById(R.id.btn_red);
    blue = (Button) findViewById(R.id.btn_blue);
    yellow = (Button) findViewById(R.id.btn_yellow);
    undo = (Button) findViewById(R.id.undo);

    red.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            paint.setColor(Color.RED);
        }
    });

    yellow.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            paint.setColor(Color.YELLOW);
        }
    });
    blue.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            paint.setColor(Color.BLUE);
        }
    });
    undo.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            myView.onClickUndo();
        }
    });
}

@Override
public boolean onTouch(View v, MotionEvent event) {
    // TODO Auto-generated method stub
    return false;
}

// flood fill
public class MyView extends View {

    final Point p1 = new Point();
    Bitmap mBitmap;
    ProgressDialog pd;
    Canvas canvas;
    private Path path;

    // Bitmap mutableBitmap ;
    public MyView(Context context) {
        super(context);

        paint = new Paint();
        paint.setAntiAlias(true);
        pd = new ProgressDialog(context);
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeJoin(Paint.Join.ROUND);
        paint.setStrokeWidth(5f);
        mBitmap = BitmapFactory.decodeResource(getResources(),
                R.drawable.gp1_1).copy(Bitmap.Config.ARGB_8888, true);

        this.path = new Path();

    }

    public void onClickUndo() {
        if (paths.size() > 0) {
            undonePaths.add(paths.remove(paths.size() - 1));
            invalidate();
        } else {
            Toast.makeText(getContext(), getString(R.string.nomore), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        this.canvas = canvas;
        paint.setColor(Color.GREEN);
      //   int width = drawingLayout.getWidth();
     // int height = drawingLayout.getHeight();
    // float centerX = (width - mBitmap.getWidth()) * 0.5f;
    //float centerY = (height - mBitmap.getHeight()) * 0.5f;
        canvas.drawBitmap(mBitmap, 0, 0, paint);
        ///////////////////////////////
        for (Path p : paths) {
            canvas.drawPath(p, paint);
            //////////////////////////
        }

    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        float x = event.getX();
        float y = event.getY();
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:

                p1.x = (int) x;
                p1.y = (int) y;
                final int sourceColor = mBitmap.getPixel((int) x, (int) y);
                final int targetColor = paint.getColor();
                new TheTask(mBitmap, p1, sourceColor, targetColor).execute();
                paths.add(path);

                invalidate();
        }
        return true;
    }

    public void clear() {
        path.reset();
        invalidate();
    }

    public int getCurrentPaintColor() {
        return paint.getColor();
    }

    class TheTask extends AsyncTask<Void, Integer, Void> {

        Bitmap bmp;
        Point pt;
        int replacementColor, targetColor;

        public TheTask(Bitmap bm, Point p, int sc, int tc) {
            this.bmp = bm;
            this.pt = p;
            this.replacementColor = tc;
            this.targetColor = sc;
            pd.setMessage(getString(R.string.wait));
            pd.show();
        }

        @Override
        protected void onPreExecute() {
            pd.show();

        }

        @Override
        protected void onProgressUpdate(Integer... values) {

        }

        @Override
        protected Void doInBackground(Void... params) {
            FloodFill f = new FloodFill();
            f.floodFill(bmp, pt, targetColor, replacementColor);
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            pd.dismiss();
            invalidate();
        }
    }
}

public class FloodFill {
    public void floodFill(Bitmap image, Point node, int targetColor,
                          int replacementColor) {
        int width = image.getWidth();
        int height = image.getHeight();
        int target = targetColor;
        int replacement = replacementColor;
        if (target != replacement) {
            Queue<Point> queue = new LinkedList<Point>();
            do {

                int x = node.x;
                int y = node.y;
                while (x > 0 && image.getPixel(x - 1, y) == target) {
                    x--;

                }
                boolean spanUp = false;
                boolean spanDown = false;
                while (x < width && image.getPixel(x, y) == target) {
                    image.setPixel(x, y, replacement);
                    if (!spanUp && y > 0
                            && image.getPixel(x, y - 1) == target) {
                        queue.add(new Point(x, y - 1));
                        spanUp = true;
                    } else if (spanUp && y > 0
                            && image.getPixel(x, y - 1) != target) {
                        spanUp = false;
                    }
                    if (!spanDown && y < height - 1
                            && image.getPixel(x, y + 1) == target) {
                        queue.add(new Point(x, y + 1));
                        spanDown = true;
                    } else if (spanDown && y < height - 1
                            && image.getPixel(x, y + 1) != target) {
                        spanDown = false;
                    }
                    x++;
                }
            } while ((node = queue.poll()) != null);
        }
    }
}
  }

Body:
I guess you mean the undo method doesn't work. The possible reason is the previous drawing on the canvas is not removed. Try clearing the canvas before drawing in the onDraw() method.

 @Override protected void onDraw(Canvas canvas) {
 this.canvas = canvas;
canvas. drawColor(0,PorterDuff.Mode.CLEAR); //This clears the canvas.
 paint.setColor(Color.GREEN);
 //rest of the code
 }


问:
How to get a part of the levels of a categorical variable?
My data set looks like the following:

```<code>        dsn                register_at
1 AC000W000014612   Thu Mar 02 21:34:30 UTC 2017
2 AC000W000016124   Tue Mar 14 19:40:57 UTC 2017
3 AC000W000016219   Tue Apr 14 19:29:10 UTC 2017
</code>```

I need to get just the month specification like Mar, Apr etc for each dsn. How do I grab only the month specification from the register at variable?

答:
You can use substr function as Month names are always in the same possition.

```<code>substr(df$register_at, 5, 7)
</code>```

Body:
My data set looks like the following:

        dsn                register_at
1 AC000W000014612   Thu Mar 02 21:34:30 UTC 2017
2 AC000W000016124   Tue Mar 14 19:40:57 UTC 2017
3 AC000W000016219   Tue Apr 14 19:29:10 UTC 2017

I need to get just the month specification like Mar, Apr etc for each dsn. How do I grab only the month specification from the register at variable?

Body:
You can use substr function as Month names are always in the same possition.

substr(df$register_at, 5, 7)


问:
A class for show image in square
I see a class that use this class for show images in square.

i can't understand what is this class? have any feature for show images in square?

this code used in layout xml file instead of RelativeLayout

```<code>class SquareLayout extends RelativeLayout {

public SquareLayout(Context context) {
    super(context);
}

public SquareLayout(Context context, AttributeSet attrs) {
    super(context, attrs);
}

public SquareLayout(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
}

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public SquareLayout(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
    super(context, attrs, defStyleAttr, defStyleRes);
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    // Set a square layout.
    super.onMeasure(widthMeasureSpec, widthMeasureSpec);
}
</code>```

答: The important line is super.onMeasure(widthMeasureSpec, widthMeasureSpec);. As you can see, the height is replace with the width. So you have width x width instead of width x height. That is a square. onMeasure is used to tell the system the requested Area of the view. Hope it helps

Title: A class for show image in square

Body:
I see a class that use this class for show images in square.

i can't understand what is this class? have any feature for show images in square?

this code used in layout xml file instead of RelativeLayout

class SquareLayout extends RelativeLayout {

public SquareLayout(Context context) {
    super(context);
}

public SquareLayout(Context context, AttributeSet attrs) {
    super(context, attrs);
}

public SquareLayout(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
}

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public SquareLayout(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
    super(context, attrs, defStyleAttr, defStyleRes);
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    // Set a square layout.
    super.onMeasure(widthMeasureSpec, widthMeasureSpec);
}


问:
Using getopt in C with non-option arguments
I'm making a small program in C that deals with a lot of command line arguments, so I decided to use getopt to sort them for me.

However, I want two non-option arguments (source and destination files) to be mandatory, so you have to have them as arguments while calling the program, even if there's no flags or other arguments.

Here's a simplified version of what I have to handle the arguments with flags:

```<code>while ((c = getopt(argc, argv, "i:d:btw:h:s:")) != -1) {
    switch (c) {
        case 'i': {
            i = (int)atol(optarg);
        }
        case 'd': {
            d = (int)atol(optarg);
        }
        case 'b':
            buf = 1;
            break;
        case 't':
            time = 1;
            break;
        case 'w':
            w = (int)atol(optarg);
            break;
        case 'h':
            h = (int)atol(optarg);
            break;
        case 's':
            s = (int)atol(optarg);
            break;
        default:
            break;
    }
}
</code>```

How do I edit this so that non-option arguments are also handled?

I also want to be able to have the non-options either before or after the options, so how would that be handled?

答:
Really good example could be found here: GNU Libc The code:

```<code>#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int
main (int argc, char **argv)
{
int aflag = 0;
int bflag = 0;
char *cvalue = NULL;
int index;
int c;

opterr = 0;

while ((c = getopt (argc, argv, "abc:")) != -1)
switch (c)
{
case 'a':
    aflag = 1;
    break;
case 'b':
    bflag = 1;
    break;
case 'c':
    cvalue = optarg;
    break;
case '?':
    if (optopt == 'c')
    fprintf (stderr, "Option -%c requires an argument.\n", optopt);
    else if (isprint (optopt))
    fprintf (stderr, "Unknown option `-%c'.\n", optopt);
    else
    fprintf (stderr,
        "Unknown option character `\\x%x'.\n",
        optopt);
    return 1;
default:
    abort ();
}

printf ("aflag = %d, bflag = %d, cvalue = %s\n",
    aflag, bflag, cvalue);

for (index = optind; index < argc; index++)
printf ("Non-option argument %s\n", argv[index]);
return 0;
}
</code>```

It allows to have options before and after arguments. I did compile and run test example:

```<code>$ ./a.out aa ff bb -a -ctestparam hello
aflag = 1, bflag = 0, cvalue = testparam
Non-option argument aa
Non-option argument ff
Non-option argument bb
Non-option argument hello
</code>```

Body:
I'm making a small program in C that deals with a lot of command line arguments, so I decided to use getopt to sort them for me.

However, I want two non-option arguments (source and destination files) to be mandatory, so you have to have them as arguments while calling the program, even if there's no flags or other arguments.

Here's a simplified version of what I have to handle the arguments with flags:

while ((c = getopt(argc, argv, "i:d:btw:h:s:")) != -1) {
    switch (c) {
        case 'i': {
            i = (int)atol(optarg);
        }
        case 'd': {
            d = (int)atol(optarg);
        }
        case 'b':
            buf = 1;
            break;
        case 't':
            time = 1;
            break;
        case 'w':
            w = (int)atol(optarg);
            break;
        case 'h':
            h = (int)atol(optarg);
            break;
        case 's':
            s = (int)atol(optarg);
            break;
        default:
            break;
    }
}

How do I edit this so that non-option arguments are also handled?

I also want to be able to have the non-options either before or after the options, so how would that be handled?

Body:
Really good example could be found here: GNU Libc The code:

#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int
main (int argc, char **argv)
{
int aflag = 0;
int bflag = 0;
char *cvalue = NULL;
int index;
int c;

opterr = 0;

while ((c = getopt (argc, argv, "abc:")) != -1)
switch (c)
{
case 'a':
    aflag = 1;
    break;
case 'b':
    bflag = 1;
    break;
case 'c':
    cvalue = optarg;
    break;
case '?':
    if (optopt == 'c')
    fprintf (stderr, "Option -%c requires an argument.\n", optopt);
    else if (isprint (optopt))
    fprintf (stderr, "Unknown option `-%c'.\n", optopt);
    else
    fprintf (stderr,
        "Unknown option character `\\x%x'.\n",
        optopt);
    return 1;
default:
    abort ();
}

printf ("aflag = %d, bflag = %d, cvalue = %s\n",
    aflag, bflag, cvalue);

for (index = optind; index < argc; index++)
printf ("Non-option argument %s\n", argv[index]);
return 0;
}

It allows to have options before and after arguments. I did compile and run test example:

$ ./a.out aa ff bb -a -ctestparam hello
aflag = 1, bflag = 0, cvalue = testparam
Non-option argument aa
Non-option argument ff
Non-option argument bb
Non-option argument hello


问:
Change value of flip toggle dynamically with jQuery Mobile
I'm working with jQuery Mobile, and I save some settings in a cookie. When the settings page is reloaded, I read the cookie to set all the values. I'm having trouble setting the flip toggle switch. Most elements just have to trigger the keyup or changed events, but I'm not sure how the flip toggles gets its value from the select box. Any ideas?

答:
It looks like it's broken.

Go to the page: http://jquerymobile.com/demos/1.0a2/#docs/forms/forms-switch.html  and use firebug console to run the following:

```<code>$('#slider2').val('on').trigger('keyup');
</code>```

it changes the width of "on" part of the switch, but doesn't move the slider.

So the answer is: wait for the release of JQM :)

Bug issued here: https://github.com/jquery/jquery-mobile/issues/issue/676

ContentLicense: CC BY-SA 2.5

Body:
It looks like it's broken.

Go to the page: http://jquerymobile.com/demos/1.0a2/#docs/forms/forms-switch.html  and use firebug console to run the following:

$('#slider2').val('on').trigger('keyup');

it changes the width of "on" part of the switch, but doesn't move the slider.

So the answer is: wait for the release of JQM :)

Bug issued here: https://github.com/jquery/jquery-mobile/issues/issue/676


问:
Terrible performance issues with websocket - every message triggering Angular change detection
I've got a websocket and I'm currently streaming messages at about 45 per second. At this level it completely kills chrome. All functionality in the browser window is locked up.

I've cut back my implementation to try find the root cause of this issue, suspecting it could have been some problem with how I'm processing these messages - or updating/change detection in Angular.

But now I'm left with the simplest websocket implementation I can get:

```<code>this.socket = new WebSocket('ws://localhost:5000/ws');

let i = 0;
this.socket.onmessage = (e: MessageEvent) => {
  i++;
  if (i % 100 === 0) {
    console.log('recieved' + i);
  }
};
</code>```

This is in an Angular Injectable, but it's not interacting with anything.

It writes to the console every 100 messages. This still kills the browser with 100% CPU usage, it doesn't even output to the console most of the time until I stop the message stream, then everything catches up and it squirts a few lines of "recieved x00" messages.

The messages themselves are JSON, and look like this:

```<code>{
  "Topic":"2a736d15-a2fe-43b2-8e8b-ee888f15a53a","Type":1,
  "Message": {
     "Value":2,
     "Timestamp":"2017-06-05T14:46:21.615062+01:00"
   }
}
</code>```

They're typically about 126 characters.

I'd assumed websockets can handle tens of thousands of messages per second, but I can't find any sensible metrics on google, does this sound like unreasonable performance?

I've also checked in the CPU profiler. When everthing's locked out, it's just a big wall of calls, so I turned it down to a single message a second:

Drilled down into one of these spikes (happens for every single message!):

I threw a break point in one of these locations, and it appears that Angular is doing something whenever the websocket gets triggered, and it's something to do with Zones (something I have zero experience in!):

The first thing in the stack is a ZoneTask.invoke on the Websocket itself, but then NgZone gets triggered, and ultimately a very expensive change/update chain is called:

How could all this be happening? The 7 lines of code subscribing to the websocket are completely independent from Angular's change detection right? They're not changing any values that are bound to any components. Their only link is they are sitting in a method inside an @Injectable()

答:
Sods law, as soon as I post a question I work out the answer. Usually I'd delete it but I couldn't find much on the topic so it might be useful for someone.

It was an issue with Zones. Here's a useful blog post. In general, Angular 2 uses zones to drive it's change detection:

The reason that Angular 2 uses the zone.js is to know when our handler finishes and then the NgZone service (NgZone is a class that wrap the zone service) calls to ApplicationRef.tick() method. The tick() method scans the tree components from top to bottom and calculates in each component the expressions that exist in the template. If the result of the expression is not equal to the previous result, (from the previous tick) Angular will update the DOM property that connects to this expression.

An easy solution to simply get the message performance in isolation is to run outside of the zone, and thus angular's change detection with the handy method runOutsideAngular:

```<code>this.zone.runOutsideAngular(() => {
  let i = 0;
  this.socket.onmessage = (e: MessageEvent) => {
    i++;
    if (i % 100 === 0) {
      console.log('recieved' + i);
    }
  };
});
</code>```

Body:
I've got a websocket and I'm currently streaming messages at about 45 per second. At this level it completely kills chrome. All functionality in the browser window is locked up.

I've cut back my implementation to try find the root cause of this issue, suspecting it could have been some problem with how I'm processing these messages - or updating/change detection in Angular.

But now I'm left with the simplest websocket implementation I can get:

this.socket = new WebSocket('ws://localhost:5000/ws');

let i = 0;
this.socket.onmessage = (e: MessageEvent) => {
  i++;
  if (i % 100 === 0) {
    console.log('recieved' + i);
  }
};

This is in an Angular Injectable, but it's not interacting with anything.

It writes to the console every 100 messages. This still kills the browser with 100% CPU usage, it doesn't even output to the console most of the time until I stop the message stream, then everything catches up and it squirts a few lines of "recieved x00" messages.

The messages themselves are JSON, and look like this:

{
  "Topic":"2a736d15-a2fe-43b2-8e8b-ee888f15a53a","Type":1,
  "Message": {
     "Value":2,
     "Timestamp":"2017-06-05T14:46:21.615062+01:00"
   }
}

They're typically about 126 characters.

I'd assumed websockets can handle tens of thousands of messages per second, but I can't find any sensible metrics on google, does this sound like unreasonable performance?

I've also checked in the CPU profiler. When everthing's locked out, it's just a big wall of calls, so I turned it down to a single message a second:

Drilled down into one of these spikes (happens for every single message!):

I threw a break point in one of these locations, and it appears that Angular is doing something whenever the websocket gets triggered, and it's something to do with Zones (something I have zero experience in!):

The first thing in the stack is a ZoneTask.invoke on the Websocket itself, but then NgZone gets triggered, and ultimately a very expensive change/update chain is called:

How could all this be happening? The 7 lines of code subscribing to the websocket are completely independent from Angular's change detection right? They're not changing any values that are bound to any components. Their only link is they are sitting in a method inside an @Injectable()

Body:
Sods law, as soon as I post a question I work out the answer. Usually I'd delete it but I couldn't find much on the topic so it might be useful for someone.

It was an issue with Zones. Here's a useful blog post. In general, Angular 2 uses zones to drive it's change detection:

The reason that Angular 2 uses the zone.js is to know when our handler finishes and then the NgZone service (NgZone is a class that wrap the zone service) calls to ApplicationRef.tick() method. The tick() method scans the tree components from top to bottom and calculates in each component the expressions that exist in the template. If the result of the expression is not equal to the previous result, (from the previous tick) Angular will update the DOM property that connects to this expression.

An easy solution to simply get the message performance in isolation is to run outside of the zone, and thus angular's change detection with the handy method runOutsideAngular:

this.zone.runOutsideAngular(() => {
  let i = 0;
  this.socket.onmessage = (e: MessageEvent) => {
    i++;
    if (i % 100 === 0) {
      console.log('recieved' + i);
    }
  };
});


问:
html5 canvas loading circle image
I'm trying to create a loading circle from an image in HTML5 canvas.

Here's the result I expect when percentage is at 50%:

here's what I've done after a lot of tests: (the blue stroke is just to see the circle, it'll be removed after)

var img = new Image();
img.onload = draw;
img.src = "http://i.imgur.com/HVJBZ1L.png";

var canvas = document.getElementsByTagName("canvas")[0];

canvas.width  = 500;
canvas.height = 500;

var ctx = canvas.getContext("2d");

function draw() {
    ctx.globalAlpha = 0.5
    ctx.drawImage(img, 0, 0);
    ctx.globalAlpha = 1;

    var X       = 50;
    var Y       = 50;
    var Radius  = img.width / 2;
    var end     = 40;
    var start   = 0;
    var PI2     = Math.PI * 2;
    var quart   = Math.PI / 2;
    var pct     = 50 / 100;
    var extent  = (end - start) * pct;
    var current = (end - start) / 100 * PI2 * pct - quart;

    var pattern = ctx.createPattern(img, 'no-repeat');

    ctx.beginPath();
    ctx.arc(X, Y, Radius, -quart, current);
    ctx.closePath();
    ctx.fillStyle=pattern;
   ctx.fill();
    ctx.strokeStyle = "blue";
    ctx.stroke();
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><canvas></canvas></code>```

as you can see, the result here isn't as excepted

What is wrong?

答:
First, you need to correctly calculate your center point:

```<code>var X = img.width / 2;
var Y = img.height / 2;
</code>```

Then you need to circle back in counter-clockwise direction tracing the inner radius Radius - 17:

```<code>ctx.beginPath();
ctx.arc(X, Y, Radius, -quart, current);
ctx.arc(X, Y, Radius - 17, current, -quart, true);
ctx.closePath();
</code>```

If you aren't interested in the stroke outline, you could move to the center first, and then arc:

```<code>ctx.beginPath();
ctx.moveTo(X, Y);
ctx.arc(X, Y, Radius, -quart, current);
ctx.closePath();
</code>```

Example:

var img = new Image();
img.onload = draw;
img.src = "http://i.imgur.com/HVJBZ1L.png";

var canvas = document.getElementsByTagName("canvas")[0];

canvas.width  = 500;
canvas.height = 500;

var ctx = canvas.getContext("2d");

function draw() {
    ctx.globalAlpha = 0.5
    ctx.drawImage(img, 0, 0);
    ctx.globalAlpha = 1;

    var X       = img.width / 2;
    var Y       = img.height / 2;
    var Radius  = img.width / 2;
    var end     = 40;
    var start   = 0;
    var PI2     = Math.PI * 2;
    var quart   = Math.PI / 2;
    var pct     = 50 / 100;
    var extent  = (end - start) * pct;
    var current = (end - start) / 100 * PI2 * pct - quart;

    var pattern = ctx.createPattern(img, 'no-repeat');

    ctx.beginPath();
    ctx.moveTo(X, Y);
    ctx.arc(X, Y, Radius, -quart, current);
    ctx.closePath();
    ctx.fillStyle = pattern;
    ctx.fill();
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><canvas></canvas></code>```

Title: html5 canvas loading circle image

Body:
I'm trying to create a loading circle from an image in HTML5 canvas.

Here's the result I expect when percentage is at 50%:

here's what I've done after a lot of tests: (the blue stroke is just to see the circle, it'll be removed after)

var img = new Image();
img.onload = draw;
img.src = "http://i.imgur.com/HVJBZ1L.png";

var canvas = document.getElementsByTagName("canvas")[0];

canvas.width  = 500;
canvas.height = 500;

var ctx = canvas.getContext("2d");

function draw() {
    ctx.globalAlpha = 0.5
    ctx.drawImage(img, 0, 0);
    ctx.globalAlpha = 1;

    var X       = 50;
    var Y       = 50;
    var Radius  = img.width / 2;
    var end     = 40;
    var start   = 0;
    var PI2     = Math.PI * 2;
    var quart   = Math.PI / 2;
    var pct     = 50 / 100;
    var extent  = (end - start) * pct;
    var current = (end - start) / 100 * PI2 * pct - quart;

    var pattern = ctx.createPattern(img, 'no-repeat');

    ctx.beginPath();
    ctx.arc(X, Y, Radius, -quart, current);
    ctx.closePath();
    ctx.fillStyle=pattern;
   ctx.fill();
    ctx.strokeStyle = "blue";
    ctx.stroke();
}

<canvas></canvas>

as you can see, the result here isn't as excepted

What is wrong?

Body:
First, you need to correctly calculate your center point:

var X = img.width / 2;
var Y = img.height / 2;

Then you need to circle back in counter-clockwise direction tracing the inner radius Radius - 17:

ctx.beginPath();
ctx.arc(X, Y, Radius, -quart, current);
ctx.arc(X, Y, Radius - 17, current, -quart, true);
ctx.closePath();

If you aren't interested in the stroke outline, you could move to the center first, and then arc:

ctx.beginPath();
ctx.moveTo(X, Y);
ctx.arc(X, Y, Radius, -quart, current);
ctx.closePath();

Example:

var img = new Image();
img.onload = draw;
img.src = "http://i.imgur.com/HVJBZ1L.png";

var canvas = document.getElementsByTagName("canvas")[0];

canvas.width  = 500;
canvas.height = 500;

var ctx = canvas.getContext("2d");

function draw() {
    ctx.globalAlpha = 0.5
    ctx.drawImage(img, 0, 0);
    ctx.globalAlpha = 1;

    var X       = img.width / 2;
    var Y       = img.height / 2;
    var Radius  = img.width / 2;
    var end     = 40;
    var start   = 0;
    var PI2     = Math.PI * 2;
    var quart   = Math.PI / 2;
    var pct     = 50 / 100;
    var extent  = (end - start) * pct;
    var current = (end - start) / 100 * PI2 * pct - quart;

    var pattern = ctx.createPattern(img, 'no-repeat');

    ctx.beginPath();
    ctx.moveTo(X, Y);
    ctx.arc(X, Y, Radius, -quart, current);
    ctx.closePath();
    ctx.fillStyle = pattern;
    ctx.fill();
}

<canvas></canvas>


问:
python - parsing file to json
I have some log files from where I want to extract data and export it to json.

Each time pattern is found the variables timestamp, line, frequence, crossbow, numberIt get a value, i do:

stringToJson.append({timestamp:00000, line:RRL, frequence:3434Hz, crossbow:TKESS44,  numberIt: 2})
Then I dump it:
json.dump(stringToJson, outfile)

the result is
[{timestamp:00000, line:RRL, frequence:3434Hz, crossbow:TKESS44,  numberIt: 2},{timestamp:00000, line:RRL, frequence:3434Hz, crossbow:TKESS43,  numberIt: 3},..., {timestamp:00001, line:CCL, frequence:8834Hz, crossbow:T1LS44,  numberIt: 20}, {timestamp:00001, line:CCL, frequence:8834Hz, crossbow:T1LS45,  numberIt: 21},..., ...].

I would like it:
[{00000: {"RRL":{"3434Hz":{"TKESS44":5}, {"TKESS44":5}}, {00001: {"CCL":{"8834Hz":{"T1LS44":20},{"T1LS45":20}}}}

How can I do that?

Cheers,

答:
Your python code does exactly what you ask it for; you pass it a dictionary (with keys like timestamp, line, and "frequence" and assigning values to it) and it gives you a "flat" dictionary in return.

Let's suppose your VALUES of variables correspond to the names and you can somewhat pass them like: line_value, frequence_value, timestamp_value, crossbow_value, numberIt_value.

For example:

```<code>timestamp_value = "00000"
line_value = "RRL"
frequence_value = "3434Hz"
crossbow_value = "TKESS44"
numberIt_value = 2
stringToJson.append({str(timestamp_value) : {str(line_value) : {frequence_value : {str(crossbow_value) : int(numberIt_value)}}} })
</code>```

Gives

```<code>[{'00000': {'RRL': {'3434Hz': {'TKESS44': 2}}}}]
</code>```

This does what you want, remember that that way you don't keep the keys in the dictionary, so you need to "know" the JSON structure you are building.

Title: python - parsing file to json

Body:
Your python code does exactly what you ask it for; you pass it a dictionary (with keys like timestamp, line, and "frequence" and assigning values to it) and it gives you a "flat" dictionary in return.

Let's suppose your VALUES of variables correspond to the names and you can somewhat pass them like: line_value, frequence_value, timestamp_value, crossbow_value, numberIt_value.

For example:

timestamp_value = "00000"
line_value = "RRL"
frequence_value = "3434Hz"
crossbow_value = "TKESS44"
numberIt_value = 2
stringToJson.append({str(timestamp_value) : {str(line_value) : {frequence_value : {str(crossbow_value) : int(numberIt_value)}}} })

Gives

[{'00000': {'RRL': {'3434Hz': {'TKESS44': 2}}}}]

This does what you want, remember that that way you don't keep the keys in the dictionary, so you need to "know" the JSON structure you are building.


问:
How do I add a service stack license to a .NET core project?
For my service stack license I am used to adding a web config entry

<add key="servicestack:license" ... />

How do I achieve a similar effect in ServiceStack.Core since there is no web config?

答:
The license key can be registered using any of the options listed at: https://servicestack.net/download#register

So while there's no Web.config you can use any of the other 3 options like registering the SERVICESTACK_LICENSE Environment Variable.

Also whilst .NET Core doesn't need to use Web.config or App.config you can still use one in .NET Core in ServiceStack for storing any <appSettings>, e.g:

```<code><?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <appSettings>
        <add key="servicestack:license" value="{LicenseKey}" />
    </appSettings>
</configuration>
</code>```

But you'll need to register the license key explicitly from the AppSettings with:

```<code>using ServiceStack;

public class AppHost : AppHostBase
{
    public AppHost()
        : base("Service Name", typeof(MyServices).GetAssembly())
    {
        var licenseKeyText = AppSettings.GetString("servicestack:license");
        Licensing.RegisterLicense(licenseKeyText);
    }

    public override void Configure(Container container)
    {
    }
}
</code>```

Or if you don't want to use Web.config you can use any other AppSettings options.

Body:
The license key can be registered using any of the options listed at: https://servicestack.net/download#register

So while there's no Web.config you can use any of the other 3 options like registering the SERVICESTACK_LICENSE Environment Variable.

Also whilst .NET Core doesn't need to use Web.config or App.config you can still use one in .NET Core in ServiceStack for storing any <appSettings>, e.g:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <appSettings>
        <add key="servicestack:license" value="{LicenseKey}" />
    </appSettings>
</configuration>

But you'll need to register the license key explicitly from the AppSettings with:

using ServiceStack;

public class AppHost : AppHostBase
{
    public AppHost()
        : base("Service Name", typeof(MyServices).GetAssembly())
    {
        var licenseKeyText = AppSettings.GetString("servicestack:license");
        Licensing.RegisterLicense(licenseKeyText);
    }

    public override void Configure(Container container)
    {
    }
}

Or if you don't want to use Web.config you can use any other AppSettings options.


问:
Config files editable after `npm run build`
I'm deploying a web app using react-redux soon and I was wondering if it was possible to let the user using the production version to modify a config file so that he can set his own initial settings.

Is it possible, after I run npm run build, to have a config.js file in the build folder that the user can go and directly modify?

If not, is there any better way to accomplish that using another strategy?

Thank you

答:
If I understand correct you want to expose a API to change some of settings in config for end user and then somehow restart your API servers to apply those changes.

Always a dangerous way of doing things. You can expose functionality to change few of fields of config for end user and when applied restart the node process. There are few ways to restart node process from code itself or writing a hot script which monitors changes in source directory.

But beware its risky thing to do. Hope this helps.