text:
/* globals module */
/**
 * @module commerceCountryClient
 * @description  Commerce Country Client provides an easy way to consume  Commerce REST API end-points. In order to obtain a needed routes `commerceCountryClient` uses `commerceCountryRoute`.
 */

import { injectable, inject } from "inversify";
import { IQueryModel, IGetRequestOptions, IOptions } from '../../../../common/contracts';;
import { ApiClient, IHttpResponse, httpTYPES } from '../../../../httpApi';
import { CommerceLookupsCountryBatchClient, CommerceLookupsCountryRoute, TYPES as commerceTypes } from '../../';

@injectable()
export class CommerceLookupsCountryClient {

    get routeDefinition(): CommerceLookupsCountryRoute {
        return this.commerceLookupsCountryRoute;
    }

    get batch(): CommerceLookupsCountryBatchClient {
        return this.commerceLookupsCountryBatchClient;
    }

    constructor(
        @inject(commerceTypes.CommerceLookupsCountryRoute) protected commerceLookupsCountryRoute: CommerceLookupsCountryRoute,
        @inject(commerceTypes.CommerceLookupsCountryBatchClient) protected commerceLookupsCountryBatchClient: CommerceLookupsCountryBatchClient,
        @inject(httpTYPES.ApiClient) protected apiClient: ApiClient
    ) { }

    /**
     * Returns a promise that is resolved once the find action has been performed. Success response returns a list of commerce resources matching the given criteria.
     * @method
     * @example commerceLookupsCountryClient.find({
                   pageNumber : 1,
                   pageSize : 10,
                   orderBy : '<field>',
                   orderDirection : '<asc|desc>',
                   search : '<search-phrase>'
               })
               .then(function (collection) {
                   // perform success action here
               },
                function (response, status, headers, config) {
                    // perform error handling here
               });
    **/
    find(options?: IOptions): PromiseLike<IHttpResponse<IQueryModel<any>>> {
        return this.apiClient.get(this.routeDefinition.find(options));
    }

    /**
     * Returns a promise that is resolved once the get action has been performed. Success response returns the commerce resource.
     * @method
     * @example commerceLookupsCountryClient.get('<country-id>')
                   .then(function (data) {
                       // perform success action here
                   },
                    function (response, status, headers, config) {
                        // perform error handling here
                   });
    **/
    get(id: string, options?: IGetRequestOptions): PromiseLike<IHttpResponse<any>> {
        return this.apiClient.get(this.commerceLookupsCountryRoute.get(id, options));
    }

    /**
     * Returns a promise that is resolved once the create commerce action has been performed; this action creates a new commerce resource.
     * @method
     * @example commerceLookupsCountryClient.create({
                    name : '<name>',
                    abrv: '<abbreviation>',
                    description: '<description>'
                })
                .then(function (data) {
                    // perform success action here
                },
                 function (response, status, headers, config) {
                     // perform error handling here
                });
     **/
    create(data: any): PromiseLike<IHttpResponse<any>> {
        return this.apiClient.post(this.routeDefinition.create(), this.routeDefinition.createParams(data));
    }

    /**
     * Returns a promise that is resolved once the update commerce action has been performed; this action updates a commerce resource. This route uses HAL enabled objects to obtain routes and therefore it doesn't apply `baasicCommerceCountryRouteService` route template. Here is an example of how a route can be obtained from HAL enabled objects:
     * ```
     * let params = modelMapper.removeParams(commerceCountry);
     * let uri = params['model'].links('put').href;
     * ```
     * @method
     * @example // commerceCountry is a resource previously fetched using get action.
                        commerceCountry.phoneCode = '<phone-code>';
                        commerceLookupsCountryClient.update(commerceCountry)
                            .then(function (data) {
                                // perform success action here
                            },
                             function (response, status, headers, config) {
                                 // perform error handling here
                            });
     **/
    update(data: any): PromiseLike<IHttpResponse<void>> {
        return this.apiClient.put<void>(this.routeDefinition.update(data), this.routeDefinition.updateParams(data));
    }

    /**
     * Returns a promise that is resolved once the remove action has been performed. This action will remove a commerce resource from the system if successfully completed. This route uses HAL enabled objects to obtain routes and therefore it doesn't apply `commerceLookupsCountryRoute` route template. Here is an example of how a route can be obtained from HAL enabled objects:
     * ```
     * let params = modelMapper.removeParams(commerceCountry);
     * let uri = params['model'].links('delete').href;
     * ```
     * @method
     * @example // commerceCountry is a resource previously fetched using get action.
                    commerceLookupsCountryClient.remove(commerceCountry)
                        .then(function (data) {
                            // perform success action here
                        },
                         function (response, status, headers, config) {
                             // perform error handling here
                        });
     **/
    remove(data: any): PromiseLike<IHttpResponse<void>> {
        return this.apiClient.delete<void>(this.routeDefinition.delete(data));
    }
}

/**
 * @copyright (c) 2017 Mono Ltd
 * @license MIT
 * @author Mono Ltd
 * @overview
 ***Notes:**
 - Refer to the [Baasic REST API](http://dev.baasic.com/api/reference/home) for detailed information about available Baasic REST API end-points.
 - All end-point objects are transformed by the associated route service.
 */


text:
module.exports =  {
  presets: [
    [require.resolve('babel-preset-env'), {
      targets: {
        browsers: ['> 1%', 'last 4 versions', 'ie >= 9', 'Firefox ESR']
      }
    }],
    require.resolve('babel-preset-react')
  ],
  plugins: [
    require.resolve('babel-plugin-transform-runtime'),
    require.resolve('babel-plugin-transform-object-rest-spread'),
    require.resolve('babel-plugin-transform-class-properties'),
    require.resolve('babel-plugin-syntax-dynamic-import')
  ]
}

redpajama_set_name: RedPajamaGithub


text:
package com.lys.mvc.action;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * 异常处理 Action
 * @author shuang
 */
@Scope(value = "prototype")
@Controller("ErrorAction")
@RequestMapping(value = "/error")
public class ErrorAction extends BaseAjaxAction {
	/**
	 * SESSION并发处理
	 * @return
	 */
	@RequestMapping(value="/concurrentSessionFilter")
	public String concurrentSessionFilter(){
		return "error/sessionComplicating";
	}
	/**
	 * 没有访问url的权限
	 * @return
	 */
	@RequestMapping(value="/nonFunction")
	public String nonFunction(){
		return "error/nonFunction";
	}
}


text:
package sql.fredy.sqltools;

import sql.fredy.ui.TableComboBox;
import sql.fredy.ui.ImageButton;
import sql.fredy.share.t_connect;
import sql.fredy.metadata.SingleColumnInfo;
import sql.fredy.metadata.IsAutoIncrement;
import sql.fredy.metadata.TableColumns;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.util.logging.*;
import java.sql.*;
import javax.swing.*;
import javax.swing.BorderFactory;
import javax.swing.border.Border;
import javax.swing.border.TitledBorder;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.event.*;
import javax.swing.table.*;
import javax.swing.border.*;
import java.awt.datatransfer.*;

public class ChangeTable extends JPanel {

// Fredy's make Version
private static String fredysVersion = "Version 1.6  2. Jan. 2003";

public String getVersion() {return fredysVersion; }

    private Logger logger;

    t_connect con=null;

    /**
     * Get the value of con.
     * @return value of con.
     */
    public t_connect getCon() {
        if ( con == null) {
	    con = new t_connect(getHost(),
				getUser(),
				getPassword(),
				getDatabase());
	    if ( ! con.acceptsConnection() ) con = null;
	}

	return con;
    }

    /**
     * Set the value of con.
     * @param v  Value to assign to con.
     */
    public void setCon(t_connect  v) {
	this.con = v;
        setHost(con.getHost());
	setUser(con.getUser());
	setPassword(con.getPassword());
	setDatabase(con.getDatabase());
    }

    String host;

    /**
       * Get the value of host.
       * @return Value of host.
       */
    public String getHost() {return host;}

    /**
       * Set the value of host.
       * @param v  Value to assign to host.
       */
    public void setHost(String  v) {this.host = v;}

    String user;

    /**
       * Get the value of user.
       * @return Value of user.
       */
    public String getUser() {return user;}

    /**
       * Set the value of user.
       * @param v  Value to assign to user.
       */
    public void setUser(String  v) {this.user = v;}

    String password;

    /**
       * Get the value of password.
       * @return Value of password.
       */
    public String getPassword() {return password;}

    /**
       * Set the value of password.
       * @param v  Value to assign to password.
       */
    public void setPassword(String  v) {this.password = v;}

    String database;

    /**
       * Get the value of database.
       * @return Value of database.
       */
    public String getDatabase() {return database;}

    /**
       * Set the value of database.
       * @param v  Value to assign to database.
       */
    public void setDatabase(String  v) {this.database = v;}

    String schema;

    /**
       * Get the value of schema.
       * @return Value of schema.
       */
    public String getSchema() {return schema;}

    /**
       * Set the value of schema.
       * @param v  Value to assign to schema.
       */
    public void setSchema(String  v) {this.schema = v;}

    private TableComboBox tbc;
    private TableColumns tCols;
    private JTable rows;
    private ChangeTableModel ctm;
    private Vector orig,origParam;
    private JTextArea sqlCmd, msg;
    private JCheckBox showCmd;
    private JTabbedPane tp;
    public ImageButton exit;

    public ChangeTable(String host,
		       String user,
		       String password,
		       String database,
		       String schema) {

	this.host     = host;
	this.user     = user;
	this.password = password;
	this.database = database;
	setSchema(schema);
	init();
    }

    public ChangeTable(t_connect con,String schema) {
	setCon(con);
	setSchema(schema);
	init();
    }
    public ChangeTable(t_connect con) {
	setCon(con);
	setSchema("%");
	init();
    }

    private void init() {

	logger = Logger.getLogger("sql.fredy.admin");

	orig = new Vector();
        origParam = new Vector();
	sqlCmd = new JTextArea();

	this.setLayout(new GridBagLayout());
	GridBagConstraints gbc;
	Insets insets = new Insets(1,1,1,1);
	gbc = new GridBagConstraints();

	gbc.anchor= GridBagConstraints.CENTER;
        gbc.fill  = GridBagConstraints.NONE;
	gbc.insets = insets;
	gbc.gridx = 0;
	gbc.gridy = 0;

	//this.add(BorderLayout.CENTER,selectPanel());
	//this.add(BorderLayout.SOUTH,listPanel());

	this.add(selectPanel(),gbc);

	gbc.anchor= GridBagConstraints.CENTER;
        gbc.fill  = GridBagConstraints.BOTH;
	gbc.insets = insets;
	gbc.gridx = 0;
	gbc.gridy = 1;
	gbc.weightx = 1.0;
	gbc.weighty = 1.0;
	this.add(listPanel(),gbc);
    }

    private JPanel selectPanel() {

	JPanel panel = new JPanel();
	panel.setLayout(new FlowLayout());
	panel.add(new JLabel("Table:"));
	ImageButton add = new ImageButton(null,"newrow.gif","Add a Row to this table");
	ImageButton drop = new ImageButton(null,"delete.gif","Delete this row from the table");
        final ImageButton ok   = new ImageButton(null,"check.gif","generate SQL");
	exit = new ImageButton(null,"exit.gif","Exit");

	add.addActionListener(new ActionListener() {
	    public void actionPerformed(ActionEvent e) {
	        addRow();
		}});

	ok.addActionListener(new ActionListener() {
	    public void actionPerformed(ActionEvent e) {
		alterTable();
		}});

	tbc = new TableComboBox(getHost(),getUser(),getPassword(),getDatabase(),getSchema());
	tbc.addActionListener(new ActionListener() {
	    public void actionPerformed(ActionEvent e) {
		setListContent((String)tbc.getSelectedItem());
		}});

	showCmd = new JCheckBox("Editor");
	showCmd.setToolTipText("To enable SQL-Command editing before executing");
	showCmd.setSelected(true);
	showCmd.addActionListener(new ActionListener() {
	    public void actionPerformed(ActionEvent e) {
		if (showCmd.isSelected() ) {
		    ok.setToolTipText("generate SQL"); }
		else {  ok.setToolTipText("update Table"); }
		}});

	panel.add(tbc);
	panel.add(add);
	panel.add(ok);
	//panel.add(drop);
	panel.add(exit);
	panel.add(showCmd);

	return panel;

    }

