text:
"""A place to store information about events, such as format strings, etc."""

import logging
import re

from plaso.lib import errors
from plaso.lib import registry
from plaso.lib import utils

class EventTimestamp(object):
  """Class to manage event data."""
  # The timestamp_desc values.
  ACCESS_TIME = u'Last Access Time'
  CHANGE_TIME = u'Metadata Modification Time'
  CREATION_TIME = u'Creation Time'
  MODIFICATION_TIME = u'Content Modification Time'
  ENTRY_MODIFICATION_TIME = u'Metadata Modification Time'
  # Added time and Creation time are considered the same.
  ADDED_TIME = u'Creation Time'
  # Written time and Modification time are considered the same.
  WRITTEN_TIME = u'Content Modification Time'
  EXIT_TIME = u'Exit Time'
  LAST_RUNTIME = u'Last Time Executed'
  DELETED_TIME = u'Content Deletion Time'

  FILE_DOWNLOADED = u'File Downloaded'
  PAGE_VISITED = u'Page Visited'
  # TODO: change page visited into last visited time.
  LAST_VISITED_TIME = u'Last Visited Time'

  LAST_CHECKED_TIME = u'Last Checked Time'

  EXPIRATION_TIME = u'Expiration Time'
  START_TIME = u'Start Time'
  END_TIME = u'End Time'

  FIRST_CONNECTED = u'First Connection Time'
  LAST_CONNECTED = u'Last Connection Time'

  LAST_PRINTED = u'Last Printed Time'

class EventFormatterManager(object):
  """Class to manage the event formatters."""
  @classmethod
  def GetFormatter(cls, event_object):
    """Retrieves the formatter for a specific event object.

       This function builds a map of data types and the corresponding event
       formatters. At the moment this map is only build once.

    Args:
      event_object: The event object (EventObject) which is used to identify
                    the formatter.

    Returns:
      The corresponding formatter (EventFormatter) if available or None.

    Raises:
      RuntimeError if a duplicate event formatter is found while building
      the map of event formatters.
    """
    if not hasattr(cls, 'event_formatters'):
      cls.event_formatters = {}
      cls.default_formatter = DefaultFormatter()
      for cls_formatter in EventFormatter.classes:
        try:
          formatter = EventFormatter.classes[cls_formatter]()

          # Raise on duplicate formatters.
          if formatter.DATA_TYPE in cls.event_formatters:
            raise RuntimeError((
                u'event formatter for data type: {:s} defined in: {:s} and '
                u'{:s}.').format(
                    formatter.DATA_TYPE, cls_formatter,
                    cls.event_formatters[
                        formatter.DATA_TYPE].__class__.__name__))
          cls.event_formatters[formatter.DATA_TYPE] = formatter
        except RuntimeError as exeception:
          # Ignore broken formatters.
          logging.warning(u'{:s}'.format(exeception))

      cls.event_formatters.setdefault(None)

    if event_object.data_type in cls.event_formatters:
      return cls.event_formatters[event_object.data_type]
    else:
      logging.warning(
          u'Using default formatter for data type: {:s}'.format(
              event_object.data_type))
      return cls.default_formatter

  @classmethod
  def GetSourceStrings(cls, event_object):
    """Retrieves the formatted source long and short strings for an event.

    Args:
      event_object: The event object (EventObject) which is used to identify
                    the formatter.

    Returns:
      A list that contains the source_short and source_long version of the
      event.
    """
    formatter = cls.GetFormatter(event_object)
    if not formatter:
      return u'', u''
    return formatter.GetSources(event_object)

  @classmethod
  def GetMessageStrings(cls, event_object):
    """Retrieves the formatted message strings for a specific event object.

    Args:
      event_object: The event object (EventObject) which is used to identify
                    the formatter.

    Returns:
      A list that contains both the longer and shorter version of the message
      string.
    """
    formatter = cls.GetFormatter(event_object)
    if not formatter:
      return u'', u''
    return formatter.GetMessages(event_object)

class EventFormatter(object):
  """Base class to format event type specific data using a format string.

     Define the (long) format string and the short format string by defining
     FORMAT_STRING and FORMAT_STRING_SHORT. The syntax of the format strings
     is similar to that of format() where the place holder for a certain
     event object attribute is defined as {attribute_name}.
  """
  __metaclass__ = registry.MetaclassRegistry
  __abstract = True

  # The data type is a unique identifier for the event data. The current
  # approach is to define it as human readable string in the format
  # root:branch: ... :leaf, e.g. a page visited entry inside a Chrome History
  # database is defined as: chrome:history:page_visited.
  DATA_TYPE = u'internal'

  # The format string.
  FORMAT_STRING = u''
  FORMAT_STRING_SHORT = u''

  # The source short and long strings.
  SOURCE_SHORT = u'LOG'
  SOURCE_LONG = u''

  def __init__(self):
    """Set up the formatter and determine if this is the right formatter."""
    # Forcing the format string to be unicode to make sure we don't
    # try to format it as an ASCII string.
    self.format_string = unicode(self.FORMAT_STRING)
    self.format_string_short = unicode(self.FORMAT_STRING_SHORT)
    self.source_string = unicode(self.SOURCE_LONG)
    self.source_string_short = unicode(self.SOURCE_SHORT)

  def GetMessages(self, event_object):
    """Return a list of messages extracted from an event object.

    The l2t_csv and other formats are dependent on a message field,
    referred to as description_long and description_short in l2t_csv.

    Plaso does not store this field explicitly, it only contains a format
    string and the appropriate attributes.

    This method takes the format string and converts that back into a
    formatted string that can be used for display.

    Args:
      event_object: The event object (EventObject) containing the event
                    specific data.

    Returns:
      A list that contains both the longer and shorter version of the message
      string.

    Raises:
      WrongFormatter: if the event object cannot be formatted by the formatter.
    """
    if self.DATA_TYPE != event_object.data_type:
      raise errors.WrongFormatter(u'Unsupported data type: {:s}.'.format(
          event_object.data_type))

    event_values = event_object.GetValues()

    try:
      msg = self.format_string.format(**event_values)
    except KeyError as exception:
      msgs = []
      msgs.append(u'Format error: [{0:s}] for: <{1:s}>'.format(
          exception, self.format_string))
      for attr, value in event_object.GetValues().iteritems():
        msgs.append(u'{0}: {1}'.format(attr, value))

      msg = u' '.join(msgs)

    # Strip carriage return and linefeed form the message strings.
    # Using replace function here because it is faster
    # than re.sub() or string.strip().
    msg = msg.replace('\r', u'').replace('\n', u'')

    if not self.format_string_short:
      msg_short = msg
    else:
      try:
        msg_short = self.format_string_short.format(**event_values)
        # Using replace function here because it is faster
        # than re.sub() or string.strip().
        msg_short = msg_short.replace('\r', u'').replace('\n', u'')
      except KeyError:
        msg_short = u'Unable to format short message string: {0:s}'.format(
            self.format_string_short)

    # Truncate the short message string if necessary.
    if len(msg_short) > 80:
      msg_short = u'{:s}...'.format(msg_short[0:77])

    return msg, msg_short

  def GetSources(self, event_object):
    """Return a list containing source short and long."""
    if self.DATA_TYPE != event_object.data_type:
      raise errors.WrongFormatter('Unsupported data type: {:s}.'.format(
          event_object.data_type))

    return self.source_string_short, self.source_string

class ConditionalEventFormatter(EventFormatter):
  """Base class to conditionally format event data using format string pieces.

     Define the (long) format string and the short format string by defining
     FORMAT_STRING_PIECES and FORMAT_STRING_SHORT_PIECES. The syntax of the
     format strings pieces is similar to of the event formatter
     (EventFormatter). Every format string piece should contain a single
     attribute name or none.

     FORMAT_STRING_SEPARATOR is used to control the string which the separate
     string pieces should be joined. It contains a space by default.
  """
  __abstract = True

  # The format string pieces.
  FORMAT_STRING_PIECES = [u'']
  FORMAT_STRING_SHORT_PIECES = [u'']

  # The separator used to join the string pieces.
  FORMAT_STRING_SEPARATOR = u' '

  def __init__(self):
    """Initializes the conditional formatter.

       A map is build of the string pieces and their corresponding attribute
       name to optimize conditional string formatting.

    Raises:
      RuntimeError: when an invalid format string piece is encountered.
    """
    super(ConditionalEventFormatter, self).__init__()

    # The format string can be defined as:
    # {name}, {name:format}, {name!conversion}, {name!conversion:format}
    regexp = re.compile('{[a-z][a-zA-Z0-9_]*[!]?[^:}]*[:]?[^}]*}')
    regexp_name = re.compile('[a-z][a-zA-Z0-9_]*')

    # The format string pieces map is a list containing the attribute name
    # per format string piece. E.g. ["Description: {description}"] would be
    # mapped to: [0] = "description". If the string piece does not contain
    # an attribute name it is treated as text that does not needs formatting.
    self._format_string_pieces_map = []
    for format_string_piece in self.FORMAT_STRING_PIECES:
      result = regexp.findall(format_string_piece)
      if not result:
        # The text format string piece is stored as an empty map entry to
        # keep the index in the map equal to the format string pieces.
        self._format_string_pieces_map.append('')
      elif len(result) == 1:
        # Extract the attribute name.
        attribute_name = regexp_name.findall(result[0])[0]
        self._format_string_pieces_map.append(attribute_name)
      else:
        raise RuntimeError((
            u'Invalid format string piece: [{:s}] contains more than 1 '
            u'attribute name.').format(format_string_piece))

    self._format_string_short_pieces_map = []
    for format_string_piece in self.FORMAT_STRING_SHORT_PIECES:
      result = regexp.findall(format_string_piece)
      if not result:
        # The text format string piece is stored as an empty map entry to
        # keep the index in the map equal to the format string pieces.
        self._format_string_short_pieces_map.append('')
      elif len(result) == 1:
        # Extract the attribute name.
        attribute_name = regexp_name.findall(result[0])[0]
        self._format_string_short_pieces_map.append(attribute_name)
      else:
        raise RuntimeError((
            u'Invalid short format string piece: [{:s}] contains more '
            u'than 1 attribute name.').format(format_string_piece))

  def GetMessages(self, event_object):
    """Returns a list of messages extracted from an event object.

    Args:
      event_object: The event object (EventObject) containing the event
                    specific data.

    Returns:
      A list that contains both the longer and shorter version of the message
      string.
    """
    if self.DATA_TYPE != event_object.data_type:
      raise errors.WrongFormatter(u'Unsupported data type: {:s}.'.format(
          event_object.data_type))

    # Using getattr here to make sure the attribute is not set to None.
    # if A.b = None, hasattr(A, b) is True but getattr(A, b, None) is False.
    string_pieces = []
    for map_index, attribute_name in enumerate(self._format_string_pieces_map):
      if not attribute_name or hasattr(event_object, attribute_name):
        if attribute_name:
          attribute = getattr(event_object, attribute_name, None)
          # If an attribute is an int, yet has zero value we want to include
          # that in the format string, since that is still potentially valid
          # information. Otherwise we would like to skip it.
          if type(attribute) not in (bool, int, long, float) and not attribute:
            continue
        string_pieces.append(self.FORMAT_STRING_PIECES[map_index])
    self.format_string = unicode(
        self.FORMAT_STRING_SEPARATOR.join(string_pieces))

    string_pieces = []
    for map_index, attribute_name in enumerate(
        self._format_string_short_pieces_map):
      if not attribute_name or getattr(event_object, attribute_name, None):
        string_pieces.append(self.FORMAT_STRING_SHORT_PIECES[map_index])
    self.format_string_short = unicode(
        self.FORMAT_STRING_SEPARATOR.join(string_pieces))

    return super(ConditionalEventFormatter, self).GetMessages(event_object)

