text:
package com.meread.buildenv;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import freemarker.template.Configuration;
import freemarker.template.ObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import net.sf.expectit.Expect;
import net.sf.expectit.ExpectBuilder;
import net.sf.expectit.MultiResult;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import static net.sf.expectit.filter.Filters.removeColors;
import static net.sf.expectit.filter.Filters.removeNonPrintable;
import static net.sf.expectit.matcher.Matchers.anyOf;
import static net.sf.expectit.matcher.Matchers.contains;

/**
 * Created by yangxg on 16/1/14.
 */
public class BuildThread {

    private Logger logger = LoggerFactory.getLogger(BuildThread.class);

    private static final int bufferSize = 1024;
    private Session session;
    private Expect expect;
    private Channel channel;

    private HostInfo hostInfo;

    Set<HostInfo> otherHostInfo;

    private static final String ROOT_USER = "root";

    private static final String HADOOP_USER = "hdp";

    public BuildThread(HostInfo hostInfo) {
        this.hostInfo = hostInfo;
        init();
    }

    private Set<HostInfo> getOtherHostInfo() {
        Set<HostInfo> result = new HashSet<>();
        result.addAll(BuildEnv.ALL_HOST);
        result.remove(hostInfo);
        return result;
    }

    public void configJava() throws IOException {
        System.out.println("~~~~~~~~~~~~~安装jdk/scala/maven  start~~~~~~~~~~~~~~");
//        expect.sendLine("java -version");
//            expect.sendLine("wget --no-check-certificate --no-cookies --header \"Cookie: oraclelicense=accept-securebackup-cookie\" http://download.oracle.com/otn-pub/java/jdk/7u79-b15/jdk-7u79-linux-x64.rpm");
//            ready(ROOT_USER);
//            expect.sendLine("rpm -ivh jdk-7u79-linux-x64.rpm");
//            ready(ROOT_USER);
        expect.sendLine("tar xvzf /vagrant/download/scala-2.11.7.tgz");
        ready(ROOT_USER);
        expect.sendLine("mv scala-2.11.7 /usr/local/scala");
        ready(ROOT_USER);

        expect.sendLine("tar xvzf /vagrant/download/apache-maven-3.3.9-bin.tar.gz");
        ready(ROOT_USER);
        expect.sendLine("mv apache-maven-3.3.9 /usr/local/maven");
        ready(ROOT_USER);

        expect.sendLine("echo -e 'SCALA_HOME=/usr/local/scala' >> /etc/profile");
        ready(ROOT_USER);
        expect.sendLine("echo -e 'MAVEN_HOME=/usr/local/maven' >> /etc/profile");
        ready(ROOT_USER);
        expect.sendLine("echo -e 'JAVA_HOME=/usr/java/jdk1.7.0_79' >> /etc/profile");
        ready(ROOT_USER);
        expect.sendLine("echo -e 'JRE_HOME=$JAVA_HOME/jre' >> /etc/profile");
        ready(ROOT_USER);
        expect.sendLine("echo -e 'PATH=$PATH:$JAVA_HOME/bin:$JRE_HOME/bin:$SCALA_HOME/bin:$MAVEN_HOME/bin' >> /etc/profile");
        ready(ROOT_USER);
        expect.sendLine("echo -e 'CLASSPATH=.:$JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar:$JRE_HOME/lib' >> /etc/profile");
        ready(ROOT_USER);
        expect.sendLine("echo -e 'export SCALA_HOME JAVA_HOME JRE_HOME PATH CLASSPATH' >> /etc/profile");
        ready(ROOT_USER);
        expect.sendLine("source /etc/profile");
        ready(ROOT_USER);
        System.out.println("~~~~~~~~~~~~~安装jdk  end~~~~~~~~~~~~~~");
    }

    private void init() {
        otherHostInfo = getOtherHostInfo();
        JSch jSch = new JSch();
        java.util.Properties config = new java.util.Properties();
        config.put("StrictHostKeyChecking", "no");
        try {
            session = jSch.getSession(hostInfo.getUser(), hostInfo.getIp(), hostInfo.getPort());
            session.setConfig(config);
            session.setPassword(hostInfo.getPassword());
            session.connect(5000);
            System.out.println(hostInfo.getIp() + "已连接...");
            channel = session.openChannel("shell");
            channel.connect();
            expect = new ExpectBuilder()
                    .withOutput(channel.getOutputStream())
                    .withInputs(channel.getInputStream(), channel.getExtInputStream())
                    .withEchoInput(System.out)
                    .withEchoOutput(System.err)
                    .withInputFilters(removeColors(), removeNonPrintable())
                    .withExceptionOnFailure()
                    .withTimeout(80000, TimeUnit.SECONDS)
                    .withAutoFlushEcho(true)
                    .withCombineInputs(true)
                    .build();
            System.out.println(expect.getClass().getName());
        } catch (JSchException | IOException e) {
            e.printStackTrace();
            destroy();
            throw new RuntimeException("无法连接" + hostInfo.getIp() + ":" + hostInfo.getPort());
        }
    }