    private void alterTable() {
        sqlCmd.setText("");
	String cmd = "";
	for (int i = 0; i < orig.size();i++) {
	    SingleColumnInfo sci = new SingleColumnInfo();
	    sci = (SingleColumnInfo)orig.elementAt(i);

	    String  param = (String)ctm.getValueAt(i,3);
            int colSize=0;
	    try {
		colSize = Integer.parseInt(param);
	    } catch (NumberFormatException nfe) { colSize=0; }

            boolean bool1 = true;
	    Boolean bool2 = new Boolean(bool1);
	    bool2 = (Boolean)ctm.getValueAt(i,ctm.NULL_FIELD);

	    String colName = (String)ctm.getValueAt(i,ctm.NAME_FIELD);
	    String typName = (String)ctm.getValueAt(i,ctm.TYP_FIELD);
	    String keyPara = (String)ctm.getValueAt(i,ctm.ADD_FIELD);

	    if ( ( sci.getColumn_name() !=colName  )  ||
		 ( sci.getType_name().toLowerCase()!= typName.toLowerCase() )  ||
		 (  (boolean)sci.isNullable()      != bool2.booleanValue() )   ||
		 (  keyPara   != (String)origParam.elementAt(i) ) ||     // a change because AutoIncr etc
		 (  (int)sci.getColumn_size()      != colSize ) ) {
		 cmd = "alter table " + tbc.getSelectedItem() +
		        " modify " + sci.getColumn_name() + " " + typName;

                 if ( (param.length() > 0) && (Character.isDigit(param.trim().charAt(0))) ) {
		     cmd = cmd +  "(" + param +") ";
		 } else {
		     cmd = cmd + " " + param + " ";
		 }

		 if ( ! bool2.booleanValue() ) cmd = cmd + " not null";

		 cmd = cmd + " " + (String)ctm.getValueAt(i,ctm.ADD_FIELD);

		sqlCmd.append(cmd +  ";\n");
	    }
	}

	for (int j = orig.size();j < ctm.getRowCount(); j++) {
	    String  param = (String)ctm.getValueAt(j,3);
            int colSize=0;
	    try {
		colSize = Integer.parseInt(param);
	    } catch (NumberFormatException nfe) { colSize=0; }

            boolean bool1 = true;
	    Boolean bool2 = new Boolean(bool1);
	    bool2 = (Boolean)ctm.getValueAt(j,2);

	    String colName = (String)ctm.getValueAt(j,0);
	    String typName = (String)ctm.getValueAt(j,1);

	    if ( colName.length() > 0 ) {
		cmd = "alter table " + tbc.getSelectedItem() +
	          " add " +
		    colName + " " + typName ;
	            if ( param.length() > 0 ) {
			if (Character.isDigit(param.trim().charAt(0)) ) {
			    cmd = cmd + "(" + param + ")";
			} else {
			    cmd = cmd + " " + param + " ";
			}
		    }

		    if ( ! bool2.booleanValue() ) cmd = cmd + " not null ";
		    cmd = cmd + " " + (String)ctm.getValueAt(j,ctm.ADD_FIELD);
		    sqlCmd.append(cmd + ";\n");
	    }
	}
	if ( ! showCmd.isSelected()) executeCmd();

    }

  private void executeCmd() {
    StringTokenizer st = new StringTokenizer(sqlCmd.getText(),";");
    while (st.hasMoreTokens()) {
       execSQL(st.nextToken());
    }
  }

  private void execSQL(String sqlQuery) {
      sqlQuery.replaceAll(System.getProperty("line.separator")," ");
      if ( sqlQuery.length() > 4) {
	  getCon();
	  try
	      {
		  int records = con.stmt.executeUpdate(sqlQuery);
		  message(Integer.toString(records)+" rows affected");
		  logger.log(Level.INFO,"User " + getUser() + ": " +
			     Integer.toString(records)+" rows affected " +
			     "with SQL-cmd: " + sqlQuery);

	      } catch (Exception excpt) {
		  logger.log(Level.WARNING,"User " + getUser() + ": " +
			     "throws exception " + excpt.getMessage().toString() +
			     " with: " + sqlQuery);
		  message(excpt.getMessage().toString());
	      }
      }
  }

  private void message(String m) {

    msg.append("\n");
    msg.append(m);

  }

    private void addRow() {

       Vector v = new Vector();
       v.addElement((String)"");
       v.addElement((String)"varchar");
       v.addElement((Boolean)new Boolean(true));
       v.addElement((String)"20");
       v.addElement((String)" ");
       ctm.addRow(v);
       doCellEditors();

    }

    private void setListContent(String tableName) {
	ctm.clearData();
	orig.clear();
	origParam.clear();
	tCols = new TableColumns(getCon(),tableName );
        IsAutoIncrement isa = new IsAutoIncrement(getCon(),tableName );
	for (int i = 0; i <= tCols.getNumberOfColumns();i++) {
	    Vector v = new Vector();
	    SingleColumnInfo sci = new SingleColumnInfo();
	    sci = tCols.getColumn(i);
	    orig.addElement((SingleColumnInfo) sci); // this saves the original Layout
	    v.addElement((String)sci.getColumn_name());
	    v.addElement((String)sci.getType_name().toLowerCase());
	    Boolean bool = new Boolean(sci.isNullable());
	    v.addElement((Boolean)bool);
	    v.addElement((String)Integer.toString(sci.getColumn_size()));

	    // additonal Parameters
	    String ap="";
	    isa.setColumn(sci.getColumn_name());

            if  ( ( sci.isPrimaryKey()   )   && ( isa.autoIncrement() ) )
		ap = " AUTO_INCREMENT PRIMARY KEY ";
	    if  ( ( sci.isPrimaryKey()   )   && ( ! isa.autoIncrement() ) )
		ap = " PRIMARY KEY ";
            if  ( ( ! sci.isPrimaryKey() ) && ( isa.autoIncrement() ) )
		ap = " AUTO_INCREMENT ";

	    origParam.add((String) ap);
	    v.addElement((String)ap);

	    ctm.addRow(v);
	}
	doCellEditors();
    }

    private void doCellEditors() {

	JComboBox typ = new JComboBox();
        String[] items = {
	     "char",
	     "VARCHAR",
	     "BLOB",
	     "INT",
	     "FLOAT",
	     "DOUBLE",
	     "ENUM",
	     "SET",
	     "DATE",
	     "DATETIME",
	     "TIMESTAMP"
	};

        JComboBox paras = new JComboBox(new String[]  {"","PRIMARY KEY","AUTO_INCREMENT","AUTO_INCREMENT PRIMARY KEY" } );
	paras.setEditable(true);

	//for (int i = 0; i < items.length;i++) typ.addItem(items[i].toLowerCase());
	for (int i = 0; i < items.length;i++) typ.addItem(items[i]);

	TableColumn      typColumn   = rows.getColumnModel().getColumn(ctm.TYP_FIELD);
	typColumn.setCellEditor(new DefaultCellEditor(typ));

	TableColumn      paraColumn   = rows.getColumnModel().getColumn(ctm.ADD_FIELD);
	paraColumn.setCellEditor(new DefaultCellEditor(paras));
    }

    private JTabbedPane listPanel() {

        tp = new JTabbedPane();

	JPanel panel = new JPanel();
	panel.setLayout(new GridBagLayout());

	ctm = new ChangeTableModel();
	rows = new JTable(ctm);

	rows.getTableHeader().setReorderingAllowed(false);
	rows.setPreferredScrollableViewportSize(new Dimension(400,150));

	JScrollPane scrollpane = new JScrollPane(rows);
	GridBagConstraints gbc;
	Insets insets = new Insets(1,1,1,1);
	gbc = new GridBagConstraints();
	gbc.anchor= GridBagConstraints.WEST;
        gbc.fill  = GridBagConstraints.BOTH;
	gbc.insets = insets;
	gbc.gridx = 0;
	gbc.gridy = 0;
	gbc.weightx = 1.0;
	gbc.weighty = 1.0;
	panel.add(scrollpane,gbc);
	setListContent((String)tbc.getSelectedItem());

	tp.add("Table",panel);

        JPanel p2 = new JPanel();
	p2.setLayout(new BorderLayout());
	sqlCmd = new JTextArea();
	p2.add(BorderLayout.CENTER,new JScrollPane(sqlCmd));

	JPanel p3 = new JPanel();
	p3.setLayout(new FlowLayout());

	final Toolkit tk = this.getToolkit();
	ImageButton copy = new ImageButton(null,"copy.gif","Copies selection to the clipboard");
	copy.addActionListener(new ActionListener() {
	    public void actionPerformed(ActionEvent e) {
		sqlCmd.selectAll();
		String s = sqlCmd.getSelectedText();
		StringSelection ss = new StringSelection(s);
		tk.getSystemClipboard().setContents(ss,ss);
		}});

	p3.add(copy);

	ImageButton selectAll = new ImageButton(null,"select.gif","select all Text");
	selectAll.addActionListener(new ActionListener() {
	    public void actionPerformed(ActionEvent e) {
		sqlCmd.selectAll();
		}});
	p3.add(selectAll);

	ImageButton clear = new ImageButton(null,"clear.gif","Clears content");
	clear.addActionListener(new ActionListener() {
	    public void actionPerformed(ActionEvent e) {
	        sqlCmd.setText("");
		}});

	p3.add(clear);

	ImageButton exc = new ImageButton(null,"database.gif","Commit changes");
	exc.addActionListener(new ActionListener() {
	    public void actionPerformed(ActionEvent e) {
	        executeCmd();;
		}});
	p3.add(exc);
	p2.add(BorderLayout.SOUTH,p3);

	tp.add("SQL",p2);

	msg = new JTextArea();
	msg.setEditable(false);
        msg.setLineWrap(true);
	tp.add("Message",new JScrollPane(msg));

	return tp;
    }

    public static void main(String args[]){

	String host     = "localhost";
	String user     = System.getProperty("user.name");
        String schema   = "%";
        String database = null;
        String password = null;

	System.out.println("ChangeTable\n" +
			   "------------\n" +
			   "Syntax: java sql.fredy.sqltools.ChangeTable\n" +
			   "        Parameters: -h Host (default: localhost)\n" +
			   "                    -u User (default: " + System.getProperty("user.name") + ")\n" +
			   "                    -p Password\n" +
			   "                    -d database\n" +
			   "                    -s Schema (default: %)\n");

	int i = 0;
	while ( i < args.length) {
            if (args[i].equals("-h")) {
                i++;
                host = args[i];
            }
            if (args[i].equals("-u")) {
                i++;
                user = args[i];
            }
            if (args[i].equals("-p")) {
                i++;
                password = args[i];
            }
            if (args[i].equals("-d")) {
                i++;
                database = args[i];
            }

            if (args[i].equals("-s")) {
                i++;
                schema = args[i];
            }
	    i++;
	};

	if ( database == null) {
	    System.out.println("No database provided. Program stopped!");
	    System.exit(0);
	}

	t_connect con = new t_connect(host,user,password,database);
	if ( ! con.acceptsConnection() ) {
	    System.out.println("I'm not able to connect. Error:\n" + con.getError());
	    System.exit(0);
	}

	ChangeTable ct = new ChangeTable(con,schema);
	JFrame frame = new JFrame("Fredy's Change Table");
	frame.getContentPane().add(ct);
	frame.pack();
	frame.addWindowListener(new WindowAdapter() {
		public void windowActivated(WindowEvent e) {}
		public void windowClosed(WindowEvent e) {}
		public void windowClosing(WindowEvent e) {System.exit(0);}
		public void windowDeactivated(WindowEvent e) {}
		public void windowDeiconified(WindowEvent e) {}
		public void windowIconified(WindowEvent e) {}
		public void windowOpened(WindowEvent e) {}});
	ct.exit.addActionListener(new ActionListener() {
		public void actionPerformed(ActionEvent e) {
                    System.exit(0);
		}});

	frame.setVisible(true);
    }

}


