text:
require 'chef/provisioning/aws_driver/aws_provider'
require 'date'
require 'ipaddr'
require 'set'

class Chef::Provider::AwsSecurityGroup < Chef::Provisioning::AWSDriver::AWSProvider
  include Chef::Provisioning::AWSDriver::TaggingStrategy::EC2ConvergeTags

  provides :aws_security_group

  def action_create
    sg = super

    apply_rules(sg)
  end

  protected

  def create_aws_object
    converge_by "create security group #{new_resource.name} in #{region}" do
      options = { description: new_resource.description }
      options[:vpc] = new_resource.vpc if new_resource.vpc
      options = AWSResource.lookup_options(options, resource: new_resource)
      Chef::Log.debug("VPC: #{options[:vpc]}")

      sg = new_resource.driver.ec2.security_groups.create(new_resource.name, options)
      retry_with_backoff(AWS::EC2::Errors::InvalidSecurityGroupsID::NotFound, AWS::EC2::Errors::InvalidGroup::NotFound) do
        sg.tags['Name'] = new_resource.name
      end
      sg
    end
  end

  def update_aws_object(sg)
    if !new_resource.description.nil? && new_resource.description != sg.description
      raise "Security group descriptions cannot be changed after being created!  Desired description for #{new_resource.name} (#{sg.id}) was \"#{new_resource.description}\" and actual description is \"#{sg.description}\""
    end
    if !new_resource.vpc.nil?
      desired_vpc = Chef::Resource::AwsVpc.get_aws_object_id(new_resource.vpc, resource: new_resource)
      if desired_vpc != sg.vpc_id
        raise "Security group VPC cannot be changed after being created!  Desired VPC for #{new_resource.name} (#{sg.id}) was #{new_resource.vpc} (#{desired_vpc}) and actual VPC is #{sg.vpc_id}"
      end
    end
    apply_rules(sg)
  end

  def destroy_aws_object(sg)
    converge_by "delete security group #{new_resource.to_s} in #{region}" do
      sg.delete
    end
  end

  private

  def apply_rules(sg)
    vpc = sg.vpc
    if !new_resource.outbound_rules.nil?
      update_outbound_rules(sg, vpc)
    end

    if !new_resource.inbound_rules.nil?
      update_inbound_rules(sg, vpc)
    end
  end

  def update_inbound_rules(sg, vpc)
    #
    # Get desired rules
    #
    desired_rules = {}

    case new_resource.inbound_rules
    when Hash
      new_resource.inbound_rules.each do |sources_spec, port_spec|
        add_rule(desired_rules, get_port_ranges(port_spec), get_actors(vpc, sources_spec))
      end

    when Array
      # [ { port: X, protocol: Y, sources: [ ... ]}]
      new_resource.inbound_rules.each do |rule|
        port_ranges = get_port_ranges(rule)
        add_rule(desired_rules, port_ranges, get_actors(vpc, rule[:sources]))
      end

    else
      raise ArgumentError, "inbound_rules must be a Hash or Array (was #{new_resource.inbound_rules.inspect})"
    end

    #
    # Actually update the rules (remove, add)
    #
    update_rules(desired_rules, sg.ip_permissions_list,

      authorize: proc do |port_range, protocol, actors|
        names = actors.map { |a| a.is_a?(Hash) ? a[:group_id] : a }
        converge_by "authorize #{names.join(', ')} to send traffic to group #{new_resource.name} (#{sg.id}) on port_range #{port_range.inspect} with protocol #{protocol || 'nil'}" do
          sg.authorize_ingress(protocol, port_range, *actors)
        end
      end,

      revoke: proc do |port_range, protocol, actors|
        names = actors.map { |a| a.is_a?(Hash) ? a[:group_id] : a }
        converge_by "revoke the ability of #{names.join(', ')} to send traffic to group #{new_resource.name} (#{sg.id}) on port_range #{port_range.inspect} with protocol #{protocol || 'nil'}" do
          sg.revoke_ingress(protocol, port_range, *actors)
        end
      end
    )
  end

  def update_outbound_rules(sg, vpc)
    #
    # Get desired rules
    #
    desired_rules = {}

    case new_resource.outbound_rules
    when Hash
      new_resource.outbound_rules.each do |port_spec, sources_spec|
        add_rule(desired_rules, get_port_ranges(port_spec), get_actors(vpc, sources_spec))
      end

    when Array
      # [ { port: X, protocol: Y, sources: [ ... ]}]
      new_resource.outbound_rules.each do |rule|
        add_rule(desired_rules, get_port_ranges(rule), get_actors(vpc, rule[:destinations]))
      end

    else
      raise ArgumentError, "outbound_rules must be a Hash or Array (was #{new_resource.outbound_rules.inspect})"
    end

    #
    # Actually update the rules (remove, add)
    #
    update_rules(desired_rules, sg.ip_permissions_list_egress,

      authorize: proc do |port_range, protocol, actors|
        names = actors.map { |a| a.is_a?(Hash) ? a[:group_id] : a }
        converge_by "authorize group #{new_resource.name} (#{sg.id}) to send traffic to #{names.join(', ')} on port_range #{port_range.inspect} with protocol #{protocol || 'nil'}" do
          sg.authorize_egress(*actors, ports: port_range, protocol: protocol)
        end
      end,

      revoke: proc do |port_range, protocol, actors|
        names = actors.map { |a| a.is_a?(Hash) ? a[:group_id] : a }
        converge_by "revoke the ability of group #{new_resource.name} (#{sg.id}) to send traffic to #{names.join(', ')} on port_range #{port_range.inspect} with protocol #{protocol || 'nil'}" do
          sg.revoke_egress(*actors, ports: port_range, protocol: protocol)
        end
      end
    )
  end

  def update_rules(desired_rules, actual_rules_list, authorize: nil, revoke: nil)
    actual_rules = {}
    actual_rules_list.each do |rule|
      port_range = {
        port_range: rule[:from_port] ? rule[:from_port]..rule[:to_port] : -1..-1,
        protocol: rule[:ip_protocol].to_s.to_sym
      }
      add_rule(actual_rules, [ port_range ], rule[:groups]) if rule[:groups]
      add_rule(actual_rules, [ port_range ], rule[:ip_ranges].map { |r| r[:cidr_ip] }) if rule[:ip_ranges]
    end

    #
    # Get the list of permissions to add and remove
    #
    actual_rules.each do |port_range, actors|
      if desired_rules[port_range]
        intersection = actors & desired_rules[port_range]
        # Anything unhandled in desired_rules will be added
        desired_rules[port_range] -= intersection
        # Anything unhandled in actual_rules will be removed
        actual_rules[port_range] -= intersection
      end
    end

    #
    # Add any new rules
    #
    desired_rules.each do |port_range, actors|
      unless actors.empty?
        authorize.call(port_range[:port_range], port_range[:protocol], actors)
      end
    end

    #
    # Remove any rules no longer in effect
    #
    actual_rules.each do |port_range, actors|
      unless actors.empty?
        revoke.call(port_range[:port_range], port_range[:protocol], actors)
      end
    end
  end

  def add_rule(rules, port_ranges, actors)
    unless actors.empty?
      port_ranges.each do |port_range|
        rules[port_range] ||= Set.new
        rules[port_range] += actors
      end
    end
  end

  # When protocol is unspecified (anything besides tcp, udp or icmp) then
  # you cannot specify ports.  When specifying tcp, udp, or icmp AWS wants
  # port_range 0..0.  -1..-1 will cause error
  def get_port_ranges(port_spec)
    case port_spec
    when Integer
      port_spec = 0 if port_spec == -1
      [ { port_range: port_spec..port_spec, protocol: :tcp } ]
    when Range
      port_spec = 0..0 if port_spec == (-1..-1)
      [ { port_range: port_spec, protocol: :tcp } ]
    when Array
      port_spec.map { |p| get_port_ranges(p) }.flatten
    when String, Symbol
      protocol = port_spec.to_s.downcase.to_sym
      if protocol.to_s =~ /(any|all|-1)/i
        [ { port_range: -1..-1, protocol: :"-1" } ]
      else
        [ { port_range: 0..0, protocol: protocol } ]
      end
    when Hash
      port_range = port_spec[:port_range] || port_spec[:ports] || port_spec[:port] || 0
      port_range = port_range..port_range if port_range.is_a?(Integer)
      if port_spec[:protocol]
        protocol = port_spec[:protocol].to_s.downcase.to_sym
        if protocol.to_s =~ /(any|all|-1)/i
          [ { port_range: -1..-1, protocol: :"-1" } ]
        else
          [ { port_range: port_range, protocol: protocol } ]
        end
      else
        get_port_ranges(port_range)
      end
      # The to_s.to_sym dance is because if you specify a protocol number, AWS symbolifies it,
      # but 26.to_sym doesn't work (so we have to to_s it first).
    when nil
      [ { port_range: -1..-1, protocol: :"-1" } ]
    end
  end

  #
  # Turns an actor_spec into a uniform array, containing CIDRs, AWS::EC2::LoadBalancers and AWS::EC2::SecurityGroups.
  #
  def get_actors(vpc, actor_spec)
    result = case actor_spec

    # An array is always considered a list of actors.  Each one may follow any supported format.
    when Array
      actor_spec.map { |a| get_actors(vpc, a) }

    # Hashes come in several forms:
    when Hash
      # The default AWS Ruby SDK form with :user_id, :group_id and :group_name forms
      if actor_spec.keys.all? { |key| [ :user_id, :group_id, :group_name ].include?(key) }
        if actor_spec.has_key?(:group_name)
          actor_spec[:group_id] ||= vpc.security_groups.filter('group-name', actor_spec[:group_name]).first.id
        end
        actor_spec[:user_id] ||= new_resource.driver.account_id
        { user_id: actor_spec[:user_id], group_id: actor_spec[:group_id] }

      # load_balancer: <load balancer name>
      elsif actor_spec.keys == [ :load_balancer ]
        lb = Chef::Resource::AwsLoadBalancer.get_aws_object(actor_spec[:load_balancer], resource: new_resource)
        get_actors(vpc, lb)

      # security_group: <security group name>
      elsif actor_spec.keys == [ :security_group ]
        Chef::Resource::AwsSecurityGroup.get_aws_object(actor_spec[:security_group], resource: new_resource)

      else
        raise "Unable to reference security group with spec #{actor_spec}"
      end

    # If a load balancer is specified, grab it and then get its automatic security group
    when /^elb-[a-fA-F0-9]{8}$/, AWS::ELB::LoadBalancer, Chef::Resource::AwsLoadBalancer
      lb = Chef::Resource::AwsLoadBalancer.get_aws_object(actor_spec, resource: new_resource)
      get_actors(vpc, lb.source_security_group)

    # If a security group is specified, grab it
    when /^sg-[a-fA-F0-9]{8}$/, AWS::EC2::SecurityGroup, Chef::Resource::AwsSecurityGroup
      Chef::Resource::AwsSecurityGroup.get_aws_object(actor_spec, resource: new_resource)

    # If an IP addresses / CIDR are passed, return it verbatim; otherwise, assume it's the
    # name of a security group.
    when String
      begin
        IPAddr.new(actor_spec)
        # Add /32 to the end of raw IP addresses
        actor_spec =~ /\// ? actor_spec : "#{actor_spec}/32"
      rescue IPAddr::InvalidAddressError
        Chef::Resource::AwsSecurityGroup.get_aws_object(actor_spec, resource: new_resource)
      end

    else
      raise "Unexpected actor #{actor_spec} in rules list"
    end

    result = { user_id: result.owner_id, group_id: result.id } if result.is_a?(AWS::EC2::SecurityGroup)

    [ result ].flatten
  end

end


text:
@extends('templates.pages')

@section('pagetitle', ' - Logout')
@section('bannertitle', 'Thank you for using Wavlite!')
@section('leader', 'Not ready to leave yet?')
@section('bannerbutton')

				Log Back In!

@stop

<?php
/*
 * I am going to set a JavaScript timer for this page so that after 10 sections
 * the page will automatically redirect to the home page.
 */
?>

@section('content')