    public void destroy() {
        if (channel != null) {
            channel.disconnect();
        }
        if (expect != null) {
            try {
                expect.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (session != null) {
            session.disconnect();
        }
    }

    public void configHostName() throws IOException {
        expect.sendLine("echo '' > /etc/hosts");
        ready(ROOT_USER);
        for (HostInfo info : BuildEnv.ALL_HOST) {
            expect.sendLine("echo '" + info.getIp() + " " + info.getHostName() + "' >> /etc/hosts");
            ready(ROOT_USER);
        }
    }

    public void installLocalRpm() throws IOException {
        expect.sendLine("yum -y remove mariadb-libs");
        expect.expect(contains("Complete!"));
        expect.sendLine("yum -y localinstall /vagrant/download/*.rpm");
        expect.expect(contains("Complete!"));
    }

    public void configSSH(String user) throws IOException {
        System.out.println("~~~~~~~~~~~~~configSSH  start~~~~~~~~~~~~~~");
        this.expect.sendLine("ssh-keygen -t rsa -P \"\" -f ~/.ssh/id_rsa");
        ready(user);
        this.expect.sendLine("cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys");
        ready(user);
        this.expect.sendLine("\\cp -f /vagrant/src/main/resources/ssh/config ~/.ssh");
        ready(user);
        for (HostInfo hi : otherHostInfo) {
            String copyId = "ssh-copy-id -i ~/.ssh/id_rsa.pub " + user + "@" + hi.getHostName();
            this.expect.sendLine(copyId);
            ready(user);
        }
        this.expect.sendLine("chmod 700 -R ~/.ssh");
        ready(user);
        System.out.println("~~~~~~~~~~~~~configSSH  成功~~~~~~~~~~~~~~");
    }

    private void ready(String user) throws IOException {
        expect.expect(contains(user + "@" + hostInfo.getHostName()));
        System.out.flush();
    }

    public void installRequired() throws IOException {
        expect.sendLine("yum -y update");
        ready(ROOT_USER);
        expect.sendLine("yum -y install git nano vim lsof gcc prelink expect openssl-devel libyaml-devel libffi-devel readline-devel zlib-devel gdbm-devel ncurses-devel gcc-c++ automake autoconf");
        ready(ROOT_USER);
        expect.sendLine("yum -y install perl-Compress-Raw-Bzip2 perl-Compress-Raw-Zlib perl-DBI perl-IO-Compress perl-Net-Daemon perl-PlRPC nmap nmap-ncat");
        ready(ROOT_USER);
        expect.sendLine("yum -y install epel-release net-tools");
        ready(ROOT_USER);
        expect.sendLine("yum --enablerepo=epel -y install sshpass");
        ready(ROOT_USER);
        expect.sendLine("systemctl stop firewalld.service");
        ready(ROOT_USER);
        expect.sendLine("systemctl disable firewalld.service");
        ready(ROOT_USER);
        expect.sendLine("setenforce 0");
        ready(ROOT_USER);
        expect.sendLine("sed -i -e 's/^SELINUX=.*/SELINUX=disabled/' /etc/sysconfig/selinux");
        ready(ROOT_USER);
        this.expect.sendLine("\\cp -f /vagrant/src/main/resources/ssh/ssh-copy-id.modified /usr/bin/ssh-copy-id");
        ready(ROOT_USER);
    }

    public void clearSSH(String user) throws IOException {
        this.expect.sendLine("rm -f ~/.ssh/id_rsa && rm -f ~/.ssh/id_rsa.pub && rm -f ~/.ssh/authorized_keys");
        ready(user);
    }

    private void installMariaDB() throws IOException, TemplateException {
        expect.sendLine("\\cp -f /vagrant/src/main/resources/MariaDB.repo /etc/yum.repos.d/MariaDB.repo");
        ready(ROOT_USER);
        expect.sendLine("yum -y --enablerepo=mariadb install MariaDB-client MariaDB-Galera-server galera");
        MultiResult multiResult = this.expect.expect(anyOf(contains("Complete"), contains("Nothing")));
        if (multiResult.getResults().get(0).isSuccessful()) {
            expect.sendLine("yum -y --enablerepo=mariadb install MariaDB-client MariaDB-Galera-server galera");
            expect.expect(anyOf(contains("Complete"), contains("Nothing")));
        }
        genServerConfFile();
    }

    private void localInstallMariaDB() throws IOException, TemplateException {
        expect.sendLine("yum localinstall /vagrant/download/");
        ready(ROOT_USER);
        expect.sendLine("yum -y --enablerepo=mariadb install MariaDB-client MariaDB-Galera-server galera");
        MultiResult multiResult = this.expect.expect(anyOf(contains("Complete"), contains("Nothing")));
        if (multiResult.getResults().get(0).isSuccessful()) {
            expect.sendLine("yum -y --enablerepo=mariadb install MariaDB-client MariaDB-Galera-server galera");
            expect.expect(anyOf(contains("Complete"), contains("Nothing")));
        }
        genServerConfFile();
    }

    public void copyConfig(boolean isFirst) throws IOException, TemplateException {
        genServerConfFile();
        expect.sendLine("\\cp -f /vagrant/src/main/resources/template/server.cnf." + hostInfo.getHostName() + " /etc/my.cnf.d/server.cnf");
        ready(ROOT_USER);
        if (isFirst) {
            configMariaDBFirst();
        }
    }

    public void genServerConfFile() throws IOException, TemplateException {
        Configuration cfg = new Configuration(Configuration.VERSION_2_3_23);
        cfg.setObjectWrapper(ObjectWrapper.BEANS_WRAPPER);
        cfg.setClassForTemplateLoading(this.getClass(), "/");
        Template template = cfg.getTemplate("template/galera_server.ftl");

        // Build the data-model
        Map<String, Object> data = new HashMap<>();
        data.put("ownHostInfo", hostInfo);
        data.put("otherHostInfos", otherHostInfo);
        // Console output
        String path = getClass().getClassLoader().getResource("").getFile();
        FileWriter out = new FileWriter(path + "/template/server.cnf." + hostInfo.getHostName());
        template.process(data, out);
        out.flush();
        out.close();

    }

    public void configMariaDBFirst() throws IOException {
        expect.sendLine("/etc/rc.d/init.d/mysql bootstrap");
        ready(ROOT_USER);
        mysql_secure_installation();
    }

    private void mysql_secure_installation() throws IOException {
        expect.sendLine("sudo /usr/bin/mysql_secure_installation");
        expect.expect(contains("Enter current password"));
        expect.send("\n");
        MultiResult result = expect.expect(anyOf(contains("password"), contains("Access denied")));
        if (result.getResults().get(1).isSuccessful()) {
            expect.send("vagrant\n");
        }
        expect.send("Y\n");
        expect.expect(contains("New password"));
        expect.send("vagrant\n");
        expect.expect(contains("Re-enter"));
        expect.send("vagrant\n");
        expect.expect(contains("Remove anonymous users"));
        expect.send("Y\n");
        expect.expect(contains("Disallow root login remotely"));
        expect.send("n\n");
        expect.expect(contains("Remove test database and access to it"));
        expect.send("n\n");
        expect.expect(contains("Reload"));
        expect.send("Y\n");
        ready(ROOT_USER);
    }

    public void stopMysql() throws IOException {
        expect.send("systemctl stop mysql");
        ready(ROOT_USER);
    }

    public void configMysqlRootLogin() throws IOException {
        expect.sendLine("mysql -uroot -pvagrant -e \"use mysql;update user set host = '%' where user = 'root';\"");
        ready(ROOT_USER);
        expect.sendLine("mysql -uroot -pvagrant -e 'FLUSH PRIVILEGES;'");
        ready(ROOT_USER);
    }

    public void configHaproxy() throws IOException {
        expect.sendLine("yum -y install haproxy");
        expect.expect(contains("Complete!"));
        expect.sendLine("chkconfig haproxy on");
        ready(ROOT_USER);
        expect.sendLine("\\cp -f /vagrant/src/main/resources/haproxy.cfg /etc/haproxy/haproxy.cfg");
        ready(ROOT_USER);
        expect.sendLine("mysql -uroot -h11.11.11.101 -pvagrant -e \"CREATE USER 'haproxy'@'11.11.11.101';\"");
        ready(ROOT_USER);
        expect.sendLine("mysql -uroot -h11.11.11.101 -pvagrant -e \"CREATE USER 'haproxy'@'11.11.11.102';\"");
        ready(ROOT_USER);
        expect.sendLine("mysql -uroot -h11.11.11.101 -pvagrant -e \"CREATE USER 'haproxy'@'11.11.11.103';\"");
        ready(ROOT_USER);
        expect.sendLine("mysql -uroot -h11.11.11.101 -pvagrant -e \"CREATE USER 'haproxy'@'11.11.11.104';\"");
        ready(ROOT_USER);
        expect.sendLine("mysql -uroot -h11.11.11.101 -pvagrant -e 'FLUSH PRIVILEGES;'");
        ready(ROOT_USER);
        expect.sendLine("service haproxy restart");
        ready(ROOT_USER);
    }

    public void startMysql() throws IOException {
        //        mysql -u root -pvagrant -e "show status like 'wsrep%'"
        expect.sendLine("systemctl start mysql");
        ready(ROOT_USER);
        expect.sendLine("mysql");
        expect.expect(contains("using password"));
    }

    public void installRedis() throws IOException {
        System.out.println("~~~~~~~~~~~~~安装redis  start~~~~~~~~~~~~~~");
        expect.sendLine("rm -rf redis-3.0.6");
        ready(ROOT_USER);
        expect.sendLine("tar -zxvf /vagrant/download/redis-3.0.6.tar.gz -C .");
        ready(ROOT_USER);
        expect.sendLine("cd redis-3.0.6");
        ready(ROOT_USER);
        expect.sendLine("make && make install");
        ready(ROOT_USER);
        expect.sendLine("yum -y install ruby rubygems");
        ready(ROOT_USER);
        expect.sendLine("gem sources --add https://ruby.taobao.org/ --remove https://rubygems.org/");
        ready(ROOT_USER);
        expect.sendLine("gem install redis");
        ready(ROOT_USER);
        //6379
        expect.sendLine("utils/install_server.sh");
        expect.expect(contains("the redis port for this instance"));
        expect.send("\n");
        expect.expect(contains("the redis config file name"));
        expect.send("\n");
        expect.expect(contains("the redis log file name"));
        expect.send("\n");
        expect.expect(contains("the data directory for this instance"));
        expect.send("\n");
        expect.expect(contains("executable path"));
        expect.send("\n");
        expect.expect(contains("ENTER"));
        expect.send("\n");
        ready(ROOT_USER);

        //6380
        expect.sendLine("utils/install_server.sh");
        expect.expect(contains("the redis port for this instance"));
        expect.send("6380\n");
        expect.expect(contains("the redis config file name"));
        expect.send("\n");
        expect.expect(contains("the redis log file name"));
        expect.send("\n");
        expect.expect(contains("the data directory for this instance"));
        expect.send("\n");
        expect.expect(contains("executable path"));
        expect.send("\n");
        expect.expect(contains("ENTER"));
        expect.send("\n");
        ready(ROOT_USER);
        System.out.println("~~~~~~~~~~~~~安装redis  end~~~~~~~~~~~~~~");
    }

    public void configRedisCluster() throws IOException {
        expect.sendLine("\\cp -f /vagrant/src/main/resources/redis/6379.conf /etc/redis/6379.conf");
        ready(ROOT_USER);
        expect.sendLine("\\cp -f /vagrant/src/main/resources/redis/6380.conf /etc/redis/6380.conf");
        ready(ROOT_USER);
        expect.sendLine("service redis_6379 restart && service redis_6380 restart");
        ready(ROOT_USER);
    }

    public void createRedisCluster() throws IOException {
        expect.sendLine("/root/redis-3.0.6/src/redis-trib.rb create --replicas 1 11.11.11.101:6379 11.11.11.101:6380 11.11.11.102:6379 11.11.11.102:6380 11.11.11.103:6379 11.11.11.103:6380");
        expect.expect(contains("above configuration"));
        expect.send("yes\n");
        ready(ROOT_USER);
    }

    public void installMongo() throws IOException {
        expect.sendLine("\\cp -f /vagrant/src/main/resources/mongo/mongodb-org-3.2.repo /etc/yum.repos.d/mongodb-org-3.2.repo");
        ready(ROOT_USER);
        expect.sendLine("yum install -y mongodb-org");
        ready(ROOT_USER);
    }

    public void copyMongodbConfig() throws IOException {
        //配置Shard Server
        expect.sendLine("mkdir -p /data/mongodb/{data/{sh0,sh1},backup/{sh0,sh1},log/{sh0,sh1},conf/{sh0,sh1}}");
        ready(ROOT_USER);
        expect.sendLine("\\cp -f /vagrant/src/main/resources/mongo/mongodb0.conf /data/mongodb/conf/sh0/mongodb.conf");
        ready(ROOT_USER);
        expect.sendLine("\\cp -f /vagrant/src/main/resources/mongo/mongodb1.conf /data/mongodb/conf/sh1/mongodb.conf");
        ready(ROOT_USER);
        //配置Config Server
        expect.sendLine("mkdir -p /data/mongodb/{data/cf0,backup/cf0,log/cf0,conf/cf0}");
        ready(ROOT_USER);
        expect.sendLine("\\cp -f /vagrant/src/main/resources/mongo/config.conf /data/mongodb/conf/cf0/config.conf");
        ready(ROOT_USER);
        expect.sendLine("mkdir -p /data/mongodb/{data/ms0,backup/ms0,log/ms0,conf/ms0}");
        ready(ROOT_USER);
        expect.sendLine("\\cp -f /vagrant/src/main/resources/mongo/mongos.conf /data/mongodb/conf/ms0/mongos.conf");
        ready(ROOT_USER);
    }

    public void startShardServer() throws IOException {
        //启动Shard Server
        expect.sendLine("mongod --config /data/mongodb/conf/sh0/mongodb.conf");
        ready(ROOT_USER);
        expect.sendLine("mongod --config /data/mongodb/conf/sh1/mongodb.conf");
        ready(ROOT_USER);
    }

    public void startConfigServer() throws IOException {
        //启动Config Server
        expect.sendLine("mongod --config /data/mongodb/conf/cf0/config.conf");
        ready(ROOT_USER);
    }

    public void startQueryRouters() throws IOException {
        //启动Query Routers
        expect.sendLine("mongos --config /data/mongodb/conf/ms0/mongos.conf");
        ready(ROOT_USER);
    }

    public void configMongoShard() throws IOException {
        //初始化副本集1
        expect.sendLine("mongo --port 27010");
        expect.expect(contains(">"));
        expect.sendLine("use admin");
        expect.expect(contains(">"));
        InputStream resource0 = getClass().getClassLoader().getResourceAsStream("mongo/sh0.bson");
        String content0 = IOUtils.toString(resource0, StandardCharsets.UTF_8);
        String sh0 = "cfg=" + content0;
        System.out.println(sh0);
        expect.sendLine(sh0);
        expect.expect(contains(">"));
        expect.sendLine("rs.initiate(cfg);");
        expect.expect(anyOf(contains("PRIMARY>"), contains("OTHER>"), contains("SECONDARY>")));
        expect.sendLine("exit");
        ready(ROOT_USER);

        //初始化副本集2
        expect.sendLine("mongo --port 27011");
        expect.expect(contains(">"));
        expect.sendLine("use admin");
        expect.expect(contains(">"));
        InputStream resource1 = getClass().getClassLoader().getResourceAsStream("mongo/sh1.bson");
        String content1 = IOUtils.toString(resource1, StandardCharsets.UTF_8);
        String sh1 = "cfg=" + content1;
        System.out.println(sh1);
        expect.sendLine(sh1);
        expect.expect(contains(">"));
        expect.sendLine("rs.initiate(cfg);");
        expect.expect(anyOf(contains("PRIMARY>"), contains("OTHER>"), contains("SECONDARY>")));
        expect.sendLine("exit");
        ready(ROOT_USER);

        //配置分片
        expect.sendLine("mongo --port 30000");
        expect.expect(contains("mongos>"));
        expect.sendLine("use admin");
        expect.expect(contains("mongos>"));
        expect.sendLine("sh.addShard(\"sh0/11.11.11.101:27010,11.11.11.102:27010,11.11.11.103:27010\");");
        expect.expect(contains("mongos>"));
        expect.sendLine("sh.addShard(\"sh1/11.11.11.101:27011,11.11.11.102:27011,11.11.11.103:27011\");");
        expect.expect(contains("mongos>"));

        expect.sendLine("use mydb;");
        expect.expect(contains("mongos>"));

        expect.sendLine("db.createCollection(\"test\");");
        expect.expect(contains("mongos>"));

        expect.sendLine("sh.enableSharding(\"mydb\");");
        expect.expect(contains("mongos>"));

        expect.sendLine("sh.shardCollection(\"mydb.test\", {\"_id\":1});");
        expect.expect(contains("mongos>"));

        expect.sendLine("exit");
        ready(ROOT_USER);
    }

    public void configMongoAutorun() throws IOException {
        expect.sendLine("\\cp -f /vagrant/src/main/resources/mongo/rc.local /etc/rc.local");
        ready(ROOT_USER);
        expect.sendLine("chmod +x /etc/rc.d/rc.local");
        ready(ROOT_USER);
    }

    public void createHadoopUser() throws IOException {
        expect.sendLine("useradd -d /usr/hdp " + HADOOP_USER + " && chmod -R 755 /usr/hdp");
        ready(ROOT_USER);
        expect.sendLine("passwd " + HADOOP_USER);
        expect.expect(contains("New password"));
        expect.sendLine("vagrant");
        expect.expect(contains("Retype"));
        expect.sendLine("vagrant");
        ready(ROOT_USER);
        expect.sendLine("chmod 755 /usr/hdp/.bash_profile");
        ready(ROOT_USER);
        expect.sendLine("\\cp -f /vagrant/src/main/resources/hadoop/sysctl.conf /etc/sysctl.conf");
        ready(ROOT_USER);
    }

    public void copyHadoopConfig() throws IOException {
        expect.sendLine("su " + HADOOP_USER);
        ready(HADOOP_USER);
        configSSH(HADOOP_USER);
        expect.sendLine("cd ~");
        ready(HADOOP_USER);
        expect.sendLine("mkdir hadoop spark");
        ready(HADOOP_USER);
        expect.sendLine("tar zxf /vagrant/download/hadoop-2.6.3.tar.gz -C ~/hadoop --strip-components 1 ");
        ready(HADOOP_USER);
        expect.sendLine("echo -e ' ' >> ~/.bash_profile");
        ready(HADOOP_USER);
        expect.sendLine("echo -e 'export HADOOP_HOME=/usr/hdp/hadoop' >> ~/.bash_profile");
        ready(HADOOP_USER);
        expect.sendLine("echo -e 'export HADOOP_COMMON_HOME=$HADOOP_HOME' >> ~/.bash_profile");
        ready(HADOOP_USER);
        expect.sendLine("echo -e 'export HADOOP_HDFS_HOME=$HADOOP_HOME' >> ~/.bash_profile");
        ready(HADOOP_USER);
        expect.sendLine("echo -e 'export HADOOP_MAPRED_HOME=$HADOOP_HOME' >> ~/.bash_profile");
        ready(HADOOP_USER);
        expect.sendLine("echo -e 'export HADOOP_YARN_HOME=$HADOOP_HOME' >> ~/.bash_profile");
        ready(HADOOP_USER);
        expect.sendLine("echo -e 'export HADOOP_OPTS=\"-Djava.library.path=$HADOOP_HOME/lib/native\"' >> ~/.bash_profile");
        ready(HADOOP_USER);
        expect.sendLine("echo -e 'export HADOOP_COMMON_LIB_NATIVE_DIR=$HADOOP_HOME/lib/native' >> ~/.bash_profile");
        ready(HADOOP_USER);
        expect.sendLine("tar -zxf /vagrant/download/spark-1.5.2-bin-hadoop2.6.tgz -C ~/spark --strip-components 1");
        ready(HADOOP_USER);
        expect.sendLine("echo 'export SPARK_HOME=/usr/hdp/spark' >> ~/.bash_profile");
        ready(HADOOP_USER);

        expect.sendLine("echo -e 'export PATH=$PATH:$HADOOP_HOME/sbin:$HADOOP_HOME/bin:$SPARK_HOME/bin' >> ~/.bash_profile");
        ready(HADOOP_USER);
        expect.sendLine("source ~/.bash_profile");
        ready(HADOOP_USER);
    }

    public void configHadoop() throws IOException {
        expect.sendLine("mkdir ~/datanode");
        ready(HADOOP_USER);
        expect.sendLine("ssh node2 \"mkdir ~/datanode\" && ssh node3 \"mkdir ~/datanode\"");
        ready(HADOOP_USER);
        expect.sendLine("\\cp -f /vagrant/src/main/resources/hadoop/hdfs-site.xml ~/hadoop/etc/hadoop/hdfs-site.xml");
        ready(HADOOP_USER);
        expect.sendLine("scp ~/hadoop/etc/hadoop/hdfs-site.xml node2:~/hadoop/etc/hadoop/");
        ready(HADOOP_USER);
        expect.sendLine("scp ~/hadoop/etc/hadoop/hdfs-site.xml node3:~/hadoop/etc/hadoop/");
        ready(HADOOP_USER);

        expect.sendLine("\\cp -f /vagrant/src/main/resources/hadoop/core-site.xml ~/hadoop/etc/hadoop/core-site.xml");
        ready(HADOOP_USER);
        expect.sendLine("scp ~/hadoop/etc/hadoop/core-site.xml node2:~/hadoop/etc/hadoop/");
        ready(HADOOP_USER);
        expect.sendLine("scp ~/hadoop/etc/hadoop/core-site.xml node3:~/hadoop/etc/hadoop/");
        ready(HADOOP_USER);

        expect.sendLine("sed -i -e 's/\\${JAVA_HOME}/\\/usr\\/java\\/default/' ~/hadoop/etc/hadoop/hadoop-env.sh");
        ready(HADOOP_USER);
        expect.sendLine("scp ~/hadoop/etc/hadoop/hadoop-env.sh node2:~/hadoop/etc/hadoop/");
        ready(HADOOP_USER);
        expect.sendLine("scp ~/hadoop/etc/hadoop/hadoop-env.sh node3:~/hadoop/etc/hadoop/");
        ready(HADOOP_USER);

        expect.sendLine("mkdir ~/namenode");
        ready(HADOOP_USER);
        expect.sendLine("\\cp -f /vagrant/src/main/resources/hadoop/hdfs-site-master.xml ~/hadoop/etc/hadoop/hdfs-site.xml");
        ready(HADOOP_USER);
        expect.sendLine("\\cp -f /vagrant/src/main/resources/hadoop/mapred-site.xml ~/hadoop/etc/hadoop/mapred-site.xml");
        ready(HADOOP_USER);
        expect.sendLine("\\cp -f /vagrant/src/main/resources/hadoop/yarn-site.xml ~/hadoop/etc/hadoop/yarn-site.xml");
        ready(HADOOP_USER);
        expect.sendLine("\\cp -f /vagrant/src/main/resources/hadoop/slaves ~/hadoop/etc/hadoop/slaves");
        ready(HADOOP_USER);
    }

    public void startHadoop() throws IOException {
        expect.sendLine("~/hadoop/bin/hdfs namenode -format");
        ready(HADOOP_USER);
        expect.sendLine("~/hadoop/sbin/start-dfs.sh");
        ready(HADOOP_USER);
        expect.sendLine("~/hadoop/sbin/start-yarn.sh");
        ready(HADOOP_USER);
        expect.sendLine("jps");
        ready(HADOOP_USER);

        expect.sendLine("~/hadoop/bin/hdfs dfs -mkdir /test");
        ready(HADOOP_USER);
        expect.sendLine("~/hadoop/bin/hdfs dfs -copyFromLocal ~/hadoop/NOTICE.txt /test");
        ready(HADOOP_USER);
        expect.sendLine("~/hadoop/bin/hdfs dfs -cat /test/NOTICE.txt");
        ready(HADOOP_USER);
        expect.sendLine("~/hadoop/bin/hadoop jar ~/hadoop/share/hadoop/mapreduce/hadoop-mapreduce-examples-2.6.3.jar wordcount /test/NOTICE.txt /output01");
        ready(HADOOP_USER);
        expect.sendLine("~/hadoop/bin/hdfs dfs -ls /output01");
        ready(HADOOP_USER);
        expect.sendLine("~/hadoop/bin/hdfs dfs -cat /output01/part-r-00000");
        ready(HADOOP_USER);
    }

    public void configSpark() throws IOException {
        expect.sendLine("\\cp -f /vagrant/src/main/resources/spark/spark-env.sh ~/spark/conf/spark-env.sh");
        ready(HADOOP_USER);
        expect.sendLine("chmod 755 ~/spark/conf/spark-env.sh");
        ready(HADOOP_USER);
        expect.sendLine("\\cp -f /vagrant/src/main/resources/spark/slaves ~/spark/conf/slaves");
        ready(HADOOP_USER);
    }

}


text:
fn main() {
    let _result = &Some(42).deref();
//~^ ERROR no method named `deref` found for type `std::option::Option<{integer}>`
}

redpajama_set_name: RedPajamaGithub


text:
class Solution(object):
    def findRelativeRanks(self, nums):
        """
        :type nums: List[int]
        :rtype: List[str]
        """
        def reverse(x, y):
            return y - x

        sort = sorted(nums, reverse)
        rank = ["Gold Medal", "Silver Medal", "Bronze Medal"] + map(str, range(4, len(nums) + 1))
        return map(dict(zip(sort, rank)).get, nums)


text:
title: "Illustrated in purble and blue tones"
excerpt: "PaperFaces portrait of @dopplegl drawn with Paper by 53 on an iPad."
image:
  feature: paperfaces-dopplegl-twitter-lg.jpg
  thumb: paperfaces-dopplegl-twitter-150.jpg
tags: [portrait, illustration, Paper by 53]
---

PaperFaces portrait of [@dopplegl](http://twitter.com/dopplegl).

{% include boilerplate/paperfaces.html %}


text:
<?php

namespace FivePercent\Component\VarTagValidator\Metadata;

/**
 * Property metadata
 *
 * @author Vitaliy Zhuk <zhuk2205@gmail.com
 */
class PropertyMetadata
{
    /**
     * @var array
     */
    private $types;

    /**
     * Construct
     *
     * @param array $types
     */
    public function __construct(array $types)
    {
        $this->types = $types;
    }

    /**
     * Get types
     *
     * @return array
     */
    public function getTypes()
    {
        return $this->types;
    }
}


text:
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.stent = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
'use strict';

exports.__esModule = true;

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

// errors
var ERROR_MISSING_MACHINE = exports.ERROR_MISSING_MACHINE = function ERROR_MISSING_MACHINE(name) {
  return 'There\'s no machine with name ' + name;
};
var ERROR_MISSING_STATE = exports.ERROR_MISSING_STATE = 'Configuration error: missing initial "state"';
var ERROR_MISSING_TRANSITIONS = exports.ERROR_MISSING_TRANSITIONS = 'Configuration error: missing "transitions"';
var ERROR_WRONG_STATE_FORMAT = exports.ERROR_WRONG_STATE_FORMAT = function ERROR_WRONG_STATE_FORMAT(state) {
  var serialized = (typeof state === 'undefined' ? 'undefined' : _typeof(state)) === 'object' ? JSON.stringify(state, null, 2) : state;

  return 'The state should be an object and it should always have at least "name" property. You passed ' + serialized;
};
var ERROR_UNCOVERED_STATE = exports.ERROR_UNCOVERED_STATE = function ERROR_UNCOVERED_STATE(state) {
  return 'You just transitioned the machine to a state (' + state + ') which is not defined or it has no actions. This means that the machine is stuck.';
};
var ERROR_NOT_SUPPORTED_HANDLER_TYPE = exports.ERROR_NOT_SUPPORTED_HANDLER_TYPE = 'Wrong handler type passed. Please read the docs https://github.com/krasimir/stent';
var ERROR_RESERVED_WORD_USED_AS_ACTION = exports.ERROR_RESERVED_WORD_USED_AS_ACTION = function ERROR_RESERVED_WORD_USED_AS_ACTION(word) {
  return 'Sorry, you can\'t use ' + word + ' as a name for an action. It is reserved.';
};
var ERROR_GENERATOR_FUNC_CALL_FAILED = exports.ERROR_GENERATOR_FUNC_CALL_FAILED = function ERROR_GENERATOR_FUNC_CALL_FAILED(type) {
  return 'The argument passed to `call` is falsy (' + type + ')';
};

// middlewares
var MIDDLEWARE_PROCESS_ACTION = exports.MIDDLEWARE_PROCESS_ACTION = 'onActionDispatched';
var MIDDLEWARE_ACTION_PROCESSED = exports.MIDDLEWARE_ACTION_PROCESSED = 'onActionProcessed';
var MIDDLEWARE_STATE_WILL_CHANGE = exports.MIDDLEWARE_STATE_WILL_CHANGE = 'onStateWillChange';
var MIDDLEWARE_PROCESS_STATE_CHANGE = exports.MIDDLEWARE_PROCESS_STATE_CHANGE = 'onStateChanged';
var MIDDLEWARE_GENERATOR_STEP = exports.MIDDLEWARE_GENERATOR_STEP = 'onGeneratorStep';
var MIDDLEWARE_GENERATOR_END = exports.MIDDLEWARE_GENERATOR_END = 'onGeneratorEnd';
var MIDDLEWARE_GENERATOR_RESUMED = exports.MIDDLEWARE_GENERATOR_RESUMED = 'onGeneratorResumed';
var MIDDLEWARE_MACHINE_CREATED = exports.MIDDLEWARE_MACHINE_CREATED = 'onMachineCreated';
var MIDDLEWARE_MACHINE_CONNECTED = exports.MIDDLEWARE_MACHINE_CONNECTED = 'onMachineConnected';
var MIDDLEWARE_MACHINE_DISCONNECTED = exports.MIDDLEWARE_MACHINE_DISCONNECTED = 'onMachineDisconnected';
var MIDDLEWARE_REGISTERED = exports.MIDDLEWARE_REGISTERED = 'onMiddlewareRegister';

// misc
var DEVTOOLS_KEY = exports.DEVTOOLS_KEY = '__hello__stent__';
},{}],2:[function(require,module,exports){
'use strict';

exports.__esModule = true;

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

exports.default = createMachine;

var _handleAction = require('./helpers/handleAction');

var _handleAction2 = _interopRequireDefault(_handleAction);

var _handleActionLatest = require('./helpers/handleActionLatest');

var _handleActionLatest2 = _interopRequireDefault(_handleActionLatest);

var _validateConfig = require('./helpers/validateConfig');

var _validateConfig2 = _interopRequireDefault(_validateConfig);

var _registerMethods = require('./helpers/registerMethods');

var _registerMethods2 = _interopRequireDefault(_registerMethods);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var IDX = 0;
var getMachineID = function getMachineID() {
  return '_@@@' + ++IDX;
};

function createMachine(name, config) {
  if ((typeof name === 'undefined' ? 'undefined' : _typeof(name)) === 'object') {
    if (typeof config === 'undefined') {
      config = name;
      name = getMachineID();
    } else {
      config = {
        state: name,
        transitions: config
      };
      name = getMachineID();
    }
  }

  var machine = { name: name };

  (0, _validateConfig2.default)(config);

  var _config = config,
      initialState = _config.state,
      transitions = _config.transitions;

  var dispatch = function dispatch(action) {
    for (var _len = arguments.length, payload = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
      payload[_key - 1] = arguments[_key];
    }

    return _handleAction2.default.apply(undefined, [machine, action].concat(payload));
  };
  var dispatchLatest = function dispatchLatest(action) {
    for (var _len2 = arguments.length, payload = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
      payload[_key2 - 1] = arguments[_key2];
    }

    return _handleActionLatest2.default.apply(undefined, [machine, action].concat(payload));
  };

  machine.state = initialState;
  machine.transitions = transitions;

  (0, _registerMethods2.default)(machine, transitions, dispatch, dispatchLatest);

  return machine;
}
module.exports = exports['default'];
},{"./helpers/handleAction":5,"./helpers/handleActionLatest":6,"./helpers/registerMethods":10,"./helpers/validateConfig":13}],3:[function(require,module,exports){
'use strict';

exports.__esModule = true;
exports.flush = flush;
exports.getMapping = getMapping;
exports.destroy = destroy;
exports.default = connect;

var _ = require('../');

var _handleMiddleware = require('./handleMiddleware');

var _handleMiddleware2 = _interopRequireDefault(_handleMiddleware);

var _constants = require('../constants');

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var idIndex = 0;
var mappings = null;

var getId = function getId() {
  return 'm' + ++idIndex;
};
var setup = function setup() {
  if (mappings !== null) return;
  mappings = {};
  _.Machine.addMiddleware({
    onStateChanged: function onStateChanged() {
      for (var id in mappings) {
        var _mappings$id = mappings[id],
            done = _mappings$id.done,
            machines = _mappings$id.machines;

        if (machines.map(function (m) {
          return m.name;
        }).indexOf(this.name) >= 0) {
          done && done.apply(undefined, machines);
        }
      }
    }
  });
};

function flush() {
  mappings = null;
}

function getMapping() {
  return mappings;
}

function destroy(machineId) {
  for (var mId in mappings) {
    mappings[mId].machines = mappings[mId].machines.filter(function (_ref) {
      var name = _ref.name;
      return name !== machineId;
    });
    (0, _handleMiddleware2.default)(_constants.MIDDLEWARE_MACHINE_DISCONNECTED, null, mappings[mId].machines);
    if (mappings[mId].machines.length === 0) {
      delete mappings[mId];
    }
  }
}

function connect() {
  var _ref2 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
      meta = _ref2.meta;

  setup();
  var withFunc = function withFunc() {
    for (var _len = arguments.length, names = Array(_len), _key = 0; _key < _len; _key++) {
      names[_key] = arguments[_key];
    }

    var machines = names.map(function (name) {
      return _.Machine.get(name);
    });
    var mapFunc = function mapFunc(done, once, silent) {
      var id = getId();

      !once && (mappings[id] = { done: done, machines: machines });
      !silent && done && done.apply(undefined, machines);

      return function disconnect() {
        (0, _handleMiddleware2.default)(_constants.MIDDLEWARE_MACHINE_DISCONNECTED, null, machines, meta);
        if (mappings && mappings[id]) delete mappings[id];
      };
    };

    (0, _handleMiddleware2.default)(_constants.MIDDLEWARE_MACHINE_CONNECTED, null, machines, meta);
    return {
      'map': mapFunc,
      'mapOnce': function mapOnce(done) {
        return mapFunc(done, true);
      },
      'mapSilent': function mapSilent(done) {
        return mapFunc(done, false, true);
      }
    };
  };

  return { 'with': withFunc };
}
},{"../":15,"../constants":1,"./handleMiddleware":8}],4:[function(require,module,exports){
'use strict';

exports.__esModule = true;
exports.default = call;
function call(func) {
  for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
    args[_key - 1] = arguments[_key];
  }

  return { __type: 'call', func: func, args: args };
};
module.exports = exports['default'];
},{}],5:[function(require,module,exports){
'use strict';

exports.__esModule = true;

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

exports.default = handleAction;

var _constants = require('../constants');

var _updateState = require('./updateState');

var _updateState2 = _interopRequireDefault(_updateState);

var _handleMiddleware = require('./handleMiddleware');

var _handleMiddleware2 = _interopRequireDefault(_handleMiddleware);

var _handleGenerator = require('./handleGenerator');

var _handleGenerator2 = _interopRequireDefault(_handleGenerator);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function handleAction(machine, action) {
  for (var _len = arguments.length, payload = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
    payload[_key - 2] = arguments[_key];
  }

  var state = machine.state,
      transitions = machine.transitions;

  if (!transitions[state.name]) return false;

  var handler = transitions[state.name][action];

  if (typeof handler === 'undefined') return false;

  _handleMiddleware2.default.apply(undefined, [_constants.MIDDLEWARE_PROCESS_ACTION, machine, action].concat(payload));

  // string as a handler
  if (typeof handler === 'string') {
    (0, _updateState2.default)(machine, _extends({}, state, { name: transitions[state.name][action] }));

    // object as a handler
  } else if ((typeof handler === 'undefined' ? 'undefined' : _typeof(handler)) === 'object') {
    (0, _updateState2.default)(machine, handler);

    // function as a handler
  } else if (typeof handler === 'function') {
    var _transitions$state$na;

    var response = (_transitions$state$na = transitions[state.name])[action].apply(_transitions$state$na, [machine].concat(payload));

    // generator
    if (response && typeof response.next === 'function') {
      var generator = response;

      return (0, _handleGenerator2.default)(machine, generator, function (response) {
        (0, _updateState2.default)(machine, response);
        _handleMiddleware2.default.apply(undefined, [_constants.MIDDLEWARE_ACTION_PROCESSED, machine, action].concat(payload));
      });
    } else {
      (0, _updateState2.default)(machine, response);
    }

    // wrong type of handler
  } else {
    throw new Error(_constants.ERROR_NOT_SUPPORTED_HANDLER_TYPE);
  }

  _handleMiddleware2.default.apply(undefined, [_constants.MIDDLEWARE_ACTION_PROCESSED, machine, action].concat(payload));
};
module.exports = exports['default'];
},{"../constants":1,"./handleGenerator":7,"./handleMiddleware":8,"./updateState":12}],6:[function(require,module,exports){
'use strict';

exports.__esModule = true;
exports.default = handleActionLatest;

var _handleAction = require('./handleAction');

var _handleAction2 = _interopRequireDefault(_handleAction);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var actions = {};

function handleActionLatest(machine, action) {
  actions[action] && actions[action]();

  for (var _len = arguments.length, payload = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
    payload[_key - 2] = arguments[_key];
  }

  actions[action] = _handleAction2.default.apply(undefined, [machine, action].concat(payload));
};
module.exports = exports['default'];
},{"./handleAction":5}],7:[function(require,module,exports){
'use strict';

exports.__esModule = true;

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

exports.default = handleGenerator;

var _handleMiddleware = require('./handleMiddleware');

var _handleMiddleware2 = _interopRequireDefault(_handleMiddleware);

var _constants = require('../constants');

var _updateState = require('./updateState');

var _updateState2 = _interopRequireDefault(_updateState);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function handleGenerator(machine, generator, done, resultOfPreviousOperation) {
  var generatorNext = function generatorNext(gen, res) {
    return !canceled && gen.next(res);
  };
  var generatorThrow = function generatorThrow(gen, error) {
    return !canceled && gen.throw(error);
  };
  var cancelGenerator = function cancelGenerator() {
    cancelInsideGenerator && cancelInsideGenerator();
    canceled = true;
  };
  var canceled = false;
  var cancelInsideGenerator;

  var iterate = function iterate(result) {
    if (canceled) return;

    if (!result.done) {
      (0, _handleMiddleware2.default)(_constants.MIDDLEWARE_GENERATOR_STEP, machine, result.value);

      // yield call
      if (_typeof(result.value) === 'object' && result.value.__type === 'call') {
        var _result$value = result.value,
            func = _result$value.func,
            args = _result$value.args;

        if (!func) {
          var error = (0, _constants.ERROR_GENERATOR_FUNC_CALL_FAILED)(typeof func === 'undefined' ? 'undefined' : _typeof(func));
          (0, _handleMiddleware2.default)(_constants.MIDDLEWARE_GENERATOR_RESUMED, machine, error);
          return iterate(generatorThrow(generator, new Error(error)));
        }

        try {
          var funcResult = func.apply(undefined, args);

          if (!funcResult) {
            (0, _handleMiddleware2.default)(_constants.MIDDLEWARE_GENERATOR_RESUMED, machine);
            iterate(generatorNext(generator));
            return;
          }

          // promise
          if (typeof funcResult.then !== 'undefined') {
            funcResult.then(function (result) {
              (0, _handleMiddleware2.default)(_constants.MIDDLEWARE_GENERATOR_RESUMED, machine, result);
              return iterate(generatorNext(generator, result));
            }, function (error) {
              (0, _handleMiddleware2.default)(_constants.MIDDLEWARE_GENERATOR_RESUMED, machine, error);
              return iterate(generatorThrow(generator, error));
            });
            // generator
          } else if (typeof funcResult.next === 'function') {
            try {
              cancelInsideGenerator = handleGenerator(machine, funcResult, function (generatorResult) {
                (0, _handleMiddleware2.default)(_constants.MIDDLEWARE_GENERATOR_RESUMED, machine, generatorResult);
                iterate(generatorNext(generator, generatorResult));
              });
            } catch (error) {
              return iterate(generatorThrow(generator, error));
            }
          } else {
            (0, _handleMiddleware2.default)(_constants.MIDDLEWARE_GENERATOR_RESUMED, machine, funcResult);
            iterate(generatorNext(generator, funcResult));
          }
        } catch (error) {
          return iterate(generatorThrow(generator, error));
        }

        // a return statement of the normal function
      } else {
        (0, _updateState2.default)(machine, result.value);
        (0, _handleMiddleware2.default)(_constants.MIDDLEWARE_GENERATOR_RESUMED, machine);
        iterate(generatorNext(generator));
      }

      // the end of the generator (return statement)
    } else {
      (0, _handleMiddleware2.default)(_constants.MIDDLEWARE_GENERATOR_END, machine, result.value);
      done(result.value);
    }
  };

  iterate(generatorNext(generator, resultOfPreviousOperation));

  return cancelGenerator;
}
module.exports = exports['default'];
},{"../constants":1,"./handleMiddleware":8,"./updateState":12}],8:[function(require,module,exports){
'use strict';

exports.__esModule = true;
exports.default = handleMiddleware;

var _ = require('../');

function handleMiddleware(hook, machine) {
  for (var _len = arguments.length, args = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
    args[_key - 2] = arguments[_key];
  }

  var middlewares = _.Machine.middlewares;

  if (middlewares.length === 0) {
    return;
  }

  var loop = function loop(index, process) {
    return index < middlewares.length - 1 ? process(index + 1) : null;
  };

  (function process(index) {
    var middleware = middlewares[index];

    if (middleware && typeof middleware[hook] !== 'undefined') {
      middleware[hook].apply(machine, args);
    }
    loop(index, process);
  })(0);
}
module.exports = exports['default'];
},{"../":15}],9:[function(require,module,exports){
"use strict";

exports.__esModule = true;
exports.default = isEmptyObject;
function isEmptyObject(obj) {
  var name;
  for (name in obj) {
    if (obj.hasOwnProperty(name)) return false;
  }
  return true;
}
module.exports = exports['default'];
},{}],10:[function(require,module,exports){
'use strict';

exports.__esModule = true;
exports.default = registerMethods;

var _toCamelCase = require('./toCamelCase');

var _toCamelCase2 = _interopRequireDefault(_toCamelCase);

var _constants = require('../constants');

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var reserved = ['name', 'transitions', 'state', 'destroy'];

function registerMethods(machine, transitions, dispatch, dispatchLatest) {
  for (var state in transitions) {

    (function (state) {
      machine[(0, _toCamelCase2.default)('is ' + state)] = function () {
        return machine.state.name === state;
      };
    })(state);

    for (var action in transitions[state]) {
      var normalized = (0, _toCamelCase2.default)(action);
      var normalizedAllowed = (0, _toCamelCase2.default)('is ' + action + ' allowed');
      if (reserved.indexOf(normalized) >= 0) {
        throw new Error((0, _constants.ERROR_RESERVED_WORD_USED_AS_ACTION)(normalized));
      }
      (function (n, na, a) {
        machine[n] = function () {
          for (var _len = arguments.length, payload = Array(_len), _key = 0; _key < _len; _key++) {
            payload[_key] = arguments[_key];
          }

          return dispatch.apply(undefined, [a].concat(payload));
        };
        machine[n].latest = function () {
          for (var _len2 = arguments.length, payload = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
            payload[_key2] = arguments[_key2];
          }

          return dispatchLatest.apply(undefined, [a].concat(payload));
        };
        machine[na] = function () {
          return !transitions[machine.state.name] || typeof transitions[machine.state.name][a] !== 'undefined';
        };
      })(normalized, normalizedAllowed, action);
    }
  }
}
module.exports = exports['default'];
},{"../constants":1,"./toCamelCase":11}],11:[function(require,module,exports){
"use strict";

exports.__esModule = true;
var startRe = /^[\W_]+/;
var re = /[\W_]+/g;

exports.default = function (text) {
  return text
  // Trim the delimiter from the start of the string
  // to ensure the starting character in the result is never capitalized
  // e.g., `-camel-case` --> 'camelCase' instead of 'CamelCase'
  .replace(startRe, "").split(re).reduce(function (result, word, idx) {
    if (idx === 0) {
      word = word.charAt(0).toLowerCase() + word.substr(1);
    } else {
      word = word.charAt(0).toUpperCase() + word.substr(1);
    }
    result += word;
    return result;
  }, "");
};

module.exports = exports['default'];
},{}],12:[function(require,module,exports){
'use strict';

exports.__esModule = true;
exports.default = updateState;

var _validateState = require('./validateState');

var _validateState2 = _interopRequireDefault(_validateState);

var _isEmptyObject = require('./isEmptyObject');

var _isEmptyObject2 = _interopRequireDefault(_isEmptyObject);

var _handleMiddleware = require('./handleMiddleware');

var _handleMiddleware2 = _interopRequireDefault(_handleMiddleware);

var _constants = require('../constants');

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function updateState(machine, state) {
  var newState;

  if (typeof state === 'undefined') return;
  if (typeof state === 'string' || typeof state === 'number') {
    newState = { name: state.toString() };
  } else {
    newState = (0, _validateState2.default)(state);
  }

  if (typeof machine.transitions[newState.name] === 'undefined' || (0, _isEmptyObject2.default)(machine.transitions[newState.name])) {
    throw new Error((0, _constants.ERROR_UNCOVERED_STATE)(newState.name));
  }

  (0, _handleMiddleware2.default)(_constants.MIDDLEWARE_STATE_WILL_CHANGE, machine);

  machine.state = newState;

  (0, _handleMiddleware2.default)(_constants.MIDDLEWARE_PROCESS_STATE_CHANGE, machine);
}
module.exports = exports['default'];
},{"../constants":1,"./handleMiddleware":8,"./isEmptyObject":9,"./validateState":14}],13:[function(require,module,exports){
'use strict';

exports.__esModule = true;

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

exports.default = validateConfig;

var _constants = require('../constants');

function validateConfig(config) {
  if ((typeof config === 'undefined' ? 'undefined' : _typeof(config)) !== 'object') throw new Error(_constants.ERROR_MISSING_STATE);

  var state = config.state,
      transitions = config.transitions;

  if ((typeof state === 'undefined' ? 'undefined' : _typeof(state)) !== 'object') throw new Error(_constants.ERROR_MISSING_STATE);
  if ((typeof transitions === 'undefined' ? 'undefined' : _typeof(transitions)) !== 'object') throw new Error(_constants.ERROR_MISSING_TRANSITIONS);
  return true;
}
module.exports = exports['default'];
},{"../constants":1}],14:[function(require,module,exports){
'use strict';

exports.__esModule = true;

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

exports.default = validateState;

var _constants = require('../constants');

function validateState(state) {
  if (state && (typeof state === 'undefined' ? 'undefined' : _typeof(state)) === 'object' && typeof state.name !== 'undefined') return state;
  throw new Error((0, _constants.ERROR_WRONG_STATE_FORMAT)(state));
}
module.exports = exports['default'];
},{"../constants":1}],15:[function(require,module,exports){
'use strict';

exports.__esModule = true;
exports.Machine = undefined;

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

var _createMachine = require('./createMachine');

var _createMachine2 = _interopRequireDefault(_createMachine);

var _constants = require('./constants');

var _connect = require('./helpers/connect');

var _connect2 = _interopRequireDefault(_connect);

var _call = require('./helpers/generators/call');

var _call2 = _interopRequireDefault(_call);

var _handleMiddleware = require('./helpers/handleMiddleware');

var _handleMiddleware2 = _interopRequireDefault(_handleMiddleware);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var MachineFactory = function () {
  function MachineFactory() {
    _classCallCheck(this, MachineFactory);

    this.machines = {};
    this.middlewares = [];
    this.connect = _connect2.default;
    this.call = _call2.default;
  }

  MachineFactory.prototype.create = function create(name, config) {
    var _this = this;

    var machine = (0, _createMachine2.default)(name, config, this.middlewares);

    this.machines[machine.name] = machine;
    (0, _handleMiddleware2.default)(_constants.MIDDLEWARE_MACHINE_CREATED, machine, machine);
    machine.destroy = function () {
      return _this.destroy(machine);
    };
    return machine;
  };

  MachineFactory.prototype.get = function get(name) {
    if ((typeof name === 'undefined' ? 'undefined' : _typeof(name)) === 'object') name = name.name;
    if (this.machines[name]) return this.machines[name];
    throw new Error((0, _constants.ERROR_MISSING_MACHINE)(name));
  };

  MachineFactory.prototype.flush = function flush() {
    this.machines = {};
    this.middlewares = [];
    (0, _connect.flush)();
  };

  MachineFactory.prototype.addMiddleware = function addMiddleware(middleware) {
    if (Array.isArray(middleware)) {
      this.middlewares = this.middlewares.concat(middleware);
    } else {
      this.middlewares.push(middleware);
    }
    if (middleware.__initialize) middleware.__initialize(this);
    if (middleware[_constants.MIDDLEWARE_REGISTERED]) middleware[_constants.MIDDLEWARE_REGISTERED]();
  };

  MachineFactory.prototype.destroy = function destroy(machine) {
    var m = machine;
    if (typeof machine === 'string') {
      m = this.machines[machine];
      if (!m) throw new Error((0, _constants.ERROR_MISSING_MACHINE)(machine));
    }
    delete this.machines[m.name];
    (0, _connect.destroy)(m.name);
  };

  return MachineFactory;
}();

var factory = new MachineFactory();

exports.Machine = factory;

if (typeof window !== 'undefined') {
  window[_constants.DEVTOOLS_KEY] = factory;
}
},{"./constants":1,"./createMachine":2,"./helpers/connect":3,"./helpers/generators/call":4,"./helpers/handleMiddleware":8}]},{},[15])(15)
});