text:
layout: post
title:  "[Swift]LeetCode学习笔记(167) Two Sum II"
date:   2019-10-31 23:30:00 +0800
categories: 算法
---

Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2.

### Note:

```
* Your returned answers (both index1 and index2) are not zero-based.
* You may assume that each input would have exactly one solution and you may not use the same element twice.
```

### Example:

```
Input: numbers = [2,7,11,15], target = 9
Output: [1,2]
Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.
```

### 解法一

```swift
class Solution {
    func twoSum(_ numbers: [Int], _ target: Int) -> [Int] {
        if numbers.count == 0 || numbers.count == 1 || (numbers.count == 2 && (numbers[0] + numbers[1] != target)) {
            return []
        }
        var smallIndex = 0
        var bigIndex = numbers.count - 1

        while smallIndex < bigIndex {
            if numbers[smallIndex] + numbers[bigIndex] == target {
                return [smallIndex+1, bigIndex+1]
            } else if numbers[smallIndex] + numbers[bigIndex] > target {
                bigIndex -= 1
            } else if numbers[smallIndex] + numbers[bigIndex] < target {
                smallIndex += 1
            }
        }

        return []
    }
}
```

### 思路简述

这题就是两数之和的进化版,给定数组是排好序的,那么就超级简单了,直接上双指针,一头一尾,不断往中间迫近就好了,知道输出正确答案,没有就输出空。


text:
package com.obsidian.compiler.StaticCodeAnalyzer.Errors;

import com.obsidian.compiler.Lava.LvRangeInFile;
import com.obsidian.compiler.Lava.LvValue;
import com.obsidian.compiler.StaticCodeAnalyzer.ScaErrorSource;

/**
 * Created by Jonathon on 6/19/2017.
 */
public class CannotPerformSeqAccessOnType extends CompileError {

	LvRangeInFile source;
	LvValue base;

	public CannotPerformSeqAccessOnType(LvRangeInFile source, LvValue base) {
		super();
		this.source = source;
		this.base = base;
	}

	@Override
	public String getTitle() {
		return "Cannot perform sequential access on type " + base.type.getHumanName(true);
	}

	@Override
	public ScaErrorSource getFirstSource() {
		return new ScaErrorSource(this.source, this.getTitle());
	}

}


text:
// -----------------------------------------------------------------------
//  <copyright file="IdentityService.UserRole.cs" company="OSharp开源团队">
//      Copyright (c) 2014-2018 OSharp. All rights reserved.
//  </copyright>
//  <site>http://www.osharp.org</site>
//  <last-editor>郭明锋</last-editor>
//  <last-date>2018-06-27 4:44</last-date>
// -----------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;

using OSharp.Hosting.Identity.Dtos;
using OSharp.Hosting.Identity.Entities;

using Microsoft.AspNetCore.Identity;

using OSharp.Collections;
using OSharp.Data;
using OSharp.Identity;
using OSharp.Identity.Events;

namespace OSharp.Hosting.Identity
{
    public partial class IdentityService
    {
        /// <summary>
        /// 获取 用户角色信息查询数据集
        /// </summary>
        public IQueryable<UserRole> UserRoles
        {
            get { return UserRoleRepository.QueryAsNoTracking(); }
        }

        /// <summary>
        /// 检查用户角色信息信息是否存在
        /// </summary>
        /// <param name="predicate">检查谓语表达式</param>
        /// <param name="id">更新的用户角色信息编号</param>
        /// <returns>用户角色信息是否存在</returns>
        public Task<bool> CheckUserRoleExists(Expression<Func<UserRole, bool>> predicate, Guid id = default(Guid))
        {
            return UserRoleRepository.CheckExistsAsync(predicate, id);
        }

        /// <summary>
        /// 更新用户角色信息
        /// </summary>
        /// <param name="dtos">用户角色信息集合</param>
        /// <returns>业务操作结果</returns>
        public async Task<OperationResult> UpdateUserRoles(params UserRoleInputDto[] dtos)
        {
            Check.Validate<UserRoleInputDto,Guid>(dtos, nameof(dtos));

            List<string> userNames = new List<string>();
            OperationResult result = await UserRoleRepository.UpdateAsync(dtos,
                (dto, entity) =>
                {
                    string userName = UserRoleRepository.QueryAsNoTracking(m => m.UserId == entity.UserId).Select(m => m.User.UserName).FirstOrDefault();
                    userNames.AddIfNotNull(userName);
                    return Task.FromResult(0);
                });
            if (result.Succeeded && userNames.Count > 0)
            {
                OnlineUserCacheRemoveEventData eventData = new OnlineUserCacheRemoveEventData() { UserNames = userNames.ToArray() };
                await EventBus.PublishAsync(eventData);
            }
            return result;
        }

        /// <summary>
        /// 删除用户角色信息
        /// </summary>
        /// <param name="ids">用户角色信息编号</param>
        /// <returns>业务操作结果</returns>
        public async Task<OperationResult> DeleteUserRoles(Guid[] ids)
        {
            List<string>userNames = new List<string>();
            OperationResult result = await UserRoleRepository.DeleteAsync(ids,
                (entity) =>
                {
                    string userName = UserRoleRepository.QueryAsNoTracking(m => m.UserId == entity.UserId).Select(m => m.User.UserName).FirstOrDefault();
                    userNames.AddIfNotNull(userName);
                    return Task.FromResult(0);
                });
            if (result.Succeeded && userNames.Count > 0)
            {
                OnlineUserCacheRemoveEventData eventData = new OnlineUserCacheRemoveEventData(){UserNames = userNames.ToArray()};
                await EventBus.PublishAsync(eventData);
            }

            return result;
        }

        /// <summary>
        /// 设置用户的角色
        /// </summary>
        /// <param name="userId">用户编号</param>
        /// <param name="roleIds">角色编号集合</param>
        /// <returns>业务操作结果</returns>
        public async Task<OperationResult> SetUserRoles(int userId, int[] roleIds)
        {
            User user = await UserManager.FindByIdAsync(userId.ToString());
            if (user == null)
            {
                return new OperationResult(OperationResultType.QueryNull, $"编号为"{userId}"的用户不存在");
            }
            IList<string> roleNames = RoleManager.Roles.Where(m => roleIds.Contains(m.Id)).Select(m => m.Name).ToList();
            IList<string> existRoleNames = await UserManager.GetRolesAsync(user);
            string[] addRoleNames = roleNames.Except(existRoleNames).ToArray();
            string[] removeRoleNames = existRoleNames.Except(roleNames).ToArray();

            if (!addRoleNames.Union(removeRoleNames).Any())
            {
                return OperationResult.NoChanged;
            }

            try
            {
                IdentityResult result = await UserManager.AddToRolesAsync(user, addRoleNames);
                if (!result.Succeeded)
                {
                    return result.ToOperationResult();
                }
                result = await UserManager.RemoveFromRolesAsync(user, removeRoleNames);
                if (!result.Succeeded)
                {
                    return result.ToOperationResult();
                }
                await UserManager.UpdateSecurityStampAsync(user);

                //更新用户缓存使角色生效
                OnlineUserCacheRemoveEventData eventData = new OnlineUserCacheRemoveEventData() { UserNames = new[] { user.UserName } };
                await EventBus.PublishAsync(eventData);
            }
            catch (InvalidOperationException ex)
            {
                return new OperationResult(OperationResultType.Error, ex.Message);
            }
            if (addRoleNames.Length > 0 && removeRoleNames.Length == 0)
            {
                return new OperationResult(OperationResultType.Success, $"用户"{user.UserName}"添加角色"{addRoleNames.ExpandAndToString()}"操作成功");
            }
            if (addRoleNames.Length == 0 && removeRoleNames.Length > 0)
            {
                return new OperationResult(OperationResultType.Success, $"用户"{user.UserName}"移除角色"{removeRoleNames.ExpandAndToString()}"操作成功");
            }
            return new OperationResult(OperationResultType.Success,
                $"用户"{user.UserName}"添加角色"{addRoleNames.ExpandAndToString()}",移除角色"{removeRoleNames.ExpandAndToString()}"操作成功");
        }
    }
}


text:
package org.openo.nfvo.emsdriver.northbound.client;

import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;

import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;

/**
 * HttpClient
  */
public class HttpClientFactory{

	public static CloseableHttpClient getSSLClientFactory() throws Exception {

		SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
             //信任所有
             public boolean isTrusted(X509Certificate[] chain,
                             String authType) throws CertificateException {
                 return true;
             }
         }).build();
         SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
         CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();

         return httpclient;
	}

}


text:
/* bundleLogger
   ------------
   Provides gulp style logs to the bundle method in browserify.js
*/

var log = require('fancy-log')
var colors = require('ansi-colors')
var prettyHrtime = require('pretty-hrtime')
var startTime