Logout View

							Nothing to show here at this time. Good place to remind users of any upcoming events or other "reminder" messages.

						Home

@stop

redpajama_set_name: RedPajamaGithub


text:
<?php
include 'includes/Helpers.php';
$test_url = (isset($_SERVER['HTTPS']) ? "https" : "http") . "://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
if($test_url != $config['base_url'].'/' xor $test_url != $config['base_url'].'/index.php'){} else {
  $config['base_url'] = str_replace('/index.php', '/', $test_url);
  trigger_error($lang['url_not_configured']);
}

$art_array = array_slice(scandir('articles'), 2);
//On prend que les articles valides
$articles = artTrueArray($art_array);

//On associe ces articles à leurs valeurs
foreach ($articles as $key => $art) {
  $articles[$key] = artInfo($key);
}
//On les range par ordre décroissant, du plus récent au plus vieux
$articles = timeSort($articles);
//On affiche le bon titre
$page = array(
  'title' => $config['short_blog_name'].' • '. $config['complete_blog_name'],
  'desc' => $config['blog_desc'],
  'type' => 'website',
  'cover' => $config['base_url'].'/assets/img/static/bg.jpg'
);

view('index.php');


text:
package au.edu.unsw.cse.data.api.security;

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

import org.apache.oltu.oauth2.as.issuer.OAuthIssuerImpl;
import org.apache.oltu.oauth2.as.issuer.ValueGenerator;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;

import com.auth0.jwt.JWTSigner;

import au.edu.unsw.cse.data.api.domain.entity.User;

public class OAuthJwtIssuerImpl extends OAuthIssuerImpl {

	private final Map<String, Object> claims;

	public OAuthJwtIssuerImpl(ValueGenerator vg) {
		super(vg);
		claims = new HashMap<String, Object>();
	}

	@Override
	public String accessToken() throws OAuthSystemException {
		final String issuer = "data.api";
		final String secret = "bg)0nn^rh!q0f8)4ku17iz-)dagzm$qjfts$@64cu4#jhb!sx-";

		final long iat = System.currentTimeMillis() / 1000l; // issued at claim
		final long exp = iat + 60L; // expires claim. In this case the token
									// expires in 60 seconds

		final JWTSigner signer = new JWTSigner(secret);
		claims.put("iss", issuer);
//		claims.put("exp", exp);
//		claims.put("iat", iat);

		final String jwt = signer.sign(claims);

		return jwt;
	}

	public void setClaims(User user) {
		claims.put(Claims.USERNAME, user.getUserName());
	}

	public void setClaim(String claim, String value) {
		claims.put(claim, value);
	}
}


text:
<?php

class SelectableOption extends WireData { // implements LanguagesValueInterface {

	static protected $defaults = array(
		'id' => 0,
		'sort' => 0,
		'title' => '',
		'value' => '',
	);

	/**
	 * Output formatting on/off
	 *
	 * @var bool
	 *
	 */
	protected $of = false;

	public function __construct() {
		foreach(self::$defaults as $property => $value) {
			$this->set($property, $value);
		}
	}

	static public function isProperty($property) {
		return array_key_exists($property, self::$defaults);
	}

	/**
	 * Turn output formatting on or off, or get current value
	 *
	 * @param null|bool $of Omit to return current value, or specify true|false to set
	 * @return bool
	 *
	 */
	public function of($of = null) {
		if(is_null($of)) return $this->of;
		$this->of = $of ? true : false;
		return $this->of;
	}

	public function get($key) {

		if($this->of && $key == 'title') return $this->getTitle();
		if($this->of && $key == 'value') return $this->getValue();

		return parent::get($key);
	}

	public function set($key, $value) {
		if(strpos($key, 'title') === 0 || strpos($key, 'value') === 0) {
			if(strpos($value, '|') !== false) {
				$this->error("$key may not contain the character '|'");
				$value = str_replace('|', ' ', $value);
			}
		}
		return parent::set($key, $value);
	}

	/**
	 * Return all values stored in this SelectableOption
	 *
	 * @param bool $returnHash Makes it return a string hash of all values
	 * @return string|array
	 *
	 */
	public function values($returnHash = false) {
		$values = array(
			'title' => $this->get('title'),
			'value' => $this->get('value'),
			'sort' => $this->get('sort'),
			'data' => $this->get('data'),
		);
		if($this->wire('languages')) {
			foreach($this->wire('languages') as $language) {
				if($language->isDefault()) continue;
				$values["title$language"] = $this->get("title$language");
				$values["value$language"] = $this->get("value$language");
			}
		}
		if($returnHash) return sha1(print_r($values, true));
		return $values;
	}

	/**
	 * Get the language-aware property
	 *
	 * @param string $property Either 'title' or 'value'
	 * @return string
	 *
	 */
	protected function getProperty($property) {
		if($this->wire('languages')) {
			$language = $this->wire('user')->language;
			if($language->isDefault()) {
				$value = parent::get($property);
			} else {
				$value = parent::get("$property$language");
				// fallback to default language title if no title present for language
				if(!strlen($value)) $value = parent::get($property);
			}
		} else {
			$value = parent::get($property);
		}
		if($this->of) $value = $this->wire('sanitizer')->entities($value);
		return $value;
	}

	/**
	 * Get the language-aware value
	 *
	 * @return string
	 *
	 */
	public function getValue() {
		return $this->getProperty('value');
	}

	/**
	 * Get the language-aware title
	 *
	 * @return string
	 *
	 */
	public function getTitle() {
		return $this->getProperty('title');
	}

	public function __toString() {
		return (string) $this->id;
	}

	/**
	 * Sets the value for a given language
	 *
	 * @param int|Language $languageID
	 * @param mixed $value
	 *
	public function setLanguageValue($languageID, $value) {
		$language = is_object($languageID) ? $languageID : $this->wire('languages')->get($languageID);
		if($language && $language->id) {
			if($language->isDefault()) $language = '';
			$this->set("title$language", $value);
		}
	}
	 */

	/**
	 * Given a language, returns the value in that language
	 *
	 * @param Language|int
	 * @return int|string
	 *
	public function getLanguageValue($languageID) {
		$language = is_object($languageID) ? $languageID : $this->wire('languages')->get($languageID);
		if($language && $language->id) {
			if($language->isDefault()) $language = '';
			return $this->get("title$language");
		}
		return '';
	}
	 */
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Util.Common
{
    /// <summary>
    /// 工具类:Dictionary
    /// </summary>
    public class UtilDictionary
    {
        /// <summary>
        /// 移除多个存在指定键的键值
        /// </summary>
        /// <param name="data"></param>
        /// <param name="keys"></param>
        public static void Removes(Dictionary<String, object> data, params string[] keys)
        {
            foreach (var key in keys)
            {
                if (data.ContainsKey(key)) data.Remove(key);
            }
        }
    }
}


text:
ColorMap
========

.. autoclass:: pyqtgraph.ColorMap
    :members:

    .. automethod:: pyqtgraph.ColorMap.__init__


text:
package org.toobs.data.beanutil;

import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.StringTokenizer;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConversionException;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.MethodUtils;
import org.apache.commons.beanutils.NestedNullException;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.validation.BindException;
import org.springframework.validation.Errors;
import org.toobs.data.ICollectionLoader;
import org.toobs.data.IObjectLoader;
import org.toobs.data.beanutil.converter.StringToDateConverter;
//import org.toobs.data.base.PermissionedObject;
import org.toobs.framework.biz.collections.ICollectionCreator;
import org.toobs.framework.biz.validation.IValidator;
//import org.toobs.framework.exception.BaseException;
import org.toobs.framework.exception.PermissionException;
import org.toobs.framework.exception.ValidationException;
import org.toobs.framework.servlet.ContextHelper;
import org.toobs.framework.util.Configuration;
import org.toobs.framework.util.constants.PlatformConstants;
import org.toobs.framework.util.string.StringResource;

@SuppressWarnings("unchecked")
public class BeanMonkey {

  /**
   * To get the logger instance
   */
  private static Log log = LogFactory.getLog(BeanMonkey.class);

  private static BeanFactory beanFactory = BeanMonkey.getBeanFactoryInstance();

  private static Class objectClass;

  static {
    String objectClassProperty = "";
    try {
      objectClassProperty = Configuration.getInstance().getProperty("toobs.beanmonkey.objectClass");
      objectClass = Class.forName(objectClassProperty);
    } catch (ClassNotFoundException e) {
      log.error("Class for toobs.beanmonkey.objectClass property: " + objectClassProperty + " not found");
    }
  }

  /**
   * A utility method that just returns a new instance of a bean factory object.
   * @return
   */
  public static BeanFactory getBeanFactoryInstance()
  {
    return ContextHelper.getInstance().getWebApplicationContext().getParentBeanFactory();
  }

  public static void populate(Object bean, Map properties, Collection errorMessages)
  throws IllegalAccessException, InvocationTargetException, ValidationException, PermissionException {

    IValidator v = null;
    String className = bean.getClass().getSimpleName();
    String validatorName = className + "Validator";
    if (beanFactory.containsBean(validatorName)) {
      v = (IValidator) beanFactory.getBean(validatorName);
    } else {
      log.warn("No validator " + validatorName + " for " + className);
    }
    if (v != null) {
      v.prePopulate(bean, properties);
    }

    populate(bean, properties, true);

    Errors e = new BindException(bean, className.substring(0, className.length()-4));

    if (properties.containsKey("MultipartValidationError")) {
      String docProperty = (String)properties.get("MultipartValidationField");
      try {
        PropertyDescriptor descriptor = PropertyUtils.getPropertyDescriptor(bean, docProperty);
        if (descriptor != null) {
          BeanUtils.setProperty(bean, docProperty, null);
          e.rejectValue(docProperty,
              docProperty +"."+(String)properties.get("MultipartValidationError"), (String)properties.get("MultipartValidationMessage"));
        }
      } catch (NoSuchMethodException nsm) {
      }
    }

    if (v != null) {
      if (e.getAllErrors() == null || e.getAllErrors().size() == 0) {
        v.prepare(bean, properties);
        v.validate(bean, e);
      }
    }

    if (e.getAllErrors() != null && e.getAllErrors().size() > 0) {
      errorMessages.addAll(e.getAllErrors());
    }
  }

  public static void populate(Object bean, Map properties) throws IllegalAccessException, InvocationTargetException, ValidationException, PermissionException {

    IValidator v = null;
    String className = bean.getClass().getSimpleName();
    String validatorName = className + "Validator";
    if (beanFactory.containsBean(validatorName)) {
      v = (IValidator) beanFactory.getBean(validatorName);
    } else {
      log.warn("No validator " + validatorName + " for " + className);
    }

    if (v != null) {
      v.prePopulate(bean, properties);
    }

    populate(bean, properties, true);

    String objectName = (String) properties.get("returnObjectType") == null ? className
        : (String) properties.get("returnObjectType");

    Errors e = new BindException(bean, objectName);

    if (properties.containsKey("MultipartValidationError")) {
      String docProperty = (String)properties.get("MultipartValidationField");
      try {
        PropertyDescriptor descriptor = PropertyUtils.getPropertyDescriptor(bean, docProperty);
        if (descriptor != null) {
          BeanUtils.setProperty(bean, docProperty, null);
          e.rejectValue(docProperty,
              docProperty +"."+(String)properties.get("MultipartValidationError"), (String)properties.get("MultipartValidationMessage"));
        }
      } catch (NoSuchMethodException nsm) {
      }
    }

    if (v != null) {
      if (e.getAllErrors() == null || e.getAllErrors().size() == 0) {
        v.prepare(bean, properties);
        v.validate(bean, e);
        if (e.getAllErrors() == null || e.getAllErrors().size() == 0) {
          v.audit(bean, properties);
        }
      }
    }

    if (e.getAllErrors() != null && e.getAllErrors().size() > 0) {
      throw new ValidationException(e);
    }
  }