text:
package org.kie.dmn.core.compiler;

import org.kie.dmn.api.core.DMNType;

public interface DMNTypeRegistry {

    DMNType unknown();

    DMNType registerType(DMNType type);

    DMNType resolveType(String namespace, String name);

}


text:
@implementation BangActionSheet

-(void)layoutSubviews{
    [super layoutSubviews];
    for (UIView *subViwe in self.subviews) {
        if ([subViwe isKindOfClass:[UIButton class]]) {
            UIButton *button = (UIButton*)subViwe;
            [button setTitleColor:CONTENT_COLOR forState:UIControlStateNormal];

        }
    }

}

@end


text:
package com.thisisnoble.javatest;

import java.util.*;

import com.thisisnoble.javatest.impl.CompositeEvent;

public class TestPublisher implements Publisher   // This needed to be rewritten to hold a collection of composite events
{                                                 // as they were published by the Orchestrator.
  private Vector< CompositeEvent > events;

  public TestPublisher()
  {
    events = new Vector< CompositeEvent >();
  }

  @Override
  public void publish( Event event )
  {
  	events.add( ( CompositeEvent ) event );
  }

  public synchronized Event getLastEvent()
  {
 		CompositeEvent ce = null;

 		if( events.size() > 0 )
 		{
  		ce = events.remove( 0 );
 		}

 		return ce;
  }
}