module.exports = {
  start: function (filepath) {
    startTime = process.hrtime()
    log('Bundling', colors.green(filepath) + '...')
  },

  end: function (filepath) {
    var taskTime = process.hrtime(startTime)
    var prettyTime = prettyHrtime(taskTime)
    log('Bundled', colors.green(filepath), 'in', colors.magenta(prettyTime))
  }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<release-info>
 <version>2009.2.1</version>
 <deps>
  <php>5.2.1</php>
  <packages>
   <package version="1.4.1" name="Archive"/>
   <package version="1.3.1" name="Authentication"/>
   <package version="1.1" name="AuthenticationDatabaseTiein">
    <deps>
     <package version="1.3" name="Database"/>
     <package version="1.1" name="Authentication"/>
    </deps>
   </package>
   <package version="1.8" name="Base"/>
   <package version="1.5" name="Cache"/>
   <package version="1.3.5" name="Configuration"/>
   <package version="1.6.1" name="ConsoleTools"/>
   <package version="1.4.7" name="Database"/>
   <package version="1.4.4" name="DatabaseSchema"/>
   <package version="1.2.1" name="Debug"/>
   <package version="1.3.1" name="Document"/>
   <package version="1.4" name="EventLog"/>
   <package version="1.0.2" name="EventLogDatabaseTiein">
    <deps>
     <package version="1.0.3" name="EventLog"/>
     <package version="1.2" name="Database"/>
    </deps>
   </package>
   <package version="1.1.1" name="Execution"/>
   <package version="1.3" name="Feed"/>
   <package version="1.2" name="File"/>
   <package version="1.5" name="Graph"/>
   <package version="1.0.1" name="GraphDatabaseTiein">
    <deps>
     <package version="1.1" name="Graph"/>
    </deps>
   </package>
   <package version="1.1.3" name="ImageAnalysis"/>
   <package version="1.3.8" name="ImageConversion">
    <deps>
     <package version="1.1.3" name="ImageAnalysis"/>
    </deps>
   </package>
   <package version="1.7.1" name="Mail"/>
   <package version="1.1.3" name="MvcTools"/>
   <package version="1.0" name="MvcAuthenticationTiein"/>
   <package version="1.0" name="MvcFeedTiein">
    <deps>
     <package version="1.1" name="MvcTools"/>
     <package version="1.2.1" name="Feed"/>
    </deps>
   </package>
   <package version="1.0.1" name="MvcMailTiein">
    <deps>
     <package version="1.0" name="MvcTools"/>
     <package version="1.7" name="Mail"/>
    </deps>
   </package>
   <package version="1.0" name="MvcTemplateTiein">
    <deps>
     <package version="1.0" name="MvcTools"/>
     <package version="1.3.1" name="Template"/>
    </deps>
   </package>
   <package version="1.7.1" name="PersistentObject">
    <deps>
     <package version="1.3" name="Database"/>
    </deps>
   </package>
   <package version="1.3" name="PersistentObjectDatabaseSchemaTiein">
    <deps>
     <package version="1.3" name="PersistentObject"/>
     <package version="1.2" name="DatabaseSchema"/>
     <package version="1.3" name="ConsoleTools"/>
    </deps>
   </package>
   <package version="1.0.6" name="PhpGenerator"/>
   <package version="1.0.9" name="Search"/>
   <package version="1.1.1" name="SignalSlot"/>
   <package version="1.0.8" name="SystemInformation"/>
   <package version="1.4.2" name="Template"/>
   <package version="1.1.1" name="TemplateTranslationTiein">
    <deps>
     <package version="1.4" name="Template"/>
     <package version="1.3" name="Translation"/>
     <package version="1.5" name="ConsoleTools"/>
    </deps>
   </package>
   <package version="1.3.2" name="Translation"/>
   <package version="1.1.2" name="TranslationCacheTiein">
    <deps>
     <package version="1.1.2" name="Translation"/>
     <package version="1.1.4" name="Cache"/>
    </deps>
   </package>
   <package version="1.1.4" name="Tree"/>
   <package version="1.1.1" name="TreeDatabaseTiein">
    <deps>
     <package version="1.1" name="Tree"/>
     <package version="1.3" name="Database"/>
    </deps>
   </package>
   <package version="1.0" name="TreePersistentObjectTiein">
    <deps>
     <package version="1.0" name="Tree"/>
     <package version="1.3" name="PersistentObject"/>
    </deps>
   </package>
   <package version="1.2.2" name="Url"/>
   <package version="1.4" name="UserInput"/>
   <package version="1.1.4" name="Webdav"/>
   <package version="1.4.1" name="Workflow"/>
   <package version="1.4" name="WorkflowDatabaseTiein">
    <deps>
     <package version="1.3" name="Database"/>
     <package version="1.4" name="Workflow"/>
    </deps>
   </package>
   <package version="1.1" name="WorkflowEventLogTiein">
    <deps>
     <package version="1.1" name="EventLog"/>
     <package version="1.0" name="Workflow"/>
    </deps>
   </package>
   <package version="1.0" name="WorkflowSignalSlotTiein">
    <deps>
     <package version="1.1" name="SignalSlot"/>
     <package version="1.2" name="Workflow"/>
    </deps>
   </package>
  </packages>
 </deps>
</release-info>


text:
var CryptoJS = require('../vendor/cryptojs/crypto');

// Add SHA3 to strings
String.prototype.sha3 = function(length, encoding) {

  length = length || 512;
  encoding = encoding || 'hex';

  var _validLengths = [224, 256, 384, 512],
      _validEncoding = ['latin1', 'hex', 'base64'];

  // Length of hash
  if (typeof length !== 'number') {
    throw Error('Please give the length as a number');
  }
  if (_validLengths.indexOf(length) == -1) {
    throw Error('Hash length can only be ' + _validLengths.join(', ') + ' bits long');
  }

  // Encoding of hash
  if (typeof encoding !== 'string') {
    throw Error('Encoding must be a string');
  }

  if (_validEncoding.indexOf(encoding.toLowerCase()) == -1) {
    throw Error('Can only encode in the following formats: ' + _validEncoding.join(', ').trim());
  }

  return String(CryptoJS.SHA3(this.toString(), {outputLength: length}).toString(CryptoJS.enc[encoding.capitalize()]));
};

// Add MD5
String.prototype.md5 = function() {
  return String(CryptoJS.MD5(this.toString()).toString());
};

// Ciphers
var _validCiphers = {
  'aes': CryptoJS.AES,
  'tripledes': CryptoJS.TripleDES,
  'rabbit': CryptoJS.Rabbit,
  'rc4drop': CryptoJS.RC4Drop
};

// Verify encrypt and decrypt parameters are valid
function verifyForEncryption(passphrase, cipher) {
  if (typeof passphrase !== 'string') {
    return 'Passphrase must be a string';
  }

  if (cipher) {
    if (cipher && typeof cipher !== 'string') {
      return 'Cipher must be a string';
    }

    if (Object.keys(_validCiphers).indexOf(cipher.toLowerCase()) == -1) {
      return 'Invalid cipher given. Can only use the following ciphers:' + Object.keys(_validCiphers).join(', ');
    }
  }

  return false;
}

// Encrypt
String.prototype.encrypt = function(passphrase, cipher) {

  var err = verifyForEncryption(passphrase, cipher);
  if (err) {
    throw Error(err);
  }

  cipher = cipher || 'aes';

  return String(_validCiphers[cipher].encrypt(this.toString(), passphrase).toString());
};

// Decrypt
String.prototype.decrypt = function(passphrase, cipher) {

  var err = verifyForEncryption(passphrase, cipher);
  if (err) {
    throw Error(err);
  }

  cipher = cipher || 'aes';
  try {
    return String(_validCiphers[cipher].decrypt(this.toString(), passphrase).toString(CryptoJS.enc.Utf8));
  } catch (e) {
    return '';
  }

};


text:
<?php
/**
 * Utility class representing links to different views of a record
 * for CMS authors, usually for {@link SiteTree} objects with "stage" and "live" links.
 * Useful both in the CMS and alongside the page template (for logged in authors).
 * The class can be used for any {@link DataObject} subclass implementing the {@link CMSPreviewable} interface.
 *
 * New item types can be defined by extending the {@link SilverStripeNavigatorItem} class,
 * for example the "cmsworkflow" module defines a new "future state" item with a date selector
 * to view embargoed data at a future point in time. So the item doesn't always have to be a simple link.
 *
 * @package cms
 * @subpackage content
 */
class SilverStripeNavigator extends ViewableData {

	/**
	 * @var DataObject|CMSPreviewable
	 */
	protected $record;

	/**
	 * @param DataObject $record
	 * @throws InvalidArgumentException if record doesn't implement CMSPreviewable
	 */
	public function __construct($record) {
		parent::__construct();
		if (!($record instanceof CMSPreviewable)) {
			throw new InvalidArgumentException(sprintf(
				'SilverStripeNavigator: Record of type %s doesn\'t implement CMSPreviewable',
				get_class($record)
			));
		}

		$this->record = $record;
	}

	/**
	 * @return SS_List of SilverStripeNavigatorItem
	 */
	public function getItems() {
		$items = array();

		$classes = ClassInfo::subclassesFor('SilverStripeNavigatorItem');
		array_shift($classes);

		// Sort menu items according to priority
		$i = 0;
		foreach($classes as $class) {
			// Skip base class
			if($class == 'SilverStripeNavigatorItem') continue;

			$i++;
			/** @var SilverStripeNavigatorItem $item */
			$item = new $class($this->record);
			if(!$item->canView()) continue;

			// This funny litle formula ensures that the first item added with the same priority will be left-most.
			$priority = $item->getPriority() * 100 - 1;

			// Ensure that we can have duplicates with the same (default) priority
			while(isset($items[$priority])) $priority++;

			$items[$priority] = $item;
		}
		ksort($items);

		// Drop the keys and let the ArrayList handle the numbering, so $First, $Last and others work properly.
		return new ArrayList(array_values($items));
	}

	/**
	 * @return DataObject
	 */
	public function getRecord() {
		return $this->record;
	}

	/**
	 * @param DataObject $record
	 * @return array template data
	 */
	static public function get_for_record($record) {
		$html = '';
		$message = '';
		$navigator = new SilverStripeNavigator($record);
		$items = $navigator->getItems();
		foreach($items as $item) {
			$text = $item->getHTML();
			if($text) $html .= $text;
			$newMessage = $item->getMessage();
			if($newMessage && $item->isActive()) $message = $newMessage;
		}

		return array(
			'items' => $html,
			'message' => $message
		);
	}
}

/**
 * Navigator items are links that appear in the $SilverStripeNavigator bar.
 * To add an item, extend this class - it will be automatically picked up.
 * When instanciating items manually, please ensure to call {@link canView()}.
 *
 * @package cms
 * @subpackage content
 */
class SilverStripeNavigatorItem extends ViewableData {

	/**
	 * @var DataObject|CMSPreviewable
	 */
	protected $record;

	/**
	 * @param DataObject $record
	 */
	public function __construct($record) {
		parent::__construct();
		$this->record = $record;
	}

	/**
	 * @return string HTML, mostly a link - but can be more complex as well.
	 * For example, a "future state" item might show a date selector.
	 */
	public function getHTML() {}

	/**
	* @return string
	* Get the Title of an item
	*/
	public function getTitle() {}

	/**
	 * Machine-friendly name.
	 */
	public function getName() {
		return substr(get_class($this), strpos(get_class($this), '_')+1);
	}

	/**
	 * Optional link to a specific view of this record.
	 * Not all items are simple links, please use {@link getHTML()}
	 * to represent an item in markup unless you know what you're doing.
	 *
	 * @return string
	 */
	public function getLink() {}

	/**
	 * @return string
	 */
	public function getMessage() {}

	/**
	 * @return DataObject
	 */
	public function getRecord() {
		return $this->record;
	}

	/**
	 * @return int
	 */
	public function getPriority() {
		return $this->stat('priority');
	}

	/**
	 * As items might convey different record states like a "stage" or "live" table,
	 * an item can be active (showing the record in this state).
	 *
	 * @return boolean
	 */
	public function isActive() {
		return false;
	}

	/**
	 * Filters items based on member permissions or other criteria,
	 * such as if a state is generally available for the current record.
	 *
	 * @param Member
	 * @return Boolean
	 */
	public function canView($member = null) {
		return true;
	}

	/**
	 * Counts as "archived" if the current record is a different version from both live and draft.
	 *
	 * @return boolean
	 */
	public function isArchived() {
		if(!SS_Object::has_extension($this->record->ClassName, 'Versioned')) return false;

		if(!isset($this->record->_cached_isArchived)) {
			$baseTable = ClassInfo::baseDataClass($this->record->class);
			$currentDraft = Versioned::get_one_by_stage($baseTable, 'Stage', array(
				"\"$baseTable\".\"ID\"" => $this->record->ID
			));
			$currentLive = Versioned::get_one_by_stage($baseTable, 'Live', array(
				"\"$baseTable\".\"ID\"" => $this->record->ID
			));

			$this->record->_cached_isArchived = (
				(!$currentDraft || ($currentDraft && $this->record->Version != $currentDraft->Version))
				&& (!$currentLive || ($currentLive && $this->record->Version != $currentLive->Version))
			);
}

		return $this->record->_cached_isArchived;
	}
}

/**
 * @package cms
 * @subpackage content
 */
class SilverStripeNavigatorItem_CMSLink extends SilverStripeNavigatorItem {
	/** @config */
	private static $priority = 10;

	public function getHTML() {
		return sprintf(
			'%s',
			$this->record->CMSEditLink(),
			_t('ContentController.CMS', 'CMS')
		);
	}

	public function getTitle() {
		return _t('ContentController.CMS', 'CMS', 'Used in navigation. Should be a short label');
	}

	public function getLink() {
		return $this->record->CMSEditLink();
	}

	public function isActive() {
		return (Controller::curr() instanceof LeftAndMain);
	}

	public function canView($member = null) {
		return (
		// Don't show in CMS
			!(Controller::curr() instanceof LeftAndMain)
			// Don't follow redirects in preview, they break the CMS editing form
			&& !($this->record instanceof RedirectorPage)
		);
	}
}

/**
 * @package cms
 * @subpackage content
 */
class SilverStripeNavigatorItem_StageLink extends SilverStripeNavigatorItem {
	/** @config */
	private static $priority = 20;

	public function getHTML() {
		$draftPage = $this->getDraftPage();
		if (!$draftPage) {
			return null;
		}

		$linkClass = $this->isActive() ? 'class="current" ' : '';
		$linkTitle = _t('ContentController.DRAFTSITE', 'Draft Site');
		$recordLink = Convert::raw2att(Controller::join_links($draftPage->AbsoluteLink(), "?stage=Stage"));
		return "$linkTitle";
	}

	public function getTitle() {
		return _t('ContentController.DRAFT', 'Draft', 'Used for the Switch between draft and published view mode. Needs to be a short label');
	}

	public function getMessage() {
		return "
".  _t('ContentController.DRAFTSITE', 'Draft Site') ."
";
	}

	public function getLink() {
		$date = Versioned::current_archived_date();
		return Controller::join_links(
			$this->record->PreviewLink(),
			'?stage=Stage',
			$date ? '?archiveDate=' . $date : null
		);
	}

	public function canView($member = null) {
		return (
			SS_Object::has_extension($this->record->ClassName, 'Versioned')
			&& $this->getDraftPage()
			// Don't follow redirects in preview, they break the CMS editing form
			&& !($this->record instanceof RedirectorPage)
		);
	}

	public function isActive() {
		return (
			Versioned::current_stage() == 'Stage'
			&& !(ClassInfo::exists('SiteTreeFutureState') && SiteTreeFutureState::get_future_datetime())
			&& !$this->isArchived()
		);
	}

	protected function getDraftPage() {
		$baseTable = ClassInfo::baseDataClass($this->record->class);
		return Versioned::get_one_by_stage($baseTable, 'Stage', array(
			"\"$baseTable\".\"ID\"" => $this->record->ID
		));
	}
}

/**
 * @package cms
 * @subpackage content
 */
class SilverStripeNavigatorItem_LiveLink extends SilverStripeNavigatorItem {
	/** @config */
	private static $priority = 30;

	public function getHTML() {
		$livePage = $this->getLivePage();
		if (!$livePage) {
			return null;
		}

		$linkClass = $this->isActive() ? 'class="current" ' : '';
		$linkTitle = _t('ContentController.PUBLISHEDSITE', 'Published Site');
		$recordLink = Convert::raw2att(Controller::join_links($livePage->AbsoluteLink(), "?stage=Live"));
		return "$linkTitle";
	}

	public function getTitle() {
		return _t('ContentController.PUBLISHED', 'Published', 'Used for the Switch between draft and published view mode. Needs to be a short label');
	}

	public function getMessage() {
		return "
".  _t('ContentController.PUBLISHEDSITE', 'Published Site') ."
";
	}

	public function getLink() {
		return Controller::join_links($this->record->PreviewLink(), '?stage=Live');
	}

	public function canView($member = null) {
		return (
			SS_Object::has_extension($this->record->ClassName, 'Versioned')
			&& $this->getLivePage()
			// Don't follow redirects in preview, they break the CMS editing form
			&& !($this->record instanceof RedirectorPage)
		);
	}

	public function isActive() {
		return (
			(!Versioned::current_stage() || Versioned::current_stage() == 'Live')
			&& !$this->isArchived()
		);
	}

	protected function getLivePage() {
		$baseTable = ClassInfo::baseDataClass($this->record->class);
		return Versioned::get_one_by_stage($baseTable, 'Live', array(
			"\"$baseTable\".\"ID\"" => $this->record->ID
		));
	}
}

/**
 * @package cms
 * @subpackage content
 */
class SilverStripeNavigatorItem_ArchiveLink extends SilverStripeNavigatorItem {
	/** @config */
	private static $priority = 40;

	public function getHTML() {
		$linkClass = $this->isActive() ? 'ss-ui-button current' : 'ss-ui-button';
		$linkTitle = _t('ContentController.ARCHIVEDSITE', 'Preview version');
		$recordLink = Convert::raw2att(Controller::join_links(
			$this->record->AbsoluteLink(),
			'?archiveDate=' . urlencode($this->record->LastEdited)
		));
		return "$linkTitle";
	}

	public function getTitle() {
		return _t('SilverStripeNavigator.ARCHIVED', 'Archived');
	}

	public function getMessage() {
		$date = Versioned::current_archived_date();
		if (empty($date)) {
			return null;
		}

		/** @var SS_Datetime $dateObj */
			$dateObj = DBField::create_field('Datetime', $date);
		$title = _t('ContentControl.NOTEWONTBESHOWN', 'Note: this message will not be shown to your visitors');
		return "
"
			. _t('ContentController.ARCHIVEDSITEFROM', 'Archived site from')
			. "
" . $dateObj->Nice() . "
";
		}

	public function getLink() {
		return Controller::join_links(
			$this->record->PreviewLink(),
			'?archiveDate=' . urlencode($this->record->LastEdited)
		);
	}

	public function canView($member = null) {
		return (
			SS_Object::has_extension($this->record->ClassName, 'Versioned')
			&& $this->isArchived()
			// Don't follow redirects in preview, they break the CMS editing form
			&& !($this->record instanceof RedirectorPage)
		);
	}

	public function isActive() {
		return $this->isArchived();
	}
	}


text:
#ifndef __NAME_H__
#define __NAME_H__

#include <pcl/common/pca.h>
#include <pcl/point_types.h>
#include <iostream>

class OrientedBoundingBox
{
	public:
		OrientedBoundingBox ();
		void compute_obb_pca (pcl::PointCloud<pcl::PointXYZ>::ConstPtr cloud,
													 Eigen::Quaternionf &quaternion,
													 Eigen::Vector3f &translation,
													 Eigen::Vector3f &dims);
		// Not implemented yet
		void compute_obb_pca_hull (pcl::PointCloud<pcl::PointXYZ>::ConstPtr cloud,
															 Eigen::Quaternionf &quaternion,
															 Eigen::Vector3f &translation,
															 Eigen::Vector3f &dims);
	private:
		/* data */
};

#endif /* __NAME_H__ */


text:
"""
Adventure view

"""

import logging
from flask import Blueprint, jsonify, abort, request
from mongoengine import DoesNotExist
from werkzeug.exceptions import BadRequest
from slugify import slugify
from app.decorators import crossdomain
from app.views.auth import OAUTH
from app.models.adventure import Adventure

MOD_ADVENTURE = Blueprint('adventure', __name__, url_prefix='/api/v1/adventure')

@MOD_ADVENTURE.route('/', methods=['GET'])
@crossdomain(origin='*')
def list_adventures():
    """List all Adventures."""
    adventures_dict = []
    try:
        adventures = Adventure.objects()
        for adventure in adventures:
            adventures_dict.append(adventure.to_dict())
    except DoesNotExist as err:
        logging.info(err)

    return jsonify(adventures=adventures_dict)

@MOD_ADVENTURE.route('/<slug>', methods=['GET'])
@crossdomain(origin='*')
def get_adventure(slug):
    """Get Adventure."""
    try:
        adventure = Adventure.objects.get(slug=slug)
        return jsonify(adventure.to_dict())
    except DoesNotExist:
        abort(404)
    return

@MOD_ADVENTURE.route('/', methods=['POST'])
@crossdomain(origin='*')
@OAUTH.require_oauth('email')
def add_adventure():
    """Add Adventure."""
    try:
        name = request.values.get('name', None)
        description = request.values.get('description', None)
        user = request.oauth.user
        adventure = Adventure(
            slug=slugify(name),
            name=name,
            description=description,
            users=[user],
            delorme=None,
            adafruit=None,
            points=[]
        )
        adventure.save()

        return jsonify(adventure.to_dict())
    except TypeError as err:
        logging.error(err)
        abort(400)
    except BadRequest:
        abort(400)
    return

@MOD_ADVENTURE.route('/<slug>', methods=['DELETE'])
@crossdomain(origin='*')
@OAUTH.require_oauth('email')
def delete_point(slug):
    """Delete Adventure."""
    adventure = Adventure.objects.get(slug=slug)
    try:
        adventure.delete()
        return jsonify({'status': 'ok'})
    except DoesNotExist:
        abort(404)
    return


text:
package ccv3

import (
	"bytes"
	"encoding/json"
	"io"
	"mime/multipart"
	"os"
	"path/filepath"

	"code.cloudfoundry.org/cli/api/cloudcontroller"
	"code.cloudfoundry.org/cli/api/cloudcontroller/ccerror"
	"code.cloudfoundry.org/cli/api/cloudcontroller/ccv3/internal"
)

type PackageState string

const (
	PackageStateProcessingUpload PackageState = "PROCESSING_UPLOAD"
	PackageStateReady            PackageState = "READY"
	PackageStateFailed           PackageState = "FAILED"
	PackageStateAwaitingUpload   PackageState = "AWAITING_UPLOAD"
	PackageStateCopying          PackageState = "COPYING"
	PackageStateExpired          PackageState = "EXPIRED"
)

type PackageType string

const (
	PackageTypeBits   PackageType = "bits"
	PackageTypeDocker PackageType = "docker"
)

type Package struct {
	GUID          string               `json:"guid,omitempty"`
	Links         APILinks             `json:"links,omitempty"`
	Relationships PackageRelationships `json:"relationships"`
	State         PackageState         `json:"state,omitempty"`
	Type          PackageType          `json:"type"`
}

type PackageRelationships struct {
	Application Relationship `json:"app"`
}

// GetPackage returns the package with the given GUID.
func (client *Client) GetPackage(guid string) (Package, Warnings, error) {
	request, err := client.newHTTPRequest(requestOptions{
		RequestName: internal.GetPackageRequest,
		URIParams:   internal.Params{"guid": guid},
	})
	if err != nil {
		return Package{}, nil, err
	}

	var responsePackage Package
	response := cloudcontroller.Response{
		Result: &responsePackage,
	}
	err = client.connection.Make(request, &response)

	return responsePackage, response.Warnings, err
}

// CreatePackage creates a package with the given settings, Type and the Space
// must be set.
func (client *Client) CreatePackage(pkg Package) (Package, Warnings, error) {
	bodyBytes, err := json.Marshal(pkg)
	if err != nil {
		return Package{}, nil, err
	}

	request, err := client.newHTTPRequest(requestOptions{
		RequestName: internal.PostPackageRequest,
		Body:        bytes.NewBuffer(bodyBytes),
	})

	var responsePackage Package
	response := cloudcontroller.Response{
		Result: &responsePackage,
	}
	err = client.connection.Make(request, &response)

	return responsePackage, response.Warnings, err
}

// UploadPackage uploads a file to a given package's Upload resource.
func (client *Client) UploadPackage(pkg Package, fileToUpload string) (Package, Warnings, error) {
	link, ok := pkg.Links["upload"]
	if !ok {
		return Package{}, nil, ccerror.UploadLinkNotFoundError{PackageGUID: pkg.GUID}
	}

	body, contentType, err := client.createUploadStream(fileToUpload, "bits")
	if err != nil {
		return Package{}, nil, err
	}

	request, err := client.newHTTPRequest(requestOptions{
		URL:    link.HREF,
		Method: link.Method,
		Body:   body,
	})
	request.Header.Set("Content-Type", contentType)

	var responsePackage Package
	response := cloudcontroller.Response{
		Result: &responsePackage,
	}
	err = client.connection.Make(request, &response)

	return responsePackage, response.Warnings, err
}

func (client *Client) createUploadStream(path string, paramName string) (io.Reader, string, error) {
	file, err := os.Open(path)
	if err != nil {
		return nil, "", err
	}
	defer file.Close()

	body := &bytes.Buffer{}
	writer := multipart.NewWriter(body)
	part, err := writer.CreateFormFile(paramName, filepath.Base(path))
	if err != nil {
		return nil, "", err
	}
	_, err = io.Copy(part, file)

	err = writer.Close()
	if err != nil {
		return nil, "", err
	}

	return body, writer.FormDataContentType(), nil
}


text:
#ifndef _VELOCITY_CONTROLLER_H
#define _VELOCITY_CONTROLLER_H

#include "stdint.h"
#include "stdbool.h"

#define VELOCITY_UPDATE_FREQ  			33
#define VELOCITY_UPDATE_DT   				(float)(1.0/VELOCITY_UPDATE_FREQ)
#define VELOCITY_CONTROLLER_OUT_MAX   750
#define VELOCITY_CONTROLLER_OUT_MIN   -750

/* Exported functions ------------------------------------------------------- */
extern void  velocityControllerInit(void);
extern bool  velocityControllerTest(void);
extern int16_t VelocityController(uint8_t motor_id, const float VelocityActual, float VelocityDesired);

#endif
/***************************** °¢²¨Â޿Ƽ¼ www.apollorobot.cn (END OF FILE) *********************************/


text:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="jwraats.jackevers.nl.airportandroid.AirportCollectionFragment">

    <GridView android:id="@android:id/list" android:layout_width="match_parent"
        android:layout_height="match_parent" android:numColumns="2" />

    <TextView android:id="@android:id/empty" android:layout_width="match_parent"
        android:layout_height="match_parent" android:gravity="center" />

</FrameLayout>


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>Welcome to CC Basket's documentation! — ccbasket 0.0.1 documentation</title>

    <link rel="stylesheet" href="_static/default.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />

    <link rel="top" title="ccbasket 0.0.1 documentation" href="#" />
    <link rel="next" title="Getting Started" href="gettingstarted.html" />

Navigation

          index

          next |

ccbasket 0.0.1 documentation »

Welcome to CC Basket’s documentation!¶

ccbasket is a lightweight, robust basket application for Django projects.

Contents:

Getting Started

License

What is ccbasket not?

What is ccbasket?

Installing

Meet The Basket

How It Works

Basket

Models

Why no product models?

Defining Your Own Product Models

Basket

Managers

Views

updatebasket

Supports Ajax Calls

Forms

BasketForm

Signals

request_total_for_product

Adding To Basket

Removing From Basket

Other Signals

Template Tags & Filters

Filters

Tags

Context Processors

Caching

Configuration

CCBASKET_SESSION_KEY_NAME

CCBASKET_MAX_ITEMS

CCBASKET_SINGLE_QUANTITY

CCBASKET_CACHE_PREFIX

CCBASKET_CACHE_TIMEOUT

Logging

Use Cases

Background to ccbasket

Feedback

Reporting Bugs

Feature Requests

Indices and tables¶

Index

Module Index

Search Page

Table Of Contents

Welcome to CC Basket’s documentation!

Indices and tables

Next topic

Getting Started

This Page

Show Source

Quick search

    <form class="search" action="search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

    Enter search terms or a module, class or function name.

Navigation

          index

          next |

ccbasket 0.0.1 documentation »

        © Copyright 2011, C&C Design Consultants LTD.
      Created using Sphinx 1.1.3.


text:
package org.eclipse.ceylon.cmr.impl;

import java.io.File;

import org.eclipse.ceylon.cmr.api.RepositoryManager;
import org.eclipse.ceylon.model.cmr.Repository;
import org.eclipse.ceylon.model.cmr.RepositoryException;

/**
 * Existing file.
 *
 * @author Ales Justin
 */
public class FileArtifactResult extends AbstractCeylonArtifactResult {
    private final File file;
    private final String repositoryDisplayString;

    protected FileArtifactResult(Repository repository, RepositoryManager manager, String name, String version,
            File file, String repositoryDisplayString) {
        super(repository, manager, name, version);
        this.file = file;
        this.repositoryDisplayString = repositoryDisplayString;
    }

    protected File artifactInternal() throws RepositoryException {
        return file;
    }

    @Override
    public String repositoryDisplayString() {
        return repositoryDisplayString;
    }
}


text:
"use strict";
var utils = require('../utils/utils.js');
var socketHandler = require('./socketHandler.js');

var fileHandler = {};

var totalFileReceived = 0;

fileHandler.receiveFile = function(socket, file, fileName) {

	totalFileReceived++;

    socket.msgCount++;
    socket.user.msgCount++;

    var action = {};
    action.type = 'Send File';
    action.time = utils.getTime();
    action.url = socket.url;
    action.detail = "File Name: "+fileName;
    socket.user.actionList.push(action);

    socketHandler.recordSocketActionTime(socket);

};

module.exports = fileHandler;


text:
import { NgModule, ApplicationRef } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { Store, StoreModule } from '@ngrx/store';
import { AppRoutingModule, appRoutingComponent } from './app-routing.module';

import { removeNgStyles, createNewHosts, createInputTransfer } from '@angularclass/hmr';
import { rootReducer, StoreType } from './reducers';
import 'rxjs/add/operator/take';

import { AppComponent } from './app.component';
import { PageNotFoundComponent } from './components/404/page-not-found.component';

@NgModule({
    imports: [
        BrowserModule,
        FormsModule,
        HttpModule,
        AppRoutingModule,
        StoreModule.provideStore(rootReducer),
    ],
    declarations: [
        appRoutingComponent,
        AppComponent,
    ],
    providers: [],
    bootstrap: [AppComponent]
})
export class AppModule {
    constructor(public appRef: ApplicationRef, private _store: Store<any>) { }
    hmrOnInit(store: StoreType) {
        if (!store || !store.state) return;
        console.log('HMR store', JSON.stringify(store, null, 2));

        if (store.state) {
            this._store.dispatch({ type: 'SET_ROOT_STATE', payload: store.state });
        }

        if ('restoreInputValues' in store) {
            let restoreInputValues = store.restoreInputValues;
            setTimeout(restoreInputValues);
        }

        this.appRef.tick();
        delete store.state;
        delete store.restoreInputValues;
    }

    hmrOnDestroy(store: StoreType) {
        const cmpLocation = this.appRef.components.map(cmp => cmp.location.nativeElement);
        this._store.take(1).subscribe(s => store.state = s);
        store.disposeOldHosts = createNewHosts(cmpLocation);
        store.restoreInputValues = createInputTransfer();
        removeNgStyles();
    }

    hmrAfterDestroy(store: StoreType) {
        store.disposeOldHosts();
        delete store.disposeOldHosts;
    }
}


text:
// Copyright (c) 2010-2015, Shane Jarych
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
//   list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
//   this list of conditions and the following disclaimer in the documentation
//   and/or other materials provided with the distribution.
//
// * Neither the name of lib65oh2 nor the names of its contributors may be used
//   to endorse or promote products derived from this software without specific
//   prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include <cxxtest/TestSuite.h>
#include "Core.h"
#include "BasicMemoryController.h"
#include "ProcessorStatus.h"
#include "InstructionSet.h"
#include "BRK.h"

/**
 * @class  Various tests against the BRK class
 */
class BRK_test : public CxxTest::TestSuite
{
public:
    /**
     * @brief  Sets up the testing constructs
     */
    void setUp()
    {
        _core = new Core;
        _memory = new BasicMemoryController;
        _iset = new InstructionSet(*_core, *_memory);
        _op = new BRK;
    }

    /**
     * @brief  Tears down the testing constructs
     */
    void tearDown()
    {
        delete _op;
        delete _iset;
        delete _memory;
        delete _core;
    }

    /**
     * @brief  Tests the basic functionality of the BRK instruction
     */
    void testBasic()
    {
        ProcessorStatus& p = _core->getP();
        p.set(ProcessorStatus::CARRY);
        _core->setPC(0x1234);

        // invoke BRK
        int cycles = _iset->execute(0x00);
        TS_ASSERT_EQUALS(7, cycles);

        // ensure state of cpu is correct
        TS_ASSERT_EQUALS(0xFFFE, _core->getPC());
        TS_ASSERT( p.test(ProcessorStatus::IRQDISABLE) );
        TS_ASSERT_EQUALS(0xFC, _core->getSP());

        // test stack
        data8_t sdata = *_memory->get(0x01FF);
        TS_ASSERT_EQUALS(0x12, sdata);
        sdata = *_memory->get(0x01FE);
        TS_ASSERT_EQUALS(0x36, sdata);  // PC + 2 on stack
        sdata = *_memory->get(0x01FD);
        TS_ASSERT_EQUALS(0x01, sdata);
    }

private:
    Core* _core;
    MemoryController* _memory;
    InstructionSet* _iset;
    BRK* _op;
};


text:
// Write a method GetMax() with two parameters that returns the larger of two integers.
// Write a program that reads 3 integers from the console and prints the largest of them using the method GetMax().

using System;
using System.Linq;

class GetLargestNumber
{
    private static int GetMax(int firstNumber, int secondNumber)
    {
        if (firstNumber > secondNumber)
        {
            return firstNumber;
        }

        return secondNumber;
    }

    private static int GetMax(int firstNumber, int secondNumber, Func<int, int, int> compare)
    {
        int max = compare(firstNumber, secondNumber);
        return max;
    }

    static void Main()
    {
        int[] numbers = Console.ReadLine().Split(' ').Select(x => int.Parse(x)).ToArray();

        int maxNumber = GetMax(numbers[0], numbers[1]);
        maxNumber = GetMax(maxNumber, numbers[2]);
        Console.WriteLine(maxNumber);

        //Func<int, int, int> comparer = (x, y) => x > y ? x : y;
        //maxNumber = GetMax(1, 2, comparer);
        //Console.WriteLine(maxNumber);
    }
}


text:
import("core.base.socket")
import("core.base.scheduler")

function _session(sock, filepath)

    local file = io.open(filepath, 'rb')
    if file then
        local send = sock:sendfile(file, {block = true})
        print("%s: send %s %d bytes!", sock, filepath, send)
        file:close()
    end
    sock:close()
end

function _listen(addr, port, filepath)

    local sock = socket.bind(addr, port)
    sock:listen(100)
    print("%s: listening %s:%d ..", sock, addr, port)
    while true do
        local sock_client = sock:accept()
        if sock_client then
            print("%s: accepted", sock_client)
            scheduler.co_start(_session, sock_client, filepath)
        end
    end
    sock:close()
end

function main(filepath)
    scheduler.co_start(_listen, "127.0.0.1", 9090, filepath)
end


text:
layout: post
title: 最后一遍-L30-Substring with Concatenation of All Words
categories: LeetCode
---

~~~

//You are given a string s and an array of strings words of the same length. Ret
//urn all starting indices of substring(s) in s that is a concatenation of each wo
//rd in words exactly once, in any order, and without any intervening characters.
//
//
// You can return the answer in any order.
//
//
// Example 1:
//
//
//Input: s = "barfoothefoobarman", words = ["foo","bar"]
//Output: [0,9]
//Explanation: Substrings starting at index 0 and 9 are "barfoo" and "foobar" re
//spectively.
//The output order does not matter, returning [9,0] is fine too.
//
//
// Example 2:
//
//
//Input: s = "wordgoodgoodgoodbestword", words = ["word","good","best","word"]
//Output: []
//
//
// Example 3:
//
//
//Input: s = "barfoofoobarthefoobarman", words = ["bar","foo","the"]
//Output: [6,9,12]
//
//
//
// Constraints:
//
//
// 1 <= s.length <= 104
// s consists of lower-case English letters.
// 1 <= words.length <= 5000
// 1 <= words[i].length <= 30
// words[i] consists of lower-case English letters.
//
// Related Topics Hash Table String Sliding Window
// 👍 2050 👎 1896
~~~

按照题目的意思,进行编码

首先是使用HashMap的算法

~~~java
class Solution {
    private HashMap<String, Integer> wordCount = new HashMap<String, Integer>();
    private int wordLength;
    private int substringSize;
    private int k;

    private boolean check(int i, String s) {
        // Copy the original dictionary to use for this index
        HashMap<String, Integer> remaining = new HashMap<>(wordCount);
        int wordsUsed = 0;

        // Each iteration will check for a match in words
        for (int j = i; j < i + substringSize; j += wordLength) {
            String sub = s.substring(j, j + wordLength);
            if (remaining.getOrDefault(sub, 0) != 0) {
                remaining.put(sub, remaining.get(sub) - 1);
                wordsUsed++;
            } else {
                break;
            }
        }

        return wordsUsed == k;
    }

    public List<Integer> findSubstring(String s, String[] words) {
        int n = s.length();
        k = words.length;
        wordLength = words[0].length();
        substringSize = wordLength * k;

        for (String word : words) {
            wordCount.put(word, wordCount.getOrDefault(word, 0) + 1);
        }

        List<Integer> answer = new ArrayList<>();
        for (int i = 0; i < n - substringSize + 1; i++) {
            if (check(i, s)) {
                answer.add(i);
            }
        }

        return answer;
    }
}
~~~

优化后,使用滑动窗口+HashMap的样式

~~~java

class Solution {
    private HashMap<String, Integer> wordCount = new HashMap<String, Integer>();
    private int n;
    private int wordLength;
    private int substringSize;
    private int k;

    private void slidingWindow(int left, String s, List<Integer> answer) {
        HashMap<String, Integer> wordsFound = new HashMap<>();
        int wordsUsed = 0;
        boolean excessWord = false;

        // Do the same iteration pattern as the previous approach - iterate
        // word_length at a time, and at each iteration we focus on one word
        for (int right = left; right <= n - wordLength; right += wordLength) {

            String sub = s.substring(right, right + wordLength);
            if (!wordCount.containsKey(sub)) {
                // Mismatched word - reset the window
                wordsFound.clear();
                wordsUsed = 0;
                excessWord = false;
                left = right + wordLength;
            } else {
                // If we reached max window size or have an excess word
                while (right - left == substringSize || excessWord) {
                    String leftmostWord = s.substring(left, left + wordLength);
                    left += wordLength;
                    wordsFound.put(leftmostWord, wordsFound.get(leftmostWord) - 1);

                    if (wordsFound.get(leftmostWord) >= wordCount.get(leftmostWord)) {
                        // This word was an excess word
                        excessWord = false;
                    } else {
                        // Otherwise we actually needed it
                        wordsUsed--;
                    }
                }

                // Keep track of how many times this word occurs in the window
                wordsFound.put(sub, wordsFound.getOrDefault(sub, 0) + 1);
                if (wordsFound.get(sub) <= wordCount.get(sub)) {
                    wordsUsed++;
                } else {
                    // Found too many instances already
                    excessWord = true;
                }

                if (wordsUsed == k && !excessWord) {
                    // Found a valid substring
                    answer.add(left);
                }
            }
        }
    }

    public List<Integer> findSubstring(String s, String[] words) {
        n = s.length();
        k = words.length;
        wordLength = words[0].length();
        substringSize = wordLength * k;

        for (String word : words) {
            wordCount.put(word, wordCount.getOrDefault(word, 0) + 1);
        }

        List<Integer> answer = new ArrayList<>();
        for (int i = 0; i < wordLength; i++) {
            slidingWindow(i, s, answer);
        }

        return answer;
    }
}
~~~


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>net.oneandone.maven.poms</groupId>
    <artifactId>lazy-foss-parent</artifactId>
    <version>1.0.2</version>
    <relativePath />
  </parent>

  <name>Metadata</name>
  <description>See ${project.url}.</description>
  <url>https://github.com/mlhartme/metadata</url>
  <inceptionYear>2004</inceptionYear>

  <groupId>net.oneandone</groupId>
  <artifactId>metadata</artifactId>
  <version>1.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <developers>
    <developer>
      <name>Michael Hartmeier</name>
      <id>mlhartme</id>
      <url>http://github.com/mlhartme/</url>
      <organization>1 & 1 Internet AG</organization>
      <organizationUrl>https://github.com/1and1</organizationUrl>
      <roles>
        <role>developer</role>
      </roles>
      <timezone>+1</timezone>
    </developer>
  </developers>

  <scm>
    <connection>scm:git:ssh://git@github.com/mlhartme/metadata.git</connection>
    <developerConnection>scm:git:ssh://git@github.com/mlhartme/metadata.git</developerConnection>
    <url>https://github.com/mlhartme/metadata</url>
    <tag>HEAD</tag>
  </scm>

  <issueManagement>
    <system>GitHub</system>
    <url>https://github.com/mlhartme/metadata/issues/</url>
  </issueManagement>

  <dependencies>
    <dependency>
      <groupId>net.oneandone</groupId>
      <artifactId>sushi</artifactId>
      <version>3.1.6</version>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <scope>test</scope>
    </dependency>

  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <configuration>
          <useFile>false</useFile>
        </configuration>
      </plugin>
    </plugins>
  </build>

  <reporting>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-changes-plugin</artifactId>
        <configuration>
          <onlyMilestoneIssues>false</onlyMilestoneIssues>
        </configuration>
      </plugin>
    </plugins>
  </reporting>
</project>


text:
<?php
declare (strict_types = 1);

namespace GrottoPress\Jentil\Setups\Scripts;

use GrottoPress\Jentil\Utilities;
use GrottoPress\Jentil\Utilities\FileSystem;
use GrottoPress\Jentil\AbstractTheme;
use GrottoPress\Jentil\AbstractTestCase;
use Codeception\Util\Stub;
use tad\FunctionMocker\FunctionMocker;

class MenuTest extends AbstractTestCase
{
    public function testRun()
    {
        $add_action = FunctionMocker::replace('add_action');

        $script = new Menu(Stub::makeEmpty(AbstractTheme::class, [
            'meta' => ['slug' => 'jentil'],
        ]));

        $script->run();

        $add_action->wasCalledTimes(2);

        $add_action->wasCalledWithOnce([
            'wp_enqueue_scripts',
            [$script, 'enqueue']
        ]);

        $add_action->wasCalledWithOnce([
            'wp_enqueue_scripts',
            [$script, 'localize']
        ]);
    }

    public function testEnqueue()
    {
        $enqueue = FunctionMocker::replace('wp_enqueue_script');

        $test_js = \codecept_data_dir('scripts/test.js');

        $jentil = Stub::makeEmpty(AbstractTheme::class, [
            'utilities' => Stub::makeEmpty(Utilities::class),
            'meta' => ['slug' => 'jentil'],
        ]);

        $jentil->utilities->fileSystem = Stub::makeEmpty(FileSystem::class, [
            'dir' => function (
                string $type,
                string $append
            ) use ($test_js): string {
                return 'path' === $type ? $test_js : "http://my.url/test.js";
            },
        ]);

        $script = new Menu($jentil);

        $script->enqueue();

        $enqueue->wasCalledOnce();
        $enqueue->wasCalledWithOnce([
            $script->id,
            'http://my.url/test.js',
            ['jquery'],
            \filemtime($test_js),
            true,
        ]);
    }

    public function testLocalize()
    {
        $localize = FunctionMocker::replace('wp_localize_script');

        FunctionMocker::replace('esc_html__');

        $script = new Menu(Stub::makeEmpty(AbstractTheme::class, [
            'meta' => ['slug' => 'jentil'],
        ]));

        $script->localize();

        $localize->wasCalledOnce();
        $localize->wasCalledWithOnce([$script->id, 'jentilMenuL10n']);
    }
}


text:
<?PHP

session_start();
include_once '../common/db.php';
//echo "<pre>";
//session_destroy();
//print_r($_REQUEST);
$username = $conn->real_escape_string($_POST['username']);
$password = $conn->real_escape_string($_POST['password']);
$select = "select * from users where username = '$username' and password = '$password'";
//exit;
$result = $conn->query($select);
if ($result->num_rows > 0) {
    // output data of each row
    while ($row = $result->fetch_assoc()) {
        $_SESSION['adminusername'] = $row['username'];
        $_SESSION['adminusertype'] = $row['user_type'];
        $_SESSION['adminfullName'] = $row['name'];
        $_SESSION['adminuserid'] = $row['id'];
    }
//    print_r($_SESSION);
    echo "<script>window.location.href='dashboard.php';</script>";
    exit;
//    header("location: /users.php");
    exit;
} else {
    echo "<script>window.location.href='login.php?e=fail';</script>";
    exit;
}
?>


text:
from optparse import make_option

import django

from evostream.default import api
from evostream.management.base import BaseEvoStreamCommand

class Command(BaseEvoStreamCommand):
    help = 'Create secondary name for internal stream.'

    requires_system_checks = False

    if django.VERSION[:2] > (1, 7):
        def add_arguments(self, parser):
            parser.add_argument('localStreamName', type=str,
                                help='The original stream name.')
            parser.add_argument('aliasName', type=str,
                                help='The alias alternative to the'
                                     'localStreamName.')
            parser.add_argument('--expire-period', action='store',
                                type=int, default=-600,
                                dest='expirePeriod',
                                help='The expiration period for this alias. '
                                     'Negative values will be treated as '
                                     'one-shot but no longer than the '
                                     'absolute positive value in seconds, 0 '
                                     'means it will not expire, positive '
                                     'values mean the alias can be used '
                                     'multiple times but expires after this '
                                     'many seconds. The default is -600 '
                                     '(one-shot, 10 mins)')
    else:
        args = '<localStreamName> <aliasName>'

        option_list = BaseEvoStreamCommand.option_list + (
            make_option('--expire-period', action='store',
                        type='int', default=-600,
                        dest='expirePeriod',
                        help='The expiration period for this alias. Negative '
                             'values will be treated as one-shot but no '
                             'longer than the absolute positive value in '
                             'seconds, 0 means it will not expire, positive '
                             'values mean the alias can be used multiple '
                             'times but expires after this many seconds. The '
                             'default is -600 (one-shot, 10 mins)'),
        )

    def get_results(self, localStreamName, aliasName, *args, **options):
        return api.add_stream_alias(localStreamName=localStreamName,
                                    aliasName=aliasName, **options)


text:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule, Routes } from '@angular/router';