  public static Collection populateCollection(String beanClazz, String indexPropertyName, Map properties, boolean noload, boolean errorMode, Collection errorMessages)
    throws IllegalAccessException, InvocationTargetException, ValidationException, ClassNotFoundException, InstantiationException, PermissionException {

    String className = beanClazz.substring(beanClazz.lastIndexOf(".") + 1);

    IValidator v = null;
    String validatorName = className + "Validator";
    if (beanFactory.containsBean(validatorName)) {
      v = (IValidator) beanFactory.getBean(validatorName);
    } else {
      log.warn("No validator for " + className);
    }

    Collection validationErrors = new ArrayList();
    Collection returnObjs = populateCollection(v, beanClazz, indexPropertyName, properties, true, noload);

    if (v == null) {
      return returnObjs;
    }

    String objectName = (String) properties.get("returnObjectType") == null ? className
        : (String) properties.get("returnObjectType");

    /* Validate Collection level properties - size() > 0 etc */
    Errors e = new BindException(returnObjs, objectName);
    v.validateCollection(returnObjs, e);
    if (e.getAllErrors() != null && e.getAllErrors().size() > 0) {
      validationErrors.add(e);
      //return returnObjs;
    } else {

      Iterator it = returnObjs.iterator();
      while (it.hasNext()) {
        Object bean = it.next();

        v.prepare(bean, properties);
        boolean doCreate = v.doCreateCollectionMember(bean);
        if (!doCreate) {
          it.remove();
          continue;
        }

        e = new BindException(bean, objectName);
        v.validate(bean, e);

        /* Safe bean in DoItRunner
        validationErrorObjects.add(v.getSafeBean(bean, properties));
        */
        if (e.getAllErrors() != null && e.getAllErrors().size() > 0) {
          validationErrors.add(e);
        } else if (errorMode) {
          it.remove();
        }
      }
    }

    if(validationErrors.size() > 0){
      if (errorMessages != null) {
        Iterator errIter = validationErrors.iterator();
        while (errIter.hasNext()) {
          Errors err = (Errors)errIter.next();
          errorMessages.addAll(err.getAllErrors());
        }
      } else {
        throw new ValidationException(validationErrors);
      }
    }
    /*
    if(validationErrors.size() > 0){
      //properties.put("ValidationErrors", validationErrors);
      //properties.put("ValidationErrorObject", validationErrorObjects);
      throw new ValidationException(validationErrors);
    }
    */
    //If there are no errors, null out the errorsObjects to conserve memory.
    //validationErrorObjects = null;

    return returnObjs;
  }

  public static Collection populateCollection(IValidator v, String beanClazz, String indexPropertyName,
      Map properties, boolean validate, boolean noload) throws IllegalAccessException,
      InvocationTargetException, ValidationException,
      ClassNotFoundException, InstantiationException, PermissionException {

    // Do nothing unless all arguments have been specified
    if ((beanClazz == null) || (properties == null) || (indexPropertyName == null)) {
      log.warn("Proper parameters not present.");
      return null;
    }

    ArrayList returnObjs = new ArrayList();

    Object[] indexProperty = (Object[]) properties.get(indexPropertyName);
    if (indexProperty == null){
      log.warn("indexProperty [" + indexProperty + "] does not exist in the map.");
      return returnObjs;
    }

    Class beanClass = Class.forName(beanClazz);

    String beanClazzName = beanClass.getSimpleName(); //  beanClazz.substring(beanClazz.lastIndexOf(".") + 1);
    IObjectLoader odao = null;
    ICollectionLoader cdao = null;
    if (objectClass.isAssignableFrom(beanClass)) {
      odao = (IObjectLoader) beanFactory.getBean(Introspector.decapitalize(beanClazzName.substring(0,beanClazzName.length()-4)) + "Dao");
      if (odao == null) {
        throw new InvocationTargetException(new Exception("Object DAO class " + Introspector.decapitalize(beanClazzName) + "Dao could not be loaded"));
      }
    } else {
      cdao = (ICollectionLoader) beanFactory.getBean(Introspector.decapitalize(beanClazzName.substring(0,beanClazzName.length()-4)) + "Dao");
      if (cdao == null) {
        throw new InvocationTargetException(new Exception("Collection DAO class " + Introspector.decapitalize(beanClazzName) + "Dao could not be loaded"));
      }
    }

    boolean namespaceStrict = properties.containsKey("namespaceStrict");

    for(int index = 0; index < indexProperty.length; index++) {
      String guid = (String)indexProperty[index];

      boolean newBean = false;
      Object bean = null;
      if (!noload && guid != null && guid.length() > 0) {
        bean = (odao != null) ? odao.load(guid) : cdao.load(Integer.parseInt(guid));
      }
      if (bean == null) {
        bean = Class.forName(beanClazz).newInstance();
        newBean = true;
      }
      if (v != null) {
        v.prePopulate(bean, properties);
      }
      if (log.isDebugEnabled()) {
        log.debug("BeanMonkey.populate(" + bean + ", " + properties + ")");
      }

      Errors e = null;

      if (validate) {
        String beanClassName = null;
        beanClassName = bean.getClass().getName();
        beanClassName = beanClassName
            .substring(beanClassName.lastIndexOf(".") + 1);
        e = new BindException(bean, beanClassName);
      }

      String namespace = null;
      if (properties.containsKey("namespace") && !"".equals(properties.get("namespace"))) {
        namespace = (String)properties.get("namespace") + ".";
      }

      // Loop through the property name/value pairs to be set
      Iterator names = properties.keySet().iterator();
      while (names.hasNext()) {

        // Identify the property name and value(s) to be assigned
        String name = (String) names.next();
        if (name == null || (indexPropertyName.equals(name) && !noload) || (namespaceStrict && !name.startsWith(namespace))) {
          continue;
        }

        Object value = null;
        if(properties.get(name) == null) {
          log.warn("Property [" + name + "] does not have a value in the map.");
          continue;
        }
        if(properties.get(name).getClass().isArray() && index < ((Object[])properties.get(name)).length){
          value = ((Object[])properties.get(name))[index];
        } else if(properties.get(name).getClass().isArray()) {
          value = ((Object[])properties.get(name))[0];
        } else {
          value = properties.get(name);
        }
        if (namespace != null) {
          name = name.replace(namespace, "");
        }

        PropertyDescriptor descriptor = null;
        Class type = null; // Java type of target property
        try {
          descriptor = PropertyUtils.getPropertyDescriptor(bean, name);
          if (descriptor == null) {
            continue; // Skip this property setter
          }
        } catch (NoSuchMethodException nsm) {
          continue; // Skip this property setter
        } catch (IllegalArgumentException iae) {
          continue; // Skip null nested property
        }
        if (descriptor.getWriteMethod() == null) {
          if (log.isDebugEnabled()) {
            log.debug("Skipping read-only property");
          }
          continue; // Read-only, skip this property setter
        }
        type = descriptor.getPropertyType();
        String className = type.getName();

        try {
          value = evaluatePropertyValue(name, className, namespace, value, properties, bean);
        } catch (NoSuchMethodException nsm) {
          continue;
        }

        try {
          BeanUtils.setProperty(bean, name, value);
        } catch (ConversionException ce) {
          log.error("populate - exception [bean:" + bean.getClass().getName() + " name:" + name + " value:" + value + "] ");
          if (validate) {
            e.rejectValue(name, name + ".conversionError", ce.getMessage());
          } else {
            throw new ValidationException(bean, className, name, ce.getMessage());
          }
        } catch (Exception be) {
          log.error("populate - exception [bean:" + bean.getClass().getName() + " name:" + name + " value:" + value + "] ");
          if (validate) {
            e.rejectValue(name, name + ".error", be.getMessage());
          } else {
            throw new ValidationException(bean, className, name, be.getMessage());
          }
        }
      }
      /*
      if (newBean && cdao != null) {
        BeanUtils.setProperty(bean, "id", -1);
      }
      */
      if (validate && e.getErrorCount() > 0) {
        throw new ValidationException(e);
      }

      returnObjs.add(bean);
    }

    return returnObjs;
  }

  public static void populate(Object bean, Map properties, boolean validate)
      throws IllegalAccessException, InvocationTargetException,
      ValidationException, PermissionException {

    // Do nothing unless both arguments have been specified
    if ((bean == null) || (properties == null)) {
      return;
    }
    if (log.isDebugEnabled()) {
      log.debug("BeanMonkey.populate(" + bean + ", " + properties + ")");
    }

    Errors e = null;
    if (validate) {
      String beanClassName = null;
      beanClassName = bean.getClass().getName();
      beanClassName = beanClassName
          .substring(beanClassName.lastIndexOf(".") + 1);
      e = new BindException(bean, beanClassName);
    }

    String namespace = null;
    if (properties.containsKey("namespace") && !"".equals(properties.get("namespace"))) {
      namespace = (String)properties.get("namespace") + ".";
    }

    // Loop through the property name/value pairs to be set
    Iterator names = properties.keySet().iterator();
    while (names.hasNext()) {

      // Identify the property name and value(s) to be assigned
      String name = (String) names.next();
      if (name == null) {
        continue;
      }
      Object value = properties.get(name);
      if (namespace != null) {
        name = name.replace(namespace, "");
      }

      PropertyDescriptor descriptor = null;
      Class type = null; // Java type of target property
      try {
        descriptor = PropertyUtils.getPropertyDescriptor(bean, name);
        if (descriptor == null) {
          continue; // Skip this property setter
        }
      } catch (NoSuchMethodException nsm) {
        continue; // Skip this property setter
      } catch (IllegalArgumentException iae) {
        continue; // Skip null nested property
      }

      if (descriptor.getWriteMethod() == null) {
        if (log.isDebugEnabled()) {
          log.debug("Skipping read-only property");
        }
        continue; // Read-only, skip this property setter
      }
      type = descriptor.getPropertyType();
      String className = type.getName();

      try {
        value = evaluatePropertyValue(name, className, namespace,
            value, properties, bean);
      } catch (NoSuchMethodException nsm) {
        continue;
      }

      try {
        if(value != null) {
          BeanUtils.setProperty(bean, name, value);
        }
      } catch (ConversionException ce) {
        log.error("populate - exception [bean:" + bean.getClass().getName() + " name:" + name + " value:" + value + "] ");
        if (validate) {
          e.rejectValue(name, name + ".conversionError", ce.getMessage());
        } else {
          throw new ValidationException(bean, className, name, ce.getMessage());
        }
      } catch (Exception be) {
        log.error("populate - exception [bean:" + bean.getClass().getName() + " name:" + name + " value:" + value + "] ");
        if (validate) {
          e.rejectValue(name, name + ".error", be.getMessage());
        } else {
          throw new ValidationException(bean, className, name, be.getMessage());
        }
      }
    }
    if (validate && e.getErrorCount() > 0) {
      throw new ValidationException(e);
    }
  }