class DefaultFormatter(EventFormatter):
  """Default formatter for events that do not have any defined formatter."""

  DATA_TYPE = u'event'
  FORMAT_STRING = u'<WARNING DEFAULT FORMATTER> Attributes: {attribute_driven}'
  FORMAT_STRING_SHORT = u'<DEFAULT> {attribute_driven}'

  def GetMessages(self, event_object):
    """Return a list of messages extracted from an event object."""
    text_pieces = []

    for key, value in event_object.GetValues().items():
      if key in utils.RESERVED_VARIABLES:
        continue
      text_pieces.append(u'{}: {}'.format(key, value))

    event_object.attribute_driven = u' '.join(text_pieces)
    # Due to the way the default formatter behaves it requires the data_type
    # to be set as 'event', otherwise it will complain and deny processing
    # the event.
    # TODO: Change this behavior and allow the default formatter to accept
    # arbitrary data types (as it should).
    old_data_type = getattr(event_object, 'data_type', None)
    event_object.data_type = self.DATA_TYPE
    msg, msg_short = super(DefaultFormatter, self).GetMessages(event_object)
    event_object.data_type = old_data_type
    return msg, msg_short

class TextEventFormatter(EventFormatter):
  """Text event formatter."""

  DATA_TYPE = u'text:entry'
  FORMAT_STRING = u'{text}'