import { MatSelectModule } from '@angular/material/select';
import { MatIconModule } from '@angular/material/icon';
import { ComponentDetailsModule } from '../../../../components/shared/component-details/component-details.module';
import { CovalentBaseEchartsModule } from '@covalent/echarts/base';
import { CovalentTooltipEchartsModule } from '@covalent/echarts/tooltip';
import { CovalentTreemapEchartsModule } from '@covalent/echarts/treemap';
import { setEchartRoutes } from '../../echarts-content';
import { DocumentationToolsModule } from '../../../../documentation-tools';
import { TypesTreemapComponent } from './treemap.component';

const routes: Routes = setEchartRoutes({
  overviewDemoComponent: TypesTreemapComponent,
  id: 'treemap',
});

@NgModule({
  declarations: [TypesTreemapComponent],
  imports: [
    CommonModule,
    // Material
    MatSelectModule,
    MatIconModule,
    // Covalent Echarts
    CovalentBaseEchartsModule,
    CovalentTreemapEchartsModule,
    CovalentTooltipEchartsModule,
    // Docs
    ComponentDetailsModule,
    DocumentationToolsModule,
    // Routes
    RouterModule.forChild(routes),
  ],
  exports: [],
  providers: [],
})
export class TreemapModule {}


text:
package org.apache.flex.compiler.internal.codegen.js.jsc;