/*
   package com.thisisnoble.javatest;

public class TestPublisher implements Publisher {

    private Event lastEvent;

    @Override
    public void publish(Event event) {
        this.lastEvent = event;
    }

    public Event getLastEvent() {
        Event result = lastEvent;
        lastEvent = null;
        return result;
    }
}
*/


text:
@implementation FLModalPopoverController

static NSMutableArray* s_stack = nil;

@synthesize modal = _modal;
@synthesize wasDismissedCallback = _wasDismissedCallback;

+ (void) initialize
{
	if(!s_stack)
	{
		s_stack = [[NSMutableArray alloc] init];
	}
}

- (id) initWithContentViewController:(UIViewController*) controller isModal:(BOOL) isModal
{
	if((self = [self initWithContentViewController:controller]))
	{
		_isModal = isModal;
	}

	return self;
}

- (id) initWithContentViewController:(UIViewController*) controller
{
	if((self = [super initWithContentViewController:controller]))
	{
		[s_stack addObject:self];
		self.delegate = self;
	}

	return self;
}

- (void) dealloc
{
	FLRelease(_shield);
	self.delegate = nil;
	FLSuperDealloc();
}

- (void) hideShieldView
{
	if(_shield)
	{
		[_shield hideShield];
		FLReleaseWithNil(_shield);
	}
}