text:
Then /^I should see the current version of bard$/ do
  version = File.read("#{ROOT}/VERSION").chomp
  @stdout.should =~ /bard\s+\(#{Regexp.escape(version)}\)/
end

Then /^I should see the current version of git$/ do
  version = `git --version`[/[0-9]+\.[0-9]+\.[0-9]+/]
  @stdout.should =~ /git\s+\(#{Regexp.escape(version)}/
end

Then /^I should see the current version of rubygems$/ do
  version = `gem --version`.chomp
  @stdout.should =~ /rubygems\s+\(#{Regexp.escape(version)}\)/
end

Then /^I should see the current version of ruby$/ do
  version = `ruby --version`[/[0-9]+\.[0-9]+\.[0-9]+/]
  @stdout.should =~ /ruby\s+\(#{Regexp.escape(version)}\)/
end

Given /^"([^\"]*)" is missing$/ do |file|
  type "rm #{file}"
end

Given /^the database is missing$/ do
  File.open "config/database.yml", "w" do |f|
    f.puts <<-DB
development:
  adapter: mysql
  username: root
  password:
  database: bad_bad_bad
  socket: /var/run/mysqld/mysqld.sock
DB
  end
end

Given /^the submodule is missing$/ do
  type "rm -rf submodule"
  type "mkdir submodule"
end

Given /^the submodule has a detached head$/ do
  Dir.chdir "submodule" do
    type "git checkout `git rev-parse HEAD`"
  end
end

redpajama_set_name: RedPajamaGithub


text:
package com.bennavetta.util.tycho.impl;

import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.maven.model.Model;
import org.apache.maven.model.Repository;
import org.sonatype.aether.artifact.Artifact;
import org.sonatype.aether.util.artifact.DefaultArtifact;

import com.bennavetta.util.tycho.ArtifactInfo;
import com.bennavetta.util.tycho.WrapRequest;

public class DefaultWrapRequest implements WrapRequest
{
	private Model parent;
	private Set<ArtifactInfo> artifacts;
	private List<Repository> repositories;
	private File bndDirectory;

	public Model getParent()
	{
		return parent;
	}
	public void setParent(Model parent)
	{
		this.parent = parent;
	}

	public List<Repository> getRepositories()
	{
		return repositories;
	}
	public void setRepositories(List<Repository> repositories)
	{
		this.repositories = repositories;
	}

	public void addRepository(Repository repository)
	{
		if(repositories == null)
			repositories = new ArrayList<>();
		repositories.add(repository);
	}

	@Override
	public Set<ArtifactInfo> getArtifacts()
	{
		return artifacts;
	}

	public void setArtifacts(Set<ArtifactInfo> artifacts)
	{
		this.artifacts = artifacts;
	}

	public void addArtifact(ArtifactInfo info)
	{
		if(artifacts == null)
			artifacts = new HashSet<>();
		artifacts.add(info);
	}

	public void addArtifact(Artifact artifact)
	{
		if(artifacts == null)
			artifacts = new HashSet<>();
		artifacts.add(new DefaultArtifactInfo(artifact));
	}

	public void addArtifact(String groupId, String artifactId, String version)
	{
		addArtifact(new DefaultArtifact(groupId + ":" + artifactId + ":" + version));
	}

	public File getBndDirectory()
	{
		return bndDirectory;
	}
	public void setBndDirectory(File bndDirectory)
	{
		this.bndDirectory = bndDirectory;
	}
}


text:
/*********************************************************************
*
* Software License Agreement (BSD License)
*
*  Author: Noé Pérez Higueras
*********************************************************************/
#ifndef PURE_PLANNER_ROS_H_
#define PURE_PLANNER_ROS_H_

#include <ros/ros.h>
#include <costmap_2d/costmap_2d.h>
#include <costmap_2d/costmap_2d_publisher.h>
#include <costmap_2d/costmap_2d_ros.h>

#include <simple_local_planner/world_model.h>
#include <simple_local_planner/costmap_model.h>
#include <simple_local_planner/pure_planner.h>

#include <tf/transform_datatypes.h>

#include <nav_msgs/Odometry.h>
#include <geometry_msgs/PoseStamped.h>
#include <geometry_msgs/Twist.h>
#include <geometry_msgs/Point.h>

#include <tf/transform_listener.h>

#include <boost/thread.hpp>

#include <string>

#include <angles/angles.h>

#include <nav_core/base_local_planner.h>

//Dynamic reconfigure
#include <dynamic_reconfigure/server.h>
#include <simple_local_planner/SimpleLocalPlannerConfig.h>

#include <simple_local_planner/odometry_helper_ros.h>

namespace simple_local_planner {
  /**
   * @class TrajectoryPlannerROS
   * @brief A ROS wrapper for the trajectory controller that queries the param server to construct a controller
   */
  class PurePlannerROS : public nav_core::BaseLocalPlanner {
    public:
      /**
       * @brief  Default constructor for the ros wrapper
       */
      PurePlannerROS();

      /**
       * @brief  Constructs the ros wrapper
       * @param name The name to give this instance of the trajectory planner
       * @param tf A pointer to a transform listener
       * @param costmap The cost map to use for assigning costs to trajectories
       */
      PurePlannerROS(std::string name,
                           tf::TransformListener* tf,
                           costmap_2d::Costmap2DROS* costmap_ros);

      /**
       * @brief  Constructs the ros wrapper
       * @param name The name to give this instance of the trajectory planner
       * @param tf A pointer to a transform listener
       * @param costmap The cost map to use for assigning costs to trajectories
       */
      void initialize(std::string name, tf::TransformListener* tf,
          costmap_2d::Costmap2DROS* costmap_ros);

      /**
       * @brief  Destructor for the wrapper
       */
      ~PurePlannerROS();

      /**
       * @brief  Given the current position, orientation, and velocity of the robot,
       * compute velocity commands to send to the base
       * @param cmd_vel Will be filled with the velocity command to be passed to the robot base
       * @return True if a valid trajectory was found, false otherwise
       */
      bool computeVelocityCommands(geometry_msgs::Twist& cmd_vel);

      /**
       * @brief  Set the plan that the controller is following
       * @param orig_global_plan The plan to pass to the controller
       * @return True if the plan was updated successfully, false otherwise
       */
      bool setPlan(const std::vector<geometry_msgs::PoseStamped>& orig_global_plan);

      /**
       * @brief  Check if the goal pose has been achieved
       * @return True if achieved, false otherwise
       */
      bool isGoalReached();

      bool isInitialized() {
        return initialized_;
      }

      /** @brief Return the inner TrajectoryPlanner object.  Only valid after initialize(). */
      PurePlanner* getPlanner() const { return tc_; }

    private:
      /**
       * @brief Callback to update the local planner's parameters based on dynamic reconfigure
       */
      void reconfigureCB(SimpleLocalPlannerConfig &config, uint32_t level);

      /**
       * @brief Once a goal position is reached... rotate to the goal orientation
       * @param  global_pose The pose of the robot in the global frame
       * @param  robot_vel The velocity of the robot
       * @param  goal_th The desired th value for the goal
       * @param  cmd_vel The velocity commands to be filled
       * @return  True if a valid trajectory was found, false otherwise
       */
      //bool rotateToGoal(const tf::Stamped<tf::Pose>& global_pose, const tf::Stamped<tf::Pose>& robot_vel, double goal_th, geometry_msgs::Twist& cmd_vel);

      /**
       * @brief Stop the robot taking into account acceleration limits
       * @param  global_pose The pose of the robot in the global frame
       * @param  robot_vel The velocity of the robot
       * @param  cmd_vel The velocity commands to be filled
       * @return  True if a valid trajectory was found, false otherwise
       */
      //bool stopWithAccLimits(const tf::Stamped<tf::Pose>& global_pose, const tf::Stamped<tf::Pose>& robot_vel, geometry_msgs::Twist& cmd_vel);

      //std::vector<double> loadYVels(ros::NodeHandle node);

      /*double sign(double x){
        return x < 0.0 ? -1.0 : 1.0;
      }*/

      WorldModel* world_model_; ///< @brief The world model that the controller will use
      PurePlanner* tc_; ///< @brief The trajectory controller

      costmap_2d::Costmap2DROS* costmap_ros_; ///< @brief The ROS wrapper for the costmap the controller will use
      costmap_2d::Costmap2D* costmap_; ///< @brief The costmap the controller will use
      //MapGridVisualizer map_viz_; ///< @brief The map grid visualizer for outputting the potential field generated by the cost function
      tf::TransformListener* tf_; ///< @brief Used for transforming point clouds
      std::string global_frame_; ///< @brief The frame in which the controller will run
      //double max_sensor_range_; ///< @brief Keep track of the effective maximum range of our sensors
      //nav_msgs::Odometry base_odom_; ///< @brief Used to get the velocity of the robot
      std::string robot_base_frame_; ///< @brief Used as the base frame id of the robot
      //double rot_stopped_velocity_, trans_stopped_velocity_;
      std::vector<geometry_msgs::PoseStamped> global_plan_;
      //bool prune_plan_;
      boost::recursive_mutex odom_lock_;

	  //Controller freq
	  double controller_freq_;

	  // Robot Configuration Parameters
	  double max_vel_x_, min_vel_x_;
      double max_vel_th_, min_vel_th_;
      double max_trans_acc_;
	  double max_rot_acc_;
	  double min_in_place_vel_th_;

	  //Goal tolerance parameters
	  double yaw_goal_tolerance_;
  	  double xy_goal_tolerance_;
  	  double wp_tolerance_;

	  double sim_time_;
  	  double sim_granularity_;
  	  double angular_sim_granularity_;

	  double sim_period_;
      bool rotating_to_goal_;
      bool reached_goal_;

      ros::Publisher g_plan_pub_, l_plan_pub_;

      dynamic_reconfigure::Server<SimpleLocalPlannerConfig> *dsrv_;
      simple_local_planner::SimpleLocalPlannerConfig default_config_;
      bool setup_;

      bool initialized_;

	  simple_local_planner::OdometryHelperRos odom_helper_;

      std::vector<geometry_msgs::Point> footprint_spec_;
  };
};
#endif


text:
                <button type="button" class="close" data-dismiss="modal" ng-click="done();">×Close</button>

Value Set Metrics

Completeness

Entries: {{ metrics.entriesCount }}

Missing: {{ metrics.missing.length }}

                    <missing-tree metrics="metrics"></missing-tree>

Average Lenth of Path to LCA

 0">

Similarity

                                    Value Set
                                    % Similar

                                    {{ similarity.indexMap[$index] }}
                                    {{ score | percentage:1}}

                <button type="button" class="btn btn-default" ng-click="done()">Done</button>


text:
package org.hisp.dhis.datasummary;

import java.util.HashMap;
import java.util.Map;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;

/**
 * DataSummary object to transfer System Statistics
 *
 * @author Joao Antunes
 */
@JacksonXmlRootElement
public class DataSummary
{
    private Map<String, Long> objectCounts = new HashMap<>();

    private Map<Integer, Integer> activeUsers = new HashMap<>();

    private Map<String, Integer> userInvitations = new HashMap<>();

    private Map<Integer, Integer> dataValueCount = new HashMap<>();

    private Map<Integer, Long> eventCount = new HashMap<>();

    public DataSummary()
    {
    }

    public DataSummary( Map<String, Long> objectCounts,
        Map<Integer, Integer> activeUsers, Map<String, Integer> userInvitations,
        Map<Integer, Integer> dataValueCount, Map<Integer, Long> eventCount )
    {
        this.objectCounts = objectCounts;
        this.activeUsers = activeUsers;
        this.userInvitations = userInvitations;
        this.dataValueCount = dataValueCount;
        this.eventCount = eventCount;
    }

    @JsonProperty
    public Map<String, Long> getObjectCounts()
    {
        return objectCounts;
    }

    public void setObjectCounts( Map<String, Long> objectCounts )
    {
        this.objectCounts = objectCounts;
    }

    @JsonProperty
    public Map<Integer, Integer> getActiveUsers()
    {
        return activeUsers;
    }

    public void setActiveUsers( Map<Integer, Integer> activeUsers )
    {
        this.activeUsers = activeUsers;
    }

    @JsonProperty
    public Map<String, Integer> getUserInvitations()
    {
        return userInvitations;
    }

    public void setUserInvitations( Map<String, Integer> userInvitations )
    {
        this.userInvitations = userInvitations;
    }

    @JsonProperty
    public Map<Integer, Integer> getDataValueCount()
    {
        return dataValueCount;
    }

    public void setDataValueCount( Map<Integer, Integer> dataValueCount )
    {
        this.dataValueCount = dataValueCount;
    }

    @JsonProperty
    public Map<Integer, Long> getEventCount()
    {
        return eventCount;
    }

    @JsonProperty
    public void setEventCount( Map<Integer, Long> eventCount )
    {
        this.eventCount = eventCount;
    }
}


text:
/* jshint browser: true */
/* global Backbone, _, girder */

(function (app) {
    "use strict";

    // A model of the locations Sitar looks for visualizations and data.
    app.model.SitarRoot = Backbone.Model.extend({
        initialize: function (options) {
            options = options || {};
            this.login = options.login;

            if (!this.login) {
                throw new Error("option 'login' is required");
            }
        },

        sync: function (method, model, options) {
            switch (method) {
                case "read": {
                    return this.readHandler(options);
                }

                default: {
                    throw new Error("action '" + method + "' not allowed");
                }
            }
        },

        validate: function (attr) {
            if (!attr.visFolder) {
                return "visFolder missing";
            } else if (!attr.dataFolder) {
                return "dataFolder missing";
            }
        },

        readHandler: function (options) {
            var success,
                error,
                failure;

            options = options || {};

            success = options.success || Backbone.$.noop;
            error = options.error || Backbone.$.noop;

            failure = Backbone.$.Deferred();
            failure.reject();

            return girder.restRequest({
                method: "GET",
                path: "/user",
                data: {
                    text: this.login
                }
            }).then(_.bind(function (users) {
                users = _.where(users, {
                    login: this.login
                });

                if (users.length === 0) {
                    return failure;
                }

                return girder.restRequest({
                    path: "/folder",
                    data: {
                        parentType: "user",
                        parentId: users[0]._id,
                        text: "sitar"
                    }
                });
            }, this)).then(function (home) {
                home = home && home[0] && home[0]._id;

                if (home) {
                    return Backbone.$.when(
                        girder.restRequest({
                            path: "/folder",
                            data: {
                                parentType: "folder",
                                parentId: home,
                                text: "visualizations"
                            }
                        }),

                        girder.restRequest({
                            path: "/folder",
                            data: {
                                parentType: "folder",
                                parentId: home,
                                text: "data"
                            }
                        })
                    );
                } else {
                    return failure;
                }
            }).then(_.bind(function (visFolder, dataFolder) {
                this.set("visFolder", visFolder[0][0]._id);
                this.set("dataFolder", dataFolder[0][0]._id);

                success();
            }, this), error);
        }
    });
}(window.app));


text:
package com.microsoft.azure.management.sql.v2014_04_01.implementation;

import com.microsoft.azure.arm.model.implementation.WrapperImpl;
import com.microsoft.azure.management.sql.v2014_04_01.BackupLongTermRetentionVaults;
import rx.Observable;
import rx.functions.Func1;
import java.util.List;
import com.microsoft.azure.management.sql.v2014_04_01.BackupLongTermRetentionVault;

class BackupLongTermRetentionVaultsImpl extends WrapperImpl<BackupLongTermRetentionVaultsInner> implements BackupLongTermRetentionVaults {
    private final SqlManager manager;

    BackupLongTermRetentionVaultsImpl(SqlManager manager) {
        super(manager.inner().backupLongTermRetentionVaults());
        this.manager = manager;
    }

    public SqlManager manager() {
        return this.manager;
    }

    @Override
    public BackupLongTermRetentionVaultImpl define(String name) {
        return wrapModel(name);
    }

    private BackupLongTermRetentionVaultImpl wrapModel(BackupLongTermRetentionVaultInner inner) {
        return  new BackupLongTermRetentionVaultImpl(inner, manager());
    }

    private BackupLongTermRetentionVaultImpl wrapModel(String name) {
        return new BackupLongTermRetentionVaultImpl(name, this.manager());
    }

    @Override
    public Observable<BackupLongTermRetentionVault> listByServerAsync(String resourceGroupName, String serverName) {
        BackupLongTermRetentionVaultsInner client = this.inner();
        return client.listByServerAsync(resourceGroupName, serverName)
        .flatMap(new Func1<List<BackupLongTermRetentionVaultInner>, Observable<BackupLongTermRetentionVaultInner>>() {
            @Override
            public Observable<BackupLongTermRetentionVaultInner> call(List<BackupLongTermRetentionVaultInner> innerList) {
                return Observable.from(innerList);
            }
        })
        .map(new Func1<BackupLongTermRetentionVaultInner, BackupLongTermRetentionVault>() {
            @Override
            public BackupLongTermRetentionVault call(BackupLongTermRetentionVaultInner inner) {
                return wrapModel(inner);
            }
        });
    }

    @Override
    public Observable<BackupLongTermRetentionVault> getAsync(String resourceGroupName, String serverName) {
        BackupLongTermRetentionVaultsInner client = this.inner();
        return client.getAsync(resourceGroupName, serverName)
        .map(new Func1<BackupLongTermRetentionVaultInner, BackupLongTermRetentionVault>() {
            @Override
            public BackupLongTermRetentionVault call(BackupLongTermRetentionVaultInner inner) {
                return wrapModel(inner);
            }
       });
    }

}


text:
require 'spec_helper'

describe Hashie do
  it 'has a version' do
    Hashie::VERSION.should_not be_nil
  end
end


text:
package html_to_image;

import gui.ava.html.image.generator.HtmlImageGenerator;

/**
 * @author li
 * @version 1 (2015年5月26日 上午10:33:48)
 * @since Java7
 */
public class Html2ImageTest {
    public static void main(String[] args) {
        HtmlImageGenerator imageGenerator = new HtmlImageGenerator();
        imageGenerator.loadUrl("http://www.baidu.com");
        imageGenerator.saveAsImage("D:/hello-world.png");
        // imageGenerator.saveAsHtmlWithMap("hello-world.html", "d:/hello-world.png");
        System.err.println("done");
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using Tailviewer.Archiver.Plugins;
using Tailviewer.Archiver.Repository;

namespace Tailviewer.PluginRepository.Entities
{
	/// <summary>
	///     Describes a plugin in the repository's database.
	/// </summary>
	/// <remarks>
	///     Making breaking changes to this type is not advised because it will
	///     break existing repositories.
	/// </remarks>
	[DataContract]
	public class PublishedPlugin
	{
		public PublishedPlugin()
		{
		}

		public PublishedPlugin(IPluginPackageIndex pluginIndex)
		{
			Name = pluginIndex.Name;
			Author = pluginIndex.Author;
			Website = pluginIndex.Website;
			Description = pluginIndex.Description;
			RequiredInterfaces = pluginIndex.ImplementedPluginInterfaces
			                                .Select(x => new PluginInterface(x.InterfaceTypename, x.InterfaceVersion))
			                                .ToList();
		}

		/// <summary>
		///     The identifier (id + version) of the plugin.
		/// </summary>
		[DataMember]
		public PluginIdentifier Identifier { get; set; }

		/// <summary>
		///     The username of the person to add this plugin to the repository.
		/// </summary>
		[DataMember]
		public string Publisher { get; set; }

		/// <summary>
		///     The name of the plugin.
		/// </summary>
		[DataMember]
		public string Name { get; set; }

		/// <summary>
		///     The author of the plugin.
		/// </summary>
		[DataMember]
		public string Author { get; set; }

		/// <summary>
		///     The uri to the website of the plugin.
		/// </summary>
		[DataMember]
		public string Website { get; set; }

		/// <summary>
		///     Human readable description of the plugin.
		/// </summary>
		[DataMember]
		public string Description { get; set; }

		/// <summary>
		///     The size of the plugin in bytes.
		/// </summary>
		[DataMember]
		public long SizeInBytes { get; set; }

		/// <summary>
		///     The date the plugin was built.
		/// </summary>
		/// <remarks>
		///     Is determined from the linker timestamp in the PE header of the plugin's assembly.
		/// </remarks>
		[DataMember]
		public DateTime BuildDate { get; set; }

		/// <summary>
		///     The date the plugin was published (i.e. added) in this repository.
		/// </summary>
		[DataMember]
		public DateTime PublishDate { get; set; }

		/// <summary>
		///     The list of interfaces required by the plugin.
		/// </summary>
		[DataMember]
		public List<PluginInterface> RequiredInterfaces { get; set; }
	}
}


text:
"""A simple three-species chemical kinetics system known as "Robertson's
example", as presented in:

H. H. Robertson, The solution of a set of reaction rate equations, in Numerical
Analysis: An Introduction, J. Walsh, ed., Academic Press, 1966, pp. 178-182.
"""

# exported from PySB model 'robertson'

import numpy
import scipy.weave, scipy.integrate
import collections
import itertools
import distutils.errors

_use_inline = False
# try to inline a C statement to see if inline is functional
try:
    scipy.weave.inline('int i;', force=1)
    _use_inline = True
except distutils.errors.CompileError:
    pass

Parameter = collections.namedtuple('Parameter', 'name value')
Observable = collections.namedtuple('Observable', 'name species coefficients')
Initial = collections.namedtuple('Initial', 'param_index species_index')

class Model(object):

    def __init__(self):
        self.y = None
        self.yobs = None
        self.integrator = scipy.integrate.ode(self.ode_rhs)
        self.integrator.set_integrator('vode', method='bdf',
                                       with_jacobian=True)
        self.y0 = numpy.empty(3)
        self.ydot = numpy.empty(3)
        self.sim_param_values = numpy.empty(6)
        self.parameters = [None] * 6
        self.observables = [None] * 3
        self.initial_conditions = [None] * 3

        self.parameters[0] = Parameter('k1', 0.040000000000000001)
        self.parameters[1] = Parameter('k2', 30000000)
        self.parameters[2] = Parameter('k3', 10000)
        self.parameters[3] = Parameter('A_0', 1)
        self.parameters[4] = Parameter('B_0', 0)
        self.parameters[5] = Parameter('C_0', 0)

        self.observables[0] = Observable('A_total', [0], [1])
        self.observables[1] = Observable('B_total', [1], [1])
        self.observables[2] = Observable('C_total', [2], [1])

        self.initial_conditions[0] = Initial(3, 0)
        self.initial_conditions[1] = Initial(4, 1)
        self.initial_conditions[2] = Initial(5, 2)

    if _use_inline:

        def ode_rhs(self, t, y, p):
            ydot = self.ydot
            scipy.weave.inline(r'''
                ydot[0] = -p[0]*y[0] + p[2]*y[1]*y[2];
                ydot[1] = p[0]*y[0] - p[1]*pow(y[1], 2) - p[2]*y[1]*y[2];
                ydot[2] = p[1]*pow(y[1], 2);
                ''', ['ydot', 't', 'y', 'p'])
            return ydot

    else:

        def ode_rhs(self, t, y, p):
            ydot = self.ydot
            ydot[0] = -p[0]*y[0] + p[2]*y[1]*y[2]
            ydot[1] = p[0]*y[0] - p[1]*pow(y[1], 2) - p[2]*y[1]*y[2]
            ydot[2] = p[1]*pow(y[1], 2)
            return ydot

    def simulate(self, tspan, param_values=None, view=False):
        if param_values is not None:
            # accept vector of parameter values as an argument
            if len(param_values) != len(self.parameters):
                raise Exception("param_values must have length %d" %
                                len(self.parameters))
            self.sim_param_values[:] = param_values
        else:
            # create parameter vector from the values in the model
            self.sim_param_values[:] = [p.value for p in self.parameters]
        self.y0.fill(0)
        for ic in self.initial_conditions:
            self.y0[ic.species_index] = self.sim_param_values[ic.param_index]
        if self.y is None or len(tspan) != len(self.y):
            self.y = numpy.empty((len(tspan), len(self.y0)))
            if len(self.observables):
                self.yobs = numpy.ndarray(len(tspan),
                                zip((obs.name for obs in self.observables),
                                    itertools.repeat(float)))
            else:
                self.yobs = numpy.ndarray((len(tspan), 0))
            self.yobs_view = self.yobs.view(float).reshape(len(self.yobs),
                                                           -1)
        # perform the actual integration
        self.integrator.set_initial_value(self.y0, tspan[0])
        self.integrator.set_f_params(self.sim_param_values)
        self.y[0] = self.y0
        t = 1
        while self.integrator.successful() and self.integrator.t < tspan[-1]:
            self.y[t] = self.integrator.integrate(tspan[t])
            t += 1
        for i, obs in enumerate(self.observables):
            self.yobs_view[:, i] = \
                (self.y[:, obs.species] * obs.coefficients).sum(1)
        if view:
            y_out = self.y.view()
            yobs_out = self.yobs.view()
            for a in y_out, yobs_out:
                a.flags.writeable = False
        else:
            y_out = self.y.copy()
            yobs_out = self.yobs.copy()
        return (y_out, yobs_out)


text:
A simple maze game using SDL2.

##TODO
- end game conditions
- OO?
- proper levels via maze generation or room-based generation
- items?
- enemies?


text:
package org.gdg.frisbee.android.api.model;

public interface GdgResponse {
}


text:
<?php
/**
 * User: zach
 * Date: 6/3/13
 * Time: 7:49 AM
 */

namespace Sherlock\tests;

use Sherlock\Sherlock;

class CustomFilterScoreTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var \Sherlock\sherlock
     */
    protected $object;

    public function __construct()
    {
    }

    /**
     * Sets up the fixture, for example, opens a network connection.
     * This method is called before a test is executed.
     */
    protected function setUp()
    {
        $this->object = new Sherlock();
        $this->object->addNode('localhost', '9200');
    }

    /**
     * Tears down the fixture, for example, closes a network connection.
     * This method is called after a test is executed.
     */
    protected function tearDown()
    {

    }

    /**
     * @covers sherlock\Sherlock\components\queries\CustomFiltersScore::query
     * @covers sherlock\Sherlock\components\queries\CustomFiltersScore::filters
     * @covers sherlock\Sherlock\components\queries\CustomFiltersScore::score_mode
     * @covers sherlock\Sherlock\components\queries\CustomFiltersScore::max_boost
     * @covers sherlock\Sherlock\requests\SearchRequest::query
     * @covers sherlock\Sherlock\requests\SearchRequest::toJSON
     */
    public function testSingleInlineFilter()
    {
        $req = $this->object->search();
        $req->index("testqueries")->type("test");
        $filter = array(
            'filter' => Sherlock::filterBuilder()->Term()->field("auxillary")->term("auxillary"),
            'boost'  => 2,
        );

        $query = Sherlock::queryBuilder()->CustomFiltersScore()->query(
                     Sherlock::queryBuilder()->Term()->field("auxillary")->term("auxillary")
                 )
                 ->filters($filter)
                 ->score_mode("first")
                 ->max_boost(0.5);

        $req->query($query);

        $data         = $req->toJSON();
        $expectedData = '{"query":{"custom_filters_score":{"query":{"term":{"auxillary":{"value":"auxillary"}}},"filters":[{"filter":{"term":{"auxillary":"auxillary","_cache":true}},"boost":2}],"score_mode":"first","max_boost":0.5}}}';
        $this->assertEquals($expectedData, $data);

        $resp = $req->execute();

    }

    /**
     * @covers sherlock\Sherlock\components\queries\CustomFiltersScore::query
     * @covers sherlock\Sherlock\components\queries\CustomFiltersScore::filters
     * @covers sherlock\Sherlock\components\queries\CustomFiltersScore::score_mode
     * @covers sherlock\Sherlock\components\queries\CustomFiltersScore::max_boost
     * @covers sherlock\Sherlock\requests\SearchRequest::query
     * @covers sherlock\Sherlock\requests\SearchRequest::toJSON
     */
    public function testMultipleInlineFilter()
    {
        $req = $this->object->search();
        $req->index("testqueries")->type("test");
        $filter = array(
            'filter' => Sherlock::filterBuilder()->Term()->field("auxillary")->term("auxillary"),
            'boost'  => 2,
        );

        $query = Sherlock::queryBuilder()->CustomFiltersScore()->query(
                     Sherlock::queryBuilder()->Term()->field("auxillary")->term("auxillary")
                 )
                 ->filters($filter, $filter, $filter)
                 ->score_mode("first")
                 ->max_boost(0.5);

        $req->query($query);

        $data         = $req->toJSON();
        $expectedData = '{"query":{"custom_filters_score":{"query":{"term":{"auxillary":{"value":"auxillary"}}},"filters":[{"filter":{"term":{"auxillary":"auxillary","_cache":true}},"boost":2},{"filter":{"term":{"auxillary":"auxillary","_cache":true}},"boost":2},{"filter":{"term":{"auxillary":"auxillary","_cache":true}},"boost":2}],"score_mode":"first","max_boost":0.5}}}';
        $this->assertEquals($expectedData, $data);

        $resp = $req->execute();

    }

    /**
     * @covers sherlock\Sherlock\components\queries\CustomFiltersScore::query
     * @covers sherlock\Sherlock\components\queries\CustomFiltersScore::filters
     * @covers sherlock\Sherlock\components\queries\CustomFiltersScore::score_mode
     * @covers sherlock\Sherlock\components\queries\CustomFiltersScore::max_boost
     * @covers sherlock\Sherlock\requests\SearchRequest::query
     * @covers sherlock\Sherlock\requests\SearchRequest::toJSON
     */
    public function testSingleArrayFilter()
    {
        $req = $this->object->search();
        $req->index("testqueries")->type("test");
        $filter = array(
            array(
                'filter' => Sherlock::filterBuilder()->Term()->field("auxillary")->term("auxillary"),
                'boost'  => 2,
            )
        );

        $query = Sherlock::queryBuilder()->CustomFiltersScore()->query(
                     Sherlock::queryBuilder()->Term()->field("auxillary")->term("auxillary")
                 )
                 ->filters($filter)
                 ->score_mode("first")
                 ->max_boost(0.5);

        $req->query($query);

        $data         = $req->toJSON();
        $expectedData = '{"query":{"custom_filters_score":{"query":{"term":{"auxillary":{"value":"auxillary"}}},"filters":[{"filter":{"term":{"auxillary":"auxillary","_cache":true}},"boost":2}],"score_mode":"first","max_boost":0.5}}}';
        $this->assertEquals($expectedData, $data);

        $resp = $req->execute();

    }

    /**
     * @covers sherlock\Sherlock\components\queries\CustomFiltersScore::query
     * @covers sherlock\Sherlock\components\queries\CustomFiltersScore::filters
     * @covers sherlock\Sherlock\components\queries\CustomFiltersScore::score_mode
     * @covers sherlock\Sherlock\components\queries\CustomFiltersScore::max_boost
     * @covers sherlock\Sherlock\requests\SearchRequest::query
     * @covers sherlock\Sherlock\requests\SearchRequest::toJSON
     */
    public function testMultipleArrayFilter()
    {
        $req = $this->object->search();
        $req->index("testqueries")->type("test");
        $filter = array(
            array(
                'filter' => Sherlock::filterBuilder()->Term()->field("auxillary")->term("auxillary"),
                'boost'  => 2,
            ),
            array(
                'filter' => Sherlock::filterBuilder()->Term()->field("auxillary")->term("auxillary"),
                'boost'  => 2,
            ),
            array(
                'filter' => Sherlock::filterBuilder()->Term()->field("auxillary")->term("auxillary"),
                'boost'  => 2,
            ),
        );

        $query = Sherlock::queryBuilder()->CustomFiltersScore()->query(
                     Sherlock::queryBuilder()->Term()->field("auxillary")->term("auxillary")
                 )
                 ->filters($filter)
                 ->score_mode("first")
                 ->max_boost(0.5);

        $req->query($query);

        $data         = $req->toJSON();
        $expectedData = '{"query":{"custom_filters_score":{"query":{"term":{"auxillary":{"value":"auxillary"}}},"filters":[{"filter":{"term":{"auxillary":"auxillary","_cache":true}},"boost":2},{"filter":{"term":{"auxillary":"auxillary","_cache":true}},"boost":2},{"filter":{"term":{"auxillary":"auxillary","_cache":true}},"boost":2}],"score_mode":"first","max_boost":0.5}}}';
        $this->assertEquals($expectedData, $data);

        $resp = $req->execute();

    }

    /**
     * @expectedException \Exception
     *
     * @covers sherlock\Sherlock\components\queries\CustomFiltersScore::query
     * @covers sherlock\Sherlock\components\queries\CustomFiltersScore::filters
     * @covers sherlock\Sherlock\components\queries\CustomFiltersScore::filter
     * @covers sherlock\Sherlock\requests\SearchRequest::query
     * @covers sherlock\Sherlock\requests\SearchRequest::toJSON
     */
    public function testInvalidFilterParam()
    {
        $req = $this->object->search();
        $req->index("testqueries")->type("test");
        $filter = array(
            'filter' => Sherlock::queryBuilder()->Term()->field("auxillary")->term("auxillary"),
            'boost'  => 2,
        );

        $query = Sherlock::queryBuilder()->CustomFiltersScore()->query(
                     Sherlock::queryBuilder()->Term()->field("auxillary")->term("auxillary")
                 )
                 ->filters($filter);

        $req->query($query);

    }

    /**
     * @covers sherlock\Sherlock\components\queries\CustomFiltersScore::filter
     * @covers sherlock\Sherlock\requests\SearchRequest::query
     * @covers sherlock\Sherlock\requests\SearchRequest::toJSON
     */
    public function testFilter()
    {
        $req = $this->object->search();
        $req->index("testqueries")->type("test");
        $filter = Sherlock::filterBuilder()->Term()->field("auxillary")->term("auxillary");

        $query = Sherlock::queryBuilder()->CustomFiltersScore()->query(
                     Sherlock::queryBuilder()->Term()->field("auxillary")->term("auxillary")
                 )
                 ->filter($filter, 2)
                 ->score_mode("first")
                 ->max_boost(0.5);

        $req->query($query);

        $data         = $req->toJSON();
        $expectedData = '{"query":{"custom_filters_score":{"query":{"term":{"auxillary":{"value":"auxillary"}}},"filters":[{"filter":{"term":{"auxillary":"auxillary","_cache":true}},"boost":2}],"score_mode":"first","max_boost":0.5}}}';
        $this->assertEquals($expectedData, $data);

        $resp = $req->execute();

    }

    /**
     * @covers sherlock\Sherlock\components\queries\CustomFiltersScore::filter
     * @covers sherlock\Sherlock\requests\SearchRequest::query
     * @covers sherlock\Sherlock\requests\SearchRequest::toJSON
     */
    public function testMultipleFilter()
    {
        $req = $this->object->search();
        $req->index("testqueries")->type("test");
        $filter = Sherlock::filterBuilder()->Term()->field("auxillary")->term("auxillary");

        $query = Sherlock::queryBuilder()->CustomFiltersScore()->query(
                     Sherlock::queryBuilder()->Term()->field("auxillary")->term("auxillary")
                 )
                 ->filter($filter, 2)
                 ->filter($filter, 3)
                 ->filter($filter, 4)
                 ->score_mode("first")
                 ->max_boost(0.5);

        $req->query($query);

        $data         = $req->toJSON();
        $expectedData = '{"query":{"custom_filters_score":{"query":{"term":{"auxillary":{"value":"auxillary"}}},"filters":[{"filter":{"term":{"auxillary":"auxillary","_cache":true}},"boost":2},{"filter":{"term":{"auxillary":"auxillary","_cache":true}},"boost":3},{"filter":{"term":{"auxillary":"auxillary","_cache":true}},"boost":4}],"score_mode":"first","max_boost":0.5}}}';
        $this->assertEquals($expectedData, $data);

        $resp = $req->execute();

    }
}


text:
using Microsoft.AspNet.Identity;
using MultiHostDemo.Entities;
using MultiHostDemo.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Principal;
using System.Text;
using System.Threading.Tasks;

namespace MultiHostDemo.ExtensionMethods
{
    public static class IPrincipalExtensions
    {
        private static ApplicationDbContext Repo { get { return new ApplicationDbContext(); } }

        public static bool IsInRole(this IPrincipal user, RoleType role)
        {
            //Contract.Requires<ArgumentNullException>(user != null, "user");

            return user.IsInRole(role.ToString());
        }

        public static Guid UserId(this IPrincipal user)
        {
            //Contract.Requires<ArgumentNullException>(user != null, "user");

            Guid id = Guid.Empty;
            if (Guid.TryParse(user.Identity.GetUserId(), out id))
            {
                return id;
            }

            return Guid.Empty;
        }

        internal static AppUser GetAppUser(this IPrincipal user)
        {
            Guid id = user.UserId();

            if (id == Guid.Empty)
            {
                return null;
            }

            return Repo.Users.Find(id); // could fail... check for nulls.
        }

        public static string Email(this IPrincipal user)
        {
            //Contract.Requires<ArgumentNullException>(user != null, "user");

            AppUser appUser = user.GetAppUser();

            if (appUser == null)
            {
                return string.Empty;
            }

            return appUser.Email;
        }

        public static string FirstName(this IPrincipal user)
        {
            //Contract.Requires<ArgumentNullException>(user != null, "user");

            AppUser appUser = user.GetAppUser();

            if (appUser == null)
            {
                return string.Empty;
            }

            return appUser.FirstName;
        }

        public static string LastName(this IPrincipal user)
        {
            //Contract.Requires<ArgumentNullException>(user != null, "user");

            AppUser appUser = user.GetAppUser();

            if (appUser == null)
            {
                return string.Empty;
            }

            return appUser.LastName;
        }
    }
}


text:
<?php

use yii\helpers\Html;

/* @var $this yii\web\View */
/* @var $user \yii2mod\user\models\UserModel */

$resetLink = Yii::$app->urlManager->createAbsoluteUrl(['site/password-reset', 'token' => $user->password_reset_token]);
?>

Hello <?php echo Html::encode($user->username) ?>,

Follow the link below to reset your password:

<?php echo Html::a(Html::encode($resetLink), $resetLink) ?>


text:
package org.apache.flink.python.env.beam;

import org.apache.flink.api.common.JobID;
import org.apache.flink.python.env.PythonDependencyInfo;
import org.apache.flink.util.FileUtils;
import org.apache.flink.util.OperatingSystem;

import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.attribute.PosixFilePermission;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import static org.apache.flink.python.env.beam.ProcessPythonEnvironmentManager.PYFLINK_GATEWAY_DISABLED;
import static org.apache.flink.python.env.beam.ProcessPythonEnvironmentManager.PYTHON_ARCHIVES_DIR;
import static org.apache.flink.python.env.beam.ProcessPythonEnvironmentManager.PYTHON_FILES_DIR;
import static org.apache.flink.python.env.beam.ProcessPythonEnvironmentManager.PYTHON_REQUIREMENTS_CACHE;
import static org.apache.flink.python.env.beam.ProcessPythonEnvironmentManager.PYTHON_REQUIREMENTS_DIR;
import static org.apache.flink.python.env.beam.ProcessPythonEnvironmentManager.PYTHON_REQUIREMENTS_FILE;
import static org.apache.flink.python.env.beam.ProcessPythonEnvironmentManager.PYTHON_REQUIREMENTS_INSTALL_DIR;
import static org.apache.flink.python.env.beam.ProcessPythonEnvironmentManager.PYTHON_WORKING_DIR;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

/** Tests for the {@link ProcessPythonEnvironmentManager}. */
public class ProcessPythonEnvironmentManagerTest {

    private static String tmpDir;
    private static boolean isUnix;

    @BeforeClass
    public static void prepareTempDirectory() throws IOException {
        File tmpFile = File.createTempFile("process_environment_manager_test", "");
        if (tmpFile.delete() && tmpFile.mkdirs()) {
            tmpDir = tmpFile.getAbsolutePath();
        } else {
            throw new IOException(
                    "Create temp directory: " + tmpFile.getAbsolutePath() + " failed!");
        }

        for (int i = 0; i < 6; i++) {
            File distributedFile = new File(tmpDir, "file" + i);
            try (FileOutputStream out = new FileOutputStream(distributedFile)) {
                out.write(i);
            }
        }

        for (int i = 0; i < 2; i++) {
            File distributedDirectory = new File(tmpDir, "dir" + i);
            if (distributedDirectory.mkdirs()) {
                for (int j = 0; j < 2; j++) {
                    File fileInDirs = new File(tmpDir, "dir" + i + File.separator + "file" + j);
                    try (FileOutputStream out = new FileOutputStream(fileInDirs)) {
                        out.write(i);
                        out.write(j);
                    }
                }
            } else {
                throw new IOException(
                        "Create temp dir: " + distributedDirectory.getAbsolutePath() + " failed!");
            }
        }

        isUnix =
                OperatingSystem.isFreeBSD()
                        || OperatingSystem.isLinux()
                        || OperatingSystem.isMac()
                        || OperatingSystem.isSolaris();
        for (int i = 0; i < 2; i++) {
            File zipFile = new File(tmpDir, "zip" + i);
            try (ZipArchiveOutputStream zipOut =
                    new ZipArchiveOutputStream(new FileOutputStream(zipFile))) {
                ZipArchiveEntry zipfile0 = new ZipArchiveEntry("zipDir" + i + "/zipfile0");
                zipfile0.setUnixMode(0711);
                zipOut.putArchiveEntry(zipfile0);
                zipOut.write(new byte[] {1, 1, 1, 1, 1});
                zipOut.closeArchiveEntry();
                ZipArchiveEntry zipfile1 = new ZipArchiveEntry("zipDir" + i + "/zipfile1");
                zipfile1.setUnixMode(0644);
                zipOut.putArchiveEntry(zipfile1);
                zipOut.write(new byte[] {2, 2, 2, 2, 2});
                zipOut.closeArchiveEntry();
            }
            File zipExpected =
                    new File(String.join(File.separator, tmpDir, "zipExpected" + i, "zipDir" + i));
            if (!zipExpected.mkdirs()) {
                throw new IOException(
                        "Create temp dir: " + zipExpected.getAbsolutePath() + " failed!");
            }
            File zipfile0 = new File(zipExpected, "zipfile0");
            try (FileOutputStream out = new FileOutputStream(zipfile0)) {
                out.write(new byte[] {1, 1, 1, 1, 1});
            }
            File zipfile1 = new File(zipExpected, "zipfile1");
            try (FileOutputStream out = new FileOutputStream(zipfile1)) {
                out.write(new byte[] {2, 2, 2, 2, 2});
            }

            if (isUnix) {
                if (!(zipfile0.setReadable(true, true)
                        && zipfile0.setWritable(true, true)
                        && zipfile0.setExecutable(true))) {
                    throw new IOException(
                            "Set unixmode 711 to temp file: "
                                    + zipfile0.getAbsolutePath()
                                    + "failed!");
                }
                if (!(zipfile1.setReadable(true)
                        && zipfile1.setWritable(true, true)
                        && zipfile1.setExecutable(false))) {
                    throw new IOException(
                            "Set unixmode 644 to temp file: "
                                    + zipfile1.getAbsolutePath()
                                    + "failed!");
                }
            }
        }
    }

    @AfterClass
    public static void cleanTempDirectory() {
        if (tmpDir != null) {
            FileUtils.deleteDirectoryQuietly(new File(tmpDir));
            tmpDir = null;
        }
    }

    @Test
    public void testPythonFiles() throws Exception {
        // use LinkedHashMap to preserve the path order in environment variable
        Map<String, String> pythonFiles = new LinkedHashMap<>();
        pythonFiles.put(String.join(File.separator, tmpDir, "zip0"), "test_zip.zip");
        pythonFiles.put(String.join(File.separator, tmpDir, "file1"), "test_file1.py");
        pythonFiles.put(String.join(File.separator, tmpDir, "file2"), "test_file2.egg");
        pythonFiles.put(String.join(File.separator, tmpDir, "dir0"), "test_dir");
        PythonDependencyInfo dependencyInfo =
                new PythonDependencyInfo(pythonFiles, null, null, new HashMap<>(), "python");

        try (ProcessPythonEnvironmentManager environmentManager =
                createBasicPythonEnvironmentManager(dependencyInfo)) {
            environmentManager.open();
            String baseDir = environmentManager.getBaseDirectory();
            Map<String, String> environmentVariable = environmentManager.getPythonEnv();

            String[] expectedUserPythonPaths =
                    new String[] {
                        String.join(File.separator, baseDir, PYTHON_FILES_DIR, "zip0", "test_zip"),
                        String.join(File.separator, baseDir, PYTHON_FILES_DIR, "file1"),
                        String.join(
                                File.separator,
                                baseDir,
                                PYTHON_FILES_DIR,
                                "file2",
                                "test_file2.egg"),
                        String.join(File.separator, baseDir, PYTHON_FILES_DIR, "dir0", "test_dir")
                    };
            String expectedPythonPath = String.join(File.pathSeparator, expectedUserPythonPaths);

            assertEquals(expectedPythonPath, environmentVariable.get("PYTHONPATH"));
            assertFileEquals(
                    new File(String.join(File.separator, tmpDir, "file1")),
                    new File(
                            String.join(
                                    File.separator,
                                    baseDir,
                                    PYTHON_FILES_DIR,
                                    "file1",
                                    "test_file1.py")));
            assertFileEquals(
                    new File(String.join(File.separator, tmpDir, "zipExpected0")),
                    new File(
                            String.join(
                                    File.separator,
                                    baseDir,
                                    PYTHON_FILES_DIR,
                                    "zip0",
                                    "test_zip")));
            assertFileEquals(
                    new File(String.join(File.separator, tmpDir, "file2")),
                    new File(
                            String.join(
                                    File.separator,
                                    baseDir,
                                    PYTHON_FILES_DIR,
                                    "file2",
                                    "test_file2.egg")));
            assertFileEquals(
                    new File(String.join(File.separator, tmpDir, "dir0")),
                    new File(
                            String.join(
                                    File.separator,
                                    baseDir,
                                    PYTHON_FILES_DIR,
                                    "dir0",
                                    "test_dir")));
        }
    }

    @Test
    public void testRequirements() throws Exception {
        PythonDependencyInfo dependencyInfo =
                new PythonDependencyInfo(
                        new HashMap<>(),
                        String.join(File.separator, tmpDir, "file0"),
                        String.join(File.separator, tmpDir, "dir0"),
                        new HashMap<>(),
                        "python");

        try (ProcessPythonEnvironmentManager environmentManager =
                createBasicPythonEnvironmentManager(dependencyInfo)) {
            File baseDirectory = new File(tmpDir, "python-dist-" + UUID.randomUUID().toString());
            if (!baseDirectory.mkdirs()) {
                throw new IOException(
                        "Could not find a unique directory name in '"
                                + tmpDir
                                + "' for storing the generated files of python dependency.");
            }
            String tmpBase = baseDirectory.getAbsolutePath();
            Map<String, String> environmentVariable =
                    environmentManager.constructEnvironmentVariables(tmpBase);

            Map<String, String> expected = new HashMap<>();
            expected.put("python", "python");
            expected.put("BOOT_LOG_DIR", tmpBase);
            expected.put(PYFLINK_GATEWAY_DISABLED, "true");
            expected.put(PYTHON_REQUIREMENTS_FILE, String.join(File.separator, tmpDir, "file0"));
            expected.put(PYTHON_REQUIREMENTS_CACHE, String.join(File.separator, tmpDir, "dir0"));
            expected.put(
                    PYTHON_REQUIREMENTS_INSTALL_DIR,
                    String.join(File.separator, tmpBase, PYTHON_REQUIREMENTS_DIR));
            assertEquals(expected, environmentVariable);
        }
    }

    @Test
    public void testArchives() throws Exception {
        // use LinkedHashMap to preserve the file order in python working directory
        Map<String, String> archives = new LinkedHashMap<>();
        archives.put(String.join(File.separator, tmpDir, "zip0"), "py27.zip");
        archives.put(String.join(File.separator, tmpDir, "zip1"), "py37");
        PythonDependencyInfo dependencyInfo =
                new PythonDependencyInfo(new HashMap<>(), null, null, archives, "python");

        try (ProcessPythonEnvironmentManager environmentManager =
                createBasicPythonEnvironmentManager(dependencyInfo)) {
            environmentManager.open();
            String tmpBase = environmentManager.getBaseDirectory();
            Map<String, String> environmentVariable = environmentManager.getPythonEnv();

            Map<String, String> expected = getBasicExpectedEnv(environmentManager);
            expected.put(
                    PYTHON_WORKING_DIR, String.join(File.separator, tmpBase, PYTHON_ARCHIVES_DIR));
            assertEquals(expected, environmentVariable);
            assertFileEquals(
                    new File(String.join(File.separator, tmpDir, "zipExpected0")),
                    new File(String.join(File.separator, tmpBase, PYTHON_ARCHIVES_DIR, "py27.zip")),
                    true);
            assertFileEquals(
                    new File(String.join(File.separator, tmpDir, "zipExpected1")),
                    new File(String.join(File.separator, tmpBase, PYTHON_ARCHIVES_DIR, "py37")),
                    true);
        }
    }

    @Test
    public void testPythonExecutable() throws Exception {
        PythonDependencyInfo dependencyInfo =
                new PythonDependencyInfo(
                        new HashMap<>(), null, null, new HashMap<>(), "/usr/local/bin/python");

        try (ProcessPythonEnvironmentManager environmentManager =
                createBasicPythonEnvironmentManager(dependencyInfo)) {
            environmentManager.open();
            Map<String, String> environmentVariable = environmentManager.getPythonEnv();

            Map<String, String> expected = getBasicExpectedEnv(environmentManager);
            expected.put("python", "/usr/local/bin/python");
            assertEquals(expected, environmentVariable);
        }
    }

    @Test
    public void testCreateRetrievalToken() throws Exception {
        PythonDependencyInfo dependencyInfo =
                new PythonDependencyInfo(new HashMap<>(), null, null, new HashMap<>(), "python");
        Map<String, String> sysEnv = new HashMap<>();
        sysEnv.put("FLINK_HOME", "/flink");

        try (ProcessPythonEnvironmentManager environmentManager =
                new ProcessPythonEnvironmentManager(
                        dependencyInfo, new String[] {tmpDir}, sysEnv, new JobID())) {
            environmentManager.open();
            String retrievalToken = environmentManager.createRetrievalToken();

            File retrievalTokenFile = new File(retrievalToken);
            byte[] content = new byte[(int) retrievalTokenFile.length()];
            try (DataInputStream input = new DataInputStream(new FileInputStream(retrievalToken))) {
                input.readFully(content);
            }
            assertEquals("{\"manifest\": {}}", new String(content));
        }
    }

    @Test
    public void testSetLogDirectory() throws Exception {
        PythonDependencyInfo dependencyInfo =
                new PythonDependencyInfo(new HashMap<>(), null, null, new HashMap<>(), "python");

        try (ProcessPythonEnvironmentManager environmentManager =
                new ProcessPythonEnvironmentManager(
                        dependencyInfo, new String[] {tmpDir}, new HashMap<>(), new JobID())) {
            environmentManager.open();
            Map<String, String> env =
                    environmentManager.constructEnvironmentVariables(
                            environmentManager.getBaseDirectory());
            Map<String, String> expected = getBasicExpectedEnv(environmentManager);
            expected.put("BOOT_LOG_DIR", environmentManager.getBaseDirectory());
            assertEquals(expected, env);
        }
    }

    @Test
    public void testOpenClose() throws Exception {
        PythonDependencyInfo dependencyInfo =
                new PythonDependencyInfo(new HashMap<>(), null, null, new HashMap<>(), "python");

        try (ProcessPythonEnvironmentManager environmentManager =
                createBasicPythonEnvironmentManager(dependencyInfo)) {
            environmentManager.open();
            environmentManager.createRetrievalToken();

            String tmpBase = environmentManager.getBaseDirectory();
            assertTrue(new File(tmpBase).isDirectory());
            environmentManager.close();
            assertFalse(new File(tmpBase).exists());
        }
    }

    private static void assertFileEquals(File expectedFile, File actualFile)
            throws IOException, NoSuchAlgorithmException {
        assertFileEquals(expectedFile, actualFile, false);
    }

    private static void assertFileEquals(File expectedFile, File actualFile, boolean checkUnixMode)
            throws IOException, NoSuchAlgorithmException {
        assertTrue(actualFile.exists());
        assertTrue(expectedFile.exists());
        if (expectedFile.getAbsolutePath().equals(actualFile.getAbsolutePath())) {
            return;
        }

        if (isUnix && checkUnixMode) {
            Set<PosixFilePermission> expectedPerm =
                    Files.getPosixFilePermissions(Paths.get(expectedFile.toURI()));
            Set<PosixFilePermission> actualPerm =
                    Files.getPosixFilePermissions(Paths.get(actualFile.toURI()));
            assertEquals(expectedPerm, actualPerm);
        }

        if (expectedFile.isDirectory()) {
            assertTrue(actualFile.isDirectory());
            String[] expectedSubFiles = expectedFile.list();
            assertArrayEquals(expectedSubFiles, actualFile.list());
            if (expectedSubFiles != null) {
                for (String fileName : expectedSubFiles) {
                    assertFileEquals(
                            new File(expectedFile.getAbsolutePath(), fileName),
                            new File(actualFile.getAbsolutePath(), fileName));
                }
            }
        } else {
            assertEquals(expectedFile.length(), actualFile.length());
            if (expectedFile.length() > 0) {
                assertTrue(org.apache.commons.io.FileUtils.contentEquals(expectedFile, actualFile));
            }
        }
    }

    private static Map<String, String> getBasicExpectedEnv(
            ProcessPythonEnvironmentManager environmentManager) {
        Map<String, String> map = new HashMap<>();
        String tmpBase = environmentManager.getBaseDirectory();
        map.put("python", "python");
        map.put("BOOT_LOG_DIR", tmpBase);
        map.put(PYFLINK_GATEWAY_DISABLED, "true");
        return map;
    }

    private static ProcessPythonEnvironmentManager createBasicPythonEnvironmentManager(
            PythonDependencyInfo dependencyInfo) {
        return new ProcessPythonEnvironmentManager(
                dependencyInfo, new String[] {tmpDir}, new HashMap<>(), new JobID());
    }
}


text:
/*
 The backbone.js views for the item type : Video .
includes:

DiscoveryListVideoView
DiscoveryCompactListVideoView
DiscoveryThumbVideoView
DiscoveryMapVideoView
DiscoveryTimelineVideoView
HomeCarouselVideoView
HomePreviewPopupVideoView
ItemPageVideoView
LightboxVideoView
 */

var DiscoveryListVideoView = DiscoveryListItemView.extend({
	render : function() {
		$(this.el).html(this.res);
		return this;
	},
});

var DiscoveryCompactListVideoView = DiscoveryCompactListItemView.extend({
	render : function() {
		$(this.el).html(this.res);
		return this;
	},
});

var DiscoveryThumbVideoView = DiscoveryThumbItemView.extend({
	render : function() {
		$(this.el).html(this.res);
		return this;
	}
});

var DiscoveryMapVideoView = DiscoveryMapItemView.extend({
	render : function() {
		$(this.el).html(this.res);
		return this;
	}
});

var DiscoveryTimelineVideoView = DiscoveryTimelineItemView.extend({
	render : function() {
		$(this.el).html(this.res);
		return this;
	}
});

var HomeCarouselVideoView = HomeCarouselItemView.extend({
	render : function() {
		$(this.el).html(this.res);
		return this;
	}
});

var HomePreviewPopupVideoView = HomePreviewPopupItemView.extend({
	render : function() {
		$(this.el).html(this.res);
		return this;

	}
});

var PageVideoView = PageItemView.extend({
	render : function() {
		$(this.el).html(this.res);
		return this;
	}
});

var LightboxVideoView = LightboxItemView.extend({

	render : function() {
		preview = this.res.find(".lightbox-preview");
		w = preview.width();
		h = preview.height();

		switch (this.model.get("source")){
		case "Youtube":
			video = $("<iframe class='youtube-player lightbox-video-preview' type='text/html' frameborder='0'></iframe>");
			video.attr("src", "http://www.youtube.com/embed/" + this.model.get("uri"));
			video.css({
				"height" : h,
				"width" : w
			});
			break;
		}

		preview.append(video);
		$(this.el).html(this.res);
		return this;
	}
});


text:
#import <AIUtilities/AIOutlineView.h>

/*!
 * @class AIAlternatingRowOutlineView
 * @brief An <tt>AIOutlineView</tt> subclass supporting alternating rows.
 *
 * This functionality was added, with less control to the programmer, in OS X 10.3.  <tt>AIAlternatingRowOutlineView</tt> also supports disabling it from drawing its background (useful if cells wish to draw their own backgrounds and potentially be transparent).
 */
@interface AIAlternatingRowOutlineView : AIOutlineView <AIAlternatingRowsProtocol> {
	NSColor		*alternatingRowColor;

	BOOL		drawsBackground;
	BOOL		drawsGradientSelection;
}

/*!
 * @brief The color used for drawing alternating row backgrounds.
 *
 * Ignored if usesAlternatingRowBackgroundColors is NO.
 */
@property (readwrite, nonatomic, retain) NSColor *alternatingRowColor;

/*!
 * @brief Whether the outlineView should draw its background
 *
 * If this is NO, no background will be drawn (this means that the alternating rows will not be drawn, either).  This is useful if cells wish to draw their own backgrounds.
 */
@property (readwrite, nonatomic) BOOL drawsBackground;

/*!
 * @brief Returns the <tt>NSColor</tt> which should be used to draw the background of the specified row
 *
 * @param row An integer row
 * @return An <tt>NSColor</tt> used to draw the background for <b>row</b>
 */
- (NSColor *)backgroundColorForRow:(NSInteger)row;

@property (readwrite, nonatomic) BOOL drawsGradientSelection;
@end

@interface AIAlternatingRowOutlineView (PRIVATE_AIAlternatingRowOutlineViewAndSubclasses)
- (void)_drawRowInRect:(NSRect)rect colored:(BOOL)colored selected:(BOOL)selected;
@end


text: Python's context manager implementation for PHP


text:
import sqlite3 from 'sqlite3';

import lastUpdate from './lastUpdate';

const MAX_CHUNK_SIZE = 100;

function normalizedExportName(string) {
  return string.toLowerCase().replace(/[-_.]/g, '');
}

function normalizeRows(rows) {
  // currently just casts `isDefault` and `isType` to boolean
  return rows.map(({ isDefault, isType, ...other }) => ({
    isDefault: !!isDefault,
    isType: !!isType,
    ...other,
  }));
}

function inParam(sql, values) {
  // https://github.com/mapbox/node-sqlite3/issues/721
  return sql.replace('?#', values.map(() => '?').join(','));
}

function arrayToChunks(array, chunkSize) {
  const chunks = [];
  for (let i = 0; i < array.length; i += chunkSize) {
    chunks.push(array.slice(i, i + chunkSize));
  }
  return chunks;
}

export default class ExportsStorage {
  init(dbFilename) {
    return new Promise((resolve, reject) => {
      this.db = new sqlite3.Database(dbFilename);
      this.db.all('PRAGMA table_info(exports)', (pragmaErr, result) => {
        if (pragmaErr) {
          reject(pragmaErr);
          return;
        }
        if (result.length) {
          // DB has already been initialized
          resolve({ isFreshInstall: false });
          return;
        }
        this.db.run(
          `
            CREATE TABLE exports (
              name VARCHAR(100),
              isDefault INTEGER,
              isType INTEGER,
              path TEXT,
              packageName VARCHAR(100)
            )
          `,
          (err) => {
            if (err) {
              reject(err);
              return;
            }

            this.db.run(`
                CREATE VIRTUAL TABLE exports_full_text_search_index USING fts4(
                  name,
                  path,
                  isDefault,
                  isType,
                  packageName,
                )
              `);

            this.db.run(
              `
                CREATE TABLE mtimes (
                  path TEXT,
                  mtime NUMERIC
                )
              `,
              (err) => {
                if (err) {
                  reject(err);
                  return;
                }

                resolve({ isFreshInstall: true });
              },
            );
          },
        );
      });
    });
  }

  close() {
    return new Promise((resolve, reject) => {
      this.db.close((err) => {
        if (err) {
          reject(err);
          return;
        }
        resolve();
      });
    });
  }

  needsUpdate(files) {
    if (files.length > MAX_CHUNK_SIZE) {
      // sqlite has a max number for arguments passed. We need to execute in
      // chunks if we exceed the max.
      const promises = arrayToChunks(
        files,
        MAX_CHUNK_SIZE,
      ).map(chunk => this.needsUpdate(chunk));
      return Promise.all(promises)
        .then(chunks => chunks.reduce((a, b) => a.concat(b))); // flatten
    }

    return new Promise((resolve, reject) => {
      const filePaths = files.map(({ path: p }) => p);
      this.db.all(
        inParam(
          `
            SELECT path, mtime FROM mtimes
            WHERE (path IN (?#))
          `,
          filePaths,
        ),
        filePaths,
        (err, items) => {
          if (err) {
            reject(err);
            return;
          }
          const mtimes = {};
          items.forEach(({ path: pathToFile, mtime }) => {
            mtimes[pathToFile] = mtime;
          });
          const filtered = files.filter(({ path: pathToFile, mtime }) => (
            mtime !== mtimes[pathToFile]
          ));
          resolve(filtered);
        },
      );
    });
  }

  allFiles() {
    return new Promise((resolve, reject) => {
      this.db.all('SELECT path FROM mtimes', (err, files) => {
        if (err) {
          reject(err);
          return;
        }
        resolve(files.map(({ path }) => path));
      });
    });
  }

  updateMtime(pathToFile, mtime) {
    return new Promise((resolve, reject) => {
      this.db.get('SELECT mtime FROM mtimes WHERE (path = ?)', pathToFile, (
        err,
        item,
      ) => {
        if (err) {
          reject(err);
          return;
        }
        if (item) {
          this.db.run(
            'UPDATE mtimes SET mtime = ? WHERE (path = ?)',
            mtime,
            pathToFile,
            (err) => {
              if (err) {
                reject(err);
                return;
              }
              resolve();
            },
          );
        } else {
          this.db.run(
            'INSERT INTO mtimes (mtime, path) VALUES (?, ?)',
            mtime,
            pathToFile,
            (err) => {
              if (err) {
                reject(err);
                return;
              }
              resolve();
            },
          );
        }
      });
    });
  }

  _insert({
    name, pathToFile, isDefault, isType, packageName, additional,
  }) {
    const exportName = isDefault ? normalizedExportName(name) : name;
    return Promise.all([
      new Promise((resolve, reject) => {
        this.db.run(
          'INSERT INTO exports (name, path, isDefault, isType, packageName) VALUES (?, ?, ?, ?, ?)',
          exportName,
          pathToFile,
          isDefault,
          isType,
          packageName,
          (err) => {
            if (err) {
              reject(err);
              return;
            }

            resolve();
          },
        );
      }),
      new Promise((resolve, reject) => {
        // `additional` is a flag used to identify what to add to the full text search index
        // The reason for this is directory paths get appended to module name which results in noisy
        // search results
        if (!additional) {
          this.db.run(
            'INSERT INTO exports_full_text_search_index VALUES (?, ?, ?, ?, ?)',
            name,
            pathToFile,
            isDefault,
            isType,
            packageName,
            (err) => {
              if (err) {
                reject(err);
              } else {
                resolve();
              }
            },
          );
        } else {
          resolve();
        }
      }),
    ]);
  }

  update({
    names = [], types = [], defaultNames, pathToFile, mtime, packageName,
  }) {
    return this.remove(pathToFile).then(() =>
      this.updateMtime(pathToFile, mtime, packageName).then(() => {
        const promises = names.map(name =>
          this._insert({
            name, pathToFile, isDefault: false, isType: false, packageName,
          }));
        promises.push(types.map(name =>
          this._insert({
            name, pathToFile, isDefault: false, isType: true, packageName,
          })));
        promises.push(...defaultNames.map(({ name, additional }) =>
          this._insert({
            name, pathToFile, isDefault: true, isType: false, packageName, additional,
          })));
        return Promise.all(promises);
      }));
  }

  _remove(pattern, operator = '=') {
    return new Promise((resolve, reject) => {
      this.db.run(
        `DELETE FROM exports WHERE (path ${operator} ?)`,
        pattern,
        (err) => {
          if (err) {
            reject(err);
            return;
          }
          this.db.run(
            `DELETE FROM exports_full_text_search_index WHERE (path ${operator} ?)`,
            pattern,
          );

          this.db.run(
            `DELETE FROM mtimes WHERE (path ${operator} ?)`,
            pattern,
            (mErr) => {
              if (mErr) {
                reject(mErr);
                return;
              }
              resolve();
            },
          );
        },
      );
    });
  }

  remove(pathToFile) {
    return this._remove(pathToFile);
  }

  removeAll(globPattern) {
    return this._remove(globPattern, 'GLOB');
  }

  purgeDeadNodeModules(workingDirectory) {
    return new Promise((resolve, reject) => {
      this.db.all(
        'SELECT path FROM mtimes WHERE (path LIKE "%/node_modules/%")',
        (err, files) => {
          if (err) {
            reject(err);
            return;
          }
          const promises = files.map(({ path: pathToFile }) => new Promise((removeResolve) => {
            lastUpdate(pathToFile, workingDirectory)
              .then(removeResolve)
              .catch(() => this.remove(pathToFile).then(removeResolve));
          }));
          Promise.all(promises).then(resolve).catch(reject);
        },
      );
    });
  }

  get(variableName) {
    return new Promise((resolve, reject) => {
      this.db.all(
        `
          SELECT name, path, isDefault, isType, packageName
          FROM exports WHERE (
            (name = ? AND isDefault = 0) OR
            (name = ? AND isDefault = 1)
          )
        `,
        variableName,
        normalizedExportName(variableName),
        (err, rows) => {
          if (err) {
            reject(err);
            return;
          }
          resolve(normalizeRows(rows));
        },
      );
    });
  }

  search(variableName) {
    return new Promise((resolve, reject) => {
      this.db.all(
        `
          SELECT name, path, isDefault, isType, packageName
          FROM exports_full_text_search_index WHERE name MATCH ?
          COLLATE NOCASE
        `,
        variableName,
        (err, rows) => {
          if (err) {
            reject(err);
            return;
          }
          resolve(normalizeRows(rows));
        },
      );
    });
  }
}


text:
using System;
using Bari.Plugins.PythonScripts.Scripting;

namespace Bari.Plugins.PythonScripts.Exceptions
{
    public class ScriptException: Exception
    {
        public ScriptException(IScript script)
            : base(String.Format("Failed to execute script {0}", script.Name))
        {
        }

        public override string ToString()
        {
            return Message;
        }
    }
}


text:
package us.terracraft.sqc.states;

import java.awt.event.KeyEvent;

import us.terracraft.sqc.GameManager;
import us.terracraft.sqc.objects.Background;
import KTech.components.*;
import KTech.core.*;
import KTech.graphics.*;

public class MenuState implements State {

	private ObjectManager manager;

	Image title = new Image("/misc/sqc.png");
	SoundClip song = new SoundClip("/sounds/theme.wav");

	public MenuState() {
		manager = new ObjectManager();

		manager.addObject(new Background(0,0, "/Backgrounds/Menubg.png"));

		song.loop();
	}

	@Override
	public void update(KTech kt, float time) {
		manager.updateObjects(kt, time); //Do not edit or remove this line

		if (kt.getInput().isKeyHeld(KeyEvent.VK_ENTER))
			GameManager.setState(new PlayState());
	}

	@Override
	public void render(KTech kt, Renderer r) {
		manager.renderObjects(kt, r); //Do not edit or remove this line

		r.drawImage(title, 50, 50);

		r.drawString("Press Enter to start", 0xffffffff, 220, 300);
	}

	@Override
	public void dispose() {
		//Make sure to dispose of all game objects to avoid memory leaks

		manager.disposeObjects();
	}
}