import java.io.FilterWriter;

import org.apache.flex.compiler.internal.codegen.js.flexjs.JSFlexJSEmitter;

/**
 * Concrete implementation of the 'FlexJS' JavaScript production.
 *
 * @author Michael Schmalle
 * @author Erik de Bruin
 */
public class JSCJSEmitter extends JSFlexJSEmitter
{

    public JSCJSEmitter(FilterWriter out)
    {
        super(out);
    }

    @Override
    public String formatQualifiedName(String name)
    {
        return name;
    }
}


text:
var assert = require('assert');
var HttpInvocation = require('../lib/http-invocation');
var SharedMethod = require('../lib/shared-method');
var extend = require('util')._extend;
var expect = require('chai').expect;

describe('HttpInvocation', function() {
  describe('namedArgs', function() {

    function expectNamedArgs(accepts, inputArgs, expectedNamedArgs) {
      var method = givenSharedStaticMethod({
        accepts: accepts
      });
      var inv = new HttpInvocation(method, null, inputArgs);
      expect(inv.namedArgs).to.deep.equal(expectedNamedArgs);
    }

    it('should correctly name a single arg', function() {
      expectNamedArgs(
        [{arg: 'a', type: 'number'}],
        [1],
        {a: 1}
      );
    });

    it('should correctly name multiple args', function() {
      expectNamedArgs(
        [{arg: 'a', type: 'number'}, {arg: 'str', type: 'string'}],
        [1, 'foo'],
        {a: 1, str: 'foo'}
      );
    });

    it('should correctly name multiple args when a partial set is provided', function() {
      expectNamedArgs(
        [{arg: 'a', type: 'number'}, {arg: 'str', type: 'string'}],
        [1],
        {a: 1}
      );
    });

    describe('HttpContext.isAcceptable()', function() {
      it('should accept an acceptable argument', function() {
        var acceptable = HttpInvocation.isAcceptable(2, {
          arg: 'foo',
          type: 'number'
        });
        expect(acceptable).to.equal(true);
      });

      it('should always accept args when type is any', function() {
        var acceptable = HttpInvocation.isAcceptable(2, {
          arg: 'bar',
          type: 'any'
        });
        expect(acceptable).to.equal(true);
      });

      it('should always accept args when type is complex', function() {
        var acceptable = HttpInvocation.isAcceptable({}, {
          arg: 'bar',
          type: 'MyComplexType'
        });
        expect(acceptable).to.equal(true);
      });

      it('should accept null arg when type is complex', function() {
        var acceptable = HttpInvocation.isAcceptable(null, {
          arg: 'bar',
          type: 'MyComplexType'
        });
        expect(acceptable).to.equal(true);
      });
    });
  });
});