  private static Object evaluatePropertyValue(String name, String className, String namespace,
      Object value, Map properties, Object bean)
      throws InvocationTargetException, IllegalAccessException,
      NoSuchMethodException, PermissionException {
    // Perform the assignment for this property
    if (className.startsWith(Configuration.getInstance().getProperty("toobs.beanmonkey.dataPackage"))) {
      className = className.substring(className.lastIndexOf(".") + 1);

      IObjectLoader odao = null;
      ICollectionLoader cdao = null;
      Object daoObject = beanFactory.getBean(Introspector.decapitalize(className) + "Dao");
      if (daoObject == null) {
        throw new InvocationTargetException(new Exception("DAO class " + Introspector.decapitalize(className) + "Dao could not be loaded"));
      }
      if (daoObject instanceof IObjectLoader) {
        odao = (IObjectLoader)daoObject;
      } else {
        cdao = (ICollectionLoader)daoObject;
      }

      String guid = null;
      if (value != null && value.getClass().isArray()) {
        if(properties.containsKey(PlatformConstants.MULTI_ACTION_INSTANCE)) {
          Object[] oldValue = (Object[]) value;
          Integer instance = (Integer)properties.get(PlatformConstants.MULTI_ACTION_INSTANCE);
          if (oldValue.length >= instance + 1) {
            guid = ((String[])oldValue)[instance];
          } else {
            throw new RuntimeException("Instance " + instance + " not found in " + oldValue + " for: " + name + " class: " + className + " in: " + bean);
          }
        } else {
          guid = ((String[]) value)[0];
        }
      } else {
        guid = (String) value;
      }
      if (guid != null && guid.length() > 0) {
        String personId = (String) properties.get("personId");
        try {
          if (odao != null) {
            value = odao.load(guid);
          } else {
            value = cdao.load(Integer.parseInt(guid));
          }
        } catch (PermissionException pe) {
          log.error("PermissionException loading object " + className + "." + name + " with guid " + guid + " by person " + personId );
          throw pe;
        } finally { }
      } else {
        value = null;
      }
    } else if ((className.equals("java.util.ArrayList") || className
        .equals("java.util.List"))
        && !(value instanceof java.util.List)) {
      Object[] values = null;
      if (value != null && value.getClass().isArray()) {
        values = ((Object[]) value);
      } else {
        values = new Object[1];
        values[0] = (Object) value;
      }
      value = new ArrayList();
      for (int aa = 0; aa < values.length; aa++) {
        if (!"".equals(values[aa]))
          ((ArrayList) value).add(values[aa]);
      }
      if (((ArrayList) value).size() == 0)
        value = null;
    } else if (className.equals("java.util.Collection")) {
      className = null;
      String typeProp = (namespace != null ? namespace : "") + name + "-Type";
      if (properties.get(typeProp) != null && properties.get(typeProp).getClass().isArray()) {
        className = ((String[]) properties.get(typeProp))[0];
      } else {
        className = (String) properties.get(typeProp);
      }

      if (className == null) {
        throw new InvocationTargetException(new Exception(
            "Missing collection type for " + name));
      }

      IObjectLoader odao = null;
      ICollectionLoader cdao = null;
      Object daoObject = beanFactory.getBean(Introspector.decapitalize(className) + "Dao");
      if (daoObject == null) {
        throw new InvocationTargetException(new Exception("DAO class " + Introspector.decapitalize(className) + "Dao could not be loaded"));
      }
      if (daoObject instanceof IObjectLoader) {
        odao = (IObjectLoader)daoObject;
      } else {
        cdao = (ICollectionLoader)daoObject;
      }

      Object[] guids = null;
      if (value != null && value.getClass().isArray()) {
        guids = ((Object[]) value);
      } else if (value != null && value instanceof ArrayList) {
        guids = new Object[((ArrayList)value).size()];
        for (int i = 0; i < guids.length; i++) {
          guids[i] = (Object)((ArrayList)value).get(i);
        }
      } else {
        guids = new Object[1];
        guids[0] = (Object) value;
      }

      String personId = (String) properties.get("personId");

      java.util.Collection valueList = (java.util.Collection) PropertyUtils.getProperty(bean, name);
      valueList.clear();

      for (int i = 0; i < guids.length; i++) {
        if (odao != null) {
          if (((String)guids[i]).length() == 0) continue;
          value = odao.load((String)guids[i]);
        } else if (cdao != null) {
          value = cdao.load((Integer)guids[i]);
        }
        if (value != null) {
          valueList.add(value);
        } else {
          if (beanFactory.containsBean(className + "CollectionCreator")) {
            ICollectionCreator collectionCreator = (ICollectionCreator)beanFactory.getBean(className + "CollectionCreator");
            try {
              collectionCreator.addCollectionElements(guids[i], valueList, properties, personId, namespace);
            } catch (Exception e) {
              throw new InvocationTargetException(e);
            }
          }
        }
      }
      value = valueList;
    } else if(className.equals("java.lang.String") && value != null && value.getClass().isArray() && ((Object[]) value).length > 1 && properties.containsKey(PlatformConstants.MULTI_ACTION_INSTANCE)) {
      Object[] oldValue = (Object[]) value;
      Integer instance = (Integer)properties.get(PlatformConstants.MULTI_ACTION_INSTANCE);
      if (oldValue.length >= instance + 1) {
        value = oldValue[instance];
      } else {
        throw new RuntimeException("Instance " + instance + " not found in " + oldValue + " for: " + name + " class: " + className + " in: " + bean);
      }
    } else if(className.equals("java.lang.String") && value != null && value.getClass().isArray() && ((Object[]) value).length > 1) {
      Object[] oldValue = (Object[]) value;
      String newValue = new String();
      for (int i = 0; i < oldValue.length; i++) {
        if(i > 0) {
        newValue = newValue + ";";
        }
        newValue = newValue + oldValue[i];
      }
      value = newValue;
    } else if((className.equals("java.lang.Integer") || className.equals("java.lang.Boolean")) && value != null) {
      if (value.getClass().isArray() && ((Object[]) value).length == 1 && ((Object[]) value)[0].equals("")) {
        value = null;
      } else if (!value.getClass().isArray() && String.valueOf(value).equals("")) {
        value = null;
      }
    } else if(className.equals("java.util.Date") && value != null) {
      if (value.getClass().isArray()) {
        value = StringToDateConverter.convert(value);
      }
    }

    return value;
  }

  public static Method findMethod(Class clazz, String methodName, Class paramType) {
    return MethodUtils.getAccessibleMethod(clazz, methodName, paramType);
  }

  public static Method findMethod(Class clazz, String methodName, Class[] paramTypes) {
    return MethodUtils.getAccessibleMethod(clazz, methodName, paramTypes);
  }

  public static String concatPropertyList(Object bean, String propertyList,
      boolean quoted) throws NoSuchMethodException, InvocationTargetException,
      IllegalAccessException {
    StringBuffer sb = new StringBuffer();
    concatPropertyList(bean, propertyList, sb, quoted);
    if (log.isDebugEnabled()) {
      log.debug("Concat result: " + sb.toString().trim());
    }
    return sb.toString().trim();
  }

  public static void concatPropertyList(Object bean, String propertyList,
      StringBuffer result, boolean quoted) throws NoSuchMethodException,
      InvocationTargetException, IllegalAccessException {
    if (bean == null || propertyList == null || result == null) {
      return;
    }

    StringTokenizer st = new StringTokenizer(propertyList, ",");
    while (st.hasMoreTokens()) {
      String name = st.nextToken();
      Object value = PropertyUtils.getProperty(bean, name);
      if (value instanceof String && value != null) {
        result.append(" ");
        if (quoted)
          result.append("\"");
        result.append(value);
        if (quoted)
          result.append("\"");
      } else if (value instanceof Collection && value != null) {
        Iterator valIter = ((Collection) value).iterator();
        while (valIter.hasNext()) {
          concatPropertyList(valIter.next(), "displayName", result, quoted);
          // result.append(" " + ConvertUtils.convert(valIter.next()));
        }
      } else if (value != null) {
        result.append(" ");
        if (quoted)
          result.append("\"");
        result.append(ConvertUtils.convert(value));
        if (quoted)
          result.append("\"");
      }
    }
  }

  public static String getSummary(String input, int length) {
    if (input == null) {
      return input;
    }

    String strippedString = StringResource.stripTags(input, false);

    if (strippedString == null || strippedString.length() <= length - 3) {
      return strippedString;// + "..."
    }

    return strippedString.substring(0, length - 3) + "...";
  }

  public static Object getPropertyValue(Object bean, String propertyPath) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
    Object value = null;
    try {
      value = PropertyUtils.getProperty(bean, propertyPath);
    } catch (NestedNullException nne) { }
    return value;
  }
}


text:
"use strict";

var java = require("java");
var List = java.import("java.util.ArrayList");
var HashMap = java.import ("java.util.HashMap");

// this currently works because we're importing the spark assembly jar elsewhere,
// but will need to import the scala library jar separately when this is split
// it into its own module
var convert = java.import("scala.collection.JavaConversions");

function syncMethodName(base) {
    return base + java.asyncOptions.syncSuffix;
}

// convert a js array into a buffer
function buffer(arr) {
    if (!Array.isArray(arr)) {
        return;
    }

    var l = new List();
    arr.forEach(function(el) {
        l[syncMethodName("add")](el);
    });
    return convert[syncMethodName("asScalaBuffer")](l);
}

// convert a js object into a map
function map(arr) {
    var hm = new HashMap();
    Object.keys(arr).forEach(function(k) {
        hm.put(k, arr[k]);
    });
    return convert[syncMethodName("asScalaMap")](hm);
}

// convert a js object into a set
function set() {

}

module.exports = {
    buffer: buffer,
    map: map,
    set: set
};


text:
'use strict';

//Setting up route
angular.module('advertisementitems').config(['$stateProvider',
	function($stateProvider) {
		// Advertisementitems state routing
		$stateProvider.
		state('listAdvertisementitems', {
			url: '/partners/advertisementitems',
			templateUrl: 'modules/advertisementitems/views/list-advertisementitems.client.view.html'
		}).
		state('createAdvertisementitem', {
			url: '/partners/advertisementitems/create',
			templateUrl: 'modules/advertisementitems/views/create-advertisementitem.client.view.html'
		}).
		state('viewAdvertisementitem', {
			url: '/partners/advertisementitems/:advertisementitemId',
			templateUrl: 'modules/advertisementitems/views/view-advertisementitem.client.view.html'
		}).
		state('editAdvertisementitem', {
			url: '/partners/advertisementitems/:advertisementitemId/edit',
			templateUrl: 'modules/advertisementitems/views/edit-advertisementitem.client.view.html'
		});
	}
]);


text:
  Easing functions (for canvas etc)

  - linear
  - inQuad
  - outQuad
  - inOutQuad
  - inCube
  - outCube
  - inOutCube
  - inQuart
  - outQuart
  - inOutQuart
  - inQuint
  - outQuint
  - inOutQuint
  - inSine
  - outSine
  - inOutSine
  - inExpo
  - outExpo
  - inOutExpo
  - inCirc
  - outCirc
  - inOutCirc
  - inBack
  - outBack
  - inOutBack
  - inBounce
  - outBounce
  - inOutBounce
  - inElastic
  - outElastic
  - inOutElastic

## Aliases

  - in-quad
  - out-quad
  - in-out-quad
  - in-cube
  - out-cube
  - in-out-cube
  - in-quart
  - out-quart
  - in-out-quart
  - in-quint
  - out-quint
  - in-out-quint
  - in-sine
  - out-sine
  - in-out-sine
  - in-expo
  - out-expo
  - in-out-expo
  - in-circ
  - out-circ
  - in-out-circ
  - in-back
  - out-back
  - in-out-back
  - in-bounce
  - out-bounce
  - in-out-bounce
  - in-elastic
  - out-elastic
  - in-out-elastic

## Example

```js
var ease = require('ease');
var requestAnimationFrame = require('raf');
var canvas = document.querySelector('canvas');
var ctx = canvas.getContext('2d');

var stop = false;
function animate() {
  if (stop) return;
  requestAnimationFrame(animate);
  draw();
}

var startx = 20;
var x = startx;
var destx = 300;
var y = 400 / 2;
var duration = 1000;
var start = Date.now();
var end = start + duration;

function draw() {
  var now = Date.now();
  if (now - start >= duration) stop = true;
  var p = (now - start) / duration;
  val = ease.inOutBounce(p);
  x = startx + (destx - startx) * val;
  canvas.width = canvas.width;
  ctx.fillStyle = 'red';
  ctx.arc(x, y, 10, 0, Math.PI * 2, false);
  ctx.fill();
}

animate();

```

## Special Thanks

