text:
package me.hypernatho.messenger;

import lombok.Getter;
import me.hypernatho.messenger.commands.admin.Spy;
import me.hypernatho.messenger.commands.player.Message;
import me.hypernatho.messenger.commands.player.Reply;
import me.hypernatho.messenger.listeners.Join;
import me.hypernatho.messenger.listeners.Quit;
import me.hypernatho.messenger.objects.Cooldown;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Properties;

public class Messenger extends JavaPlugin {

    public static Messenger getInstance() {
        return (Messenger) Bukkit.getPluginManager().getPlugin("Messenger");
    }

    @Getter public static Properties properties = new Properties();

    @Getter public static List<Player> spies = new ArrayList<Player>();
    @Getter public static HashMap<String, String> recent = new HashMap<String, String>();
    @Getter public static HashMap<String, Cooldown> cooldowns = new HashMap<String, Cooldown>();

    @Override
    public void onEnable() {
        {
            if (!getDataFolder().exists()) {
                getDataFolder().mkdir();
            }

            if (!new File(getDataFolder(), "messages.properties").exists()) {
                saveResource("messages.properties", false);
            }

            try {
                properties.load(new FileInputStream(getDataFolder() + File.separator + "messages.properties"));
            } catch (IOException e) {
                Bukkit.getConsoleSender().sendMessage("§cUnable to access messages file! Aborting plugin startup!");

                return;
            }

            if (!new File(getDataFolder(), "config.yml").exists()) {
                saveDefaultConfig();
            }
        }
        {
            getCommand("message").setExecutor(new Message());
            getCommand("reply").setExecutor(new Reply());
            getCommand("spy").setExecutor(new Spy());
        }
        {
            PluginManager pm = Bukkit.getPluginManager();
            pm.registerEvents(new Join(), this);
            pm.registerEvents(new Quit(), this);
        }
    }

    @Override
    public void onDisable() {
        List<String> list = getConfig().getStringList("spies");

        for (Player spy : spies) {
            list.add(spy.getUniqueId().toString());
        }

        getConfig().set("spies", list);
        saveConfig();
    }
}


text:
var logger = require('pomelo-logger').getLogger(__filename);
var utils = require('../util/utils');

var playerUnitDao = module.exports;

/**
 * Get an user's all players by userId
 * @param {String} mysqlc mysql client for Master DB or Slave DB
 * @param {Number} uid User Id.
 * @param {function} cb Callback function.
 */
playerUnitDao.get = function(mysqlc, playerId, cb) {
	var selectSQL = 'select * from player_unit where player_id=?';
	var args = [playerId];

	mysqlc.query(selectSQL, args, function(err, res) {
		if(err) {
			utils.invokeCallback(cb, err, null);
		}
    else {
  		if(!!res && res.length > 0) { //exists
	  		utils.invokeCallback(cb, null, res);
		  } else {
			  utils.invokeCallback(cb, null, []);
		  }
    }
	});
};

playerUnitDao.add = function(mysqlc, playerId, positionId, playerCardId, cb) {
  var insertSQL =
    'insert into player_unit(player_id, position_id, player_card_id, created_on, updated_on) values (?,?,?, ?,?)';
  var createdOn = Math.round(new Date().getTime()/1000); //unixtime
  var args = [playerId, positionId, playerCardId, createdOn, createdOn];
  console.log(playerId, positionId, playerCardId, createdOn, createdOn);

  mysqlc.query(insertSQL, args, function(err, res) {
    if (err !== null) {
			utils.invokeCallback(cb, err.message, null);
    }
    else {
      if (!!res && res.affectedRows > 0) {
        utils.invokeCallback(cb, null, true);
      }
      else {
        logger.error('add player_unit Failed!');
        utils.invokeCallback(cb, null, false);
      }
    }
  });
};

/**
 * arm equip
 * @param {Object} mysqlc mysql client reference
 * @param {Number} playerId
 * @param {Number} positionId position_id in player_unit
 * @param {Number} armPosition short for skill1|skill2|weapon|defender|shoe|jewelry
 * @param {Number} id id in player_equip
 * @returns {Boolean}
 */
playerUnitDao.arm = function(mysqlc, playerId, positionId, armPosition, armId, cb) {
  var updateStr;
  var updatedOn = Math.round(new Date().getTime()/1000); //unixtime
  var updateSQL;

  switch (armPosition) {
    case 1:
      updateStr = 'stdskill1_id=?';
      break;
    case 2:
      updateStr = 'stdskill2_id=?';
      break;
    case 3:
      updateStr = 'weapon_id=?';
      break;
    case 4:
      updateStr = 'defender_id=?';
      break;
    case 5:
      updateStr = 'shoe_id=?';
      break;
    case 6:
      updateStr = 'jewelry_id=?';
      break;
  }
  var updateSQL = '';
  if (!!updateStr) {
    updateSQL = 'update player_unit set ' + updateStr + ', updated_on=? where player_id=? and position_id=?';
    var args = [armId, updatedOn, playerId, positionId];
    mysqlc.query(updateSQL, args, function(err, res) {
      if (err !== null) {
  			utils.invokeCallback(cb, err.message, null);
      }
      else {
        if (!!res && res.affectedRows > 0) {
          utils.invokeCallback(cb, null, true);
        }
        else {
          logger.error('arm player_unit Failed!');
          utils.invokeCallback(cb, null, false);
        }
      }
    });
  }
  else {
    logger.error('arm player_unit Failed! Did nothing');
    utils.invokeCallback(cb, null, false);
  }
};

playerUnitDao.delete = function(mysqlc, id, cb) {
  var deleteSQL = 'delete from player_unit where id=?';
  var args = [id];

  mysqlc.query(deleteSQL, args, function(err, res) {
    if (err !== null) {
			utils.invokeCallback(cb, err.message, null);
    }
    else {
      if (!!res && res.affectedRows > 0) {
        utils.invokeCallback(cb, null, true);
      }
      else {
        logger.error('delete player_card Failed!' + id);
        utils.invokeCallback(cb, null, false);
      }
    }
  });
};

redpajama_set_name: RedPajamaGithub


text:
/*
 * Generated by the Jasper component of Apache Tomcat
 * Version: Apache Tomcat/7.0.63
 * Generated at: 2015-08-20 20:27:08 UTC
 * Note: The last modified time of this file was set to
 *       the last modified time of the source file after
 *       generation to assist with modification tracking.
 */
package org.apache.jsp;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;