function givenSharedStaticMethod(fn, config) {
  if (typeof fn === 'object' && config === undefined) {
    config = fn;
    fn = null;
  }
  fn = fn || function(cb) { cb(); };

  var testClass = { testMethod: fn };
  config = extend({ shared: true }, config);
  extend(testClass.testMethod, config);
  return SharedMethod.fromFunction(fn, 'testStaticMethodName', null, true);
}


text:
namespace gpdbcost
{
	using namespace gpos;
	using namespace gpopt;
	using namespace gpmd;

	//---------------------------------------------------------------------------
	//	@class:
	//		CCostModelGPDB
	//
	//	@doc:
	//		GPDB cost model
	//
	//---------------------------------------------------------------------------
	class CCostModelGPDB : public ICostModel
	{

		private:

			// definition of operator processor
			typedef CCost(FnCost)(IMemoryPool *, CExpressionHandle &, const CCostModelGPDB *, const SCostingInfo *);

			//---------------------------------------------------------------------------
			//	@struct:
			//		SCostMapping
			//
			//	@doc:
			//		Mapping of operator to a cost function
			//
			//---------------------------------------------------------------------------
			struct SCostMapping
			{
				// physical operator id
				COperator::EOperatorId m_eopid;

				// pointer to cost function
				FnCost *m_pfnc;

			}; // struct SCostMapping