- (void)dismissPopoverAnimated:(BOOL)animated
{
	FLAutorelease(FLRetain(self));
	self.delegate = nil;
	[self hideShieldView];
	[s_stack removeObject:self];
	[super dismissPopoverAnimated:animated];

	FLInvokeCallback(_wasDismissedCallback, self);
}

- (void)popoverControllerDidDismissPopover:(UIPopoverController *)popoverController
{
	FLAutorelease(FLRetain(self));
	self.delegate = nil;
	[self hideShieldView];
	[s_stack removeObject:self];

	FLInvokeCallback(_wasDismissedCallback, self);
}

- (BOOL)popoverControllerShouldDismissPopover:(UIPopoverController *)popoverController
{
	return YES;
}

- (UINavigationController*) navigationController
{
	if([self.contentViewController isKindOfClass:[FLNavigationControllerViewController class]])
	{
		return ((FLNavigationControllerViewController*) self.contentViewController).rootNavigationController;
	}

	return nil;
}

- (void) showShieldForViewController:(UIViewController*) viewController
{
	_shield = [[FLModalShield alloc] init];
	[_shield showShieldInViewController:viewController];
	self.passthroughViews = _shield.passThroughViewsForPopover;
}

+ (FLModalPopoverController*) presentViewController:(UIViewController*) contentController
	inViewController:(UIViewController*) viewController
	permittedArrowDirections:(UIPopoverArrowDirection)arrowDirections
	fromRect:(CGRect) rect
	animated:(BOOL) animated
	isModal:(BOOL) isModal
{
	FLModalPopoverController* modalController = FLAutorelease([[FLModalPopoverController alloc] initWithContentViewController:contentController isModal:isModal]);
	if(arrowDirections == 0)
	{
		rect = FLRectCenterRectInRect(viewController.view.bounds, CGRectMake(0,0,20,20));
	}
	if(isModal)
	{
		[modalController showShieldForViewController:viewController];
		contentController.modalInPopover = YES;
	}

	[modalController presentPopoverFromRect:rect inView:viewController.view permittedArrowDirections:arrowDirections animated:animated];

	return modalController;
}