These easing functions were originally written by [Robert Penner](http://robertpenner.com/easing/),
and optimized by the [tween.js](https://github.com/sole/tween.js) authors.

## License

The MIT License

Copyright (c) 2010-2012 Tween.js authors.

Easing equations Copyright (c) 2001 Robert Penner http://robertpenner.com/easing/

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.


text:
package com.makeandbuild.vessl.persistence;

import com.makeandbuild.vessl.persistence.jdbc.BaseDao;

public interface UserDao extends BaseDao<User, Long>{

}


text:
/* */
"format cjs";
'use strict';

import React from 'react';
import invariant from 'invariant';
import { createRouteFromReactElement } from './RouteUtils';
import { component, components } from './PropTypes';

var _React$PropTypes = React.PropTypes;
var string = _React$PropTypes.string;
var func = _React$PropTypes.func;

/**
 * A <Route> is used to declare which components are rendered to the
 * page when the URL matches a given pattern.
 *
 * Routes are arranged in a nested tree structure. When a new URL is
 * requested, the tree is searched depth-first to find a route whose
 * path matches the URL.  When one is found, all routes in the tree
 * that lead to it are considered "active" and their components are
 * rendered into the DOM, nested in the same order as in the tree.
 */
var Route = React.createClass({
  displayName: 'Route',

  statics: {
    createRouteFromReactElement: createRouteFromReactElement
  },

  propTypes: {
    path: string,
    component: component,
    components: components,
    getComponent: func,
    getComponents: func
  },

  /* istanbul ignore next: sanity check */
  render: function render() {
    !false ? process.env.NODE_ENV !== 'production' ? invariant(false, '<Route> elements are for router configuration only and should not be rendered') : invariant(false) : undefined;
  }

});

export default Route;


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- EN-Revision: 24249 -->
<!-- Reviewed: no -->
<sect3 id="zend.controller.plugins.standard.puthandler">
    <title>Zend_Controller_Plugin_PutHandler</title>

    <para>
        <classname>Zend_Controller_Plugin_PutHandler</classname> fournit un plugin intégré pour
        la gestion du corps des requêtes <constant>PUT</constant> en tant que paramètres de
        requête, tout comme le corps d'une requête <constant>POST</constant>. Il va inspecter
        la requête et, s'il s'agit d'une requête <constant>PUT</constant>, va utiliser la
        fonction parse_str pour découper le contenu brut de la requête <constant>PUT</constant>
        en un tableau de paramètres qui est ensuite enregistré dans l'objet de requête. Par
        exemple :
    </para>

    <programlisting language="txt"><![CDATA[
PUT /notes/5.xml HTTP/1.1

title=Hello&body=World
]]></programlisting>

    <para>
        Pour recevoir les paramètres "title" et "body" comme des paramètres de requête habituels,
        vous devez enregistrer le plugin :
    </para>

    <programlisting language="php"><![CDATA[
$front = Zend_Controller_Front::getInstance();
$front->registerPlugin(new Zend_Controller_Plugin_PutHandler());
]]></programlisting>

    <para>
        Ensuite vous pouvez accéder aux paramètres du corps de la requête <constant>PUT</constant>
        par leur nom à l'intérieur de votre contrôleur :
    </para>

    <programlisting language="php"><![CDATA[
...
public function putAction()
{
    $title = $this->getRequest()->getParam('title'); // $title = "Hello"
    $body = $this->getRequest()->getParam('body'); // $body = "World"
}
...
]]></programlisting>
</sect3>


text:
default: testacc

.PHONY: deps
deps:
	go mod download

# Run acceptance tests
.PHONY: testacc
testacc:
	TF_ACC=1 go test ./... -v $(TESTARGS) -timeout 120m


text:
package com.github.cukedoctor.mojo.model;

/** Created by pestano on 28/06/15. */
public enum Format {
  html,
  html5,
  pdf,
  all
}


text:
using System.Diagnostics;
using DiWalkthrough_001.Before_DI.Code.BLLayer;

namespace DiWalkthrough_001.Before_DI
{
    internal class Program
    {
        private static void Main()
        {
            var userManager = new UserManager();

            Debugger.Break();

            // What to expect:
            // This is going to work because the UserManager initilises its own user repository.

            userManager.EnsureUserCreated(1, "Foo");
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!-- EN-Revision: 24249 -->
<!-- Reviewed: no -->
<sect1 id="learning.multiuser.sessions">
    <title>Gérer les sessions dans ZF</title>

    <sect2 id="learning.multiuser.sessions.intro">
        <title>Introduction aux sessions</title>

        <para>
            Le succès du web est en grande partie dûe aux protocoles qui le supportent: HTTP. HTTP sur
            TCP est par nature sans état ce qui signifie que le web n'a pas "de mémoire". Ce fait
            pose des problèmes pour les développeurs voulant traiter leur application comme un
            service riche.
        </para>

        <para>
            Interagir avec l'application web c'est en fait faire la somme de toutes les requêtes
            que celle-ci reçoit. Et comme il y a beaucoup de clients, il y a beaucoup de requête,
            et le moyen d'associer une requête à un client est appelé "session".
        </para>

        <para>
            En PHP, le problème des sessions a été résolu au travers de l'extension session qui utilise
            un système de persistance, typiquement basé sur des cookies et un stockage local des variables
            dans $_SESSION. Dans Zend Framework, le composant Zend_Session ajoute de la valeur au système
            de session de PHP notamment une manipulation objet.
        </para>
    </sect2>

    <sect2 id="learning.multiuser.sessions.basic-usage">
        <title>Utilisation classique de Zend_Session</title>

        <para>
            Le composant Zend_Session est un gestionnaire de session et une API pour stocker des données
            dans la session de manière objet. L'API de la classe Zend_Session API permet de régler des options
            et de démarrer/arrêter la session alors que Zend_Session_Namespace représente un objet
            contenant des données à stocker en session.
        </para>

        <para>
            C'est générallement une bonne pratique que de démarrer sa session en bootstrap, cependant
            la première création d'un objet Zend_Session_Namespace démarrera la session par défaut.
        </para>

        <para>
            Zend_Application peut permettre de configurer Zend_Session grâce aux parties
            Zend_Application_Resource. Pour les utiliser, en supposant que votre projet utilise
            Zend_Application, ajoutez le code suivant à application.ini:
        </para>

        <programlisting language="php"><![CDATA[
resources.session.save_path = APPLICATION_PATH "/../data/session"
resources.session.use_only_cookies = true
resources.session.remember_me_seconds = 864000
]]></programlisting>

        <para>
            Comme vous le remarquez, les options utilisées sont les mêmes que celles que reconnait
            ext/session (l'extension session de PHP). Le chemin de stockage des session par exemple.
            Les fichiers ini peuvent utiliser des constantes, nous réutilisons APPLICATION_PATH
            pour calculer le chemin relatif vers un dossier arbitraire sensé stocker les sessions.
        </para>

        <para>
            La plupart des composants de Zend Framework utilisant les sessions n'ont rien besoin de plus.
            Dès lors, vous pouvez utiliser un composant faisant appel à la session, ou manipuler la session
            vous-même au travers d'un ou plusieurs objets Zend_Session_Namespace.
        </para>

        <para>
            Zend_Session_Namespace est une classe qui guide ses données vers $_SESSION. La classe s'appelle
            Zend_Session_Namespace car elle crée des espaces de noms au sein de $_SESSION, autorisant
            plusieurs composants ou objets à stocker des valeurs sans se marcher dessus. Nous allons voir
            dans l'exemple qui suit comment créer un simple compteur de session qui commence à 1000
            et se remet à zéro après 1999.
        </para>

        <programlisting language="php"><![CDATA[
$mysession = new Zend_Session_Namespace('mysession');

if (!isset($mysession->counter)) {
    $mysession->counter = 1000;
} else {
    $mysession->counter++;
}

if ($mysession->counter > 1999) {
    unset($mysession->counter);
}
]]></programlisting>

        <para>
            Comme vous le remarquez, l'objet de session utilise les méthodes magiques __get, __set,
            __isset, et __unset pour proposer une API intuitive. Les informations stockées dans
            notre exemple le sont en réalité dans $_SESSION['mysession']['counter'].
        </para>
    </sect2>

    <sect2 id="learning.multiuser.sessions.advanced-usage">
        <title>Utilisation avancée de Zend_Session</title>

        <para>
            Si vous voulez utiliser le gestionnaire de sauvegarde des sessions "DbTable", vous
            pouvez simplement ajouter ces options à application.ini:
        </para>

        <programlisting language="php"><![CDATA[
resources.session.saveHandler.class = "Zend_Session_SaveHandler_DbTable"
resources.session.saveHandler.options.name = "session"
resources.session.saveHandler.options.primary.session_id = "session_id"
resources.session.saveHandler.options.primary.save_path = "save_path"
resources.session.saveHandler.options.primary.name = "name"
resources.session.saveHandler.options.primaryAssignment.sessionId = "sessionId"
resources.session.saveHandler.options.primaryAssignment.sessionSavePath = "sessionSavePath"
resources.session.saveHandler.options.primaryAssignment.sessionName = "sessionName"
resources.session.saveHandler.options.modifiedColumn = "modified"
resources.session.saveHandler.options.dataColumn = "session_data"
resources.session.saveHandler.options.lifetimeColumn = "lifetime"
]]></programlisting>
    </sect2>
</sect1>


text:
package pro.foundev.examples.spark_streaming.logging

import play.api.libs.json._

class Log(val message: (String, String)) {

  val messageId:String = message._1.toString
  val messageBody: JsValue = Json.parse(message._2.toString)
  val serviceName = (messageBody \ ("serviceName")).as[String]
  val eventType = (messageBody \ ("type")).as[String]
  val messageText = (messageBody \("text")).as[String]

}


text:
use strict;

#use Dataset;
use Format;
use Output;

my $VERBOSE = 0;
my $DEBUG   = 1;
my $start_l = ""; #formatting help
my $end_l   = "";
my @testArgs; # different kinds of tests we want to do
my $datadir = "data";
my $extraArgs; # stuff that always gets passed to the test program

my $iterCount = 0;
my $NUMPASSES = 4;
my $TIME = 2;
my $ITERATIONS;   #Added by Doug
my $DATADIR;

sub setupOptions {
  my %options = %{shift @_};

  if($options{"time"}) {
    $TIME = $options{"time"};
  }

  if($options{"passes"}) {
    $NUMPASSES = $options{"passes"};
  }

  if($options{"dataDir"}) {
    $DATADIR = $options{"dataDir"};
  }

  # Added by Doug
  if ($options{"iterations"}) {
  	$ITERATIONS = $options{"iterations"};
  }
}

sub runTests {
  debug("Enter runTest in PerfFramework4j\n");
  my $options = shift;
  my @programs;
  my $tests = shift;
  my %datafiles;
  if($#_ >= 0) { # maybe no files/locales
    my $datafiles = shift;
    if($datafiles) {
      %datafiles = %{$datafiles};
    }
  }
  setupOutput($options);
  setupOptions($options);

  my($locale, $iter, $data, $program, $args, $variable);
#
#  Outer loop runs through the locales to test
#
  if (%datafiles) {
    foreach $locale (sort keys %datafiles ) {
      foreach $data (@{ $datafiles{$locale} }) {
	closeTable;
	my $locdata = "";
	if(!($locale eq "")) {
	  $locdata = "Locale: $locale
";
	}
	$locdata .= "Datafile: $data
";
	startTest($locdata);

	if($DATADIR) {
	  compareLoop ($tests, $locale, $DATADIR."/".$data);
	} else {
	  compareLoop ($tests, $locale, $data);
	}
      }
    }
  } else {
    compareLoop($tests);
  }
  closeOutput();
}

sub compareLoop {
  #debug("enter compareLoop\n");

  my $tests = shift;
  #debug("tests $tests");
  #my @tests = @{$tests};
  my %tests = %{$tests};
  #debug("tests $tests");
  my $locale = shift;
  my $datafile = shift;
  my $locAndData = "";
  if($locale) {
    $locAndData .= " -L $locale";
  }

  if($datafile) {
    $locAndData .= " -f $datafile";
  }

  my $args;
  my ($i, $j, $aref);
  foreach $i ( sort keys %tests ) {
    #debug("Test: $i\n");
    $aref = $tests{$i};
    my @timedata;
    my @iterPerPass;
    my @noopers;
    my @noevents;

    my $program;
    my @argsAndTest;
    for $j ( 0 .. $#{$aref} ) {
    # first we calibrate. Use time from somewhere
    # first test is used for calibration
    ##################
    #  ($program, @argsAndTest) = split(/\ /, @{ $tests{$i} }[$j]);
    #  #Modified by Doug
    #   my $commandLine;
    #  if ($ITERATIONS) {
    #  	$commandLine = "$program -i $ITERATIONS -p $NUMPASSES $locAndData @argsAndTest";
    #  } else {
    #  	$commandLine = "$program -t $TIME -p $NUMPASSES $locAndData @argsAndTest";
    # 	}
    ######################
    ######################
    my $custArgs;
    my $testCommand = @{ $tests{$i} }[$j];
      if ($testCommand =~/--/) {
      	$custArgs = $& . $';	#The matched part and the right part
      	$testCommand = $`;		#The left part for furthur processing
      } else { $custArgs = ''; }
      ($program, @argsAndTest) = split(/\ /, $testCommand);
      my $commandLine;
      if ($ITERATIONS) {
      	$commandLine = "$program @argsAndTest -i $ITERATIONS -p $NUMPASSES $locAndData $custArgs";
      } else {
      	$commandLine = "$program @argsAndTest -t $TIME -p $NUMPASSES $locAndData $custArgs";
    	}
    #debug("custArgs:$custArgs\n");
    ####################

      my @res = measure1($commandLine);
      store("$i, $program @argsAndTest", @res);

      push(@iterPerPass, shift(@res));
      push(@noopers, shift(@res));
      my @data = @{ shift(@res) };
      if($#res >= 0) {
	push(@noevents, shift(@res));
      }

      shift(@data) if (@data > 1); # discard first run

      #debug("data is @data\n");
      my $ds = Dataset->new(@data);

      push(@timedata, $ds);
    }

    outputRow($i, \@iterPerPass, \@noopers, \@timedata, \@noevents);
  }

}

#---------------------------------------------------------------------
# Measure a given test method with a give test pattern using the
# global run parameters.
#
# @param the method to run
# @param the pattern defining characters to test
# @param if >0 then the number of iterations per pass.  If <0 then
#        (negative of) the number of seconds per pass.
#
# @return array of:
#         [0] iterations per pass
#         [1] events per iteration
#         [2..] ms reported for each pass, in order
#
sub measure1 {
    # run passes
    my @t = callProg(shift); #"$program $args $argsAndTest");
    my @ms = ();
    my @b; # scratch
    for my $a (@t) {
        # $a->[0]: method name, corresponds to $method
        # $a->[1]: 'begin' data, == $iterCount
        # $a->[2]: 'end' data, of the form <ms> <eventsPerIter>
        # $a->[3...]: gc messages from JVM during pass
        @b = split(/\s+/, $a->[2]);
        #push(@ms, $b[0]);
        push(@ms, shift(@b));
    }
    my $iterCount = shift(@b);
    my $operationsPerIter = shift(@b);
    my $eventsPerIter;
    if($#b >= 0) {
      $eventsPerIter = shift(@b);
    }

#    out("Iterations per pass: $iterCount
\n");
#    out("Events per iteration: $eventsPerIter
\n");
#    debug("Iterations per pass: $iterCount
\n");
#    if($eventsPerIter) {
#      debug("Events per iteration: $eventsPerIter
\n");
#    }

    my @ms_str = @ms;
    $ms_str[0] .= " (discarded)" if (@ms_str > 1);
#    out("Raw times (ms/pass): ", join(", ", @ms_str), "
\n");
    debug("Raw times (ms/pass): ", join(", ", @ms_str), "
\n");
    if($eventsPerIter) {
      ($iterCount, $operationsPerIter, \@ms, $eventsPerIter);
    } else {
      ($iterCount, $operationsPerIter, \@ms);
    }
}

#---------------------------------------------------------------------
# Measure a given test method with a give test pattern using the
# global run parameters.
#
# @param the method to run
# @param the pattern defining characters to test
# @param if >0 then the number of iterations per pass.  If <0 then
#        (negative of) the number of seconds per pass.
#
# @return a Dataset object, scaled by iterations per pass and
#         events per iteration, to give time per event
#
sub measure2 {
    my @res = measure1(@_);
    my $iterPerPass = shift(@res);
    my $operationsPerIter = shift(@res);
    my @data = @{ shift(@res) };
    my $eventsPerIter = shift(@res);

    shift(@data) if (@data > 1); # discard first run

    my $ds = Dataset->new(@data);
    #$ds->setScale(1.0e-3 / ($iterPerPass * $operationsPerIter));
    ($ds, $iterPerPass, $operationsPerIter, $eventsPerIter);
}

#---------------------------------------------------------------------
# Invoke program and capture results, passing it the given parameters.
#
# @param the method to run
# @param the number of iterations, or if negative, the duration
#        in seconds.  If more than on pass is desired, pass in
#        a string, e.g., "100 100 100".
# @param the pattern defining characters to test
#
# @return an array of results.  Each result is an array REF
#         describing one pass.  The array REF contains:
#         ->[0]: The method name as reported
#         ->[1]: The params on the '= <meth> begin ...' line
#         ->[2]: The params on the '= <meth> end ...' line
#         ->[3..]: GC messages from the JVM, if any
#
sub callProg {
    my $cmd = shift;
    #my $pat = shift;
    #my $n = shift;

    #my $cmd = "java -cp c:\\dev\\myicu4j\\classes $TESTCLASS $method $n $pat";
    debug( "[$cmd]\n"); # for debugging
    open(PIPE, "$cmd|") or die "Can't run \"$cmd\"";
    my @out;
    while (<PIPE>) {
        push(@out, $_);
    }
    close(PIPE) or die "Program failed: \"$cmd\"";

    @out = grep(!/^\#/, @out);  # filter out comments

    #debug( "[", join("\n", @out), "]\n");

    my @results;
    my $method = '';
    my $data = [];
    foreach (@out) {
        next unless (/\S/);

        if (/^=\s*(\w+)\s*(\w+)\s*(.*)/) {
            my ($m, $state, $d) = ($1, $2, $3);
            #debug ("$_ => [[$m $state !!!$d!!! $data ]]\n");
            if ($state eq 'begin') {
                die "$method was begun but not finished" if ($method);
                $method = $m;
                push(@$data, $d);
                push(@$data, ''); # placeholder for end data
            } elsif ($state eq 'end') {
                if ($m ne $method) {
                    die "$method end does not match: $_";
                }
                $data->[1] = $d; # insert end data at [1]
                #debug( "#$method:", join(";",@$data), "\n");
                unshift(@$data, $method); # add method to start
                push(@results, $data);
                $method = '';
                $data = [];
            } else {
                die "Can't parse: $_";
            }
        }

        elsif (/^\[/) {
            if ($method) {
                push(@$data, $_);
            } else {
                # ignore extraneous GC notices
            }
        }

        else {
            die "Can't parse: $_";
        }
    }

    die "$method was begun but not finished" if ($method);

    @results;
}

sub debug  {
  my $message;
  if($DEBUG != 0) {
    foreach $message (@_) {
      print STDERR "$message";
    }
  }
}

sub measure1Alan {
  #Added here, was global
  my $CALIBRATE = 2; # duration in seconds for initial calibration

    my $method = shift;
    my $pat = shift;
    my $iterCount = shift; # actually might be -seconds/pass

    out("
Measuring $method using $pat, ");
    if ($iterCount > 0) {
        out("$iterCount iterations/pass, $NUMPASSES passes
\n");
    } else {
        out(-$iterCount, " seconds/pass, $NUMPASSES passes
\n");
    }

    # is $iterCount actually -seconds?
    if ($iterCount < 0) {

        # calibrate: estimate ms/iteration
        print "Calibrating...";
        my @t = callJava($method, $pat, -$CALIBRATE);
        print "done.\n";

        my @data = split(/\s+/, $t[0]->[2]);
        my $timePerIter = 1.0e-3 * $data[0] / $data[2];

        # determine iterations/pass
        $iterCount = int(-$iterCount / $timePerIter + 0.5);

        out("
Calibration pass ($CALIBRATE sec): ");
        out("$data[0] ms, ");
        out("$data[2] iterations = ");
        out(formatSeconds(4, $timePerIter), "/iteration
\n");
    }

    # run passes
    print "Measuring $iterCount iterations x $NUMPASSES passes...";
    my @t = callJava($method, $pat, "$iterCount " x $NUMPASSES);
    print "done.\n";
    my @ms = ();
    my @b; # scratch
    for my $a (@t) {
        # $a->[0]: method name, corresponds to $method
        # $a->[1]: 'begin' data, == $iterCount
        # $a->[2]: 'end' data, of the form <ms> <eventsPerIter>
        # $a->[3...]: gc messages from JVM during pass
        @b = split(/\s+/, $a->[2]);
        push(@ms, $b[0]);
    }
    my $eventsPerIter = $b[1];

    out("Iterations per pass: $iterCount
\n");
    out("Events per iteration: $eventsPerIter
\n");

    my @ms_str = @ms;
    $ms_str[0] .= " (discarded)" if (@ms_str > 1);
    out("Raw times (ms/pass): ", join(", ", @ms_str), "
\n");

    ($iterCount, $eventsPerIter, @ms);
}

1;

#eof


text:
package com.bchetty.series.iterators;

import com.bchetty.timeseries.iterators.WeeklyIterator;
import com.bchetty.timeseries.TimeSeries;
import com.bchetty.timeseries.TimeSeries.Weekly;
import com.bchetty.timeseries.utils.enums.Weekday;
import java.util.ArrayList;
import java.util.List;
import org.joda.time.DateTime;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;

/**
 *
 * @author b.chetty
 */
public class WeeklyIteratorTest {
    public WeeklyIteratorTest() {}

    @BeforeClass
    public static void setUpClass() {}

    @AfterClass
    public static void tearDownClass() {}

    @Before
    public void setUp() {}

    @After
    public void tearDown() {}

    /**
     * Test of hasNext method, of class WeeklyIterator.
     */
    @Test
    public void testWeekly1() {
        DateTime startOfThisWeek = DateTime.now().withDayOfWeek(Weekday.MONDAY.getWeekday());
        System.out.println("startOfThisWeek : " + startOfThisWeek);
        DateTime twoWeeksLater = startOfThisWeek.plusWeeks(2);
        System.out.println("Two Weeks After startOfThisWeek : " + twoWeeksLater);
        TimeSeries timeSeries = new TimeSeries(startOfThisWeek.toDate(), twoWeeksLater.toDate());
        WeeklyIterator weekdayIter = new WeeklyIterator(timeSeries);
        assertTrue(weekdayIter.hasNext());
    }

    /**
     * Test Weekly member of TimeSeries
     */
    @Test
    public void testWeekly2() {
        DateTime startOfThisWeek = DateTime.now().withDayOfWeek(Weekday.MONDAY.getWeekday());
        System.out.println("startOfThisWeek : " + startOfThisWeek);
        DateTime twoWeeksLater = startOfThisWeek.plusWeeks(2);
        System.out.println("Two Weeks After startOfThisWeek : " + twoWeeksLater);
        TimeSeries timeSeries = new TimeSeries(startOfThisWeek.toDate(), twoWeeksLater.toDate());
        assertTrue(timeSeries.getWeekly() != null);
        assertTrue(timeSeries.getWeekly().getWeekdays() != null && !timeSeries.getWeekly().getWeekdays().isEmpty());
        assertTrue(timeSeries.getWeekly().getWeekdays().get(0).getWeekday() == Weekday.MONDAY.getWeekday());
    }

    /**
     * Test of next method, of class WeeklyIterator.
     */
    @Test
    public void testWeekly3() {
        DateTime febFour2015 = new DateTime(2015,2,4,0,0);
        System.out.println("febFour2015 : " + febFour2015);
        DateTime febFifteen2015 = new DateTime(2015,2,15,0,0);
        System.out.println("febFifteen2015 : " + febFifteen2015);

        TimeSeries timeSeries = new TimeSeries(febFour2015.toDate(), febFifteen2015.toDate());
        Weekly weekly = new Weekly();
        List<Weekday> weekdays = new ArrayList<Weekday>();
        weekdays.add(Weekday.MONDAY);
        weekdays.add(Weekday.THURSDAY);
        weekly.setWeekdays(weekdays);
        timeSeries.setWeekly(weekly);

        WeeklyIterator weeklyIter = new WeeklyIterator(timeSeries);
        DateTime dateTime1 = new DateTime(weeklyIter.next());
        System.out.println("dateTime1 : " + dateTime1);
        assertTrue(dateTime1.getDayOfWeek() == Weekday.MONDAY.getWeekday());
        assertTrue(dateTime1.getDayOfMonth() == 9);

        DateTime dateTime2 = new DateTime(weeklyIter.next());
        System.out.println("dateTime2 : " + dateTime2);
        assertTrue(dateTime2.getDayOfWeek() == Weekday.THURSDAY.getWeekday());
        assertTrue(dateTime2.getDayOfMonth() == 5);

        DateTime dateTime3 = new DateTime(weeklyIter.next());
        System.out.println("dateTime3 : " + dateTime3);
        assertTrue(dateTime3.getDayOfWeek() == Weekday.THURSDAY.getWeekday());
        assertTrue(dateTime3.getDayOfMonth() == 12);
    }
}


text:
from unittest import TestCase, TestSuite
import xqpy

import math
import tempfile

try:
    unicode
except NameError:
    unicode = str

class TestImplementation(TestCase):
    def setUp(self):
        self.impl = self.implC()
    def tearDown(self):
        del self.impl
    def test_example(self):
        q = self.impl.prepare('./parent/child/text()')
        c = q.create_context()
        d = self.impl.parse_document('<parent><child>1</child><child>2</child></parent>')
        c.set_context_item(d)
        s = q.execute(context=c)
        self.assertEqual(list(s.values()), ['1', '2'])
    def test_file(self):
        if self.implname == 'Zorba':
            self.skipTest('Does not work with Zorba')
        with tempfile.TemporaryFile() as f:
            f.write('1 to 10'.encode('utf8'))
            f.flush()
            f.seek(0)
            q = self.impl.prepare_file(f)
            s = q.execute()
            self.assertEqual(list(s.values()), list(range(1, 11)))
    def test_document_file(self):
        if self.implname == 'Zorba':
            self.skipTest('Does not work with Zorba')
        with tempfile.TemporaryFile() as f:
            f.write('value'.encode('utf8'))
            f.flush()
            f.seek(0)
            s = self.impl.parse_document_file(f)
            # Crash on node_name, XQilla bug?
            #self.assertEqual(tuple(s.values()), ('value',))
    def test_document(self):
        if self.implname == 'Zorba':
            self.skipTest('Does not work with Zorba')
        s = self.impl.parse_document('value')
        # Crash on node_name, XQilla bug?
        #self.assertEqual(tuple(s.values()), ('value',))
    def test_expression(self):
        q = self.impl.prepare('''
        declare variable $test external;
        $test
        ''')
        c = q.create_context()
        c.set_variable('test', self.impl.create_singleton_sequence(5))
        # Bug?
        #print('set var')
        #self.assertEqual(tuple(c.get_variable('test').values()), (5,))
        #print('get var')
        s = q.execute(context=c)
        self.assertEqual(tuple(s.values()), (5, ))

class TestStaticContext(TestCase):
    def setUp(self):
        self.impl = self.implC()
        self.context = self.impl.create_context()
    def tearDown(self):
        del self.context
        del self.impl

    def test_base_uri(self):
        if self.implname == 'Zorba':
            baseuri = 'file:///'
        else:
            baseuri = ''
        self.assertEqual(baseuri, self.context.get_base_uri())
        self.context.set_base_uri('myuri:')
        self.assertEqual('myuri:', self.context.get_base_uri())
    def test_child(self):
        self.context.set_base_uri('myuri:')
        child = self.context.create_child_context()
        if self.implname != 'Zorba':
            # Zorba does not like this?
            self.assertEqual('myuri:', child.get_base_uri())
            child.set_base_uri('myuri2:')
            self.assertNotEqual('myuri2:', self.context.get_base_uri())
    def test_ns(self):
        self.context.declare_ns('pref:', 'http://test.com/')
        with self.assertRaises(xqpy.XQueryStaticError):
            self.assertEqual(None, self.context.get_ns_by_prefix('unknown:'))
        self.assertEqual('http://test.com/', self.context.get_ns_by_prefix('pref:'))
        self.assertEqual('', self.context.get_default_element_and_type_ns())
        self.context.set_default_element_and_type_ns('http://other.com/')
        self.assertEqual('http://other.com/', self.context.get_default_element_and_type_ns())
    def test_modes(self):
        tests = (
            ('xpath_compatib_mode', (xqpy.XPathMode.xpath1_0, xqpy.XPathMode.xpath2_0)),
            ('construction_mode', (xqpy.ConstructionMode.preserve, xqpy.ConstructionMode.strip)),
            ('ordering_mode', (xqpy.OrderingMode.ordered, xqpy.OrderingMode.unordered)),
            ('default_order_empty_sequences', (xqpy.OrderEmptyMode.empty_greatest, xqpy.OrderEmptyMode.empty_least)),
            ('boundary_space_policy', (xqpy.BoundarySpaceMode.preserve, xqpy.BoundarySpaceMode.strip)),
            ('copy_ns_mode',
                ((xqpy.PreserveMode.preserve, xqpy.InheritMode.inherit),
                (xqpy.PreserveMode.no_preserve, xqpy.InheritMode.inherit))),
            )
        for (fname, vals) in tests:
            for val in vals:
                if type(val) is not tuple:
                    val = (val,)
                getattr(self.context, 'set_'+fname)(*val)
                res = getattr(self.context, 'get_'+fname)()
                if type(res) is not tuple:
                    res = (res, )
                self.assertEqual(val, res)
class TestSequence(TestCase):
    def setUp(self):
        self.impl = self.implC()
    def tearDown(self):
        del self.impl
    def test_empty(self):
        s = self.impl.create_empty_sequence()
        self.assertEqual(list(s), list())
    def test_string(self):
        if self.implname == 'Zorba':
            self.skipTest('Does not work with Zorba')
        tests = (
            ("ab", "cd"),
            ("1", "dzadzq", "DZQdzq"),
            ("",),
        )
        for vals in tests:
            s = self.impl.create_string_sequence(vals)
            self.assertEqual(tuple(s.values()), vals)
            s = self.impl.create_string_sequence(vals)
            self.assertEqual(tuple(s), tuple((xqpy.String(v) for v in vals)))
    #def test_double(self):
    #    tests = (
    #        (1, 1.5),
    #        (32.5,),
    #    )
    #    for vals in tests:
    #        s = self.impl.create_double_sequence(vals)
    #        self.assertEqual(list(s.values()), list(vals))
    #        s = self.impl.create_double_sequence(vals)
    #        for d, v in zip(s, vals):
    #            self.assertEqual(d, xqpy.Double(v))
    def test_singleton(self):
        tests = [
            (3, xqpy.Decimal(3)),
        ]
        if self.implname != 'Zorba':
            # ??? not sure why they are not working
            tests.extend((
                (3.1, xqpy.Double(3.1)),
                ("test", xqpy.String("test")),
                (True, xqpy.Boolean(True)),
                (False, xqpy.Boolean(False)),
            ))
        for (pyval, xval) in tests:
            s = self.impl.create_singleton_sequence(pyval)
            self.assertEqual(list(s.values()), [pyval])
            s = self.impl.create_singleton_sequence(xval)
            self.assertEqual(list(s.values()), [pyval])
            s = self.impl.create_singleton_sequence(pyval)
            self.assertEqual(list(s), [xval])
            s = self.impl.create_singleton_sequence(pyval)
            s.__next__()
            self.assertEqual(s.string_value(), unicode(xval))
            self.assertEqual(s.type(), type(xval))
            if type(xval) is xqpy.Double or type(xval) is xqpy.Float:
                self.assertEqual(s.double_value(), pyval)
            else:
                self.assertTrue(math.isnan(s.double_value()) or s.double_value() == float(pyval))
            with self.assertRaises(StopIteration):
                s.__next__()
def implementations():
    imps = []
    if hasattr(xqpy, 'XQillaImplementation'):
        imps.append(('XQilla', xqpy.XQillaImplementation))
    if hasattr(xqpy, 'ZorbaImplementation'):
        imps.append(('Zorba', xqpy.ZorbaImplementation))
    return imps

test_cases = (TestStaticContext, TestImplementation, TestSequence)

def load_tests(loader, tests, pattern):
    suite = TestSuite()
    for (name, impl) in implementations():
        for test_class in test_cases:
            new_class = type(name + test_class.__name__, (test_class,), {})
            tests = loader.loadTestsFromTestCase(new_class)
            for test in tests:
                test.implC = impl
                test.implname = name
                suite.addTest(test)
    return suite

if __name__ == '__main__':
    unittest.main()


text:
DS2502::DS2502(uint8_t ID1, uint8_t ID2, uint8_t ID3, uint8_t ID4, uint8_t ID5, uint8_t ID6, uint8_t ID7) : OneWireItem(ID1, ID2, ID3, ID4, ID5, ID6, ID7)
{
    static_assert(MEM_SIZE < 256, "Implementation does not cover the whole address-space");

    clearMemory();
    clearStatus();

    if ((ID1 == 0x11) || (ID1 == 0x91))
    {
        // when set to DS2501, the upper two memory pages are not accessible, always read 0xFF
        for (uint8_t page = 2; page < PAGE_COUNT; ++page)
        {
            setPageUsed(page);
            setPageProtection(page);
            sizeof_memory = 64;
        }
    }
    else
    {
        sizeof_memory = 128;    // must be DS2502 then
    }
}

void DS2502::duty(OneWireHub * const hub)
{
    uint8_t  reg_TA[2], cmd, data, crc = 0; // Target address, redirected address, command, data, crc

    if (hub->recv(&cmd))  return;
    crc = crc8(&cmd,1,crc);

    if (hub->recv(reg_TA,2))  return;
    crc = crc8(reg_TA,2,crc);

    if (reg_TA[1] != 0) return; // upper byte of target adress should not contain any data

    switch (cmd)
    {
        case 0xF0:      // READ MEMORY

            if (hub->send(&crc))        break;

            crc = 0; // reInit CRC and send data
            for (uint8_t i = reg_TA[0]; i < sizeof_memory; ++i)
            {
                const uint8_t reg_RA = translateRedirection(i);
                if (hub->send(&memory[reg_RA])) return;
                crc = crc8(&memory[reg_RA],1,crc);
            }
            hub->send(&crc);
            break; // datasheet says we should return all 1s, send(255), till reset, nothing to do here, 1s are passive

        case 0xC3:      // READ DATA (like 0xF0, but repeatedly till the end of page with following CRC)

            if (hub->send(&crc)) break;

            while (reg_TA[0] < sizeof_memory)
            {
                crc = 0; // reInit CRC and send data
                const uint8_t reg_EA = (reg_TA[0] & ~PAGE_MASK) + PAGE_SIZE; // End Address
                for (uint8_t i = reg_TA[0]; i < reg_EA; ++i)
                {
                    const uint8_t reg_RA = translateRedirection(i);
                    if (hub->send(&memory[reg_RA])) return;
                    crc = crc8(&memory[reg_RA], 1, crc);
                }

                if (hub->send(&crc)) break;
                reg_TA[0] = reg_EA;
            }
            break; // datasheet says we should return all 1s, send(255), till reset, nothing to do here, 1s are passive

        case 0xAA:      // READ STATUS // TODO: nearly same code as 0xF0, but with status[] instead of memory[]

            if (hub->send(&crc)) break;

            crc = 0; // reInit CRC and send data
            for (uint8_t i = reg_TA[0]; i < STATUS_SIZE; ++i)
            {
                if (hub->send(&status[i])) return;
                crc = crc8(&status[i],1,crc);
            }
            hub->send(&crc);
            break; // datasheet says we should return all 1s, send(255), till reset, nothing to do here, 1s are passive

        case 0x0F:      // WRITE MEMORY

            while (reg_TA[0] < sizeof_memory)
            {
                if (hub->recv(&data))       break;
                crc = crc8(&data,1,crc);

                if (hub->send(&crc))        break;

                const uint8_t reg_RA = translateRedirection(reg_TA[0]);

                if (getPageProtection(reg_TA[0]))
                {
                    const uint8_t mem_zero = 0x00; // send dummy data
                    if (hub->send(&mem_zero)) break;
                }
                else
                {
                    memory[reg_RA] &= data; // EPROM-Mode
                    setPageUsed(reg_RA);
                    if (hub->send(&memory[reg_RA])) break;
                }
                crc = ++reg_TA[0];
            }
            break;

        case 0x55:      // WRITE STATUS

            while (reg_TA[0] < STATUS_SIZE)
            {
                if (hub->recv(&data))       break;
                crc = crc8(&data,1,crc);

                if (hub->send(&crc))        break;

                data = writeStatus(reg_TA[0], data);

                if (hub->send(&data)) break;

                crc = ++reg_TA[0];
            }
            break;

        default:

            hub->raiseSlaveError(cmd);
    }
}

uint8_t DS2502::translateRedirection(const uint8_t source_address) const
{
    const uint8_t  source_page    = static_cast<uint8_t >(source_address >> 5);
    const uint8_t  destin_page    = getPageRedirection(source_page);
    if (destin_page == 0x00)        return source_address;
    const uint8_t destin_address  = (source_address & PAGE_MASK) | (destin_page << 5);
    return destin_address;
}

void DS2502::clearMemory(void)
{
    memset(memory, static_cast<uint8_t>(0xFF), MEM_SIZE);
}

void DS2502::clearStatus(void)
{
    memset(status, static_cast<uint8_t>(0xFF), STATUS_SIZE);
    status[STATUS_FACTORYP] = 0x00; // last byte should be always zero
}

bool DS2502::writeMemory(const uint8_t* const source, const uint8_t length, const uint8_t position)
{
    if (position >= MEM_SIZE) return false;
    const uint16_t _length = (position + length >= MEM_SIZE) ? (MEM_SIZE - position) : length;
    memcpy(&memory[position],source,_length);

    const uint8_t page_start = static_cast<uint8_t>(position >> 5);
    const uint8_t page_stop  = static_cast<uint8_t>((position + _length) >> 5);
    for (uint8_t page = page_start; page <= page_stop; page++) setPageUsed(page);

    return (_length==length);
}

bool DS2502::readMemory(uint8_t* const destination, const uint8_t length, const uint8_t position) const
{
    if (position >= MEM_SIZE) return false;
    const uint16_t _length = (position + length >= MEM_SIZE) ? (MEM_SIZE - position) : length;
    memcpy(destination,&memory[position],_length);
    return (_length==length);
}

uint8_t DS2502::writeStatus(const uint8_t address, const uint8_t value)
{
    if (address < STATUS_UNDEF_B1)  status[address] &= value; // writing is allowed only here
    return status[address];
}

uint8_t DS2502::readStatus(const uint8_t address) const
{
    if (address >= STATUS_SIZE)     return 0xFF;
    return status[address];
}

void DS2502::setPageProtection(const uint8_t page)
{
    if (page < PAGE_COUNT)          status[STATUS_WP_PAGES] &= ~(uint8_t(1<<page));
}

bool DS2502::getPageProtection(const uint8_t page) const
{
    if (page >= PAGE_COUNT) return true;
    return ((status[STATUS_WP_PAGES] & uint8_t(1<<page)) == 0);
}

void DS2502::setPageUsed(const uint8_t page)
{
    if (page < PAGE_COUNT)  status[STATUS_WP_PAGES] &= ~(uint8_t(1<<(page+4)));
}

bool DS2502::getPageUsed(const uint8_t page) const
{
    if (page >= PAGE_COUNT) return true;
    return ((status[STATUS_WP_PAGES] & uint8_t(1<<(page+4))) == 0);
}

bool DS2502::setPageRedirection(const uint8_t page_source, const uint8_t page_destin)
{
    if (page_source >= PAGE_COUNT)  return false; // really available
    if (page_destin >= PAGE_COUNT)  return false; // virtual mem of the device

    status[page_source + STATUS_PG_REDIR] = (page_destin == page_source) ? uint8_t(0xFF) : ~page_destin; // datasheet dictates this, so no page can be redirected to page 0
    return true;
}

uint8_t DS2502::getPageRedirection(const uint8_t page) const
{
    if (page >= PAGE_COUNT) return 0x00;
    return ~(status[page + STATUS_PG_REDIR]); // TODO: maybe invert this in ReadStatus and safe some Operations? Redirection is critical and often done
}


text:
var crypto = require('crypto'),
	_ = require('underscore');
var SSHPacket = require('./ssh-packet'),
	SSHKex = require('./ssh-kex');

var state = {
	AUTHENTICATION_BEGIN: 'AUTHENTICATION_BEGIN',
};

var MESSAGE_NUMBER = {
	SSH_MSG_USERAUTH_REQUEST: 50, 			/* RFC 4252 SSH Authentication Protocol Section 6 */
	SSH_MSG_USERAUTH_FAILURE: 51,			/* RFC 4252 SSH Authentication Protocol Section 6 */
	SSH_MSG_USERAUTH_SUCCESS: 52,			/* RFC 4252 SSH Authentication Protocol Section 6 */
	SSH_MSG_USERAUTH_BANNER: 53,			/* RFC 4252 SSH Authentication Protocol Section 6 */
	SSH_MSG_USERAUTH_PK_OK: 60,				/* RFC 4252 SSH Authentication Protocol Section 7 */
	SSH_MSG_USERAUTH_PASSWD_CHANGEREQ: 60	/* RFC 4252 SSH Authentication Protocol Section 8 */
};

var AVAILABLE_METHODS = [/*'publickey', 'password'*/];
var _BANNER = null;

function SSHUserAuth() {
	this.userAuthenticated = false;

	this._didISendBanner = false;

	this._userinfo = null;
	this._username = this._servicename = this._method = null;
	this._pk_algorithm_name = this._pk_blob = null;
}

exports.SSHUserAuth = SSHUserAuth;
exports.setBanner = setBanner;
exports.setAuthenticationMethod = setAuthenticationMethod;

require('util').inherits(SSHUserAuth, require('events').EventEmitter);

SSHUserAuth.prototype.getUserInfo = function () {
	return {
		userinfo: this._userinfo,
		sshuser: {
			username: this._username,
		}
	};
};

SSHUserAuth.prototype.authenticate = function (packet, cb) {
	var payload = packet.readBinaryPacket();
	if(packet.disconnect_msg) return;
	if(!payload) return;
	var msgno = payload.readUInt8(0),
		payload = payload.slice(1, payload.length);

	if(!this.userAuthenticated) {
		if(!this._didISendBanner && _BANNER) {
			cb(null, packet.createBinaryPacket(MESSAGE_NUMBER.SSH_MSG_USERAUTH_BANNER, _BANNER));
			this._didISendBanner = true;
		}

		this._verifyAuthenticationRequest(payload, _.bind(function (err, msgno, output) {
			if(Buffer.isBuffer(output)) {
				output = packet.createBinaryPacket(msgno, output);
				return cb(null, output);
			} else if (output == -1) { /* unintended error in authentication */
				var list = SSHPacket.createNameList(['none']);
					partial_success = new Buffer(1);
				partial_success.writeUInt8(0, 0);
				output = Buffer.concat([list, partial_success], list.length + 1);
				output = packet.createBinaryPacket(MESSAGE_NUMBER.SSH_MSG_USERAUTH_FAILURE, output);

				return cb(null, output);
			} else if(output === undefined) { /* success */
				output = packet.createBinaryPacket(MESSAGE_NUMBER.SSH_MSG_USERAUTH_SUCCESS, new Buffer(0));
				this.userAuthenticated = true;
				return cb(null, output);
			}
		}, this));
	} else
		throw new Error('the user has already authenticated');
};

SSHUserAuth.prototype._verifyAuthenticationRequest = function (payload, cb) {
	var user, service, method;
	user = SSHPacket.readString(payload)
	payload = payload.slice(user.offset, payload.length);
	user = user.string.toString('utf8');
	service = SSHPacket.readString(payload)
	payload = payload.slice(service.offset, payload.length);
	service = service.string.toString('ascii');
	method = SSHPacket.readString(payload);
	payload = payload.slice(method.offset, payload.length);
	method = method.string.toString('ascii');

	if(this._username && this._username !== user) return cb(null, -1);
	if(this._servicename && this._servicename !== service) return cb(null, -1);
	if(this._method && this._method !== 'none' && this._method !== method) return cb(null, -1);

	if(method !== 'none' && (AVAILABLE_METHODS.indexOf(method) < 0))
		method = 'none';

	this._username = user;
	this._servicename = service;
	this._method = method;

	switch(method) {
	case 'none':
		var mtd = [];
		if(AVAILABLE_METHODS.length === 0) mtd.push('none');
		else mtd = AVAILABLE_METHODS;

		var partial_success = new Buffer(1),
			output = SSHPacket.createNameList(mtd);
		partial_success.writeUInt8(0, 0);
		output = Buffer.concat([output, partial_success], output.length + 1);
		return cb(null, MESSAGE_NUMBER.SSH_MSG_USERAUTH_FAILURE, output);
		break;
	case 'publickey':
		var has_signature = payload.readUInt8(0);
		payload = payload.slice(1, payload.length)

		var alg_name = SSHPacket.readString(payload);
		payload = payload.slice(alg_name.offset, payload.length);
		alg_name = alg_name.string.toString('ascii');
		var blob = SSHPacket.readString(payload);
		payload = payload.slice(blob.offset, payload.length);
		blob = blob.string;

		if(alg_name !== 'ssh-rsa') return cb(null, -1);

		if(this._pk_algorithm_name && this._pk_algorithm_name !== alg_name) return cb(null, -1);
		if(this._pk_blob && this._pk_blob.toString('hex') !== blob.toString('hex')) return cb(null, -1);

		this._pk_algorithm_name = alg_name;
		this._pk_blob = blob;
		this._pk = SSHKex.verifySSHRSAPublicKey(this._pk_blob);

		if(!has_signature) {
			alg_name = SSHPacket.createString(new Buffer(alg_name, 'ascii'));
			blob = SSHPacket.createString(blob);
			return cb(null, MESSAGE_NUMBER.SSH_MSG_USERAUTH_PK_OK, Buffer.concat([alg_name, blob], alg_name.length + blob.length));
		}

		//TODO: implement below
		var verifyf = this._verifyf(),
			signature = SSHPacket.readString(payload).string;

		verifyf.update(signature);
		if(verifyf.verify(SSH2_to_PEM(this._pk_blob), signature)) {

		} else
			return cb(null, -1);
		break;
	case 'password':
		if(payload.readUInt8(0) === 0) { // not PASSWD_CHANGEREQ
			var password = SSHPacket.readString(payload.slice(1, payload.length)).string.toString('utf8');

			this.emit('authentication', {
				method: 'password',
				username: this._username,
				password: password
			}, {
				success: _.bind(function (userinfo) {
					this._userinfo = userinfo;
					return cb();
				}, this),
				fail: function () {
					var partial_success = new Buffer(1),
						methods = SSHPacket.createNameList(AVAILABLE_METHODS);
					partial_success.writeUInt8(0, 0);
					return cb(null, MESSAGE_NUMBER.SSH_MSG_USERAUTH_FAILURE, Buffer.concat([methods, partial_success], methods.length + 1));
				},
			});
		} else {
		}
		break;
	default: throw new Error('unknown method: ' + method);
	}
};

SSHUserAuth.prototype._verifyf = function () {
	switch(this._pk_algorithm_name) {
	case 'ssh-rsa': return crypto.createVerify('RSA-SHA1');
	}
};

function SSH2_to_PEM(ssh2_formatted) {
	//TODO: implement this
	return ssh_formatted;
}

function setAuthenticationMethod (methods) {
	for(var i=0; i<methods.length; i++) {
		switch(methods[i]) {
		case 'password': AVAILABLE_METHODS.push('password'); break;
		default: throw new Error('unknown authentication method: ' + methods[i]);
		}
	}
}

function setBanner(msg, lang) {
	lang = SSHPacket.createString(new Buffer(lang || 'en', 'utf8'));
	msg = SSHPacket.createString(new Buffer(msg, 'utf8'));
	_BANNER = Buffer.concat([msg, lang], msg.length + lang.length);
}


text:
${nls.copyFeatures.title}

${nls.copyFeatures.createFeatures}

${nls.copyFeatures.createSingleFeature}

${nls.common.cancel}