			// memory pool
			IMemoryPool *m_pmp;

			// number of segments
			ULONG m_ulSegments;

			// cost model parameters
			CCostModelParamsGPDB *m_pcp;

			// array of mappings
			static
			const SCostMapping m_rgcm[];

			// return cost of processing the given number of rows
			static
			CCost CostTupleProcessing(DOUBLE dRows, DOUBLE dWidth, ICostModelParams *pcp);

			// helper function to return cost of producing output tuples from Scan operator
			static
			CCost CostScanOutput(IMemoryPool *pmp, DOUBLE dRows, DOUBLE dWidth, DOUBLE dRebinds, ICostModelParams *pcp);

			// helper function to return cost of a plan rooted by unary operator
			static
			CCost CostUnary(IMemoryPool *pmp, CExpressionHandle &exprhdl, const SCostingInfo *pci, ICostModelParams *pcp);

			// cost of spooling
			static
			CCost CostSpooling(IMemoryPool *pmp, CExpressionHandle &exprhdl, const SCostingInfo *pci, ICostModelParams *pcp);

			// add up children cost
			static
			CCost CostChildren(IMemoryPool *pmp, CExpressionHandle &exprhdl, const SCostingInfo *pci, ICostModelParams *pcp);

			// returns cost of highest costed child
			static
			CCost CostMaxChild(IMemoryPool *pmp, CExpressionHandle &exprhdl, const SCostingInfo *pci, ICostModelParams *pcp);

			// check if given operator is unary
			static
			BOOL FUnary(COperator::EOperatorId eopid);

			// cost of scan
			static
			CCost CostScan(IMemoryPool *pmp, CExpressionHandle &exprhdl, const CCostModelGPDB *pcmgpdb, const SCostingInfo *pci);

			// cost of filter
			static
			CCost CostFilter(IMemoryPool *pmp, CExpressionHandle &exprhdl, const CCostModelGPDB *pcmgpdb, const SCostingInfo *pci);

			// cost of index scan
			static
			CCost CostIndexScan(IMemoryPool *pmp, CExpressionHandle &exprhdl, const CCostModelGPDB *pcmgpdb, const SCostingInfo *pci);

			// cost of bitmap table scan
			static
			CCost CostBitmapTableScan(IMemoryPool *pmp, CExpressionHandle &exprhdl, const CCostModelGPDB *pcmgpdb, const SCostingInfo *pci);

			// cost of sequence project
			static
			CCost CostSequenceProject(IMemoryPool *pmp, CExpressionHandle &exprhdl, const CCostModelGPDB *pcmgpdb, const SCostingInfo *pci);

			// cost of CTE producer
			static
			CCost CostCTEProducer(IMemoryPool *pmp, CExpressionHandle &exprhdl, const CCostModelGPDB *pcmgpdb, const SCostingInfo *pci);

			// cost of CTE consumer
			static
			CCost CostCTEConsumer(IMemoryPool *pmp, CExpressionHandle &exprhdl, const CCostModelGPDB *pcmgpdb, const SCostingInfo *pci);

			// cost of const table get
			static
			CCost CostConstTableGet(IMemoryPool *pmp, CExpressionHandle &exprhdl, const CCostModelGPDB *pcmgpdb, const SCostingInfo *pci);

			// cost of DML
			static
			CCost CostDML(IMemoryPool *pmp, CExpressionHandle &exprhdl, const CCostModelGPDB *pcmgpdb, const SCostingInfo *pci);

			// cost of hash agg
			static
			CCost CostHashAgg(IMemoryPool *pmp, CExpressionHandle &exprhdl, const CCostModelGPDB *pcmgpdb, const SCostingInfo *pci);

			// cost of scalar agg
			static
			CCost CostScalarAgg(IMemoryPool *pmp, CExpressionHandle &exprhdl, const CCostModelGPDB *pcmgpdb, const SCostingInfo *pci);

			// cost of stream agg
			static
			CCost CostStreamAgg(IMemoryPool *pmp, CExpressionHandle &exprhdl, const CCostModelGPDB *pcmgpdb, const SCostingInfo *pci);

			// cost of sequence
			static
			CCost CostSequence(IMemoryPool *pmp, CExpressionHandle &exprhdl, const CCostModelGPDB *pcmgpdb, const SCostingInfo *pci);

			// cost of sort
			static
			CCost CostSort(IMemoryPool *pmp, CExpressionHandle &exprhdl, const CCostModelGPDB *pcmgpdb, const SCostingInfo *pci);

			// cost of TVF
			static
			CCost CostTVF(IMemoryPool *pmp, CExpressionHandle &exprhdl, const CCostModelGPDB *pcmgpdb, const SCostingInfo *pci);

			// cost of UnionAll
			static
			CCost CostUnionAll(IMemoryPool *pmp, CExpressionHandle &exprhdl, const CCostModelGPDB *pcmgpdb, const SCostingInfo *pci);

			// cost of hash join
			static
			CCost CostHashJoin(IMemoryPool *pmp, CExpressionHandle &exprhdl, const CCostModelGPDB *pcmgpdb, const SCostingInfo *pci);

			// cost of nljoin
			static
			CCost CostNLJoin(IMemoryPool *pmp,CExpressionHandle &exprhdl,  const CCostModelGPDB *pcmgpdb, const SCostingInfo *pci);

			// cost of inner index-nljoin
			static
			CCost CostInnerIndexNLJoin(IMemoryPool *pmp, CExpressionHandle &exprhdl, const CCostModelGPDB *pcmgpdb, const SCostingInfo *pci);

			// cost of motion
			static
			CCost CostMotion(IMemoryPool *pmp, CExpressionHandle &exprhdl, const CCostModelGPDB *pcmgpdb, const SCostingInfo *pci);

			// cost of bitmap scan when the NDV is small
			static
			CCost CostBitmapSmallNDV(const CCostModelGPDB *pcmgpdb, const SCostingInfo *pci, CDouble dNDV);

			// cost of bitmap scan when the NDV is large
			static
			CCost CostBitmapLargeNDV(const CCostModelGPDB *pcmgpdb, const SCostingInfo *pci, CDouble dNDV);

		public:

			// ctor
			CCostModelGPDB(IMemoryPool *pmp, ULONG ulSegments, DrgPcp *pdrgpcp = NULL);

			// dtor
			virtual
			~CCostModelGPDB();

			// number of segments
			ULONG UlHosts() const
			{
				return m_ulSegments;
			}

			// return number of rows per host
			virtual
			CDouble DRowsPerHost(CDouble dRowsTotal) const;

			// return cost model parameters
			virtual
			ICostModelParams *Pcp() const
			{
				return m_pcp;
			}

			// main driver for cost computation
			virtual
			CCost Cost(CExpressionHandle &exprhdl, const SCostingInfo *pci) const;

			// cost model type
			virtual
			ECostModelType Ecmt() const
			{
				return ICostModel::EcmtGPDBCalibrated;
			}

	}; // class CCostModelGPDB

}

#endif // !GPDBCOST_CCostModelGPDB_H

// EOF


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>RANDOM-SPATIAL-ENCOUNTER</title>

If I'm infected then individuals I randomly encounter may become

	infected. The odds of encountering anyone is heavily biased to those nearby.

	Begin micro-behaviour

RANDOM-SPATIAL-ENCOUNTER

	Begin NetLogo code:

substitute-text-area-for odds-of-encountering 1 / (1 + distance-to-me ^ 2) > random-number-between 0 1
do-every 1
   [do-if my-state = "infected"
       [do-for-n the-encounter-rate
                 all-individuals with
                  [my-state != "dead" and
                   odds-of-encountering]
          [set my-last-encounter the-other
           add-behaviours list-of-micro-behaviours "Encounter Behaviours" [POSSIBLE-INFECTION.html]]]]

	End NetLogo code

Variants

A different formula for biasing the odds to nearby

	individuals can be used. Additional encounter behaviours can be added.

Related Micro-behaviours

This relies upon the

	POSSIBLE-INFECTION micro-behaviour to possibly infect the other.

	CREATE-ENCOUNTER-RATE-SLIDER defines the-encounter-rate variable

	used here.

	RANDOM-ENCOUNTER is like this micro-behaviour without a spatial bias.

	RANDOM-SOCIAL-ENCOUNTER chooses individuals among my set of

	acquaintances.

	RANDOM-PHYSICAL-ENCOUNTER chooses individuals that are at my location.

How this works

This models individuals that have the-encounter-rate encounters per

	unit time period (e.g., a simulated week). Every second, if I'm still infected (i.e.,

	my-state = "infected") then I pick the-encounter-rate  other individuals (who are not dead) . Individuals are picked
	with a probability that is inversely proportional to the square of the
	distance to me. I give these individuals the micro-behaviour

	POSSIBLE-INFECTION. The formula adds 1 to avoid a division by zero if
	someone is co-located with me. If the-encounter-rate is a non-integer then the

	remainder is compared with a random number probabilistically to possibly

	include one additional individual. I also sets the my-last-encounter

	variable of the other individuals to me in order to keep track of how many

	infections I cause.

	do-for-n selects n agents and sets

	the-other
	to refer to each one.

History

This was implemented by Ken Kahn.


text:
int main(int argc, char const *argv[])
{
  timer timer;
  std::string data_path = "data/um/base.bin";
  auto base_data = new int[BASE_SIZE * COL_SIZE];
  data_loader::load_data(data_path, base_data, BASE_SIZE * COL_SIZE);

  timer.stop();
  timer.duration();
  return 0;
}