+ (FLModalPopoverController*) modalPopoverControllerForViewController:(UIViewController*) aController
{
	for(FLModalPopoverController* popover in s_stack)
	{
		UIViewController* contentController = popover.contentViewController;

		if(contentController == aController)
		{
			return popover;
		}

		if([contentController isKindOfClass:[UINavigationController class]])
		{
			if([((id) contentController) containsViewController:aController])
			{
				return popover;
			}
		}

		if([contentController isKindOfClass:[FLNavigationControllerViewController class]])
		{
			if([[((id) contentController) rootNavigationController] containsViewController:aController])
			{
				return popover;
			}
		}

		if(contentController.navigationController)
		{
			if(contentController.navigationController.rootViewController == aController)
			{
				return popover;
			}
		}

	}

	return nil;
}

@end


text:
//
// Copyright (C) 2006 Andras Varga and Levente Meszaros
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program; if not, see <http://www.gnu.org/licenses/>.
//

#ifndef __INET_FSMA_H
#define __INET_FSMA_H

#include "inet/common/INETDefs.h"

namespace inet {

/*
    This is an alternative FSM implementation.

    Here is an example:

    FSMA_Switch(fsm)
    {
        FSMA_State(X)
        {
            FSMA_Event_Transition(XY, isFoo, Y,
                doFoo);
            FSMA_No_Event_Transition(XZ, isFooBar, Z,
                doFooBar);
        }
        FSMA_State(Y)
        {
            FSMA_Event_Transition(YX, isBar, X,
                doBar);
        }
        FSMA_State(Z)
        {
            FSMA_Event_Transition(ZX, isBaz, X,
                doBaz);
        }
    }

    After macro expansion, a state machine code looks like something along
    these lines:

    bool ___is_event = true;
    bool ___exit = false;
    int ___c = 0;
    cFSM& ___fsm = fsm;
    while (!___exit && (___c++ < FSM_MAXT || (throw cRuntimeError(E_INFLOOP, ___fsm.getStateName())))
    {
        if (transition_seen = false, ___exit = true, ___fsm.getState() == X)
        {
            if (!___is_event)
            {
                if (transition_seen)
                    throw cRuntimeError("...");
                // enter code
            }
            transition_seen = true; if (isFoo && ___is_event)
            {
                EV_DEBUG << "firing " << XY << " transition for " << ___fsm.getName() << endl;
                doFoo;
                ___fsm.setState(Y, "Y");
                ___is_event = false;
                ___exit = false;
                continue;
            }
            transition_seen = true; if (isFooBar && !___is_event)
            {
                EV_DEBUG << "firing " << XZ << " transition for " << ___fsm.getName() << endl;
                doFooBar;
                ___fsm.setState(Z, "Z");
                ___exit = false;
                continue;
            }
        }
        if (transition_seen = false, ___exit = true, ___fsm.getState() == Y)
        {
            transition_seen = true; if (isBar && ___is_event)
            {
                EV_DEBUG << "firing " << YX << " transition for " << ___fsm.getName() << endl;
                doVar;
                ___fsm.setState(X, "X");
                ___is_event = false;
                ___exit = false;
                continue;
            }
        }
    }
 */

#define FSMA_Switch(fsm) \
    bool ___is_event = true; \
    bool ___exit = false; \
    bool ___transition_seen = false; \
    int ___c = 0; \
    cFSM& ___fsm = (fsm); \
    bool ___logging = true; \
    if (___logging) EV_DEBUG << "FSM " << ___fsm.getName() << ": processing event in state " << ___fsm.getStateName() << "\n"; \
    while (!___exit && (___c++ < FSM_MAXT || (throw cRuntimeError(E_INFLOOP, ___fsm.getStateName()), 0)))

#define FSMA_SetLogging(enabled) \
        ___logging = enabled;

#define FSMA_Print(exiting) \
    if (___logging) EV_DEBUG << "FSM " << ___fsm.getName() << ((exiting) ? ": leaving state " : ": entering state ") << ___fsm.getStateName() << endl

#define FSMA_State(s)    if (___transition_seen = false, ___exit = true, ___fsm.getState() == (s))

#define FSMA_Enter(action) \
    if (!___is_event) \
    { \
        if (___transition_seen) \
            throw cRuntimeError(&___fsm, "FSMA_Enter() must precede all FSMA_*_Transition()'s in the code"); \
        action; \
    }

#define FSMA_Event_Transition(transition, condition, target, action) \
    ___transition_seen = true; if ((condition) && ___is_event) \
    { \
        ___is_event = false; \
        FSMA_Transition(transition, (condition), target, action)

#define FSMA_No_Event_Transition(transition, condition, target, action) \
    ___transition_seen = true; if ((condition) && !___is_event) \
    { \
        FSMA_Transition(transition, (condition), target, action)

#define FSMA_Transition(transition, condition, target, action) \
    FSMA_Print(true); \
    if (___logging) EV_DEBUG << "FSM " << ___fsm.getName() << ": condition \"" << #condition << "\" holds, taking transition \"" << #transition << "\" to state " << #target << endl; \
    action; \
    ___fsm.setState(target, #target); \
    if (___logging) EV_DEBUG << "FSM " << ___fsm.getName() << ": done processing associated actions\n"; \
    FSMA_Print(false); \
    ___exit = false; \
    continue; \
    }

#define FSMA_Ignore_Event(condition) \
    ___transition_seen = true; if ((condition) && ___is_event) \
    { \
        if (___logging) EV_DEBUG << "FSM " << ___fsm.getName() << ": condition \"" << #condition << "\" holds, staying in current state"<< endl; \
        ___is_event = false; \
    }

#define FSMA_Fail_On_Unhandled_Event() \
    ___transition_seen = true; if (___is_event) \
    { \
        throw cRuntimeError(&___fsm, "Unhandled event"); \
    }

#if OMNETPP_VERSION < 0x500
#define E_INFLOOP    eINFLOOP
#endif // if OMNETPP_VERSION < 0x500

} // namespace inet

#endif // ifndef __INET_FSMA_H


text:
<?php
// include the config
require_once($_SERVER['DOCUMENT_ROOT'] .'/config/config.php');

// include the PHPMailer library
require_once($_SERVER['DOCUMENT_ROOT'] .'/included/libraries/PHPMailer.php');

// load the login class
require_once($_SERVER['DOCUMENT_ROOT'] .'/classes/Login.php');

// create a login object. when this object is created, it will do all login/logout stuff automatically
// so this single line handles the entire login process.
$login = new Login();

// If user is logged in, they don't need to reset their password
// ... ask if we are logged in here:
if ($login->isUserLoggedIn() == true) {
	// the user is logged in, redirect them to the homepage
	header("location: /");
}

// the user has just successfully entered a new password
// so we show the index page = the login page
if ($login->passwordResetWasSuccessful() == true && $login->passwordResetLinkIsValid() != true) {
	Location("/");

}
// the user wants to reset their password, or they had a mistake last time
include('included/headerout.php');
if ($login->passwordResetLinkIsValid() == true) { ?>
<form method="post" action="/password_reset/" name="new_password_form">
	<input type='hidden' name='user_name' value='<?php echo $_GET['user_name']; ?>' />
	<input type='hidden' name='user_password_reset_hash' value='<?php echo $_GET['verification_code']; ?>' />

	<?php echo "New password"; ?>
	<input id="user_password_new" type="password" name="user_password_new" pattern=".{6,}" required autocomplete="off" />

	<?php echo "Repeat new password"; ?>
	<input id="user_password_repeat" type="password" name="user_password_repeat" pattern=".{6,}" required autocomplete="off" />
	<input type="submit" name="submit_new_password" value="<?php echo "Submit new password"; ?>" />
</form>

<?php } else { ?>
<form method="post" action="/password_reset/" name="password_reset_form">
	<?php echo "Request a password reset. Enter your username and you'll get an email with instructions:"; ?>
	<input id="user_name" type="text" name="user_name" required />
	<input type="submit" name="request_password_reset" value="<?php echo "Reset my password"; ?>" />
</form>
<?php } ?>

<?php echo "Back to Login Page"; ?>
<?php
// Include footer
include($_SERVER['DOCUMENT_ROOT'] ."/included/footer.php");
?>


text:
/*
 * This is an OpenSSL-compatible implementation of the RSA Data Security,
 * Inc. MD5 Message-Digest Algorithm.
 *
 * Written by Solar Designer <solar@openwall.com> in 2001, and placed in
 * the public domain.  See md5.c for more information.
 */

/* Any 32-bit or wider unsigned integer data type will do */
typedef unsigned long MD5_u32plus;

typedef struct {
	MD5_u32plus lo, hi;
	MD5_u32plus a, b, c, d;
	unsigned char buffer[64];
	MD5_u32plus block[16];
} MD5_CTX;

extern void sat_MD5_Init(MD5_CTX *ctx);
extern void sat_MD5_Update(MD5_CTX *ctx, void *data, unsigned long size);
extern void sat_MD5_Final(unsigned char *result, MD5_CTX *ctx);


text:
package utils;

import org.webdsl.lang.Environment;

public class ThreadLocalTemplate {

    private static ThreadLocal<TemplateServlet> template = new ThreadLocal<TemplateServlet>();

    public static TemplateServlet get() {
        return template.get();
    }

    public static void set(TemplateServlet d) {
        template.set(d);
        org.apache.logging.log4j.ThreadContext.put("template", d == null ? "null" : d.getTemplateSignature());
    }

    //convenient for code generation, template call translation does a `ThreadLocalTemplate.set(this)` where `this` could be EmailServlet instead of TemplateServlet
    public static void set(EmailServlet d){
        setNull();
    }

    public static void setNull(){
        template.set(null);
        org.apache.logging.log4j.ThreadContext.put("template", "null");
    }

    public static Environment getEnv() {
        TemplateServlet ts = get();
        if(ts != null){
          return ts.getEnv();
        }
        return null;
    }
}


text:
namespace remoting {

namespace {

// PulseAudio's module-pipe-sink must be configured to use the following
// parameters for the sink we read from.
const int kSamplingRate = 48000;
const int kChannels = 2;
const int kBytesPerSample = 2;

// Read data from the pipe every 40ms.
const int kCapturingPeriodMs = 40;

#if !defined(F_SETPIPE_SZ)
// F_SETPIPE_SZ is supported only starting linux 2.6.35, but we want to be able
// to compile this code on machines with older kernel.
#define F_SETPIPE_SZ 1031
#endif  // defined(F_SETPIPE_SZ)

const int IsPacketOfSilence(const std::string& data) {
  const int64* int_buf = reinterpret_cast<const int64*>(data.data());
  for (size_t i = 0; i < data.size() / sizeof(int64); i++) {
    if (int_buf[i] != 0)
      return false;
  }
  for (size_t i = data.size() - data.size() % sizeof(int64);
       i < data.size(); i++) {
    if (data.data()[i] != 0)
      return false;
  }
  return true;
}

}  // namespace

// static
scoped_refptr<AudioPipeReader> AudioPipeReader::Create(
    scoped_refptr<base::SingleThreadTaskRunner> task_runner,
    const FilePath& pipe_name) {
  // Create a reference to the new AudioPipeReader before posting the
  // StartOnAudioThread task, otherwise it may be deleted on the audio
  // thread before we return.
  scoped_refptr<AudioPipeReader> pipe_reader =
      new AudioPipeReader(task_runner);
  task_runner->PostTask(FROM_HERE, base::Bind(
      &AudioPipeReader::StartOnAudioThread, pipe_reader, pipe_name));
  return pipe_reader;
}

void AudioPipeReader::StartOnAudioThread(const FilePath& pipe_name) {
  DCHECK(task_runner_->BelongsToCurrentThread());

  pipe_fd_ = HANDLE_EINTR(open(
      pipe_name.value().c_str(), O_RDONLY | O_NONBLOCK));
  if (pipe_fd_ < 0) {
    LOG(ERROR) << "Failed to open " << pipe_name.value();
    return;
  }

  // Set buffer size for the pipe to the double of what's required for samples
  // of each capturing period.
  int pipe_buffer_size = 2 * kCapturingPeriodMs * kSamplingRate * kChannels *
     kBytesPerSample / base::Time::kMillisecondsPerSecond;
  int result = HANDLE_EINTR(fcntl(pipe_fd_, F_SETPIPE_SZ, pipe_buffer_size));
  if (result < 0) {
    PLOG(ERROR) << "fcntl";
  }

  WaitForPipeReadable();
}

AudioPipeReader::AudioPipeReader(
    scoped_refptr<base::SingleThreadTaskRunner> task_runner)
    : task_runner_(task_runner),
      observers_(new ObserverListThreadSafe<StreamObserver>()) {
}

AudioPipeReader::~AudioPipeReader() {
}

void AudioPipeReader::AddObserver(StreamObserver* observer) {
  observers_->AddObserver(observer);
}
void AudioPipeReader::RemoveObserver(StreamObserver* observer) {
  observers_->RemoveObserver(observer);
}

void AudioPipeReader::OnFileCanReadWithoutBlocking(int fd) {
  DCHECK_EQ(fd, pipe_fd_);
  StartTimer();
}

void AudioPipeReader::OnFileCanWriteWithoutBlocking(int fd) {
  NOTREACHED();
}

void AudioPipeReader::StartTimer() {
  DCHECK(task_runner_->BelongsToCurrentThread());
  started_time_ = base::TimeTicks::Now();
  last_capture_samples_ = 0;
  timer_.Start(FROM_HERE, base::TimeDelta::FromMilliseconds(kCapturingPeriodMs),
               this, &AudioPipeReader::DoCapture);
}

void AudioPipeReader::DoCapture() {
  DCHECK(task_runner_->BelongsToCurrentThread());
  DCHECK_GT(pipe_fd_, 0);

  // Calculate how much we need read from the pipe. Pulseaudio doesn't control
  // how much data it writes to the pipe, so we need to pace the stream, so
  // that we read the exact number of the samples per second we need.
  base::TimeDelta stream_position = base::TimeTicks::Now() - started_time_;
  int64 stream_position_samples = stream_position.InMilliseconds() *
      kSamplingRate / base::Time::kMillisecondsPerSecond;
  int64 samples_to_capture =
      stream_position_samples - last_capture_samples_;
  last_capture_samples_ = stream_position_samples;
  int64 read_size =
      samples_to_capture * kChannels * kBytesPerSample;

  std::string data = left_over_bytes_;
  int pos = data.size();
  left_over_bytes_.clear();
  data.resize(read_size);

  while (pos < read_size) {
    int read_result = HANDLE_EINTR(
       read(pipe_fd_, string_as_array(&data) + pos, read_size - pos));
    if (read_result >= 0) {
      pos += read_result;
    } else {
      if (errno != EWOULDBLOCK && errno != EAGAIN)
        PLOG(ERROR) << "read";
      break;
    }
  }

  if (pos == 0) {
    WaitForPipeReadable();
    return;
  }

  // Save any incomplete samples we've read for later. Each packet should
  // contain integer number of samples.
  int incomplete_samples_bytes = pos % (kChannels * kBytesPerSample);
  left_over_bytes_.assign(data, pos - incomplete_samples_bytes,
                          incomplete_samples_bytes);
  data.resize(pos - incomplete_samples_bytes);

  if (IsPacketOfSilence(data))
    return;

  // Dispatch asynchronous notification to the stream observers.
  scoped_refptr<base::RefCountedString> data_ref =
      base::RefCountedString::TakeString(&data);
  observers_->Notify(&StreamObserver::OnDataRead, data_ref);
}

void AudioPipeReader::WaitForPipeReadable() {
  timer_.Stop();
  MessageLoopForIO::current()->WatchFileDescriptor(
      pipe_fd_, false, MessageLoopForIO::WATCH_READ,
      &file_descriptor_watcher_, this);
}

// static
void AudioPipeReaderTraits::Destruct(const AudioPipeReader* audio_pipe_reader) {
  audio_pipe_reader->task_runner_->DeleteSoon(FROM_HERE, audio_pipe_reader);
}

}  // namespace remoting


text:
package com.microsoft.azure.management.kusto.v2020_02_15;

import java.util.Collection;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.microsoft.rest.ExpandableStringEnum;

/**
 * Defines values for PrincipalType.
 */
public final class PrincipalType extends ExpandableStringEnum<PrincipalType> {
    /** Static value App for PrincipalType. */
    public static final PrincipalType APP = fromString("App");

    /** Static value Group for PrincipalType. */
    public static final PrincipalType GROUP = fromString("Group");

    /** Static value User for PrincipalType. */
    public static final PrincipalType USER = fromString("User");

    /**
     * Creates or finds a PrincipalType from its string representation.
     * @param name a name to look for
     * @return the corresponding PrincipalType
     */
    @JsonCreator
    public static PrincipalType fromString(String name) {
        return fromString(name, PrincipalType.class);
    }

    /**
     * @return known PrincipalType values
     */
    public static Collection<PrincipalType> values() {
        return values(PrincipalType.class);
    }
}


text:
import { Pipe, PipeTransform } from '@angular/core';

import { SkyDateRangeCalculatorType } from './types/date-range-calculator-type';

@Pipe({
  name: 'skyDateRangePickerEndDateResourceKey',
})
export class SkyDateRangePickerEndDateResourceKeyPipe implements PipeTransform {
  public transform(
    calculatorType: SkyDateRangeCalculatorType | undefined
  ): string {
    if (calculatorType === SkyDateRangeCalculatorType.Range) {
      return 'skyux_date_range_picker_end_date_label';
    }

    return 'skyux_date_range_picker_before_date_label';
  }
}


text:
docker pull ascensao/uniplaces-data-science

docker run  --volume `pwd`/notebooks:/project/notebooks  --volume `pwd`/config/.env:/project/notebooks/.env  --workdir /project/notebooks -it --rm -p 127.0.0.1:8888:8888 ascensao/uniplaces-data-science:latest


text:
<!DOCTYPE html>

        <title>Bootstrap 101 Template</title>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0">

        <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" />
        <link href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet">

        <link rel="stylesheet" href="custom.css">

                    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                        Toggle navigation

                    </button>
                    Jobs Framework

Discover

Teams

Jobs

Contact

Sign In

Sign Up

System Administrator - BSD/Linux

Full Time

                                        Our Data Centre Operations team is seeking a technology guru to help us maintain our multi-datacentre network infrastructure. Are you ready to tackle some of the leading software and system issues to ensure a smooth user-experience for our 45 million visitors using trivago every months? In this critical position you will tap into your in-depth knowledge of both networking best practices and security flaws to protect trivago against attack and vulnerabilities. You'll be working with top notch network equipment, systems and tools to keep our labs humming smoothly at all times. Our Data Centre Operations team is seeking a technology guru to help us maintain our multi-datacentre network infrastructure. Our Data Centre Operations team is seeking a technology guru to help us maintain our multi-datacentre network infrastructure.

Other Opportunities At Mondo Robot

                                        Web Developer - PHP & JavaScript
                                        Frontend Developer
                                        PHP Developer

                                        <button class="btn btn-lg btn-primary" type="button">Learn More</button>
                                        View Amazing Jobs

Mondo Robot

                                        Follow

                                    Come build great software with us
                                    VIEW JOBS

To be the traveler's first and independent source of information for finding the ideal hotel at the lowest rates.

                                            Koala Bear
                                            Developer

                                            Koala Bear
                                            Developer

                                            Koala Bear
                                            Developer

                                            Koala Bear
                                            Developer

                                            Koala Bear
                                            Developer

                                            Koala Bear
                                            Developer

Koala Bear

Chaot. Developer. OpenSource-Fan. Loves his life. Lives his life. What about you?

                                                    View Profile

                                    Rapid feature development for a high traffic website in a quickly evolving code base. Success is dependent on finding the right balance of architecture and speed and the right mixture of technologies for the job.

Discover

Teams

Jobs

Contact

Privacy Policy

Terms of Service

Copyright © 2014 Coder Wall. All rights reserved.


text:
<?php

?>
<?php include $app->getModuleRoot() . 'common/view/header.html.php';?>
<?php include '../../common/view/kindeditor.html.php';?>
<?php include '../../common/view/datepicker.html.php';?>
<?php include '../../common/view/chosen.html.php';?>
<?php $this->loadModel('project')->setMenu($projects, $projectID);?>

  <form method='post' id='ajaxForm' enctype='multipart/form-data' action="<?php echo $this->createLink('task', 'create', "projectID=$projectID")?>">

<?php echo $lang->task->create;?>

              <?php echo $lang->task->name?>

                  <?php echo html::input('name', '', "class='form-control'");?>
                  <?php echo $lang->task->pri;?>
                  <?php echo html::select('pri', $lang->task->priList, '', "class='form-control'")?>

              <?php echo $lang->task->assignedTo;?>

                  <?php echo html::select('assignedTo', $members, '', "class='form-control chosen'");?>
                  <?php echo html::input('teamMember', '', "class='form-control team-group hidden' readonly='readonly'");?>

                  <?php echo html::a("#modalTeam", $lang->task->team, "class='form-control btn team-group hidden' data-toggle='modal' data-target='#modalTeam'");?>

                      <input type='checkBox' name='multiple' value='1'/>
                      <?php echo $lang->task->multipleAB;?>

              <?php echo $lang->task->estimate;?>

                  <?php echo html::input('estimate', '', "class='form-control'")?>
                  <?php echo $lang->task->deadline;?>
                  <?php echo html::input('deadline', '', "class='form-control form-date'");?>

              <?php echo $lang->task->desc?>
              <?php echo html::textarea('desc', '', "class='form-control'");?>

              <?php echo $lang->task->mailto;?>
              <?php echo html::select('mailto[]', $users, '', "class='form-control chosen' multiple data-placeholder='{$lang->task->mailtoPlaceholder}'");?>

              <?php echo $lang->files;?>
              <?php echo $this->fetch('file', 'buildForm')?>

              <?php echo html::submitButton();?>

          <button type='button' class='close' data-dismiss='modal'>×关闭</button>

<?php echo $lang->task->team?>

            <?php for($i = 0; $i < 6; $i++):?>

              <?php echo html::select("team[]", $members, '', "class='form-control chosen'")?>

                  <?php echo html::input("teamEstimate[]", '', "class='form-control text-center' placeholder='{$lang->task->estimateAB}'")?>
                  <?php echo $lang->task->hour?>

            <?php endfor;?>

<?php echo html::a('javascript:void(0)', $lang->confirm, "class='btn btn-primary' data-dismiss='modal'")?>

  </form>

<?php include $app->getModuleRoot() . 'common/view/footer.html.php';?>


text:
'''
'''

__docformat__ = 'restructuredtext'
__version__ = '$Id$'

import os
import select
import threading
from ctypes import *

from pyglet import app
from pyglet.app.base import PlatformEventLoop

class XlibSelectDevice(object):
    def fileno(self):
        '''Get the file handle for ``select()`` for this device.

        :rtype: int
        '''
        raise NotImplementedError('abstract')

    def select(self):
        '''Perform event processing on the device.

        Called when ``select()`` returns this device in its list of active
        files.
        '''
        raise NotImplementedError('abstract')

    def poll(self):
        '''Check if the device has events ready to process.

        :rtype: bool
        :return: True if there are events to process, False otherwise.
        '''
        return False

class NotificationDevice(XlibSelectDevice):
    def __init__(self):
        self._sync_file_read, self._sync_file_write = os.pipe()
        self._event = threading.Event()

    def fileno(self):
        return self._sync_file_read

    def set(self):
        self._event.set()
        os.write(self._sync_file_write, '1')

    def select(self):
        self._event.clear()
        app.platform_event_loop.dispatch_posted_events()

    def poll(self):
        return self._event.isSet()

class XlibEventLoop(PlatformEventLoop):
    def __init__(self):
        super(XlibEventLoop, self).__init__()
        self._notification_device = NotificationDevice()
        self._select_devices = set()
        self._select_devices.add(self._notification_device)

    def notify(self):
        self._notification_device.set()

    def step(self, timeout=None):
        pending_devices = []

        # Check for already pending events
        for device in self._select_devices:
            if device.poll():
                pending_devices.append(device)

        # If nothing was immediately pending, block until there's activity
        # on a device.
        if not pending_devices and (timeout is None or not timeout):
            iwtd = self._select_devices
            pending_devices, _, _ = select.select(iwtd, (), (), timeout)

        if not pending_devices:
            return False

        # Dispatch activity on matching devices
        for device in pending_devices:
            device.select()

        # Dispatch resize events
        for window in app.windows:
            if window._needs_resize:
                window.switch_to()
                window.dispatch_event('on_resize',
                                      window._width, window._height)
                window.dispatch_event('on_expose')
                window._needs_resize = False

        return True


text:
package edu.upc.eetac.dsa.rnuevo.libros.api;

import javax.ws.rs.GET;
import javax.ws.rs.Path;

import edu.upc.eetac.dsa.rnuevo.libros.api.model.LibrosRootAPI;

@Path("/")
public class LibrosRootAPIResource {
	@GET
	public LibrosRootAPI getRootAPI() {
		LibrosRootAPI api = new LibrosRootAPI();
		return api;
	}
}


text:
var tap = require("tap")
  , BlockStream = require("../block-stream.js")

tap.test("basic test", function (t) {
  var b = new BlockStream(16)
  var fs = require("fs")
  var fstr = fs.createReadStream(__filename, {encoding: "utf8"})
  fstr.pipe(b)

  var stat
  t.doesNotThrow(function () {
    stat = fs.statSync(__filename)
  }, "stat should not throw")

  var totalBytes = 0
  b.on("data", function (c) {
    t.equal(c.length, 16, "chunks should be 16 bytes long")
    t.type(c, Buffer, "chunks should be buffer objects")
    totalBytes += c.length
  })
  b.on("end", function () {
    var expectedBytes = stat.size + (16 - stat.size % 16)
    t.equal(totalBytes, expectedBytes, "Should be multiple of 16")
    t.end()
  })

})


text:
/*	$NetBSD: altq_flowvalve.h,v 1.3 2006/10/12 19:59:08 peter Exp $	*/
/*	$KAME: altq_flowvalve.h,v 1.5 2002/04/03 05:38:50 kjc Exp $	*/

/*
 * Copyright (C) 1998-2002
 *	Sony Computer Science Laboratories Inc.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. 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.
 *
 * THIS SOFTWARE IS PROVIDED BY SONY CSL 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 SONY CSL 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.
 */

#ifndef _ALTQ_ALTQ_FLOWVALVE_H_
#define	_ALTQ_ALTQ_FLOWVALVE_H_

#ifdef _KERNEL

/* fv_flow structure to define a unique address pair */
struct fv_flow {
	int flow_af;		/* address family */
	union {
		struct {
			struct in_addr ip_src;
			struct in_addr ip_dst;
		} _ip;
#ifdef INET6
		struct {
			struct in6_addr ip6_src;
			struct in6_addr ip6_dst;
		} _ip6;
#endif
	} flow_un;
};

#define	flow_ip		flow_un._ip
#define	flow_ip6	flow_un._ip6

/* flowvalve entry */
struct fve {
	TAILQ_ENTRY(fve) fve_lru;	/* for LRU list */

	enum fv_state { Green, Red } fve_state;

	int	fve_p;			/* scaled average drop rate */
	int	fve_f;			/* scaled average fraction */
	int	fve_count;		/* counter to update f */
	u_int	fve_ifseq;		/* ifseq at the last update of f */
	struct timeval	fve_lastdrop;	/* timestamp of the last drop */

	struct fv_flow fve_flow;	/* unique address pair */
};

/* flowvalve structure */
struct flowvalve {
	u_int	fv_ifseq;	/* packet sequence number */
	int	fv_flows;	/* number of valid flows in the flowlist */
	int	fv_pthresh;	/* drop rate threshold */

	TAILQ_HEAD(fv_flowhead, fve) fv_flowlist;		/* LRU list */

	struct fve *fv_fves;	/* pointer to the allocated fves */

	int	*fv_p2ftab;	/* drop rate to fraction table */

	struct {
		u_int	pass;		/* # of packets that have the fve
					   but aren't predropped */
		u_int	predrop;	/* # of packets predropped */
		u_int	alloc;		/* # of fves assigned */
		u_int	escape;		/* # of fves escaped */
	} fv_stats;
};

#endif /* _KERNEL */

#endif /* _ALTQ_ALTQ_FLOWVALVE_H_ */


text:
require(File.dirname(__FILE__) + "/../../config/environment") unless defined?(Rails)

# Serves theme files from the theme directory without touching Rails too much
class ThemeServer

  def initialize(app)
    @app = app
  end

  def call(env)
    if env["PATH_INFO"] =~ /^\/theme/
      env["PATH_INFO"].gsub!(/^\/theme\//, '')
      if (file_path = (dir=Rails.root.join("themes", RefinerySetting[:theme])).join(env["PATH_INFO"])).exist?
        etag = Digest::MD5.hexdigest("#{file_path.to_s}#{file_path.mtime}")
        unless (etag == env["HTTP_IF_NONE_MATCH"])
          status, headers, body = Rack::File.new(dir).call(env)
          [status, headers.update({"ETag" => etag}), body]
        else
          [304, {"ETag" => etag}, []]
        end
      else
        [404, {}, []]
      end
    else
      @app.call(env)
    end
  end

end


text:
package com.touzbi.ansatest.inputfactorytest;

import org.junit.Test;

import com.touzbi.ansa.inputfactory.BasicFileInputFactory;
import com.touzbi.ansa.inputfactory.InputFactory;

public class BasicFileInputFactoryTest {
	private static final String FILE_PATH = "com/touzbi/ansatest/input.cfg";

	@Test
	public void test() {
		InputFactory inputFactory = new BasicFileInputFactory(FILE_PATH, false);
		System.out.println(inputFactory.getInputs());
	}
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Annls mycol. 9(1): 21 (1911)

#### Original name
Phomopsis chionanthi C.C. Chen

### Remarks
null


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Acta Soc. Bot. Pol. 32: 732 (1963)

#### Original name
Polyporus aneirinus Sommerf., 1826

### Remarks
null