public final class index_jsp extends org.apache.jasper.runtime.HttpJspBase
    implements org.apache.jasper.runtime.JspSourceDependent {

  private static final javax.servlet.jsp.JspFactory _jspxFactory =
          javax.servlet.jsp.JspFactory.getDefaultFactory();

  private static java.util.Map<java.lang.String,java.lang.Long> _jspx_dependants;

  private javax.el.ExpressionFactory _el_expressionfactory;
  private org.apache.tomcat.InstanceManager _jsp_instancemanager;

  public java.util.Map<java.lang.String,java.lang.Long> getDependants() {
    return _jspx_dependants;
  }

  public void _jspInit() {
    _el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory();
    _jsp_instancemanager = org.apache.jasper.runtime.InstanceManagerFactory.getInstanceManager(getServletConfig());
  }

  public void _jspDestroy() {
  }

  public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response)
        throws java.io.IOException, javax.servlet.ServletException {

    final javax.servlet.jsp.PageContext pageContext;
    final javax.servlet.ServletContext application;
    final javax.servlet.ServletConfig config;
    javax.servlet.jsp.JspWriter out = null;
    final java.lang.Object page = this;
    javax.servlet.jsp.JspWriter _jspx_out = null;
    javax.servlet.jsp.PageContext _jspx_page_context = null;

    try {
      response.setContentType("text/html");
      pageContext = _jspxFactory.getPageContext(this, request, response,
      			null, false, 8192, true);
      _jspx_page_context = pageContext;
      application = pageContext.getServletContext();
      config = pageContext.getServletConfig();
      out = pageContext.getOut();
      _jspx_out = out;

      out.write("\n");
      out.write("<!DOCTYPE html>\n");
      out.write("\n");

java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy");
request.setAttribute("year", sdf.format(new java.util.Date()));
request.setAttribute("tomcatUrl", "http://tomcat.apache.org/");
request.setAttribute("tomcatDocUrl", "/docs/");
request.setAttribute("tomcatExamplesUrl", "/examples/");

      out.write("\n");
      out.write("\n");
      out.write("    \n");
      out.write("        <title>");
      out.print(request.getServletContext().getServerInfo() );
      out.write("</title>\n");
      out.write("        <link href=\"favicon.ico\" rel=\"icon\" type=\"image/x-icon\" />\n");
      out.write("        <link href=\"favicon.ico\" rel=\"shortcut icon\" type=\"image/x-icon\" />\n");
      out.write("        <link href=\"tomcat.css\" rel=\"stylesheet\" type=\"text/css\" />\n");
      out.write("    \n");
      out.write("\n");
      out.write("    \n");
      out.write("
\n");
      out.write("
\n");
      out.write("                Home\n");
      out.write("                Documentation\n");
      out.write("                Configuration\n");
      out.write("                Examples\n");
      out.write("                Wiki\n");
      out.write("                Mailing Lists\n");
      out.write("                Find Help\n");
      out.write("
\n");
      out.write("
\n");
      out.write("
\n");
      out.write("
");
      out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${pageContext.servletContext.serverInfo}", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null, false));
      out.write("
\n");
      out.write("
\n");
      out.write("
\n");
      out.write("
\n");
      out.write("
If you're seeing this, you've successfully installed Tomcat. Congratulations!
\n");
      out.write("
\n");
      out.write("
\n");
      out.write("                    \n");
      out.write("
\n");
      out.write("
Recommended Reading:
\n");
      out.write("
Security Considerations HOW-TO
\n");
      out.write("
Manager Application HOW-TO
\n");
      out.write("
Clustering/Session Replication HOW-TO
\n");
      out.write("
\n");
      out.write("
\n");
      out.write("
\n");
      out.write("
\n");
      out.write("                        Server Status\n");
      out.write("
\n");
      out.write("
\n");
      out.write("                        Manager App\n");
      out.write("
\n");
      out.write("
\n");
      out.write("                        Host Manager\n");
      out.write("
\n");
      out.write("
\n");
      out.write("                \n");
      out.write("
\n");
      out.write("
\n");
      out.write("
\n");
      out.write("
Developer Quick Start
\n");
      out.write("
\n");
      out.write("
\n");
      out.write("
Tomcat Setup
\n");
      out.write("
First Web Application
\n");
      out.write("
\n");
      out.write("
\n");
      out.write("
\n");
      out.write("
\n");
      out.write("
Realms & AAA
\n");
      out.write("
JDBC DataSources
\n");
      out.write("
\n");
      out.write("
\n");
      out.write("
\n");
      out.write("
\n");
      out.write("
Examples
\n");
      out.write("
\n");
      out.write("
\n");
      out.write("
\n");
      out.write("
\n");
      out.write("
Servlet Specifications
\n");
      out.write("
Tomcat Versions
\n");
      out.write("
\n");
      out.write("
\n");
      out.write("
\n");
      out.write("
\n");
      out.write("
\n");
      out.write("
\n");
      out.write("
\n");
      out.write("
Managing Tomcat
\n");
      out.write("
For security, access to the manager webapp is restricted.\n");
      out.write("                        Users are defined in:
\n");
      out.write("
$CATALINA_HOME/conf/tomcat-users.xml
\n");
      out.write("
In Tomcat 7.0 access to the manager application is split between\n");
      out.write("                           different users.   Read more...
\n");
      out.write("
\n");
      out.write("
Release Notes
\n");
      out.write("
Changelog
\n");
      out.write("
Migration Guide
\n");
      out.write("
Security Notices
\n");
      out.write("
\n");
      out.write("
\n");
      out.write("
\n");
      out.write("
\n");
      out.write("
Documentation
\n");
      out.write("
Tomcat 7.0 Documentation
\n");
      out.write("
Tomcat 7.0 Configuration
\n");
      out.write("
Tomcat Wiki
\n");
      out.write("
Find additional important configuration information in:
\n");
      out.write("
$CATALINA_HOME/RUNNING.txt
\n");
      out.write("
Developers may be interested in:
\n");
      out.write("
\n");
      out.write("
Tomcat 7.0 Bug Database
\n");
      out.write("
Tomcat 7.0 JavaDocs
\n");
      out.write("
Tomcat 7.0 SVN Repository
\n");
      out.write("
\n");
      out.write("
\n");
      out.write("
\n");
      out.write("
\n");
      out.write("
\n");
      out.write("
Getting Help
\n");
      out.write("
FAQ and Mailing Lists
\n");
      out.write("
The following mailing lists are available:
\n");
      out.write("
\n");
      out.write("
tomcat-announce
\n");
      out.write("                                Important announcements, releases, security vulnerability notifications. (Low volume).\n");
      out.write("
\n");
      out.write("
tomcat-users
\n");
      out.write("                                User support and discussion\n");
      out.write("
\n");
      out.write("
taglibs-user
\n");
      out.write("                                User support and discussion for Apache Taglibs\n");
      out.write("
\n");
      out.write("
tomcat-dev
\n");
      out.write("                                Development mailing list, including commit messages\n");
      out.write("
\n");
      out.write("
\n");
      out.write("
\n");
      out.write("
\n");
      out.write("
\n");
      out.write("
\n");
      out.write("
\n");
      out.write("
\n");
      out.write("
\n");
      out.write("
Other Downloads
\n");
      out.write("
\n");
      out.write("
Tomcat Connectors
\n");
      out.write("
Tomcat Native
\n");
      out.write("
Taglibs
\n");
      out.write("
Deployer
\n");
      out.write("
\n");
      out.write("
\n");
      out.write("
\n");
      out.write("
\n");
      out.write("
\n");
      out.write("
Other Documentation
\n");
      out.write("
\n");
      out.write("
Tomcat Connectors
\n");
      out.write("
mod_jk Documentation
\n");
      out.write("
Tomcat Native
\n");
      out.write("
Deployer
\n");
      out.write("
\n");
      out.write("
\n");
      out.write("
\n");
      out.write("
\n");
      out.write("
\n");
      out.write("
Get Involved
\n");
      out.write("
\n");
      out.write("
Overview
\n");
      out.write("
SVN Repositories
\n");
      out.write("
Mailing Lists
\n");
      out.write("
Wiki
\n");
      out.write("
\n");
      out.write("
\n");
      out.write("
\n");
      out.write("
\n");
      out.write("
\n");
      out.write("
Miscellaneous
\n");
      out.write("
\n");
      out.write("
Contact
\n");
      out.write("
Legal
\n");
      out.write("
Sponsorship
\n");
      out.write("
Thanks
\n");
      out.write("
\n");
      out.write("
\n");
      out.write("
\n");
      out.write("
\n");
      out.write("
\n");
      out.write("
Apache Software Foundation
\n");
      out.write("
\n");
      out.write("
Who We Are
\n");
      out.write("
Heritage
\n");
      out.write("
Apache Home
\n");
      out.write("
Resources
\n");
      out.write("
\n");
      out.write("
\n");
      out.write("
\n");
      out.write("
\n");
      out.write("
\n");
      out.write("
Copyright ©1999-");
      out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${year}", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null, false));
      out.write(" Apache Software Foundation.  All Rights Reserved
\n");
      out.write("
\n");
      out.write("    \n");
      out.write("\n");
      out.write("\n");
    } catch (java.lang.Throwable t) {
      if (!(t instanceof javax.servlet.jsp.SkipPageException)){
        out = _jspx_out;
        if (out != null && out.getBufferSize() != 0)
          try {
            if (response.isCommitted()) {
              out.flush();
            } else {
              out.clearBuffer();
            }
          } catch (java.io.IOException e) {}
        if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
        else throw new ServletException(t);
      }
    } finally {
      _jspxFactory.releasePageContext(_jspx_page_context);
    }
  }
}


text:
package synthetic

import (
	"encoding/hex"
	"fmt"
	"testing"
)

// TestSourceConfig_NumElements tests that setting the number of produced
// elements for a synthetic source works correctly.
func TestSourceConfig_NumElements(t *testing.T) {
	tests := []struct {
		elms int
		want int
	}{
		{elms: 1, want: 1},
		{elms: 42, want: 42},
	}
	for _, test := range tests {
		test := test
		t.Run(fmt.Sprintf("(elm = %v)", test.elms), func(t *testing.T) {
			dfn := sourceFn{}
			cfg := DefaultSourceConfig().NumElements(test.elms).Build()

			keys, _, err := simulateSourceFn(t, &dfn, cfg)
			if err != nil {
				t.Errorf("Failure processing sourceFn: %v", err)
			}
			if got := len(keys); got != test.want {
				t.Errorf("SourceFn emitted wrong number of outputs: got: %v, want: %v",
					got, test.want)
			}
		})
	}
}

// TestSourceConfig_KeyValueSize tests that setting the size of the key and the
// value works correctly.
func TestSourceConfig_KeyValueSize(t *testing.T) {
	tests := []struct {
		size int
		want int
	}{
		{size: 1, want: 1},
		{size: 42, want: 42},
	}
	for _, test := range tests {
		test := test
		t.Run(fmt.Sprintf("(size = %v)", test.size), func(t *testing.T) {
			dfn := sourceFn{}
			cfg := DefaultSourceConfig().KeySize(test.size).ValueSize(test.size).Build()

			keys, values, err := simulateSourceFn(t, &dfn, cfg)
			if err != nil {
				t.Errorf("Failure processing sourceFn: %v", err)
			}
			if got := len(keys[0]); got != test.want {
				t.Errorf("SourceFn emitted keys of wrong size: got: %v, want: %v",
					got, test.want)
			}
			if got := len(values[0]); got != test.want {
				t.Errorf("SourceFn emitted values of wrong size: got: %v, want: %v",
					got, test.want)
			}
		})
	}
}

// TestSourceConfig_InitialSplits tests that the InitialSplits config option
// works correctly.
func TestSourceConfig_InitialSplits(t *testing.T) {
	// Test that SplitRestriction creates the expected number of restrictions.
	t.Run("NumSplits", func(t *testing.T) {
		tests := []struct {
			elms   int
			splits int
			want   int
		}{
			{elms: 42, splits: 10, want: 10},
			{elms: 4, splits: 10, want: 4},
		}
		for _, test := range tests {
			test := test
			t.Run(fmt.Sprintf("(elm = %v, splits = %v)", test.elms, test.splits), func(t *testing.T) {
				dfn := sourceFn{}
				cfg := DefaultSourceConfig().NumElements(test.elms).InitialSplits(test.splits).Build()

				rest := dfn.CreateInitialRestriction(cfg)
				splits := dfn.SplitRestriction(cfg, rest)
				if got := len(splits); got != test.want {
					t.Errorf("SplitRestriction output the wrong number of splits: got: %v, want: %v",
						got, test.want)
				}
			})
		}
	})

	// Tests correctness of the splitting. In this case, that means that even
	// after splitting, the same amount of elements are output.
	t.Run("Correctness", func(t *testing.T) {
		tests := []struct {
			elms   int
			want   int
			splits int
		}{
			{elms: 42, want: 42, splits: 10},
			{elms: 4, want: 4, splits: 10},
		}
		for _, test := range tests {
			test := test
			t.Run(fmt.Sprintf("(elm = %v)", test.elms), func(t *testing.T) {
				dfn := sourceFn{}
				cfg := DefaultSourceConfig().NumElements(test.elms).InitialSplits(test.splits).Build()

				keys, _, err := simulateSourceFn(t, &dfn, cfg)
				if err != nil {
					t.Errorf("Failure processing sourceFn: %v", err)
				}
				if got := len(keys); got != test.want {
					t.Errorf("SourceFn emitted wrong number of outputs: got: %v, want: %v",
						got, test.want)
				}
			})
		}
	})
}

// TestSourceConfig_BuildFromJSON tests correctness of building the
// SourceConfig from JSON data.
func TestSourceConfig_BuildFromJSON(t *testing.T) {
	tests := []struct {
		jsonData string
		want     SourceConfig
	}{
		{
			jsonData: "{\"num_records\": 5, \"key_size\": 2, \"value_size\": 3}",
			want:     DefaultSourceConfig().NumElements(5).KeySize(2).ValueSize(3).Build(),
		},
	}
	for _, test := range tests {
		test := test
		t.Run(fmt.Sprintf("(jsonData = %v)", test.jsonData), func(t *testing.T) {
			got := DefaultSourceConfig().BuildFromJSON([]byte(test.jsonData))
			if got != test.want {
				t.Errorf("Invalid SourceConfig: got: %#v, want: %#v", got, test.want)
			}
		})
	}
}

// TestSourceConfig_NumHotKeys tests that setting the number of hot keys
// for a synthetic source works correctly.
func TestSourceConfigBuilder_NumHotKeys(t *testing.T) {
	tests := []struct {
		elms    int
		hotKeys int
	}{
		{elms: 15, hotKeys: 2},
		{elms: 30, hotKeys: 10},
		{elms: 50, hotKeys: 25},
	}
	for _, test := range tests {
		test := test
		t.Run(fmt.Sprintf("(elm = %v)", test.hotKeys), func(t *testing.T) {
			dfn := sourceFn{}
			cfg := DefaultSourceConfig()
			cfg.NumElements(test.elms)
			cfg.HotKeyFraction(1.0)
			cfg.NumHotKeys(test.hotKeys)

			keys, _, err := simulateSourceFn(t, &dfn, cfg.Build())
			if err != nil {
				t.Errorf("Failure processing sourceFn: %v", err)
			}

			m := make(map[string]int)
			for _, key := range keys {
				encoded := hex.EncodeToString(key)
				m[encoded]++
			}

			numOfHotKeys := 0
			for _, element := range m {
				if element > 1 {
					numOfHotKeys += 1
				}
			}

			if numOfHotKeys != test.hotKeys {
				t.Errorf("SourceFn emitted wrong number of hot keys: got: %v, want: %v",
					numOfHotKeys, test.hotKeys)
			}
		})
	}
}

// simulateSourceFn calls CreateInitialRestriction, SplitRestriction,
// CreateTracker, and ProcessElement on the given sourceFn with the given
// SourceConfig, and outputs the resulting output elements. This method isn't
// expected to accurately reflect how SDFs are executed in practice (that
// should be done via integration tests), but to validate the implementations of
// those methods.
func simulateSourceFn(t *testing.T, dfn *sourceFn, cfg SourceConfig) (keys [][]byte, vals [][]byte, err error) {
	t.Helper()

	emitFn := func(key []byte, val []byte) {
		keys = append(keys, key)
		vals = append(vals, key)
	}

	rest := dfn.CreateInitialRestriction(cfg)
	splits := dfn.SplitRestriction(cfg, rest)
	dfn.Setup()
	for _, split := range splits {
		rt := dfn.CreateTracker(split)
		if err := dfn.ProcessElement(rt, cfg, emitFn); err != nil {
			return nil, nil, err
		}
	}
	return keys, vals, nil
}


text:
/**
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.aurora.scheduler.preemptor;

import com.google.common.collect.HashMultimap;
import com.google.common.collect.ImmutableMultimap;

import org.apache.aurora.gen.AssignedTask;
import org.apache.aurora.gen.JobKey;
import org.apache.aurora.gen.ScheduleStatus;
import org.apache.aurora.gen.ScheduledTask;
import org.apache.aurora.gen.TaskConfig;
import org.apache.aurora.scheduler.events.PubsubEvent.TaskStateChange;
import org.apache.aurora.scheduler.storage.entities.IAssignedTask;
import org.apache.aurora.scheduler.storage.entities.IScheduledTask;
import org.junit.Before;
import org.junit.Test;

import static org.apache.aurora.gen.ScheduleStatus.ASSIGNED;
import static org.apache.aurora.gen.ScheduleStatus.FAILED;
import static org.apache.aurora.gen.ScheduleStatus.FINISHED;
import static org.apache.aurora.gen.ScheduleStatus.KILLED;
import static org.apache.aurora.gen.ScheduleStatus.KILLING;
import static org.apache.aurora.gen.ScheduleStatus.PENDING;
import static org.apache.aurora.gen.ScheduleStatus.RUNNING;
import static org.apache.aurora.gen.ScheduleStatus.THROTTLED;
import static org.junit.Assert.assertEquals;

public class ClusterStateImplTest {

  private ClusterStateImpl state;

  @Before
  public void setUp() {
    state = new ClusterStateImpl();
  }

  @Test(expected = UnsupportedOperationException.class)
  public void testImmutable() {
    state.getSlavesToActiveTasks().clear();
  }

  @Test
  public void testTaskLifecycle() {
    IAssignedTask a = makeTask("a", "s1");

    assertVictims();
    changeState(a, THROTTLED);
    assertVictims();
    changeState(a, PENDING);
    assertVictims();
    changeState(a, ASSIGNED);
    assertVictims(a);
    changeState(a, RUNNING);
    assertVictims(a);
    changeState(a, KILLING);
    assertVictims(a);
    changeState(a, FINISHED);
    assertVictims();
  }

  @Test
  public void testTaskChangesSlaves() {
    // We do not intend to handle the case of an external failure leading to the same task ID
    // on a different slave.
    IAssignedTask a = makeTask("a", "s1");
    IAssignedTask a1 = makeTask("a", "s2");
    changeState(a, RUNNING);
    changeState(a1, RUNNING);
    assertVictims(a, a1);
  }

  @Test
  public void testMultipleTasks() {
    IAssignedTask a = makeTask("a", "s1");
    IAssignedTask b = makeTask("b", "s1");
    IAssignedTask c = makeTask("c", "s2");
    IAssignedTask d = makeTask("d", "s3");
    IAssignedTask e = makeTask("e", "s3");
    IAssignedTask f = makeTask("f", "s1");
    changeState(a, RUNNING);
    assertVictims(a);
    changeState(b, RUNNING);
    assertVictims(a, b);
    changeState(c, RUNNING);
    assertVictims(a, b, c);
    changeState(d, RUNNING);
    assertVictims(a, b, c, d);
    changeState(e, RUNNING);
    assertVictims(a, b, c, d, e);
    changeState(c, FINISHED);
    assertVictims(a, b, d, e);
    changeState(a, FAILED);
    changeState(e, KILLED);
    assertVictims(b, d);
    changeState(f, RUNNING);
    assertVictims(b, d, f);
  }

  private void assertVictims(IAssignedTask... tasks) {
    ImmutableMultimap.Builder<String, PreemptionVictim> victims = ImmutableMultimap.builder();
    for (IAssignedTask task : tasks) {
      victims.put(task.getSlaveId(), PreemptionVictim.fromTask(task));
    }
    assertEquals(HashMultimap.create(victims.build()), state.getSlavesToActiveTasks());
  }

  private IAssignedTask makeTask(String taskId, String slaveId) {
    return IAssignedTask.build(new AssignedTask()
        .setTaskId(taskId)
        .setSlaveId(slaveId)
        .setSlaveHost(slaveId + "host")
        .setTask(new TaskConfig().setJob(new JobKey("role", "env", "job"))));
  }

  private void changeState(IAssignedTask assignedTask, ScheduleStatus status) {
    IScheduledTask task = IScheduledTask.build(new ScheduledTask()
        .setStatus(status)
        .setAssignedTask(assignedTask.newBuilder()));
    state.taskChangedState(TaskStateChange.transition(task, ScheduleStatus.INIT));
  }
}


text:
package org.dozer.vo.inheritance.cc;

public class Z extends Y {

}


text:
from django.contrib import admin

from .models import Team, Request

@admin.register(Team)
class TeamAdmin(admin.ModelAdmin):
    model = Team
    filter_horizontal = ('members',)

@admin.register(Request)
class RequestAdmin(admin.ModelAdmin):
    model = Request


text:
import gtk
import gtk.gdk
import apxdot
import AssumptionNodeDialogFactory
import os
from cairis.core.ARM import *
from cairis.core.Borg import Borg

__author__ = 'Shamal Faily'

class APModelViewer(apxdot.APDotWindow):
  def __init__(self,pName = '',bvName = ''):
    apxdot.APDotWindow.__init__(self)
    b = Borg()
    self.dbProxy = b.dbProxy
    self.theInitialPersona = pName
    self.theInitialBv = bvName
    self.widget.connect('clicked', self.on_url_clicked)

    self.set_icon_from_file(b.iconDir + '/apModel.png')

  def on_url_clicked(self, widget, url, event):
    self.url = url
    urlElements = url.split('#')
    if (urlElements[0] != 'link'):
      dialog = AssumptionNodeDialogFactory.build(url)
    return True

  def ShowModal(self, associations):
    self.updateModel(associations)
    self.connect('destroy', gtk.main_quit)
    self.set_modal(True)
    gtk.main()

  def updateModel(self,associations):
    self.canonicalModel = associations
    try:
      xdotcode = self.canonicalModel.graph()

      personaNames = self.dbProxy.getDimensionNames('persona')
      bvNames = self.dbProxy.getDimensionNames('behavioural_variable')
      charNames = self.canonicalModel.personaCharacteristics

      self.loadFilters(personaNames,bvNames,charNames)
      self.set_xdotcode(xdotcode)
      self.widget.zoom_to_fit()
    except ARMException,errorText:
      print str(errorText)
#      dlg = wx.MessageDialog(self,str(errorText),'IRIS',wx.OK | wx.ICON_ERROR)
#      dlg.ShowModal()
#      dlg.Destroy()
#      return


text:
require 'spec_helper'

describe Item do
	# do something
end


text:
interface ICollectionOpts {}

export = ICollectionOpts;


text:
/**
 * @author Hugo Beilis
 * @author Leonardo Soler
 * @author Gabriel Miretti
 * @version 1.0
 */
package org.apache.harmony.jndi.tests.javax.naming.ldap;

import java.io.IOException;
import java.io.Serializable;
import java.util.Arrays;
import javax.naming.ldap.PagedResultsResponseControl;
import junit.framework.TestCase;
import org.apache.harmony.testframework.serialization.SerializationTest;
import org.apache.harmony.testframework.serialization.SerializationTest.SerializableAssert;

/**
 *
This Test class is testing the PagedResultsControls class.

 *
In the next tables we are going to see the methods that we test in this class:

 *

Constructors:

			<input class="a0" size="30" name="sas9nt11" readonly="readonly" value="" id="f00">
			<input class="a0" size="60" name="sas9nt21" readonly="readonly" value="PagedResultsResponseControl(String id, boolean criticality, byte[] value)" id="f10">

Method Summary:

Return	Method

			<input class="a0" size="30" name="sas9nt11" readonly="readonly" value="int" id="f00">
			<input class="a0" size="65" name="sas9nt21" readonly="readonly" value="getResultSize()" id="f10">

			<input class="a0" size="30" name="sas9nt11" readonly="readonly" value="byte[]" id="f00">
			<input class="a0" size="65" name="sas9nt21" readonly="readonly" value="getCookie()" id="f10">

 *
 */
public class TestPagedResultsResponseControl extends TestCase {

	/**
	 *
This method is not implemted.

	 * @param args Possible parameter to help us initiate all tests.
	 */
	public static void main(String[] args) {
	}

	public TestPagedResultsResponseControl(String name) {
		super(name);
	}

	protected void setUp() throws Exception {
		super.setUp();
	}

	protected void tearDown() throws Exception {
		super.tearDown();
	}

	/**
	 *
Test method for 'javax.naming.ldap.PagedResultsResponseControl.PagedResultsResponseControl(String, boolean, byte[])'

	 *
Here we are testing if this method constructs a paged-results response control.

	 *
The expected result is a Nullpointerexception.

	 */
	public void testPagedResultsResponseControl001() {

		try {
			PagedResultsResponseControl x=new PagedResultsResponseControl(null,false,null);
			fail("Arguments can not be null.");
		} catch (NullPointerException e) {

		} catch (IOException e) {
			fail("A null pointer exception must be thrown.");
		}
	}

	/**
	 *
Test method for 'javax.naming.ldap.PagedResultsResponseControl.PagedResultsResponseControl(String, boolean, byte[])'

	 *
Here we are testing if this method constructs a paged-results response control.

	 *
The expected result is a Nullpointerexception.

	 */
	public void testPagedResultsResponseControl002() {

		try {
			PagedResultsResponseControl x=new PagedResultsResponseControl(null,true,null);
			fail("Arguments can not be null.");
		} catch (NullPointerException e) {

		} catch (IOException e) {
			fail("A null pointer exception must be thrown.");
		}
	}

	/**
	 *
Test method for 'javax.naming.ldap.PagedResultsResponseControl.PagedResultsResponseControl(String, boolean, byte[])'

	 *
Here we are testing if this method constructs a paged-results response control.

	 *
The expected result is a IOexception.

	 */
	public void testPagedResultsResponseControl003() {

		try {
			byte[] b={};
			PagedResultsResponseControl x=new PagedResultsResponseControl(null,false,b);
			fail("The byte array must not be empty.");
		} catch (IOException e) {

		}
	}

	/**
	 *
Test method for 'javax.naming.ldap.PagedResultsResponseControl.PagedResultsResponseControl(String, boolean, byte[])'

	 *
Here we are testing if this method constructs a paged-results response control.

	 *
The expected result is a IOexception.

	 */
	public void testPagedResultsResponseControl004() {

		try {
			byte[] b={};
			PagedResultsResponseControl x=new PagedResultsResponseControl(null,true,b);
			fail("The byte array must not be empty.");
		} catch (IOException e) {

		}
	}

	/**
	 *
Test method for 'javax.naming.ldap.PagedResultsResponseControl.PagedResultsResponseControl(String, boolean, byte[])'

	 *
Here we are testing if this method constructs a paged-results response control.

	 *
The expected result is a IOexception.

	 */
	public void testPagedResultsResponseControl005() {

		try {
			byte[] b={1,2,3,4,0};
			PagedResultsResponseControl x=new PagedResultsResponseControl(null,false,b);
			fail("The byte array is not ok.");
		} catch (IOException e) {

		}
	}

	/**
	 *
Test method for 'javax.naming.ldap.PagedResultsResponseControl.PagedResultsResponseControl(String, boolean, byte[])'

	 *
Here we are testing if this method constructs a paged-results response control.

	 *
The expected result is a IOexception.

	 */
	public void testPagedResultsResponseControl006() {

		try {
			byte[] b={1,2,3,4,0};
			PagedResultsResponseControl x=new PagedResultsResponseControl(null,true,b);
			fail("The byte array is not ok.");
		} catch (IOException e) {

		}
	}

	/**
	 *
Test method for 'javax.naming.ldap.PagedResultsResponseControl.PagedResultsResponseControl(String, boolean, byte[])'

	 *
Here we are testing if this method constructs a paged-results response control.

	 *
The expected result is an instance of the class.

	 */
	public void testPagedResultsResponseControl007() {

		try {
			byte[] b={48,5,2,1,0,4,0};
			PagedResultsResponseControl x=new PagedResultsResponseControl(null,true,b);

		} catch (IOException e) {
			fail("The arguments are ok.");
		}
	}

	/**
	 *
Test method for 'javax.naming.ldap.PagedResultsResponseControl.PagedResultsResponseControl(String, boolean, byte[])'

	 *
Here we are testing if this method constructs a paged-results response control.

	 *
The expected result is an instance of the class.

	 */
	public void testPagedResultsResponseControl008() {

		try {
			byte[] b={48,5,2,1,0,4,0};
			PagedResultsResponseControl x=new PagedResultsResponseControl(null,false,b);

		} catch (IOException e) {
			fail("The arguments are ok.");
		}
	}

	/**
	 *
Test method for 'javax.naming.ldap.PagedResultsResponseControl.PagedResultsResponseControl(String, boolean, byte[])'

	 *
Here we are testing if this method constructs a paged-results response control.

	 *
The expected result is an instance of the class.

	 */
	public void testPagedResultsResponseControl010() {

		try {
			byte[] b={48,5,2,1,0,4,0};
			PagedResultsResponseControl x=new PagedResultsResponseControl("",false,b);

		} catch (IOException e) {
			fail("The arguments are ok.");
		}
	}

	/**
	 *
Test method for 'javax.naming.ldap.PagedResultsResponseControl.PagedResultsResponseControl(String, boolean, byte[])'

	 *
Here we are testing if this method constructs a paged-results response control.

	 *
The expected result is that the byte array must be copy not clone so any chance in original affect the response.

	 */
	public void testPagedResultsResponseControl011() {

		try {
			byte[] b={48,5,2,1,0,4,0};
			byte[] c={48,5,2,1,0,4,0};
			PagedResultsResponseControl x=new PagedResultsResponseControl("",false,b);
			byte[] aux = x.getEncodedValue().clone();
			for (int i = 0; i < b.length; i++) {
				b[i]=1;
			}
			for (int i = 0; i < b.length; i++) {
				assertSame(c[i],aux[i]);
				assertSame(b[i],x.getEncodedValue()[i]);
			}
		} catch (IOException e) {
			fail("The arguments are ok.");
		}
	}

	/**
	 *
Test method for 'javax.naming.ldap.PagedResultsResponseControl.getResultSize()'

	 *
Here we are testing if this method retrieves (an estimate of) the number of entries in the search result.

	 *
The expected result is in this case zero.

	 */
	public void testGetResultSize001() {

		byte[] b={48,5,2,1,0,4,0};
		try {
			PagedResultsResponseControl x=new PagedResultsResponseControl("",false,b);
			assertEquals(0,x.getResultSize());
		} catch (IOException e) {
			fail("Failed with:"+e);
		}
	}

	/**
	 *
Test method for 'javax.naming.ldap.PagedResultsResponseControl.getResultSize()'

	 *
Here we are testing if this method retrieves (an estimate of) the number of entries in the search result.

	 *
The expected result is in this case zero.

	 */
	public void testGetResultSize002() {

		byte[] b={48,5,2,1,10,4,0};
		try {
			PagedResultsResponseControl x=new PagedResultsResponseControl("",false,b);
			assertEquals(10,x.getResultSize());
		} catch (IOException e) {
			fail("Failed with:"+e);
		}
	}

	/**
	 *
Test method for 'javax.naming.ldap.PagedResultsResponseControl.getCookie()'

	 *
Here we are testing if this method retrieves the server-generated cookie.

	 *
The expected result in this case is null.

	 */
	public void testGetCookie001() {

		byte[] b={48,5,2,1,0,4,0};
		try {
			PagedResultsResponseControl x=new PagedResultsResponseControl("",false,b);
			assertEquals(null,x.getCookie());
		} catch (IOException e) {
			fail("Failed with:"+e);
		}
	}

	/**
	 *
Test method for 'javax.naming.ldap.PagedResultsResponseControl.getCookie()'

	 *
Here we are testing if this method retrieves the server-generated cookie.

	 *
The expected result in this case is a not null array.

	 */
	public void testGetCookie002() {

		byte[] b={48,7,2,1,0,4,2,1,1};
		byte[] c={1,1};
		try {
			PagedResultsResponseControl x=new PagedResultsResponseControl("",false,b);
			for (int i = 0; i < x.getCookie().length; i++) {
				assertEquals(c[i],x.getCookie()[i]);
			}
		} catch (IOException e) {
			fail("Failed with:"+e);
		}
	}

	/**
	 *
Test method for 'javax.naming.ldap.PagedResultsResponseControl.getCookie()'

	 *
Here we are testing if this method retrieves the server-generated cookie.

	 *
The expected result in this case is not null.

	 */
	public void testGetCookie003() {

		byte[] b={48,6,2,1,0,4,1,0};
		try {
			PagedResultsResponseControl x=new PagedResultsResponseControl("",false,b);
			assertNotNull(x.getCookie());
		} catch (IOException e) {
			fail("Failed with:"+e);
		}
	}

    public void testSerializationCompatibility() throws Exception{
        byte[] b={48,5,2,1,0,4,0};
        PagedResultsResponseControl object=new PagedResultsResponseControl("test", true, b);
        SerializationTest.verifyGolden(this, object, PAGEDRESULTSRESPONSECONTROL_COMPARATOR);
    }

    // comparator for PagedResultsResponseControl
    private static final SerializableAssert PAGEDRESULTSRESPONSECONTROL_COMPARATOR = new SerializableAssert() {
        public void assertDeserialized(Serializable initial,
                Serializable deserialized) {

            PagedResultsResponseControl initThr = (PagedResultsResponseControl) initial;
            PagedResultsResponseControl dserThr = (PagedResultsResponseControl) deserialized;

            // verify ResultSize
            int initResultSize = initThr.getResultSize();
            int dserResultSize = dserThr.getResultSize();
            assertTrue(initResultSize == dserResultSize);

            // verify Cookie
            byte[] initCookie = initThr.getCookie();
            byte[] dserCookie = dserThr.getCookie();
            assertTrue(Arrays.equals(initCookie, dserCookie));
        }
    };
}


text:
package de.uop.mics.bayerl.cube;

import de.uop.mics.bayerl.cube.similarity.hierarchies.dbpedia.DBPediaProperty;
import de.uop.mics.bayerl.cube.similarity.hierarchies.dbpedia.EdgeMode;
import de.uop.mics.bayerl.cube.similarity.string.DistanceAlgorithm;

/**
 * Created by sebastianbayerl on 29/07/15.
 */
public class Configuration {

    public static final boolean CACHE_SAME_AS = true;
    public static final DistanceAlgorithm STRING_DISTANCE_ALGORITHM = DistanceAlgorithm.LEVENSHTEIN;
    public static double similarity_base = 0.8;
    public static int COMMON_CONCEPT_MAX_DISTANCE = 5;
    public static int MAX_PATH_LENGTH_CATEGORY = 5;
    public static int MAX_PATH_LENGTH_PAGELINK = 3;
    public static EdgeMode EDGE_MODE = EdgeMode.BOTH;
    public static DBPediaProperty dbPediaProperty = DBPediaProperty.BROADER;
}


text:
<?php

namespace Setnet\JuanMarcetBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Imagenes
 */
class Imagenes
{
    /**
     * @var integer
     */
    private $id;

    /**
     * @var string
     */
    private $titulo;

    /**
     * @var string
     */
    private $descripcion;

    /**
     * @var \DateTime
     */
    private $created;

    /**
     * @var \DateTime
     */
    private $updated;

    /**
     * @var integer
     */
    private $estado;

    /**
     * @var \Setnet\JuanMarcetBundle\Entity\Multimedia
     */
    private $multimedia;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set titulo
     *
     * @param string $titulo
     * @return Imagenes
     */
    public function setTitulo($titulo)
    {
        $this->titulo = $titulo;

        return $this;
    }

    /**
     * Get titulo
     *
     * @return string
     */
    public function getTitulo()
    {
        return $this->titulo;
    }

    /**
     * Set descripcion
     *
     * @param string $descripcion
     * @return Imagenes
     */
    public function setDescripcion($descripcion)
    {
        $this->descripcion = $descripcion;

        return $this;
    }

    /**
     * Get descripcion
     *
     * @return string
     */
    public function getDescripcion()
    {
        return $this->descripcion;
    }

    /**
     * Set created
     *
     * @param \DateTime $created
     * @return Imagenes
     */
    public function setCreated($created)
    {
        $this->created = $created;

        return $this;
    }

    /**
     * Get created
     *
     * @return \DateTime
     */
    public function getCreated()
    {
        return $this->created;
    }

    /**
     * Set updated
     *
     * @param \DateTime $updated
     * @return Imagenes
     */
    public function setUpdated($updated)
    {
        $this->updated = $updated;

        return $this;
    }

    /**
     * Get updated
     *
     * @return \DateTime
     */
    public function getUpdated()
    {
        return $this->updated;
    }

    /**
     * Set estado
     *
     * @param integer $estado
     * @return Imagenes
     */
    public function setEstado($estado)
    {
        $this->estado = $estado;

        return $this;
    }

    /**
     * Get estado
     *
     * @return integer
     */
    public function getEstado()
    {
        return $this->estado;
    }

    /**
     * Set multimedia
     *
     * @param \Setnet\JuanMarcetBundle\Entity\Multimedia $multimedia
     * @return Imagenes
     */
    public function setMultimedia(\Setnet\JuanMarcetBundle\Entity\Multimedia $multimedia)
    {
        $this->multimedia = $multimedia;

        return $this;
    }

    /**
     * Get multimedia
     *
     * @return \Setnet\JuanMarcetBundle\Entity\Multimedia
     */
    public function getMultimedia()
    {
        return $this->multimedia;
    }
}


text:
<!DOCTYPE html>

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

		<title>PNG Cipher</title>

PNG Cipher

This is an example which shows how text can be hashed into a format which can be displayed as a PNG.

The text is taken from the introduction of Marijn Haverbeke's excellent book, "Eloquent JavaScript"

		<textarea id="data0" style="width: 400px; height: 300px; float: left;">
		Introduction

		This is a book about getting computers to do what you want them to do. Computers are about as common as screwdrivers today, but they contain a lot more hidden complexity and thus are harder to operate and understand. To many, they remain alien, slightly threatening things.

		Communicating with a computer
		We've found two effective ways of bridging the communication gap between us, squishy biological organisms with a talent for social and spatial reasoning, and computers, unfeeling manipulators of meaningless data. The first is to appeal to our sense of the physical world and build interfaces that mimic that world and allow us to manipulate shapes on a screen with our fingers. This works very well for casual machine interaction.

		But we have not yet found a good way to use the point-and-click approach to communicate things to the computer that the designer of the interface did not anticipate. For open-ended interfaces, such as instructing the computer to perform arbitrary tasks, we've had more luck with an approach that makes use of our talent for language: teaching the machine a language.

		Human languages allow words and phrases to be combined in many ways, which allows us to say many different things. Computer languages, though typically less grammatically flexible, follow a similar principle.

		Casual computing has become much more widespread in the past 20 years, and language-based interfaces, which once were the default way in which people interacted with computers, have largely been replaced with graphical interfaces. But they are still there, if you know where to look. One such language, JavaScript, is built into almost every web browser and is thus available on just about every consumer device.

		This book intends to make you familiar enough with this language to be able to make a computer do what you want.

		On programming

		I do not enlighten those who are not eager to learn, nor arouse those who are not anxious to give an explanation themselves. If I have presented one corner of the square and they cannot come back to me with the other three, I should not go over the points again.

		Confucius
		Besides explaining JavaScript, I also will introduce the basic principles of programming. Programming, it turns out, is hard. The fundamental rules are typically simple and clear. But programs built on top of these rules tend to become complex enough to introduce their own rules and complexity. You're building your own maze, in a way, and you might just get lost in it.

		There will be times when reading this book feels terribly frustrating. If you are new to programming, there will be a lot of new material to digest. Much of this material will then be combined in ways that require you to make additional connections.

		It is up to you to make the necessary effort. When you are struggling to follow the book, do not jump to any conclusions about your own capabilities. You are fine—you just need to keep at it. Take a break, reread some material, and always make sure you read and understand the example programs and exercises. Learning is hard work, but everything you learn is yours and will make subsequent learning easier.

		The computer programmer is a creator of universes for which he [sic] alone is responsible. Universes of virtually unlimited complexity can be created in the form of computer programs.

		Joseph Weizenbaum, Computer Power and Human Reason
		A program is many things. It is a piece of text typed by a programmer, it is the directing force that makes the computer do what it does, it is data in the computer's memory, yet it controls the actions performed on this same memory. Analogies that try to compare programs to objects we are familiar with tend to fall short. A superficially fitting one is that of a machine—lots of separate parts tend to be involved, and to make the whole thing tick, we have to consider the ways in which these parts interconnect and contribute to the operation of the whole.

		A computer is a machine built to act as a host for these immaterial machines. Computers themselves can do only stupidly straightforward things. The reason they are so useful is that they do these things at an incredibly high speed. A program can ingeniously combine an enormous number of these simple actions in order to do very complicated things.

		To some of us, writing computer programs is a fascinating game. A program is a building of thought. It is costless to build, it is weightless, and it grows easily under our typing hands.

		But without care, a program's size and complexity will grow out of control, confusing even the person who created it. Keeping programs under control is the main problem of programming. When a program works, it is beautiful. The art of programming is the skill of controlling complexity. The great program is subdued—made simple in its complexity.

		Many programmers believe that this complexity is best managed by using only a small set of well-understood techniques in their programs. They have composed strict rules ("best practices") prescribing the form programs should have, and the more zealous among them will consider those who go outside of this safe little zone to be bad programmers.

		What hostility to the richness of programming—to try to reduce it to something straightforward and predictable, to place a taboo on all the weird and beautiful programs! The landscape of programming techniques is enormous, fascinating in its diversity, and still largely unexplored. It is certainly dangerous going, luring the inexperienced programmer into all kinds of confusion, but that only means you should proceed with caution and keep your wits about you. As you learn there will always be new challenges and new territory to explore. Programmers who refuse to keep exploring will stagnate, forget their joy, and get bored with their craft.

		Why language matters

		In the beginning, at the birth of computing, there were no programming languages. Programs looked something like this:

		00110001 00000000 00000000
		00110001 00000001 00000001
		00110011 00000001 00000010
		01010001 00001011 00000010
		00100010 00000010 00001000
		01000011 00000001 00000000
		01000001 00000001 00000001
		00010000 00000010 00000000
		01100010 00000000 00000000
		That is a program to add the numbers from 1 to 10 together and print out the result: 1 + 2 + ... + 10 = 55. It could run on a simple, hypothetical machine. To program early computers, it was necessary to set large arrays of switches in the right position or punch holes in strips of cardboard and feed them to the computer. You can probably imagine how tedious and error-prone this procedure was. Even writing simple programs required much cleverness and discipline. Complex ones were nearly inconceivable.

		Of course, manually entering these arcane patterns of bits (the ones and zeros) did give the programmer a profound sense of being a mighty wizard. And that has to be worth something in terms of job satisfaction.

		Each line of the previous program contains a single instruction. It could be written in English like this:

		1. Store the number 0 in memory location 0.
		2. Store the number 1 in memory location 1.
		3. Store the value of memory location 1 in memory location 2.
		4. Subtract the number 11 from the value in memory location 2.
		5. If the value in memory location 2 is the number 0,
		   continue with instruction 9.
		6. Add the value of memory location 1 to memory location 0.
		7. Add the number 1 to the value of memory location 1.
		8. Continue with instruction 3.
		9. Output the value of memory location 0.
		Although that is already more readable than the soup of bits, it is still rather unpleasant. It might help to use names instead of numbers for the instructions and memory locations.

		 Set "total" to 0.
		 Set "count" to 1.
		[loop]
		 Set "compare" to "count".
		 Subtract 11 from "compare".
		 If "compare" is zero, continue at [end].
		 Add "count" to "total".
		 Add 1 to "count".
		 Continue at [loop].
		[end]
		 Output "total".
		Can you see how the program works at this point? The first two lines give two memory locations their starting values: total will be used to build up the result of the computation, and count will keep track of the number that we are currently looking at. The lines using compare are probably the weirdest ones. The program wants to see whether count is equal to 11 in order to decide whether it can stop running. Because our hypothetical machine is rather primitive, it can only test whether a number is zero and make a decision (or jump) based on that. So it uses the memory location labeled compare to compute the value of count - 11 and makes a decision based on that value. The next two lines add the value of count to the result and increment count by 1 every time the program has decided that count is not 11 yet.

		Here is the same program in JavaScript:

		var total = 0, count = 1;
		while (count <= 10) {
		  total += count;
		  count += 1;
		}
		console.log(total);
		// → 55
		This version gives us a few more improvements. Most importantly, there is no need to specify the way we want the program to jump back and forth anymore. The while language construct takes care of that. It continues executing the block (wrapped in braces) below it as long as the condition it was given holds. That condition is count <= 10, which means "count is less than or equal to 10". We no longer have to create a temporary value and compare that to zero, which was an uninteresting detail. Part of the power of programming languages is that they take care of uninteresting details for us.

		At the end of the program, after the while construct has finished, the console.log operation is applied to the result in order to write it as output.

		Finally, here is what the program could look like if we happened to have the convenient operations range and sum available, which respectively create a collection of numbers within a range and compute the sum of a collection of numbers:

		console.log(sum(range(1, 10)));
		// → 55
		The moral of this story is that the same program can be expressed in long and short, unreadable and readable ways. The first version of the program was extremely obscure, whereas this last one is almost English: log the sum of the range of numbers from 1 to 10. (We will see in later chapters how to build operations like sum and range.)

		A good programming language helps the programmer by allowing them to talk about the actions that the computer has to perform on a higher level. It helps omit uninteresting details, provides convenient building blocks (such as while and console.log), allows you to define your own building blocks (such as sum and range), and makes those blocks easy to compose.

		What is JavaScript?

		JavaScript was introduced in 1995 as a way to add programs to web pages in the Netscape Navigator browser. The language has since been adopted by all other major graphical web browsers. It has made modern web applications possible—applications with which you can interact directly, without doing a page reload for every action. But it is also used in more traditional websites to provide various forms of interactivity and cleverness.

		It is important to note that JavaScript has almost nothing to do with the programming language named Java. The similar name was inspired by marketing considerations, rather than good judgment. When JavaScript was being introduced, the Java language was being heavily marketed and was gaining popularity. Someone thought it was a good idea to try to ride along on this success. Now we are stuck with the name.

		After its adoption outside of Netscape, a standard document was written to describe the way the JavaScript language should work to make sure the various pieces of software that claimed to support JavaScript were actually talking about the same language. This is called the ECMAScript standard, after the Ecma International organization that did the standardization. In practice, the terms ECMAScript and JavaScript can be used interchangeably—they are two names for the same language.

		There are those who will say terrible things about the JavaScript language. Many of these things are true. When I was required to write something in JavaScript for the first time, I quickly came to despise it. It would accept almost anything I typed but interpret it in a way that was completely different from what I meant. This had a lot to do with the fact that I did not have a clue what I was doing, of course, but there is a real issue here: JavaScript is ridiculously liberal in what it allows. The idea behind this design was that it would make programming in JavaScript easier for beginners. In actuality, it mostly makes finding problems in your programs harder because the system will not point them out to you.

		This flexibility also has its advantages, though. It leaves space for a lot of techniques that are impossible in more rigid languages, and as you will see (for example in Chapter 10) it can be used to overcome some of JavaScript's shortcomings. After learning the language properly and working with it for a while, I have learned to actually like JavaScript.

		There have been several versions of JavaScript. ECMAScript version 3 was the widely supported version in the time of JavaScript's ascent to dominance, roughly between 2000 and 2010. During this time, work was underway on an ambitious version 4, which planned a number of radical improvements and extensions to the language. Changing a living, widely used language in such a radical way turned out to be politically difficult, and work on the version 4 was abandoned in 2008, leading to the much less ambitious version 5 coming out in 2009. We're now at the point where all major browsers support version 5, which is the language version that this book will be focusing on. A version 6 is in the process of being finalized, and some browsers are starting to support new features from this version.

		Web browsers are not the only platforms on which JavaScript is used. Some databases, such as MongoDB and CouchDB, use JavaScript as their scripting and query language. Several platforms for desktop and server programming, most notably the Node.js project (the subject of Chapter 20) are providing a powerful environment for programming JavaScript outside of the browser.

		Code, and what to do with it

		Code is the text that makes up programs. Most chapters in this book contain quite a lot of it. In my experience, reading code and writing code are indispensable parts of learning to program, so try to not just glance over the examples. Read them attentively and understand them. This may be slow and confusing at first, but I promise that you will quickly get the hang of it. The same goes for the exercises. Don't assume you understand them until you've actually written a working solution.

		I recommend you try your solutions to exercises in an actual JavaScript interpreter. That way, you'll get immediate feedback on whether what you are doing is working, and, I hope, you'll be tempted to experiment and go beyond the exercises.

		When reading this book in your browser, you can edit (and run) all example programs by clicking them.

		If you want to run the programs defined in this book outside of the book's sandbox, some care is required. Many examples stand on their own and should work in any JavaScript environment. But code in later chapters is mostly written for a specific environment (the browser or Node.js) and can run only there. In addition, many chapters define bigger programs, and the pieces of code that appear in them depend on each other or on external files. The sandbox on the website provides links to Zip files containing all of the scripts and data files necessary to run the code for a given chapter.

		Overview of this book

		This book contains roughly three parts. The first 11 chapters discuss the JavaScript language itself. The next eight chapters are about web browsers and the way JavaScript is used to program them. Finally, two chapters are devoted to Node.js, another environment to program JavaScript in.

		Throughout the book, there are five project chapters, which describe larger example programs to give you a taste of real programming. In order of appearance, we will work through building an artificial life simulation, a programming language, a platform game, a paint program, and a dynamic website.

		The language part of the book starts with four chapters to introduce the basic structure of the JavaScript language. They introduce control structures (such as the while word you saw in this introduction), functions (writing your own operations), and data structures. After these, you will be able to write simple programs. Next, Chapters 5 and 6 introduce techniques to use functions and objects to write more abstract code and thus keep complexity under control.

		After a first project chapter, the first part of the book continues with chapters on error handling and fixing, on regular expressions (an important tool for working with text data), and on modularity—another weapon against complexity. The second project chapter concludes the first part of the book.

		The second part, Chapters 12 to 19, describes the tools that browser JavaScript has access to. You'll learn to display things on the screen (Chapters 13 and 16), respond to user input (Chapters 14 and 18), and communicate over the network (Chapter 17). There are again two project chapters in this part.

		After that, Chapter 20 describes Node.js, and Chapter 21 builds a simple web system using that tool.

		Typographic conventions

		In this book, text written in a monospaced font will represent elements of programs—sometimes they are self-sufficient fragments, and sometimes they just refer to part of a nearby program. Programs (of which you have already seen a few), are written as follows:

		function fac(n) {
		  if (n == 0)
		    return 1;
		  else
		    return fac(n - 1) * n;
		}
		Sometimes, in order to show the output that a program produces, the expected output is written after it, with two slashes and an arrow in front.

		console.log(fac(8));
		// → 40320
		Good luck!
		</textarea>
		<textarea id="data1" style="width: 400px; height: 300px; float: left;">

		</textarea>

		<input value="encode" type="button" onclick="demoEncrypt()" style="font-size: 1em; display: inline-block;">
		<input value="decode" type="button" onclick="demoDecrypt()" style="font-size: 1em; display: inline-block;">


text:
package ogórek

import (
	"bufio"
	"bytes"
	"encoding/binary"
	"errors"
	"fmt"
	"io"
	"math"
	"math/big"
	"strconv"
)

// Opcodes
const (
	opMark           byte = '(' // push special markobject on stack
	opStop                = '.' // every pickle ends with STOP
	opPop                 = '0' // discard topmost stack item
	opPopMark             = '1' // discard stack top through topmost markobject
	opDup                 = '2' // duplicate top stack item
	opFloat               = 'F' // push float object; decimal string argument
	opInt                 = 'I' // push integer or bool; decimal string argument
	opBinint              = 'J' // push four-byte signed int
	opBinint1             = 'K' // push 1-byte unsigned int
	opLong                = 'L' // push long; decimal string argument
	opBinint2             = 'M' // push 2-byte unsigned int
	opNone                = 'N' // push None
	opPersid              = 'P' // push persistent object; id is taken from string arg
	opBinpersid           = 'Q' //  "       "         "  ;  "  "   "     "  stack
	opReduce              = 'R' // apply callable to argtuple, both on stack
	opString              = 'S' // push string; NL-terminated string argument
	opBinstring           = 'T' // push string; counted binary string argument
	opShortBinstring      = 'U' //  "     "   ;    "      "       "      " < 256 bytes
	opUnicode             = 'V' // push Unicode string; raw-unicode-escaped"d argument
	opBinunicode          = 'X' //   "     "       "  ; counted UTF-8 string argument
	opAppend              = 'a' // append stack top to list below it
	opBuild               = 'b' // call __setstate__ or __dict__.update()
	opGlobal              = 'c' // push self.find_class(modname, name); 2 string args
	opDict                = 'd' // build a dict from stack items
	opEmptyDict           = '}' // push empty dict
	opAppends             = 'e' // extend list on stack by topmost stack slice
	opGet                 = 'g' // push item from memo on stack; index is string arg
	opBinget              = 'h' //   "    "    "    "   "   "  ;   "    " 1-byte arg
	opInst                = 'i' // build & push class instance
	opLongBinget          = 'j' // push item from memo on stack; index is 4-byte arg
	opList                = 'l' // build list from topmost stack items
	opEmptyList           = ']' // push empty list
	opObj                 = 'o' // build & push class instance
	opPut                 = 'p' // store stack top in memo; index is string arg
	opBinput              = 'q' //   "     "    "   "   " ;   "    " 1-byte arg
	opLongBinput          = 'r' //   "     "    "   "   " ;   "    " 4-byte arg
	opSetitem             = 's' // add key+value pair to dict
	opTuple               = 't' // build tuple from topmost stack items
	opEmptyTuple          = ')' // push empty tuple
	opSetitems            = 'u' // modify dict by adding topmost key+value pairs
	opBinfloat            = 'G' // push float; arg is 8-byte float encoding

	opTrue  = "I01\n" // not an opcode; see INT docs in pickletools.py
	opFalse = "I00\n" // not an opcode; see INT docs in pickletools.py

	// Protocol 2

	opProto    = '\x80' // identify pickle protocol
	opNewobj   = '\x81' // build object by applying cls.__new__ to argtuple
	opExt1     = '\x82' // push object from extension registry; 1-byte index
	opExt2     = '\x83' // ditto, but 2-byte index
	opExt4     = '\x84' // ditto, but 4-byte index
	opTuple1   = '\x85' // build 1-tuple from stack top
	opTuple2   = '\x86' // build 2-tuple from two topmost stack items
	opTuple3   = '\x87' // build 3-tuple from three topmost stack items
	opNewtrue  = '\x88' // push True
	opNewfalse = '\x89' // push False
	opLong1    = '\x8a' // push long from < 256 bytes
	opLong4    = '\x8b' // push really big long
)

var errNotImplemented = errors.New("unimplemented opcode")
var ErrInvalidPickleVersion = errors.New("invalid pickle version")

type OpcodeError struct {
	Key byte
	Pos int
}

func (e OpcodeError) Error() string {
	return fmt.Sprintf("Unknown opcode %d (%c) at position %d: %q", e.Key, e.Key, e.Pos, e.Key)
}

// special marker
type mark struct{}

// None is a representation of Python's None.
type None struct{}

// Decoder is a decoder for pickle streams.
type Decoder struct {
	r     *bufio.Reader
	stack []interface{}
	memo  map[string]interface{}
}

// NewDecoder constructs a new Decoder which will decode the pickle stream in r.
func NewDecoder(r io.Reader) Decoder {
	reader := bufio.NewReader(r)
	return Decoder{reader, make([]interface{}, 0), make(map[string]interface{})}
}

// Decode decodes the pickle stream and returns the result or an error.
func (d Decoder) Decode() (interface{}, error) {

	insn := 0
	for {
		insn++
		key, err := d.r.ReadByte()
		if err == io.EOF {
			break
		} else if err != nil {
			return nil, err
		}

		switch key {
		case opMark:
			d.mark()
		case opStop:
			break
		case opPop:
			d.pop()
		case opPopMark:
			d.popMark()
		case opDup:
			d.dup()
		case opFloat:
			err = d.loadFloat()
		case opInt:
			err = d.loadInt()
		case opBinint:
			err = d.loadBinInt()
		case opBinint1:
			err = d.loadBinInt1()
		case opLong:
			err = d.loadLong()
		case opBinint2:
			err = d.loadBinInt2()
		case opNone:
			err = d.loadNone()
		case opPersid:
			err = d.loadPersid()
		case opBinpersid:
			err = d.loadBinPersid()
		case opReduce:
			err = d.reduce()
		case opString:
			err = d.loadString()
		case opBinstring:
			err = d.loadBinString()
		case opShortBinstring:
			err = d.loadShortBinString()
		case opUnicode:
			err = d.loadUnicode()
		case opBinunicode:
			err = d.loadBinUnicode()
		case opAppend:
			err = d.loadAppend()
		case opBuild:
			err = d.build()
		case opGlobal:
			err = d.global()
		case opDict:
			err = d.loadDict()
		case opEmptyDict:
			err = d.loadEmptyDict()
		case opAppends:
			err = d.loadAppends()
		case opGet:
			err = d.get()
		case opBinget:
			err = d.binGet()
		case opInst:
			err = d.inst()
		case opLong1:
			err = d.loadLong1()
		case opNewfalse:
			err = d.loadBool(false)
		case opNewtrue:
			err = d.loadBool(true)
		case opLongBinget:
			err = d.longBinGet()
		case opList:
			err = d.loadList()
		case opEmptyList:
			d.push([]interface{}{})
		case opObj:
			err = d.obj()
		case opPut:
			err = d.loadPut()
		case opBinput:
			err = d.binPut()
		case opLongBinput:
			err = d.longBinPut()
		case opSetitem:
			err = d.loadSetItem()
		case opTuple:
			err = d.loadTuple()
		case opTuple1:
			err = d.loadTuple1()
		case opTuple2:
			err = d.loadTuple2()
		case opTuple3:
			err = d.loadTuple3()
		case opEmptyTuple:
			d.push([]interface{}{})
		case opSetitems:
			err = d.loadSetItems()
		case opBinfloat:
			err = d.binFloat()
		case opProto:
			v, _ := d.r.ReadByte()
			if v != 2 {
				err = ErrInvalidPickleVersion
			}

		default:
			return nil, OpcodeError{key, insn}
		}

		if err != nil {
			if err == errNotImplemented {
				return nil, OpcodeError{key, insn}
			}
			return nil, err
		}
	}
	return d.pop(), nil
}

// Push a marker
func (d *Decoder) mark() {
	d.push(mark{})
}

// Return the position of the topmost marker
func (d *Decoder) marker() int {
	m := mark{}
	var k int
	for k = len(d.stack) - 1; d.stack[k] != m && k > 0; k-- {
	}
	if k >= 0 {
		return k
	}
	panic("no marker in stack")
}

// Append a new value
func (d *Decoder) push(v interface{}) {
	d.stack = append(d.stack, v)
}

// Pop a value
func (d *Decoder) pop() interface{} {
	ln := len(d.stack) - 1
	v := d.stack[ln]
	d.stack = d.stack[:ln]
	return v
}

// Discard the stack through to the topmost marker
func (d *Decoder) popMark() error {
	return errNotImplemented
}

// Duplicate the top stack item
func (d *Decoder) dup() {
	d.stack = append(d.stack, d.stack[len(d.stack)-1])
}

// Push a float
func (d *Decoder) loadFloat() error {
	line, _, err := d.r.ReadLine()
	if err != nil {
		return err
	}
	v, err := strconv.ParseFloat(string(line), 64)
	if err != nil {
		return err
	}
	d.push(interface{}(v))
	return nil
}

// Push an int
func (d *Decoder) loadInt() error {
	line, _, err := d.r.ReadLine()
	if err != nil {
		return err
	}

	var val interface{}

	switch string(line) {
	case opFalse[1:3]:
		val = false
	case opTrue[1:3]:
		val = true
	default:
		i, err := strconv.ParseInt(string(line), 10, 64)
		if err != nil {
			return err
		}
		val = i
	}

	d.push(val)
	return nil
}

// Push a four-byte signed int
func (d *Decoder) loadBinInt() error {
	var b [4]byte
	_, err := io.ReadFull(d.r, b[:])
	if err != nil {
		return err
	}
	v := binary.LittleEndian.Uint32(b[:])
	d.push(int64(v))
	return nil
}

// Push a 1-byte unsigned int
func (d *Decoder) loadBinInt1() error {
	b, _ := d.r.ReadByte()
	d.push(int64(b))
	return nil
}

// Push a long
func (d *Decoder) loadLong() error {
	line, _, err := d.r.ReadLine()
	if err != nil {
		return err
	}
	v := new(big.Int)
	v.SetString(string(line[:len(line)-1]), 10)
	d.push(v)
	return nil
}

// Push a long1
func (d *Decoder) loadLong1() error {
	rawNum := []byte{}
	b, err := d.r.ReadByte()
	if err != nil {
		return err
	}
	length, err := decodeLong(string(b))
	if err != nil {
		return err
	}
	for i := 0; int64(i) < length.Int64(); i++ {
		b2, err := d.r.ReadByte()
		if err != nil {
			return err
		}
		rawNum = append(rawNum, b2)
	}
	decodedNum, err := decodeLong(string(rawNum))
	d.push(decodedNum)
	return nil
}

// Push a 2-byte unsigned int
func (d *Decoder) loadBinInt2() error {
	var b [2]byte
	_, err := io.ReadFull(d.r, b[:])
	if err != nil {
		return err
	}
	v := binary.LittleEndian.Uint16(b[:])
	d.push(int64(v))
	return nil
}

// Push None
func (d *Decoder) loadNone() error {
	d.push(None{})
	return nil
}

// Push a persistent object id
func (d *Decoder) loadPersid() error {
	return errNotImplemented
}

// Push a persistent object id from items on the stack
func (d *Decoder) loadBinPersid() error {
	return errNotImplemented
}

type Call struct {
	Callable Class
	Args     []interface{}
}

func (d *Decoder) reduce() error {
	args := d.pop().([]interface{})
	class := d.pop().(Class)
	d.stack = append(d.stack, Call{Callable: class, Args: args})
	return nil
}

func decodeStringEscape(b []byte) string {
	// TODO
	return string(b)
}

// Push a string
func (d *Decoder) loadString() error {
	line, _, err := d.r.ReadLine()
	if err != nil {
		return err
	}

	var delim byte
	switch line[0] {
	case '\'':
		delim = '\''
	case '"':
		delim = '"'
	default:
		return fmt.Errorf("invalid string delimiter: %c", line[0])
	}

	if line[len(line)-1] != delim {
		return fmt.Errorf("insecure string")
	}

	d.push(decodeStringEscape(line[1 : len(line)-1]))
	return nil
}

func (d *Decoder) loadBinString() error {
	var b [4]byte
	_, err := io.ReadFull(d.r, b[:])
	if err != nil {
		return err
	}
	v := binary.LittleEndian.Uint32(b[:])
	s := make([]byte, v)
	_, err = io.ReadFull(d.r, s)
	if err != nil {
		return err
	}
	d.push(string(s))
	return nil
}

func (d *Decoder) loadShortBinString() error {
	b, _ := d.r.ReadByte()
	s := make([]byte, b)
	_, err := io.ReadFull(d.r, s)
	if err != nil {
		return err
	}
	d.push(string(s))
	return nil
}

func (d *Decoder) loadUnicode() error {
	line, _, err := d.r.ReadLine()
	if err != nil {
		return err
	}
	sline := string(line)

	buf := bytes.Buffer{}

	for len(sline) >= 6 {
		var r rune
		var err error
		r, _, sline, err = strconv.UnquoteChar(sline, '\'')
		if err != nil {
			return err
		}
		_, err = buf.WriteRune(r)
		if err != nil {
			return err
		}
	}
	if len(sline) > 0 {
		return fmt.Errorf("characters remaining after loadUnicode operation: %s", sline)
	}

	d.push(buf.String())
	return nil
}

func (d *Decoder) loadBinUnicode() error {
	var length int32
	for i := 0; i < 4; i++ {
		t, err := d.r.ReadByte()
		if err != nil {
			return err
		}
		length = length | (int32(t) << uint(8*i))
	}
	rawB := []byte{}
	for z := 0; int32(z) < length; z++ {
		n, err := d.r.ReadByte()
		if err != nil {
			return err
		}
		rawB = append(rawB, n)
	}
	d.push(string(rawB))
	return nil
}

func (d *Decoder) loadAppend() error {
	v := d.pop()
	l := d.stack[len(d.stack)-1]
	switch l.(type) {
	case []interface{}:
		l := l.([]interface{})
		d.stack[len(d.stack)-1] = append(l, v)
	default:
		return fmt.Errorf("loadAppend expected a list, got %t", l)
	}
	return nil
}

func (d *Decoder) build() error {
	return errNotImplemented
}

type Class struct {
	Module, Name string
}

func (d *Decoder) global() error {
	module, _, err := d.r.ReadLine()
	if err != nil {
		return err
	}
	name, _, err := d.r.ReadLine()
	if err != nil {
		return err
	}
	d.stack = append(d.stack, Class{Module: string(module), Name: string(name)})
	return nil
}

func (d *Decoder) loadDict() error {
	k := d.marker()
	m := make(map[interface{}]interface{}, 0)
	items := d.stack[k+1:]
	for i := 0; i < len(items); i += 2 {
		m[items[i]] = items[i+1]
	}
	d.stack = append(d.stack[:k], m)
	return nil
}

func (d *Decoder) loadEmptyDict() error {
	m := make(map[interface{}]interface{}, 0)
	d.push(m)
	return nil
}

func (d *Decoder) loadAppends() error {
	k := d.marker()
	l := d.stack[k-1]
	switch l.(type) {
	case []interface{}:
		l := l.([]interface{})
		for _, v := range d.stack[k+1 : len(d.stack)] {
			l = append(l, v)
		}
		d.stack = append(d.stack[:k-1], l)
	default:
		return fmt.Errorf("loadAppends expected a list, got %t", l)
	}
	return nil
}

func (d *Decoder) get() error {
	line, _, err := d.r.ReadLine()
	if err != nil {
		return err
	}
	d.push(d.memo[string(line)])
	return nil
}

func (d *Decoder) binGet() error {
	b, _ := d.r.ReadByte()
	d.push(d.memo[strconv.Itoa(int(b))])
	return nil
}

func (d *Decoder) inst() error {
	return errNotImplemented
}

func (d *Decoder) longBinGet() error {
	var b [4]byte
	_, err := io.ReadFull(d.r, b[:])
	if err != nil {
		return err
	}
	v := binary.LittleEndian.Uint32(b[:])
	d.push(d.memo[strconv.Itoa(int(v))])
	return nil
}

func (d *Decoder) loadBool(b bool) error {
	d.push(b)
	return nil
}

func (d *Decoder) loadList() error {
	k := d.marker()
	v := append([]interface{}{}, d.stack[k+1:]...)
	d.stack = append(d.stack[:k], v)
	return nil
}

func (d *Decoder) loadTuple() error {
	k := d.marker()
	v := append([]interface{}{}, d.stack[k+1:]...)
	d.stack = append(d.stack[:k], v)
	return nil
}

func (d *Decoder) loadTuple1() error {
	k := len(d.stack) - 1
	v := append([]interface{}{}, d.stack[k:]...)
	d.stack = append(d.stack[:k], v)
	return nil
}

func (d *Decoder) loadTuple2() error {
	k := len(d.stack) - 2
	v := append([]interface{}{}, d.stack[k:]...)
	d.stack = append(d.stack[:k], v)
	return nil
}

func (d *Decoder) loadTuple3() error {
	k := len(d.stack) - 3
	v := append([]interface{}{}, d.stack[k:]...)
	d.stack = append(d.stack[:k], v)
	return nil
}

func (d *Decoder) obj() error {
	return errNotImplemented
}

func (d *Decoder) loadPut() error {
	line, _, err := d.r.ReadLine()
	if err != nil {
		return err
	}
	d.memo[string(line)] = d.stack[len(d.stack)-1]
	return nil
}

func (d *Decoder) binPut() error {
	b, _ := d.r.ReadByte()
	d.memo[strconv.Itoa(int(b))] = d.stack[len(d.stack)-1]
	return nil
}

func (d *Decoder) longBinPut() error {
	var b [4]byte
	_, err := io.ReadFull(d.r, b[:])
	if err != nil {
		return err
	}
	v := binary.LittleEndian.Uint32(b[:])
	d.memo[strconv.Itoa(int(v))] = d.stack[len(d.stack)-1]
	return nil
}

func (d *Decoder) loadSetItem() error {
	v := d.pop()
	k := d.pop()
	m := d.stack[len(d.stack)-1]
	switch m.(type) {
	case map[interface{}]interface{}:
		m := m.(map[interface{}]interface{})
		m[k] = v
	default:
		return fmt.Errorf("loadSetItem expected a map, got %t", m)
	}
	return nil
}

func (d *Decoder) loadSetItems() error {
	k := d.marker()
	l := d.stack[k-1]
	switch m := l.(type) {
	case map[interface{}]interface{}:
		for i := k + 1; i < len(d.stack); i += 2 {
			m[d.stack[i]] = d.stack[i+1]
		}
		d.stack = append(d.stack[:k-1], m)
	default:
		return fmt.Errorf("loadSetItems expected a map, got %t", m)
	}
	return nil
}

func (d *Decoder) binFloat() error {
	var b [8]byte
	_, err := io.ReadFull(d.r, b[:])
	if err != nil {
		return err
	}
	u := binary.BigEndian.Uint64(b[:])
	d.stack = append(d.stack, math.Float64frombits(u))
	return nil
}

// decodeLong takes a byte array of 2's compliment little-endian binary words and converts them
// to a big integer
func decodeLong(data string) (*big.Int, error) {
	decoded := big.NewInt(0)
	var negative bool
	switch x := len(data); {
	case x < 1:
		return decoded, nil
	case x > 1:
		if data[x-1] > 127 {
			negative = true
		}
		for i := x - 1; i >= 0; i-- {
			a := big.NewInt(int64(data[i]))
			for n := i; n > 0; n-- {
				a = a.Lsh(a, 8)
			}
			decoded = decoded.Add(a, decoded)
		}
	default:
		if data[0] > 127 {
			negative = true
		}
		decoded = big.NewInt(int64(data[0]))
	}

	if negative {
		// Subtract 1 from the number
		one := big.NewInt(1)
		decoded.Sub(decoded, one)

		// Flip the bits
		bytes := decoded.Bytes()
		for i := 0; i < len(bytes); i++ {
			bytes[i] = ^bytes[i]
		}
		decoded.SetBytes(bytes)

		// Mark as negative now conversion has been completed
		decoded.Neg(decoded)
	}
	return decoded, nil
}


text:
package org.springframework.cloud.dataflow.shell.command.classic;

import java.io.File;
import java.io.IOException;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.dataflow.rest.util.DeploymentPropertiesUtils;
import org.springframework.cloud.dataflow.shell.command.common.AbstractStreamCommands;
import org.springframework.cloud.dataflow.shell.command.common.Assertions;
import org.springframework.cloud.dataflow.shell.command.common.UserInput;
import org.springframework.cloud.dataflow.shell.command.support.OpsType;
import org.springframework.cloud.dataflow.shell.command.support.RoleType;
import org.springframework.cloud.dataflow.shell.config.DataFlowShell;
import org.springframework.shell.core.CommandMarker;
import org.springframework.shell.core.annotation.CliAvailabilityIndicator;
import org.springframework.shell.core.annotation.CliCommand;
import org.springframework.shell.core.annotation.CliOption;
import org.springframework.stereotype.Component;

/**
 * Stream commands.
 *
 * @author Ilayaperumal Gopinathan
 * @author Mark Fisher
 * @author Gunnar Hillert
 * @author Glenn Renfro
 * @author Christian Tzolov
 * @author Janne Valkealahti
 */
@Component
// todo: reenable optionContext attributes
public class ClassicStreamCommands extends AbstractStreamCommands implements CommandMarker {

	private static final String DEPLOY_STREAM = "stream deploy";

	@Autowired
	public void setDataFlowShell(DataFlowShell dataFlowShell) {
		this.dataFlowShell = dataFlowShell;
	}

	@Autowired
	public void setUserInput(UserInput userInput) {
		this.userInput = userInput;
	}

	@CliAvailabilityIndicator({ DEPLOY_STREAM })
	public boolean availableWithCreateRole() {
		return dataFlowShell.hasAccess(RoleType.CREATE, OpsType.STREAM);
	}

	@CliCommand(value = DEPLOY_STREAM, help = "Deploy a previously created stream")
	public String deployStream(
			@CliOption(key = { "",
					"name" }, help = "the name of the stream to deploy", mandatory = true, optionContext = "existing-stream disable-string-converter") String name,
			@CliOption(key = {
					PROPERTIES_OPTION }, help = "the properties for this deployment") String deploymentProperties,
			@CliOption(key = {
					PROPERTIES_FILE_OPTION }, help = "the properties for this deployment (as a File)") File propertiesFile)
			throws IOException {
		int which = Assertions.atMostOneOf(PROPERTIES_OPTION, deploymentProperties, PROPERTIES_FILE_OPTION,
				propertiesFile);
		Map<String, String> propertiesToUse = DeploymentPropertiesUtils.parseDeploymentProperties(deploymentProperties,
				propertiesFile, which);
		streamOperations().deploy(name, propertiesToUse);
		return String.format("Deployment request has been sent for stream '%s'\n", name);
	}
}


text:
<?php

defined('BASEPATH') OR exit('No direct script access allowed');

require_once APPPATH.'/libraries/REST_Controller.php';

// Allow from any origin
    if (isset($_SERVER['HTTP_ORIGIN'])) {
        header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
        header('Access-Control-Allow-Credentials: true');
        header('Access-Control-Max-Age: 86400');    // cache for 1 day
    }

    // Access-Control headers are received during OPTIONS requests
    if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {

        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
            header("Access-Control-Allow-Methods: GET, POST,PUT,DELETE OPTIONS");

        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
            header("Access-Control-Allow-Headers:        {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");

        exit(0);
    }

Class Front extends REST_Controller
{
    function __construct()
    {
        parent::__construct();
        $this->load->model('front_model');
    }

    public function find_all_get()
    {
        echo json_encode($this->front_model->all());
    }
}


text:
import {
  Class
}
from 'meteor/jagi:astronomy';

Tinytest.add('Modules - Storage - Type field', function(test) {
  const Part = Class.create({
    name: 'Part',
    typeField: 'type',
    fields: {
      name: {
        type: String
      }
    }
  });

  const Engine = Part.inherit({
    name: 'Engine'
  });

  const Wheel = Part.inherit({
    name: 'Wheel'
  });

  const Vehicles = new Mongo.Collection(null);

  const Vehicle = Class.create({
    name: 'Vehicle',
    collection: Vehicles,
    typeField: 'type',
    fields: {
      name: {
        type: String
      },
      parts: {
        type: [Part],
        default () {
          return [];
        }
      }
    }
  });

  const Car = Vehicle.inherit({
    name: 'Car'
  });

  const Plane = Vehicle.inherit({
    name: 'Plane'
  });

  let vehicle = new Vehicle({
    name: 'Vehicle',
    parts: [
      new Engine({
        name: 'Engine'
      }),
      new Wheel({
        name: 'Wheel'
      })
    ]
  });
  vehicle.save();

  let plane = new Plane({
    name: 'Plane'
  });
  plane.save();

  let car = new Car({
    name: 'Car'
  });
  car.save();

  let vehicles = Vehicle.find().fetch();
  test.equal(vehicles.length, 3,
    'All child documents should be fetched'
  );
  test.instanceOf(vehicles[0], Vehicle,
    'First document should be instance of the "Vehicle" class'
  );
  test.instanceOf(vehicles[1], Plane,
    'Second document should be instance of the "Plane" class'
  );
  test.instanceOf(vehicles[2], Car,
    'Second document should be instance of the "Car" class'
  );
  vehicles = Vehicle.find({}, {
    children: false
  }).fetch();
  test.equal(vehicles.length, 1,
    'Only one document should be fetched'
  );
  test.instanceOf(vehicles[0], Vehicle,
    'First document should be instance of the "Vehicle" class'
  );
  test.instanceOf(vehicles[0].parts[0], Engine,
    'First nested document should be instance of the "Engine" class'
  );
  test.instanceOf(vehicles[0].parts[1], Wheel,
    'Second nested document should be instance of the "Wheel" class'
  );
});


text:
using System.Reflection;

namespace Spring.Util
{
    internal static class TypeExtensions
    {
        internal static string AssemblyQualifiedNameWithoutVersion(this Type type)
            => type.FullName + ", " + type.GetTypeInfo().Assembly.GetName().Name;
    }
}


text:
<?php

namespace Google\Service\Contentwarehouse;

class SpeechS3LanguageIdentificationResult extends \Google\Collection
{
  protected $collection_key = 'rankedTopSupportedLanguages';
  /**
   * @var string
   */
  public $endTimeUsec;
  protected $rankedTopSupportedLanguagesType = SpeechS3Locale::class;
  protected $rankedTopSupportedLanguagesDataType = 'array';
  /**
   * @var string
   */
  public $startTimeUsec;
  /**
   * @var string
   */
  public $topLanguageConfidence;
  /**
   * @var bool
   */
  public $voicedUtterance;

  /**
   * @param string
   */
  public function setEndTimeUsec($endTimeUsec)
  {
    $this->endTimeUsec = $endTimeUsec;
  }
  /**
   * @return string
   */
  public function getEndTimeUsec()
  {
    return $this->endTimeUsec;
  }
  /**
   * @param SpeechS3Locale[]
   */
  public function setRankedTopSupportedLanguages($rankedTopSupportedLanguages)
  {
    $this->rankedTopSupportedLanguages = $rankedTopSupportedLanguages;
  }
  /**
   * @return SpeechS3Locale[]
   */
  public function getRankedTopSupportedLanguages()
  {
    return $this->rankedTopSupportedLanguages;
  }
  /**
   * @param string
   */
  public function setStartTimeUsec($startTimeUsec)
  {
    $this->startTimeUsec = $startTimeUsec;
  }
  /**
   * @return string
   */
  public function getStartTimeUsec()
  {
    return $this->startTimeUsec;
  }
  /**
   * @param string
   */
  public function setTopLanguageConfidence($topLanguageConfidence)
  {
    $this->topLanguageConfidence = $topLanguageConfidence;
  }
  /**
   * @return string
   */
  public function getTopLanguageConfidence()
  {
    return $this->topLanguageConfidence;
  }
  /**
   * @param bool
   */
  public function setVoicedUtterance($voicedUtterance)
  {
    $this->voicedUtterance = $voicedUtterance;
  }
  /**
   * @return bool
   */
  public function getVoicedUtterance()
  {
    return $this->voicedUtterance;
  }
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(SpeechS3LanguageIdentificationResult::class, 'Google_Service_Contentwarehouse_SpeechS3LanguageIdentificationResult');


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

<title>PaymentTypes</title>
<meta name="date" content="2018-11-08">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.mercadopago.android.px.model

Class PaymentTypes

java.lang.Object

com.mercadopago.android.px.model.PaymentTypes

public final class PaymentTypes
extends java.lang.Object

Field Summary

Fields

Modifier and Type
Field and Description

static java.lang.String
ACCOUNT_MONEY

Deprecated.

static java.lang.String
ATM

static java.lang.String
BANK_TRANSFER

static java.lang.String
CREDIT_CARD

static java.lang.String
DEBIT_CARD

static java.lang.String
DIGITAL_CURRENCY

static java.lang.String
PLUGIN

static java.lang.String
PREPAID_CARD

static java.lang.String
TICKET

Method Summary

All Methods Static Methods Concrete Methods Deprecated Methods

Modifier and Type
Method and Description

static java.util.List<java.lang.String>
getAllPaymentTypes()

static boolean
isAccountMoney(java.lang.String type)

Deprecated.

static boolean
isCardPaymentType(java.lang.String paymentType)

static boolean
isCreditCardPaymentType(java.lang.String paymentTypeId)

static boolean
isPlugin(java.lang.String type)

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

CREDIT_CARD

public static java.lang.String CREDIT_CARD

DEBIT_CARD

public static java.lang.String DEBIT_CARD

PREPAID_CARD

public static java.lang.String PREPAID_CARD

TICKET

public static java.lang.String TICKET

ATM

public static java.lang.String ATM

DIGITAL_CURRENCY

public static java.lang.String DIGITAL_CURRENCY

BANK_TRANSFER

public static java.lang.String BANK_TRANSFER

ACCOUNT_MONEY

@Deprecated
public static java.lang.String ACCOUNT_MONEY

Deprecated.

PLUGIN

public static java.lang.String PLUGIN

Method Detail

isCardPaymentType

public static boolean isCardPaymentType(java.lang.String paymentType)

isAccountMoney

@Deprecated
public static boolean isAccountMoney(java.lang.String type)

Deprecated.

isPlugin

public static boolean isPlugin(java.lang.String type)

getAllPaymentTypes

public static java.util.List<java.lang.String> getAllPaymentTypes()

isCreditCardPaymentType

public static boolean isCreditCardPaymentType(java.lang.String paymentTypeId)

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
module ExampleGroupTimer
  class TimedGroup < TimedItem
    attr_reader :subgroups, :examples, :current_example

    def initialize(*args)
      super
      @subgroups, @examples = [], []
    end

    def add_group(group)
      g = TimedGroup.new(group, self)
      @subgroups << g
      g
    end

    def add_example(example)
      @current_example = TimedItem.new(example, self)
      examples << @current_example
    end

    def finish_current_example
      @current_example.finish
      @current_example = nil
    end

    def report
      super
      puts "<ol>"
      (examples + subgroups).sort_by(&:duration).reverse.each(&:report)
      puts "</ol>"
    end
  end
end


text:
namespace simcode {
namespace net {
class ThreadInfo
{
public:
    ThreadInfo():status(0), is_dynamic(false), is_busy(false), is_closed(false){}
    ~ThreadInfo(){if (thread_ptr) thread_ptr->detach();}
    bool is_dynamic; //是否动态创建的
    volatile bool is_busy; //是否忙碌
    volatile bool is_closed; //是否关闭
    volatile int64_t status;
    SimThreadPtr thread_ptr;
    void stop()
    {
        is_closed = true;
    }
};
class DynamicThreadPool
{
public:
    typedef simex::function<void()> TaskCallback;
    DynamicThreadPool(EventLoop*);
    virtual ~DynamicThreadPool();
    void start();
    void stop();
    int addTask(const TaskCallback& cb);
    void setMaxIdle(int n){maxIdle_ = n;}
    void setMaxActive(int n){maxActive_ = n;}
    void setMaxTaskSize(int n){maxTaskSize_ = n;}
    void setMaxLifeTime(int n){maxLifeTime_ = n;}
    void setMaxWaitTime(int n){maxWaitTime_ = n;}
    int taskNum();       //当前队列的任务数
    int threadNum() {return threadNum_.load();}
    void busyThread(std::vector<std::thread::id>&); //当前正在执行任务的线程数
private:
    void AddThread();
    void DelThread(const SharedPtr<ThreadInfo>&);
    void timerCreate(); //定时扫描并创建所需线程
    void timerClose();  //定时扫描并关闭多余线程
    void doTask(const SharedPtr<ThreadInfo>&);
    void turnOn(){dynamic_turn_ = true;}
    void turnOff(){dynamic_turn_ = false;}
    bool isTurnOn(){return dynamic_turn_;}
private:

    EventLoop* loop_; //定时器
    std::vector<SharedPtr<ThreadInfo>> defaultPool_;
    std::map<std::thread::id, SharedPtr<ThreadInfo>> pool_;
    std::deque<TaskCallback> deq_;
    Mutex mtx_;
    Mutex mapMtx_;
    ConditionVar cond_;
    int maxIdle_;
    int maxActive_;
    int maxTaskSize_;
    int maxLifeTime_;
    int64_t maxWaitTime_; //msec 允许等待时间
    std::atomic<int> threadNum_;
    volatile bool isClosed_;
    volatile bool dynamic_turn_;
    volatile int64_t curmsec_;
    std::vector<int> timerfds_;
};

}//endof namespace net
}//endof namespace simcode

#endif


text:
require 'test_helper'

class GitFetcherTest < ActiveSupport::TestCase
  before do
    options = {
      repo_owner: 'pain11',
      repo_name: 'Facebook'
    }
    @git_fetcher = GitFetcher.new(**options)
    create :repository, name: 'Facebook', owner: 'pain11'
  end

  describe 'Commits found for given date range' do
    before do
      GitFetcher.any_instance.stubs(:fetch_commits).returns(
        JSON.parse(File.read('test/fixtures/git_commit.json'))
      )
      GitFetcher.any_instance.stubs(:fetch_pull_request).returns(
        Hashie::Mash.new(
          JSON.parse(File.read('test/fixtures/pull_request.json'))
        )
      )
      GitFetcher.any_instance.stubs(:fetch_commit_stats).returns(
        Hashie::Mash.new(
          JSON.parse(File.read('test/fixtures/git_commit_stats.json'))
        ).stats
      )
    end

    describe 'Committer is not present in code-curiosity' do
      test 'do not create commit record' do
        assert_equal 0, Commit.count
        @git_fetcher.fetch_and_store_commits
        assert_equal 0, Commit.count
      end
    end

    describe 'Committer is present in code-curiosity' do
      before do
        @user = create(
                  :user,
                  github_handle: 'pain11',
                  created_at: Date.parse('2018-02-04')
                )
      end

      test 'create commits which are committed after sign up' do
        assert_equal 0, Commit.count
        @git_fetcher.fetch_and_store_commits
        assert_equal 1, Commit.count
      end

      describe 'commit has pull request associated with it' do
        test 'should create pull request' do
          assert_equal 0, PullRequest.count
          @git_fetcher.fetch_and_store_commits
          assert_equal 1, Commit.count
          assert_equal 1, PullRequest.count
        end
      end

      describe 'commit has no pull request associated with it' do
        test 'should not create pull request' do
          GitFetcher.any_instance.stubs(:fetch_pull_request).returns(nil)
          assert_equal 0, PullRequest.count
          @git_fetcher.fetch_and_store_commits
          assert_equal 1, Commit.count
          assert_equal 0, PullRequest.count
        end
      end

      test 'do not create commits which are commmitted before sign up' do
        @user.set(created_at: Date.today)
        assert_equal 0, Commit.count
        @git_fetcher.fetch_and_store_commits
        assert_equal 0, Commit.count
      end

      test 'set lines field' do
        assert_equal 0, Commit.count
        @git_fetcher.fetch_and_store_commits
        assert_equal 1, Commit.count
        assert_operator 0, :<, Commit.first.lines
      end
    end
  end

  describe 'Commits not found for given date range' do
    test 'do not create commit record' do
      GitFetcher.any_instance.stubs(:fetch_commits).returns([])
      assert_equal 0, Commit.count
      @git_fetcher.fetch_and_store_commits
      assert_equal 0, Commit.count
    end
  end
end


text:
<?php

namespace Glow\Http\Controllers;

use BadMethodCallException;
use Illuminate\Http\Request;

trait Paginatable
{

    use Listable;

    /**
     * @return array
     */
    protected function listDefaults() {

        return [
            'order_by' => $this->listOrderColumns()[ 0 ],
            'order_dir' => 'asc',
            'per_page' => 10,
            'page' => 1,
        ];
    }

    /**
     * @return array
     */
    protected function listRules() {

        return [
            'order_by' => 'nullable|string|in:' . implode(",", $this->listOrderColumns()),
            'order_dir' => 'nullable|string|in:asc,ASC,desc,DESC',
            'per_page' => 'nullable|integer|min:1',
            'page' => 'nullable|integer|min:1',
        ];
    }

    /**
     * @param \Illuminate\Http\Request $request
     *
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
     */
    protected function listSlice(Request $request) {

        $params = $this->listParams($request);
        $query = $this->listDefaultQuery()
                      ->orderBy($params[ 'order_by' ], $params[ 'order_dir' ]);

        return $query->paginate($params[ 'per_page' ], ['*'], 'page', $params[ 'page' ]);
    }
}