text:
""" This code implements a ceiling-marker based localization system.
    The core of the code is filling out the marker_locators
    which allow for the specification of the position and orientation
    of the markers on the ceiling of the room """

import rospy
from ar_pose.msg import ARMarkers
from tf.transformations import euler_from_quaternion, rotation_matrix, quaternion_from_matrix, quaternion_from_euler
import numpy as np
from nav_msgs.msg import Odometry
from geometry_msgs.msg import PoseStamped, Pose, Point, Quaternion
from std_msgs.msg import Header
from tf import TransformListener, TransformBroadcaster
from copy import deepcopy
from math import sin, cos, pi, atan2, fabs

ROBOT_NAME = rospy.get_namespace()[1:-1]
ROBOT_NAME = '/' + ROBOT_NAME[0:-3] #get name of robot from namespace (assumes for <robot_name>_ar for namespace of upwards facing camera)

class TransformHelpers:
    """ Some convenience functions for translating between various representions of a robot pose.
        TODO: nothing... you should not have to modify these """

    @staticmethod
    def convert_translation_rotation_to_pose(translation, rotation):
        """ Convert from representation of a pose as translation and rotation (Quaternion) tuples to a geometry_msgs/Pose message """
        return Pose(position=Point(x=translation[0],y=translation[1],z=translation[2]), orientation=Quaternion(x=rotation[0],y=rotation[1],z=rotation[2],w=rotation[3]))

    @staticmethod
    def convert_pose_inverse_transform(pose):
        """ Helper method to invert a transform (this is built into the tf C++ classes, but ommitted from Python) """
        translation = np.zeros((4,1))
        translation[0] = -pose.position.x
        translation[1] = -pose.position.y
        translation[2] = -pose.position.z
        translation[3] = 1.0

        rotation = (pose.orientation.x, pose.orientation.y, pose.orientation.z, pose.orientation.w)
        euler_angle = euler_from_quaternion(rotation)
        rotation = np.transpose(rotation_matrix(euler_angle[2], [0,0,1]))       # the angle is a yaw
        transformed_translation = rotation.dot(translation)

        translation = (transformed_translation[0], transformed_translation[1], transformed_translation[2])
        rotation = quaternion_from_matrix(rotation)
        return (translation, rotation)

    @staticmethod
    def angle_normalize(z):
        """ convenience function to map an angle to the range [-pi,pi] """
        return atan2(sin(z), cos(z))

    @staticmethod
    def angle_diff(a, b):
        """ Calculates the difference between angle a and angle b (both should be in radians)
            the difference is always based on the closest rotation from angle a to angle b
            examples:
                angle_diff(.1,.2) -> -.1
                angle_diff(.1, 2*math.pi - .1) -> .2
                angle_diff(.1, .2+2*math.pi) -> -.1
        """
        a = TransformHelpers.angle_normalize(a)
        b = TransformHelpers.angle_normalize(b)
        d1 = a-b
        d2 = 2*pi - fabs(d1)
        if d1 > 0:
            d2 *= -1.0
        if fabs(d1) < fabs(d2):
            return d1
        else:
            return d2

class MarkerLocator(object):
    def __init__(self, id, position, yaw):
        """ Create a MarkerLocator object
            id: the id of the marker (this is an index based on the file
                specified in ar_pose_multi.launch)
            position: this is a tuple of the x,y position of the marker
            yaw: this is the angle about a normal vector pointed towards
                 the STAR center ceiling
        """
        self.id = id
        self.position = position
        self.yaw = yaw

    def get_camera_position(self, marker):
        """ Outputs the position of the camera in the global coordinates """
        euler_angles = euler_from_quaternion((marker.pose.pose.orientation.x,
                                              marker.pose.pose.orientation.y,
                                              marker.pose.pose.orientation.z,
                                              marker.pose.pose.orientation.w))
        translation = np.array([marker.pose.pose.position.y,
                                -marker.pose.pose.position.x,
                                0,
                                1.0])
        translation_rotated = rotation_matrix(self.yaw-euler_angles[2], [0,0,1]).dot(translation)
        xy_yaw = (translation_rotated[0]+self.position[0],translation_rotated[1]+self.position[1],self.yaw-euler_angles[2])
        return xy_yaw

class MarkerProcessor(object):
    def __init__(self, use_dummy_transform=False):
        print 'init'
        rospy.init_node('star_center_positioning_node')
        if use_dummy_transform:
            self.odom_frame_name = ROBOT_NAME+"_odom_dummy" #identify this odom as ROBOT_NAME's
        else:
            self.odom_frame_name = ROBOT_NAME+"_odom" #identify this odom as ROBOT_NAME's

        self.marker_locators = {}

        self.add_marker_locator(MarkerLocator(0,(-6*12*2.54/100.0,0),0))
        self.add_marker_locator(MarkerLocator(1,(0.0,0.0),pi))
        self.add_marker_locator(MarkerLocator(2,(0.0,10*12*2.54/100.0),0))
        self.add_marker_locator(MarkerLocator(3,(-6*12*2.54/100.0,6*12*2.54/100.0),0))

        self.pose_correction = rospy.get_param('~pose_correction',0.0)

        self.marker_sub = rospy.Subscriber("ar_pose_marker",
                                           ARMarkers,
                                           self.process_markers)
        self.odom_sub = rospy.Subscriber(ROBOT_NAME+"/odom", Odometry, self.process_odom, queue_size=10) #publish and subscribe to the correct robot's topics
        self.star_pose_pub = rospy.Publisher(ROBOT_NAME+"/STAR_pose",PoseStamped,queue_size=10)
        self.continuous_pose = rospy.Publisher(ROBOT_NAME+"/STAR_pose_continuous",PoseStamped,queue_size=10)
        self.tf_listener = TransformListener()
        self.tf_broadcaster = TransformBroadcaster()

    def add_marker_locator(self, marker_locator):
        self.marker_locators[marker_locator.id] = marker_locator

    def process_odom(self, msg):
        p = PoseStamped(header=Header(stamp=rospy.Time(0), frame_id=self.odom_frame_name),
                        pose=msg.pose.pose)
        try:
            STAR_pose = self.tf_listener.transformPose("STAR", p)
            STAR_pose.header.stamp = msg.header.stamp
            self.continuous_pose.publish(STAR_pose)
        except Exception as inst:
            print "error is", inst

    def process_markers(self, msg):
        print 'process markers'
        for marker in msg.markers:
            # do some filtering basd on prior knowledge
            # we know the approximate z coordinate and that all angles but yaw should be close to zero
            euler_angles = euler_from_quaternion((marker.pose.pose.orientation.x,
                                                  marker.pose.pose.orientation.y,
                                                  marker.pose.pose.orientation.z,
                                                  marker.pose.pose.orientation.w))
            angle_diffs = TransformHelpers.angle_diff(euler_angles[0],pi), TransformHelpers.angle_diff(euler_angles[1],0)
            print angle_diffs, marker.pose.pose.position.z
            if (marker.id in self.marker_locators and

                3.2 <= marker.pose.pose.position.z <= 3.6 and
                fabs(angle_diffs[0]) <= .4 and
                fabs(angle_diffs[1]) <= .4):
                print "FOUND IT!"

                locator = self.marker_locators[marker.id]
                xy_yaw = list(locator.get_camera_position(marker))
                xy_yaw[0] += self.pose_correction*cos(xy_yaw[2])
                xy_yaw[1] += self.pose_correction*sin(xy_yaw[2])
                xy_yaw[2] += pi
                orientation_tuple = quaternion_from_euler(0,0,xy_yaw[2])
                pose = Pose(position=Point(x=-xy_yaw[0],y=-xy_yaw[1],z=0),
                            orientation=Quaternion(x=orientation_tuple[0], y=orientation_tuple[1], z=orientation_tuple[2], w=orientation_tuple[3]))
                # TODO: use markers timestamp instead of now() (unfortunately, not populated currently by ar_pose)
                pose_stamped = PoseStamped(header=Header(stamp=rospy.Time.now(),frame_id="STAR"),pose=pose)
                try:
                    offset, quaternion = self.tf_listener.lookupTransform(ROBOT_NAME+"_base_link", ROBOT_NAME+"_base_laser_link", rospy.Time(0)) #listen to TF frames for this robot
                except Exception as inst:
                    print "Error", inst
                    return
                # TODO: use frame timestamp instead of now()
                pose_stamped_corrected = deepcopy(pose_stamped)
                pose_stamped_corrected.pose.position.x -= offset[0]*cos(xy_yaw[2])
                pose_stamped_corrected.pose.position.y -= offset[0]*sin(xy_yaw[2])
                self.star_pose_pub.publish(pose_stamped_corrected)
                self.fix_STAR_to_odom_transform(pose_stamped_corrected)

    def fix_STAR_to_odom_transform(self, msg):
        """ Super tricky code to properly update map to odom transform... do not modify this... Difficulty level infinity. """
        (translation, rotation) = TransformHelpers.convert_pose_inverse_transform(msg.pose)
        p = PoseStamped(pose=TransformHelpers.convert_translation_rotation_to_pose(translation,rotation),header=Header(stamp=rospy.Time(),frame_id=ROBOT_NAME+"_base_link"))
        print 'trying'
        try:
            self.tf_listener.waitForTransform(ROBOT_NAME+"_odom",ROBOT_NAME+"_base_link",rospy.Time(),rospy.Duration(1.0)) #listen to TF frames for this robot
        except Exception as inst:
            print "whoops", inst
            return
        print "got transform"
        self.odom_to_STAR = self.tf_listener.transformPose(ROBOT_NAME+"_odom", p)
        (self.translation, self.rotation) = TransformHelpers.convert_pose_inverse_transform(self.odom_to_STAR.pose) #listen to TF frames for this robot

    def broadcast_last_transform(self):
        """ Make sure that we are always broadcasting the last map to odom transformation.
            This is necessary so things like move_base can work properly. """
        if not(hasattr(self,'translation') and hasattr(self,'rotation')):
            return
        self.tf_broadcaster.sendTransform(self.translation, self.rotation, rospy.get_rostime(), self.odom_frame_name, "STAR") #send position relative to base frame "STAR"

    def run(self):
        r = rospy.Rate(10)
        while not rospy.is_shutdown():
            self.broadcast_last_transform()
            r.sleep()

if __name__ == '__main__':
    nh = MarkerProcessor(use_dummy_transform=True)
    nh.run()


text:
![](https://github.com/deltaluca/www.napephys.com/blob/gh-pages/assets/nape.png?raw=true)

# Where to download

Available on github are the .cx source-code requiring my caxe preprocessor.

From the Nape website (http://napephys.com) are available the the AS3 .swcs, manuals, samples and documentation.

From haxelib, you can also install nape with 'haxelib install nape' or when updating, 'haxelib upgrade'.

# Building from source

The supplied Makefile should work fine under *nix systems, commands will be near identical from windows command line, though mingw is probably easiest approach. Caxe will have to be built also, and compiling swcs requires my flib tool.

redpajama_set_name: RedPajamaGithub


text:
#region Apache License Version 2.0

#endregion Apache License Version 2.0

using System;
using System.Reflection;
using System.Linq.Expressions;
using System.Collections.Generic;
using System.Linq;
using SF.Sys.Reflection;
using SF.Sys.Linq.Expressions;

namespace SF.Sys.Entities.AutoEntityProvider.Internals.QueryFilterProviders
{
	public class PropQueryFilterProvider : IQueryFilterProvider
	{
		class PropQueryFilter<TDataModel, TQueryArgument> : IQueryFilter<TDataModel, TQueryArgument>
		{
			public int Priority => 0;
			Lazy<Func<TQueryArgument, Expression<Func<TDataModel, bool>>>> GetFilter{get;}
			public PropQueryFilter(Lazy<Func<TQueryArgument, Expression<Func<TDataModel, bool>>>> GetFilter)
			{
				this.GetFilter = GetFilter;
			}
			public IQueryable<TDataModel> Filter(IQueryable<TDataModel> Query, IEntityServiceContext ServiceContext, TQueryArgument Arg)
			{
				var cond =  GetFilter.Value(Arg);
				if (cond == null) return Query;
				return Query.Where(cond);
			}
		}

		public IPropertyQueryFilterProvider[] PropertyQueryFilterProviders { get; }
		public PropQueryFilterProvider(IEnumerable<IPropertyQueryFilterProvider> PropertyQueryFilterProviders)
		{
			this.PropertyQueryFilterProviders = PropertyQueryFilterProviders.OrderBy(p=>p.Priority).ToArray();
		}
		static MethodInfo MethodLambda { get; } = typeof(Expression).GetMethods(
			nameof(Expression.Lambda),
			BindingFlags.Public | BindingFlags.Static
			).Single(m =>
			{
				if (!m.IsGenericMethodDefinition)
					return false;
				var ps = m.GetParameters();
				return ps.Length == 2 && ps[0].ParameterType == typeof(Expression) && ps[1].ParameterType == typeof(IEnumerable<ParameterExpression>);
			});
		static MethodInfo MethodAndAlso { get; } = typeof(Expression).GetMethod(nameof(Expression.AndAlso), BindingFlags.Public | BindingFlags.Static, null, new[] { typeof(Expression), typeof(Expression) }, null);
		static Expression<Func<TModel, bool>> CreateLambda<TModel>(
			ParameterExpression argModel,
			Expression[] Exprs
			)
		{
			var es = Exprs.Where(x => x != null).ToArray();
			if (es.Length == 0)
				return null;
			Expression expr;
			if (es.Length == 1)
				expr = es[0];
			else
			{
				Array.Reverse(es);
				expr = es.Aggregate((x, y) => Expression.AndAlso(y, x));
			}
			return Expression.Lambda<Func<TModel,bool>>(
				expr,
				argModel
				);
		}
		public IQueryFilter<TDataModel, TQueryArgument> GetFilter<TDataModel, TQueryArgument>()
		{
			var filters = (
				from prop in typeof(TQueryArgument).AllPublicInstanceProperties()
				let filter=PropertyQueryFilterProviders
						.Select(p => p.GetFilter<TDataModel, TQueryArgument>(prop))
						.Where(f => f != null)
						.FirstOrDefault()
				where filter!=null
				orderby filter.Priority
				select (prop: prop, filter: filter)
				).ToArray();
			if (filters.Length == 0)
				return null;

			return new PropQueryFilter<TDataModel, TQueryArgument>(
				new Lazy<Func<TQueryArgument, Expression<Func<TDataModel, bool>>>>(() =>
				{
					var argQuery = Expression.Parameter(typeof(TQueryArgument));
					var argModel = Expression.Parameter(typeof(TDataModel));
					var conds = filters.Select(p =>
								  Expression.Constant(
									  p.filter,
									  typeof(IPropertyQueryFilter<>).MakeGenericType(p.prop.PropertyType)
									  ).CallMethod(
										  nameof(IPropertyQueryFilter<int>.GetFilterExpression),
										  Expression.Constant(argModel),
										  argQuery.GetMember(p.prop)
									  )
								);
					var body = Expression.Call(
						typeof(PropQueryFilterProvider).GetMethodExt(
							nameof(CreateLambda),
							BindingFlags.Static | BindingFlags.NonPublic,
							new[] {typeof(ParameterExpression), typeof(Expression[]) }
							).MakeGenericMethod(typeof(TDataModel)),
						Expression.Constant(argModel),
						Expression.NewArrayInit(
							typeof(Expression),
							conds
						)
						);
					var getfilter = Expression.Lambda<Func<TQueryArgument, Expression<Func<TDataModel, bool>>>>(
							body,
							argQuery
						).Compile();

					return getfilter;
				})
			);
		}
	}
}


text:
import config from '../config';

const {watch} = config;

if (watch) {
  const script = document.createElement('script');
  script.async = true;
  script.src = '/livereload.js?port=80';
  document.body.appendChild(script);
}


text:
<?php

namespace Home\ParserBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="Football")
 *
 * @ORM\Entity(repositoryClass="Home\ParserBundle\Entity\FootballRepository")
 */

class Football
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="date", type="date")
     */
    private $date;

    /**
     * Set date
     *
     * @param \DateTime $date
//     * @return Post
     */
    public function setDate($date)
    {
        $this->date = $date;

        return $this;
    }

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

    /**
     * @ORM\Column(type="string", length=100)
     */
    protected  $hts;

    /**
     * @ORM\Column(type="string", length=100)
     */
    protected  $ats;

    /**
     * @ORM\ManyToOne(targetEntity="Team", inversedBy="names",cascade={"persist"})
     * @ORM\JoinColumn(name="hometeam", referencedColumnName="id")
     */
    protected $football_h;

    /**
     * @ORM\ManyToOne(targetEntity="Team", inversedBy="names",cascade={"persist"})
     * @ORM\JoinColumn(name="awayteam", referencedColumnName="id")
     */
    protected $football_a;

    public function setAts($ats)
    {
        $this->ats = $ats;
    }

    public function getAts()
    {
        return $this->ats;
    }

    public function setFootballA($football_a)
    {
        $this->football_a = $football_a;
    }

    public function getFootballA()
    {
        return $this->football_a;
    }

    public function setFootballH($football_h)
    {
        $this->football_h = $football_h;
    }

    public function getFootballH()
    {
        return $this->football_h;
    }

    public function setHts($hts)
    {
        $this->hts = $hts;
    }

    public function getHts()
    {
        return $this->hts;
    }

    public function setId($id)
    {
        $this->id = $id;
    }

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

}


text:
@implementation PersonProfileViewController

- (IBAction)doneAction:(id)sender {
}
- (IBAction)uploadAvatarAction:(id)sender {
}
@end


text:
angular.module('app').service('AdService', ['$http', function ($http) {
    this.getAvailableCities = function () {
        return $http.get('/api/getAvailableCities');
    };

    this.getAvailableMaterials = function () {
        return $http.get('/api/getAvailableMaterials');
    };

    this.index = function (selectedCity) {
        return $http({
            url: '/api/index',
            method: "GET",
            params: {city: selectedCity}
        });
    };

    this.getData = function (params) {
        return $http({
            url: '/api/data',
            method: "GET",
            params: params
        });
    }
}]);


text:
module Rebase.Data.Text
(
  module Data.Text,
  module Data.Text.IO,
  module Data.Text.Encoding,
)
where

import Data.Text
import Data.Text.IO
import Data.Text.Encoding


text:
class Tr8n::DailyLanguageMetric < Tr8n::LanguageMetric

  def update_metrics!
    self.user_count = Tr8n::LanguageUser.count(:conditions => ["language_id = ? and created_at >= ? and created_at < ?", language_id, metric_date, metric_date + 1.day])
    self.translator_count = Tr8n::LanguageUser.count(:conditions => ["language_id = ? and created_at >= ? and created_at < ? and translator_id is not null", language_id, metric_date, metric_date + 1.day])
    self.translation_count = Tr8n::Translation.count(:conditions => ["language_id = ? and created_at >= ? and created_at < ?", language_id, metric_date, metric_date + 1.day])

    self.key_count = Tr8n::TranslationKey.count(:conditions => ["created_at >= ? and created_at < ?", metric_date, metric_date + 1.day])
    self.locked_key_count = Tr8n::TranslationKey.count("distinct tr8n_translation_keys.id",
        :conditions => ["tr8n_translation_key_locks.language_id = ? and tr8n_translation_key_locks.locked = ? and tr8n_translation_key_locks.created_at >= ? and tr8n_translation_key_locks.created_at < ?", language_id, true, metric_date, metric_date + 1.day],
        :joins => "join tr8n_translation_key_locks on tr8n_translation_keys.id = tr8n_translation_key_locks.translation_key_id")
    self.translated_key_count = Tr8n::TranslationKey.count("distinct tr8n_translation_keys.id",
        :conditions => ["tr8n_translations.language_id = ? and tr8n_translations.created_at >= ? and tr8n_translations.created_at < ?", language_id, metric_date, metric_date + 1.day],
        :joins => "join tr8n_translations on tr8n_translation_keys.id = tr8n_translations.translation_key_id")

    save
  end

end


text:
describe PDF::Reader do
  let(:cairo_basic)   { pdf_spec_file("cairo-basic")}
  let(:oo3)           { pdf_spec_file("oo3")}
  let(:no_text_spaces) { pdf_spec_file("no_text_spaces")}
  let(:missing_pages_dict) { pdf_spec_file('missing_pages_dict') }

  describe ".open()" do

    it "passes a reader instance to a block" do
      PDF::Reader.open(cairo_basic) do |reader|
        expect(reader.pdf_version).to eql(1.4)
      end
    end
  end

  describe "#pdf_version" do
    it "returns the correct pdf_version" do
      expect(PDF::Reader.new(cairo_basic).pdf_version).to eql(1.4)
    end

    it "returns the correct pdf_version" do
      expect(PDF::Reader.new(no_text_spaces).pdf_version).to eql(1.4)
    end
  end

  describe "#page_count" do
    context "with cairo-basic" do
      it "returns the correct page_count" do
        expect(PDF::Reader.new(cairo_basic).page_count).to eql(2)
      end
    end

    context "with no_text_spaces" do
      it "returns the correct page_count" do
        expect(PDF::Reader.new(no_text_spaces).page_count).to eql(6)
      end
    end

    context "with indirect_page_count" do
      it "returns the correct page_count" do
        expect(PDF::Reader.new(pdf_spec_file("indirect_page_count")).page_count).to eql(1)
      end
    end

    context "when the PDF has no pages" do
      it 'raises MalformedPDFError if pages object is missing' do
        expect {
          PDF::Reader.new(missing_pages_dict).page_count
        }.to raise_error(PDF::Reader::MalformedPDFError)
      end
    end
  end

  describe "#info" do
    it "returns the correct info hash from cairo-basic" do
      info = PDF::Reader.new(cairo_basic).info

      expect(info.size).to eql(2)
      expect(info[:Creator]).to eql("cairo 1.4.6 (http://cairographics.org)")
      expect(info[:Producer]).to eql("cairo 1.4.6 (http://cairographics.org)")
    end

    it "returns the correct info hash from no_text_spaces" do
      info = PDF::Reader.new(no_text_spaces).info

      expect(info.size).to eql(9)
    end

    it "returns the correct info hash from a file with utf-16 encoded info" do
      info = PDF::Reader.new(oo3).info

      expect(info.size).to eql(3)
      expect(info[:Creator]).to  eql "Writer"
      expect(info[:Producer]).to eql "OpenOffice.org 3.2"
      expect(info[:CreationDate]).to eql "D:20101113071546-06'00'"
    end

    it "returns an info hash with strings marked as UTF-8" do
      info = PDF::Reader.new(oo3).info

      expect(info[:Creator].encoding).to      eql Encoding::UTF_8
      expect(info[:Producer].encoding).to     eql Encoding::UTF_8
      expect(info[:CreationDate].encoding).to eql Encoding::UTF_8
    end
  end

  describe "#metadata" do
    it "returns nil metadata from cairo-basic" do
      expect(PDF::Reader.new(cairo_basic).metadata).to be_nil
    end

    it "returns the correct metadata from no_text_spaces" do
      metadata = PDF::Reader.new(no_text_spaces).metadata

      expect(metadata).to be_a_kind_of(String)
      expect(metadata).to include("<x:xmpmeta")
    end

    it "returns the metadata string marked as UTF-8" do
      metadata = PDF::Reader.new(no_text_spaces).metadata

      expect(metadata.encoding).to eql Encoding::UTF_8
    end

    it "raises an exception if trailer Root is not a dict" do
      filename = pdf_spec_file("trailer_root_is_not_a_dict")
      pdf = PDF::Reader.new(filename)
      expect {
        pdf.metadata
      }.to raise_error(PDF::Reader::MalformedPDFError)
    end
  end

  describe "#pages" do
    it "returns an array of pages from cairo-basic" do
      pages = PDF::Reader.new(cairo_basic).pages

      expect(pages).to be_a_kind_of(Array)
      expect(pages.size).to eql(2)
      pages.each do |page|
        expect(page).to be_a_kind_of(PDF::Reader::Page)
      end
    end

    it "returns an array of pages from no_text_spaces" do
      pages = PDF::Reader.new(no_text_spaces).pages

      expect(pages).to be_a_kind_of(Array)
      expect(pages.size).to eql(6)
      pages.each do |page|
        expect(page).to be_a_kind_of(PDF::Reader::Page)
      end
    end

    it "raises aMalformedPDFError when an InvalidPageError is raised internally" do
      reader = PDF::Reader.new(pdf_spec_file("invalid_pages"))
      expect { reader.pages }.to raise_error(PDF::Reader::MalformedPDFError)
    end
  end

  describe "#page" do
    it "returns a single page from cairo-basic" do
      expect(PDF::Reader.new(cairo_basic).page(1)).to be_a_kind_of(PDF::Reader::Page)
    end

    it "returns a single page from no_text_spaces" do
      expect(PDF::Reader.new(no_text_spaces).page(1)).to be_a_kind_of(PDF::Reader::Page)
    end

    it "raises InvalidPageError when an invalid page number is requested" do
      reader = PDF::Reader.new(pdf_spec_file("cairo-basic"))
      expect { reader.page(10) }.to raise_error(PDF::Reader::InvalidPageError)
    end
  end
end


text:
/**
 * This file is part of the CernVM File System.
 */

#include "params.h"

#include <vector>

#include "options.h"
#include "util/string.h"

namespace receiver {

bool GetParamsFromFile(const std::string& repo_name, Params* params) {
  const std::string repo_config_file =
      "/etc/cvmfs/repositories.d/" + repo_name + "/server.conf";

  SimpleOptionsParser parser;
  if (!parser.TryParsePath(repo_config_file)) {
    LogCvmfs(kLogReceiver, kLogSyslogErr,
             "Could not parse repository configuration: %s.",
             repo_config_file.c_str());
    return false;
  }

  if (!parser.GetValue("CVMFS_UPSTREAM_STORAGE",
                       &params->spooler_configuration)) {
    LogCvmfs(kLogReceiver, kLogSyslogErr,
             "Missing parameter %s in repository configuration file.",
             "CVMFS_UPSTREAM_STORAGE");
    return false;
  }

  // Note: if upstream is gateway, we change it to local. This should be made to
  // abort, but it's useful for testing on a single machine
  if (HasPrefix(params->spooler_configuration, "gw", false)) {
    std::vector<std::string> tokens = SplitString(repo_name, '/');
    const std::string rname = tokens.back();
    params->spooler_configuration =
        "local,/srv/cvmfs/" + rname + "/data/txn,/srv/cvmfs/" + rname;
  }

  std::string hash_algorithm_str;
  if (!parser.GetValue("CVMFS_HASH_ALGORITHM", &hash_algorithm_str)) {
    LogCvmfs(kLogReceiver, kLogSyslogErr,
             "Missing parameter %s in repository configuration file.",
             "CVMFS_HASH_ALGORITHM");
    return false;
  }
  params->hash_alg = shash::ParseHashAlgorithm(hash_algorithm_str);

  std::string compression_algorithm_str;
  if (!parser.GetValue("CVMFS_COMPRESSION_ALGORITHM",
                       &compression_algorithm_str)) {
    LogCvmfs(kLogReceiver, kLogSyslogErr,
             "Missing parameter %s in repository configuration file.",
             "CVMFS_COMPRESSION_ALGORITHM");
    return false;
  }
  params->compression_alg =
      zlib::ParseCompressionAlgorithm(compression_algorithm_str);

  /**
   * The receiver does not store files, only catalogs.  We can safely disable
   * this option.
   */
  params->generate_legacy_bulk_chunks = false;

  std::string use_chunking_str;
  if (!parser.GetValue("CVMFS_USE_FILE_CHUNKING", &use_chunking_str)) {
    LogCvmfs(kLogReceiver, kLogSyslogErr,
             "Missing parameter %s in repository configuration file.",
             "CVMFS_USE_FILE_CHUNKING");
    return false;
  }
  if (use_chunking_str == "true") {
    params->use_file_chunking = true;
  } else if (use_chunking_str == "false") {
    params->use_file_chunking = false;
  } else {
    LogCvmfs(kLogReceiver, kLogSyslogErr,
             "Invalid value of repository parameter %s: %s",
             "CVMFS_USE_FILE_CHUNKING", use_chunking_str.c_str());
    return false;
  }

  std::string min_chunk_size_str;
  if (!parser.GetValue("CVMFS_MIN_CHUNK_SIZE", &min_chunk_size_str)) {
    LogCvmfs(kLogReceiver, kLogSyslogErr,
             "Missing parameter %s in repository configuration file.",
             "CVMFS_MIN_CHUNK_SIZE");
    return false;
  }
  params->min_chunk_size = String2Uint64(min_chunk_size_str);

  std::string avg_chunk_size_str;
  if (!parser.GetValue("CVMFS_AVG_CHUNK_SIZE", &avg_chunk_size_str)) {
    LogCvmfs(kLogReceiver, kLogSyslogErr,
             "Missing parameter %s in repository configuration file.",
             "CVMFS_AVG_CHUNK_SIZE");
    return false;
  }
  params->avg_chunk_size = String2Uint64(avg_chunk_size_str);

  std::string max_chunk_size_str;
  if (!parser.GetValue("CVMFS_MAX_CHUNK_SIZE", &max_chunk_size_str)) {
    LogCvmfs(kLogReceiver, kLogSyslogErr,
             "Missing parameter %s in repository configuration file.",
             "CVMFS_MAX_CHUNK_SIZE");
    return false;
  }
  params->max_chunk_size = String2Uint64(max_chunk_size_str);

  std::string use_autocatalogs_str;
  if (!parser.GetValue("CVMFS_AUTOCATALOGS", &use_autocatalogs_str)) {
    LogCvmfs(kLogReceiver, kLogSyslogErr,
             "Missing parameter %s in repository configuration file.",
             "CVMFS_AUTOCATALOGS");
    return false;
  }
  if (use_autocatalogs_str == "true") {
    params->use_autocatalogs = true;
  } else if (use_autocatalogs_str == "false") {
    params->use_autocatalogs = false;
  } else {
    LogCvmfs(kLogReceiver, kLogSyslogErr,
             "Invalid value of repository parameter %s: %s.",
             "CVMFS_AUTOCATALOGS", use_autocatalogs_str.c_str());
    return false;
  }

  std::string max_weight_str;
  if (parser.GetValue("CVMFS_AUTOCATALOGS_MAX_WEIGHT", &max_weight_str)) {
    params->max_weight = String2Uint64(max_weight_str);
  }

  std::string min_weight_str;
  if (parser.GetValue("CVMFS_AUTOCATALOGS_MIN_WEIGHT", &min_weight_str)) {
    params->min_weight = String2Uint64(min_weight_str);
  }

  params->enforce_limits = false;
  std::string enforce_limits_str;
  if (parser.GetValue("CVMFS_ENFORCE_LIMITS", &enforce_limits_str)) {
    if (enforce_limits_str == "true") {
      params->enforce_limits = true;
    }
  }

  // TODO(dwd): the next 3 limit variables should take defaults from
  // SyncParameters
  params->nested_kcatalog_limit = 0;
  std::string nested_kcatalog_limit_str;
  if (parser.GetValue("CVMFS_NESTED_KCATALOG_LIMIT",
                      &nested_kcatalog_limit_str)) {
    params->nested_kcatalog_limit = String2Uint64(nested_kcatalog_limit_str);
  }

  params->root_kcatalog_limit = 0;
  std::string root_kcatalog_limit_str;
  if (parser.GetValue("CVMFS_ROOT_KCATALOG_LIMIT", &root_kcatalog_limit_str)) {
    params->root_kcatalog_limit = String2Uint64(root_kcatalog_limit_str);
  }

  params->file_mbyte_limit = 0;
  std::string file_mbyte_limit_str;
  if (parser.GetValue("CVMFS_FILE_MBYTE_LIMIT", &file_mbyte_limit_str)) {
    params->file_mbyte_limit = String2Uint64(file_mbyte_limit_str);
  }

  return true;
}

}  // namespace receiver


text:
using cyclus::Material;
using cyclus::Composition;
using cyclus::toolkit::ResBuf;
using cyclus::toolkit::MatVec;
using cyclus::KeyError;
using cyclus::ValueError;
using cyclus::Request;
using cyclus::CompMap;

namespace cycamore {

Separations::Separations(cyclus::Context* ctx) : cyclus::Facility(ctx) {}

cyclus::Inventories Separations::SnapshotInv() {
  cyclus::Inventories invs;

  // these inventory names are intentionally convoluted so as to not clash
  // with the user-specified stream commods that are used as the separations
  // streams inventory names.
  invs["leftover-inv-name"] = leftover.PopNRes(leftover.count());
  leftover.Push(invs["leftover-inv-name"]);
  invs["feed-inv-name"] = feed.PopNRes(feed.count());
  feed.Push(invs["feed-inv-name"]);

  std::map<std::string, ResBuf<Material> >::iterator it;
  for (it = streambufs.begin(); it != streambufs.end(); ++it) {
    invs[it->first] = it->second.PopNRes(it->second.count());
    it->second.Push(invs[it->first]);
  }

  return invs;
}

void Separations::InitInv(cyclus::Inventories& inv) {
  leftover.Push(inv["leftover-inv-name"]);
  feed.Push(inv["feed-inv-name"]);

  cyclus::Inventories::iterator it;
  for (it = inv.begin(); it != inv.end(); ++it) {
    streambufs[it->first].Push(it->second);
  }
}

typedef std::pair<double, std::map<int, double> > Stream;
typedef std::map<std::string, Stream> StreamSet;

void Separations::EnterNotify() {
  cyclus::Facility::EnterNotify();
  std::map<int, double> efficiency_;

  StreamSet::iterator it;
  std::map<int, double>::iterator it2;

  for (it = streams_.begin(); it != streams_.end(); ++it) {
    std::string name = it->first;
    Stream stream = it->second;
    double cap = stream.first;
    if (cap >= 0) {
      streambufs[name].capacity(cap);
    }

    for (it2 = stream.second.begin(); it2 != stream.second.end(); it2++) {
      efficiency_[it2->first] += it2->second;
    }
  }

  std::vector<int> eff_pb_;
  for (it2 = efficiency_.begin(); it2 != efficiency_.end(); it2++) {
    if (it2->second > 1) {
      eff_pb_.push_back(it2->first);
    }
  }

  if (eff_pb_.size() > 0) {
    std::stringstream ss;
    ss << "In " << prototype() << ", ";
    ss << "the following nuclide(s) have a cumulative separation efficiency "
          "greater than 1:";
    for (int i = 0; i < eff_pb_.size(); i++) {
      ss << "\n    " << eff_pb_[i];
      if (i < eff_pb_.size() - 1) {
        ss << ",";
      } else {
        ss << ".";
      }
    }

    throw cyclus::ValueError(ss.str());
  }

  if (feed_commod_prefs.size() == 0) {
    for (int i = 0; i < feed_commods.size(); i++) {
      feed_commod_prefs.push_back(cyclus::kDefaultPref);
    }
  }
}

void Separations::Tick() {
  if (feed.count() == 0) {
    return;
  }
  double pop_qty = std::min(throughput, feed.quantity());
  Material::Ptr mat = feed.Pop(pop_qty, cyclus::eps_rsrc());
  double orig_qty = mat->quantity();

  StreamSet::iterator it;
  double maxfrac = 1;
  std::map<std::string, Material::Ptr> stagedsep;
  for (it = streams_.begin(); it != streams_.end(); ++it) {
    Stream info = it->second;
    std::string name = it->first;
    stagedsep[name] = SepMaterial(info.second, mat);
    double frac = streambufs[name].space() / stagedsep[name]->quantity();
    if (frac < maxfrac) {
      maxfrac = frac;
    }
  }

  std::map<std::string, Material::Ptr>::iterator itf;
  for (itf = stagedsep.begin(); itf != stagedsep.end(); ++itf) {
    std::string name = itf->first;
    Material::Ptr m = itf->second;
    if (m->quantity() > 0) {
      streambufs[name].Push(
          mat->ExtractComp(m->quantity() * maxfrac, m->comp()));
    }
  }

  if (maxfrac == 1) {
    if (mat->quantity() > 0) {
      // unspecified separations fractions go to leftovers
      leftover.Push(mat);
    }
  } else {  // maxfrac is < 1
    // push back any leftover feed due to separated stream inv size constraints
    feed.Push(mat->ExtractQty((1 - maxfrac) * orig_qty));
    if (mat->quantity() > 0) {
      // unspecified separations fractions go to leftovers
      leftover.Push(mat);
    }
  }
}

// Note that this returns an untracked material that should just be used for
// its composition and qty - not in any real inventories, etc.
Material::Ptr SepMaterial(std::map<int, double> effs, Material::Ptr mat) {
  CompMap cm = mat->comp()->mass();
  cyclus::compmath::Normalize(&cm, mat->quantity());
  double tot_qty = 0;
  CompMap sepcomp;

  CompMap::iterator it;
  for (it = cm.begin(); it != cm.end(); ++it) {
    int nuc = it->first;
    int elem = (nuc / 10000000) * 10000000;
    double eff = 0;
    if (effs.count(nuc) > 0) {
      eff = effs[nuc];
    } else if (effs.count(elem) > 0) {
      eff = effs[elem];
    } else {
      continue;
    }

    double qty = it->second;
    double sepqty = qty * eff;
    sepcomp[nuc] = sepqty;
    tot_qty += sepqty;
  }

  Composition::Ptr c = Composition::CreateFromMass(sepcomp);
  return Material::CreateUntracked(tot_qty, c);
};

std::set<cyclus::RequestPortfolio<Material>::Ptr>
Separations::GetMatlRequests() {
  using cyclus::RequestPortfolio;
  std::set<RequestPortfolio<Material>::Ptr> ports;

  int t = context()->time();
  int t_exit = exit_time();
  if (t_exit >= 0 && (feed.quantity() >= (t_exit - t) * throughput)) {
    return ports;  // already have enough feed for remainder of life
  } else if (feed.space() < cyclus::eps_rsrc()) {
    return ports;
  }

  bool exclusive = false;
  RequestPortfolio<Material>::Ptr port(new RequestPortfolio<Material>());

  Material::Ptr m = cyclus::NewBlankMaterial(feed.space());
  if (!feed_recipe.empty()) {
    Composition::Ptr c = context()->GetRecipe(feed_recipe);
    m = Material::CreateUntracked(feed.space(), c);
  }

  std::vector<cyclus::Request<Material>*> reqs;
  for (int i = 0; i < feed_commods.size(); i++) {
    std::string commod = feed_commods[i];
    double pref = feed_commod_prefs[i];
    reqs.push_back(port->AddRequest(m, this, commod, pref, exclusive));
  }
  port->AddMutualReqs(reqs);
  ports.insert(port);

  return ports;
}

void Separations::GetMatlTrades(
    const std::vector<cyclus::Trade<Material> >& trades,
    std::vector<std::pair<cyclus::Trade<Material>, Material::Ptr> >&
        responses) {
  using cyclus::Trade;

  std::vector<cyclus::Trade<cyclus::Material> >::const_iterator it;
  for (int i = 0; i < trades.size(); i++) {
    std::string commod = trades[i].request->commodity();
    if (commod == leftover_commod) {
      double amt = std::min(leftover.quantity(), trades[i].amt);
      Material::Ptr m = leftover.Pop(amt, cyclus::eps_rsrc());
      responses.push_back(std::make_pair(trades[i], m));
    } else if (streambufs.count(commod) > 0) {
      double amt = std::min(streambufs[commod].quantity(), trades[i].amt);
      Material::Ptr m = streambufs[commod].Pop(amt, cyclus::eps_rsrc());
      responses.push_back(std::make_pair(trades[i], m));
    } else {
      throw ValueError("invalid commodity " + commod +
                       " on trade matched to prototype " + prototype());
    }
  }
}

void Separations::AcceptMatlTrades(
    const std::vector<std::pair<cyclus::Trade<Material>, Material::Ptr> >&
        responses) {
  std::vector<std::pair<cyclus::Trade<cyclus::Material>,
                        cyclus::Material::Ptr> >::const_iterator trade;

  for (trade = responses.begin(); trade != responses.end(); ++trade) {
    feed.Push(trade->second);
  }
}

std::set<cyclus::BidPortfolio<Material>::Ptr> Separations::GetMatlBids(
    cyclus::CommodMap<Material>::type& commod_requests) {
  using cyclus::BidPortfolio;

  bool exclusive = false;
  std::set<BidPortfolio<Material>::Ptr> ports;

  // bid streams
  std::map<std::string, ResBuf<Material> >::iterator it;
  for (it = streambufs.begin(); it != streambufs.end(); ++it) {
    std::string commod = it->first;
    std::vector<Request<Material>*>& reqs = commod_requests[commod];
    if (reqs.size() == 0) {
      continue;
    } else if (streambufs[commod].quantity() < cyclus::eps_rsrc()) {
      continue;
    }

    MatVec mats = streambufs[commod].PopN(streambufs[commod].count());
    streambufs[commod].Push(mats);

    BidPortfolio<Material>::Ptr port(new BidPortfolio<Material>());

    for (int j = 0; j < reqs.size(); j++) {
      Request<Material>* req = reqs[j];
      double tot_bid = 0;
      for (int k = 0; k < mats.size(); k++) {
        Material::Ptr m = mats[k];
        tot_bid += m->quantity();

        // this fix the problem of the cyclus exchange manager which crashes
        // when a bid with a quantity <=0 is offered.
        if (m->quantity() > cyclus::eps_rsrc()) {
          port->AddBid(req, m, this, exclusive);
        }

        if (tot_bid >= req->target()->quantity()) {
          break;
        }
      }
    }

    double tot_qty = streambufs[commod].quantity();
    cyclus::CapacityConstraint<Material> cc(tot_qty);
    port->AddConstraint(cc);
    ports.insert(port);
  }

  // bid leftovers
  std::vector<Request<Material>*>& reqs = commod_requests[leftover_commod];
  if (reqs.size() > 0 && leftover.quantity() >= cyclus::eps_rsrc()) {
    MatVec mats = leftover.PopN(leftover.count());
    leftover.Push(mats);

    BidPortfolio<Material>::Ptr port(new BidPortfolio<Material>());

    for (int j = 0; j < reqs.size(); j++) {
      Request<Material>* req = reqs[j];
      double tot_bid = 0;
      for (int k = 0; k < mats.size(); k++) {
        Material::Ptr m = mats[k];
        tot_bid += m->quantity();

        // this fix the problem of the cyclus exchange manager which crashes
        // when a bid with a quantity <=0 is offered.
        if (m->quantity() > cyclus::eps_rsrc()) {
          port->AddBid(req, m, this, exclusive);
        }

        if (tot_bid >= req->target()->quantity()) {
          break;
        }
      }
    }

    cyclus::CapacityConstraint<Material> cc(leftover.quantity());
    port->AddConstraint(cc);
    ports.insert(port);
  }

  return ports;
}

void Separations::Tock() {}

bool Separations::CheckDecommissionCondition() {
  if (leftover.count() > 0) {
    return false;
  }

  std::map<std::string, ResBuf<Material> >::iterator it;
  for (it = streambufs.begin(); it != streambufs.end(); ++it) {
    if (it->second.count() > 0) {
      return false;
    }
  }

  return true;
}

extern "C" cyclus::Agent* ConstructSeparations(cyclus::Context* ctx) {
  return new Separations(ctx);
}

}  // namespace cycamore


text:
import calendar
import iso639
import json
import pytz
import re
import unicodedata

from dateutil.relativedelta import relativedelta
from datetime import datetime, time, timedelta
from django.utils.timesince import timeuntil
from django.utils import timezone
from enum import Enum
from temba_client.utils import format_iso8601
from uuid import UUID

LANGUAGES_BY_CODE = {}  # cache of language lookups

def parse_csv(csv, as_ints=False):
    """
    Parses a comma separated list of values as strings or integers
    """
    items = []
    for val in csv.split(","):
        val = val.strip()
        if val:
            items.append(int(val) if as_ints else val)
    return items

def str_to_bool(text):
    """
    Parses a boolean value from the given text
    """
    return text and text.lower() in ["true", "y", "yes", "1"]

class JSONEncoder(json.JSONEncoder):
    """
    JSON encoder which encodes datetime values as strings
    """

    def default(self, val):
        if isinstance(val, datetime):
            return format_iso8601(val)
        elif isinstance(val, Enum):
            return val.name
        elif hasattr(val, "to_json") and callable(val.to_json):
            return val.to_json()

        return json.JSONEncoder.default(self, val)  # pragma: no cover

def json_encode(data):
    """
    Encodes the given primitives as JSON using Django's encoder which can handle dates
    """
    return json.dumps(data, cls=JSONEncoder)

def json_decode(data):
    """
    Decodes the given JSON as primitives
    """
    if isinstance(data, bytes):
        data = data.decode("utf-8")

    return json.loads(data)

def safe_max(*args, **kwargs):
    """
    Regular max won't compare dates with NoneType and raises exception for no args
    """
    non_nones = [v for v in args if v is not None]
    if len(non_nones) == 0:
        return None
    elif len(non_nones) == 1:
        return non_nones[0]
    else:
        return max(*non_nones, **kwargs)

def normalize(text):
    """
    Normalizes text before keyword matching. Converts to lowercase, performs KD unicode normalization and replaces
    multiple whitespace characters with single spaces.
    """
    return unicodedata.normalize("NFKD", re.sub(r"\s+", " ", text.lower()))

def match_keywords(text, keywords):
    """
    Checks the given text for a keyword match
    """
    for keyword in keywords:
        if re.search(r"\b" + keyword + r"\b", text, flags=re.IGNORECASE):
            return True
    return False

def truncate(text, length=100, suffix="..."):
    """
    Truncates the given text to be no longer than the given length
    """
    if len(text) > length:
        return text[: length - len(suffix)] + suffix
    else:
        return text

def date_to_milliseconds(d):
    """
    Converts a date to a millisecond accuracy timestamp. Equivalent to Date.UTC(d.year, d.month-1, d.day) in Javascript
    """
    return calendar.timegm(datetime.combine(d, time(0, 0, 0)).replace(tzinfo=pytz.UTC).utctimetuple()) * 1000

def datetime_to_microseconds(dt):
    """
    Converts a datetime to a microsecond accuracy timestamp
    """
    seconds = calendar.timegm(dt.utctimetuple())
    return seconds * 1000000 + dt.microsecond

def microseconds_to_datetime(ms):
    """
    Converts a microsecond accuracy timestamp to a datetime
    """
    return datetime.utcfromtimestamp(ms / 1000000.0).replace(tzinfo=pytz.utc)

def month_range(offset, now=None):
    """
    Gets the UTC start and end (exclusive) of a month
    :param offset: 0 = this month, -1 last month, 1 = next month etc
    :return: the start and end datetimes as a tuple
    """
    if not now:
        now = timezone.now()

    now = now.astimezone(pytz.UTC)
    start_of_this_month = now.replace(day=1, hour=0, minute=0, second=0, microsecond=0)

    return start_of_this_month + relativedelta(months=offset), start_of_this_month + relativedelta(months=offset + 1)

def date_range(start, stop):
    """
    A date-based range generator
    """
    for n in range(int((stop - start).days)):
        yield start + timedelta(n)

class TimelineItem(object):
    """
    Wraps a message or action for easier inclusion in a merged timeline
    """

    def __init__(self, item):
        self.item = item

    def get_time(self):
        return self.item.created_on

    def to_json(self):
        return {"time": self.get_time(), "type": self.item.TIMELINE_TYPE, "item": self.item.as_json()}

def uuid_to_int(uuid):
    """
    Converts a UUID hex string to an int within the range of a Django IntegerField, and also >=0, as the URL regexes
    don't account for negative numbers.

    From https://docs.djangoproject.com/en/1.9/ref/models/fields/#integerfield
    "Values from -2147483648 to 2147483647 are safe in all databases supported by Django"
    """
    return UUID(hex=uuid).int % (2147483647 + 1)

def get_language_name(iso_code):
    """
    Gets the language name for the given ISO639-3 code.
    """
    if iso_code not in LANGUAGES_BY_CODE:
        try:
            lang = iso639.languages.get(part3=iso_code)
        except KeyError:
            lang = None

        if lang:
            # we only show up to the first semi or paren
            lang = re.split(";|\(", lang.name)[0].strip()

        LANGUAGES_BY_CODE[iso_code] = lang

    return LANGUAGES_BY_CODE[iso_code]

def is_valid_language_code(code):
    """
    Gets whether the given code is a valid ISO639-3 code.
    """
    try:
        iso639.languages.get(part3=code)
        return True
    except KeyError:
        return False

def humanize_seconds(seconds):
    now = timezone.now()
    return timeuntil(now + timedelta(seconds=seconds), now)


text:
divide :: Double -> Double -> Double
divide 0 = const 0
divide a = (/ a)


text:
import pygame  # @UnusedWildImport
from pygame.locals import *  # @UnusedWildImport
import os
os.environ['SDL_VIDEO_CENTERED'] = '1'
from ControlMultimediaUniversal import *  # @UnusedWildImport

# carrega as imagens e inicia o control
control = ControlMultimediaUniversal()

# loop principal do pygame
counter = 0
position = -300

residenceFounded = True

if control.getIp() == "Residence is offline":
    residenceFounded = False

while residenceFounded:
    for event in pygame.event.get():
        if event == None:
            break
        if event.type == QUIT or (event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE):
            control.disconnectControl()
            pygame.quit()
            os._exit(0)
        control.turnOffCaptureEvent(event)
        control.optionTVCaptureEvent(event)
        control.optionSoundCaptureEvent(event)
        control.upVolumeCaptureEvent(event)
        control.downVolumeCaptureEvent(event)
        control.upChannelCaptureEvent(event)
        control.downChannelCaptureEvent(event)
        control.muteCaptureEvent(event)

    # carrega botões na tela

    control.drawScreen(position)
    # botao desligar
    control.turnOffAnimation()
    # botao mudar opcao tv
    control.optionTVAnimation()
    # botao mudar opcao som
    control.optionSoundAnimation()
    # aumentar volume
    control.upVolumeAnimation()
    # diminuir volume
    control.downVolumeAnimation()
    # botao mudar canal cima
    control.changeChannelUPAnimation()
     # botao mudar canal baixo
    control.changeChannelDownAnimation()

    control.muteAnimation()

    # Checa o comodo que o control se encontra
    counter += 1
    if counter % 10 == 0:
        position += 1
    if position == 300:
        position = -300
        counter = 0

        # Obs:A maioria dessa variaveis referentes ao comodo devem estar no servidor e nao no control

    pygame.display.flip()


text:
@interface PRYStreamViewController ()

@end

@implementation PRYStreamViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil model:(PRYPeerflixHelper *)model fileName:(NSString *)fileName
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        _peerflixHelper = model;
        [_peerflixHelper launchStreamWithHandlersOnUpdate:^(NSDictionary *info) {
            [_fileNameLabel setStringValue:fileName];
            // Go through dictionary and set labels in UI
            [info enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
                [[self valueForKey:[NSString stringWithFormat:@"%@Label", key]] setStringValue:obj];
            }];
        } onComplete:^{
            [NSApp terminate:nil];
        }];
    }
    return self;
}

@end


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

namespace Mermaid.Loft.Infrastructure.Ioc.BaseRepository
{
    public abstract class EntityBase
    {
    }
}


text:
<?php declare(strict_types=1);
/**
 * @license MIT
 * @author Samuel Adeshina <samueladeshina73@gmail.com>
 *
 * This file is part of the EmmetBlue project, please read the license document
 * available in the root level of the project
 */
namespace EmmetBlue\Plugins\Consultancy\Infermedica;

use EmmetBlue\Core\Builder\BuilderFactory as Builder;
use EmmetBlue\Core\Factory\DatabaseConnectionFactory as DBConnectionFactory;
use EmmetBlue\Core\Builder\QueryBuilder\QueryBuilder as QB;
use EmmetBlue\Core\Exception\SQLException;
use EmmetBlue\Core\Exception\UndefinedValueException;
use EmmetBlue\Core\Session\Session;
use EmmetBlue\Core\Logger\DatabaseLog;
use EmmetBlue\Core\Logger\ErrorLog;
use EmmetBlue\Core\Constant;
use EmmetBlue\Core\Factory\ElasticSearchClientFactory as ESClientFactory;

/**
 * class Infermedica Controller
 *
 * @author Samuel Adeshina <samueladeshina73@gmail.com>
 * @since v0.0.1 20/08/2016 03:29AM
 */
class Infermedica
{
	private static $apiURL = "https://api.infermedica.com/v2/";

    private static function searcher(string $type, array $data){
        $dirts = [
            "(", ")", "-"
        ];
        foreach ($dirts as $dirt){
            $data["phrase"] = str_replace($dirt, " ", $data["phrase"]);
        }
        $phrase = $data["phrase"];
        $size = $data['size'] ?? 10000;
        $from = $data['from'] ?? 0;

        $query = explode(" ", $phrase);
        $builtQuery = [];
        foreach ($query as $element){
            $builtQuery[] = "(".$element."* ".$element."~)";
        }

        $builtQuery = implode(" AND ", $builtQuery);

        $params = [
            'index'=>'infermedica',
            'type'=>$type,
            'size'=>$size,
            'from'=>$from,
            'body'=>array(
                "query"=>array(
                    "query_string"=>array(
                        "query"=>$builtQuery
                    )
                )
            )
        ];

        $esClient = ESClientFactory::getClient();

        return $esClient->search($params);
    }

    public static function searchSymptoms(array $data){
        return self::searcher('symptoms', $data);
    }

    public static function searchLabTests(array $data){
        return self::searcher('labtests', $data);
    }

   public static function symptoms(array $data){
   		try {

            $esClient = ESClientFactory::getClient();

            $params = [
                'index'=>'infermedica',
                'type' =>'symptoms',
                'id'=>$data["id"]
            ];

            return $esClient->get($params);
        }
        catch (\Elasticsearch\Common\Exceptions\Missing404Exception $e){
        	return [];
        }
   }

   public static function labTests(array $data){
   		$result = HTTPRequestFactory::get(self::$apiURL."lab_tests/".$data["id"]);

   		return json_decode($result->body, true);
   }
}


text:
module AzProjectBlocksHelper
end


text:
package com.linkedin.pinot.core.indexsegment.utils;

import com.linkedin.pinot.common.utils.MmapUtils;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Jun 30, 2014
 *
 */
public class GenericRowColumnDataFileReader {
  private static final Logger LOGGER = LoggerFactory.getLogger(GenericRowColumnDataFileReader.class);

  RandomAccessFile file;
  private final int rows;
  private final int cols;
  private final int[] colOffSets;
  private int rowSize;
  private ByteBuffer byteBuffer;
  private final int[] columnSizes;

  /**
   *
   * @param file
   * @param rows
   * @param cols
   * @param columnSizes
   * @return
   * @throws IOException
   */
  public static GenericRowColumnDataFileReader forHeap(File file, int rows, int cols, int[] columnSizes)
      throws IOException {
    return new GenericRowColumnDataFileReader(file, rows, cols, columnSizes, false);
  }

  /**
   *
   * @param file
   * @param rows
   * @param cols
   * @param columnSizes
   * @return
   * @throws IOException
   */
  public static GenericRowColumnDataFileReader forMmap(File file, int rows, int cols, int[] columnSizes)
      throws IOException {
    return new GenericRowColumnDataFileReader(file, rows, cols, columnSizes, true);
  }

  /**
   *
   * @param dataFile
   * @param rows
   * @param cols
   * @param columnSizes in bytes
   * @throws IOException
   */
  public GenericRowColumnDataFileReader(File dataFile, int rows, int cols, int[] columnSizes, boolean isMmap)
      throws IOException {
    this.rows = rows;
    this.cols = cols;
    this.columnSizes = columnSizes;
    colOffSets = new int[columnSizes.length];
    for (int i = 0; i < columnSizes.length; i++) {
      if (i == 0) {
        colOffSets[i] = 0;
      } else {
        colOffSets[i] = colOffSets[i - 1] + columnSizes[i - 1];
      }
      rowSize += columnSizes[i];
    }
    file = new RandomAccessFile(dataFile, "rw");
    long totalSize = rowSize * rows;
    if (isMmap)
      byteBuffer = MmapUtils.mmapFile(file, FileChannel.MapMode.READ_ONLY, 0, totalSize, dataFile,  this.getClass().getSimpleName() + " byteBuffer");
    else {
      byteBuffer = MmapUtils
          .allocateDirectByteBuffer((int) totalSize, dataFile, this.getClass().getSimpleName() + " byteBuffer");
      file.getChannel().read(byteBuffer);
    }
  }

  public GenericRowColumnDataFileReader(String fileName, int rows, int cols, int[] columnSizes) throws IOException {
    this(new File(fileName), rows, cols, columnSizes, true);
  }

  /**
   * Computes the offset where the actual column data can be read
   * @param row
   * @param col
   * @return
   */
  private int computeOffset(int row, int col) {
    if (row >= rows || col >= cols) {
      String message = String.format("Input (%d,%d) is not with in expected range (%d,%d)", row, col, rows, cols);
      throw new IndexOutOfBoundsException(message);
    }
    int offset = row * rowSize + colOffSets[col];
    return offset;
  }

  /**
   *
   * @param row
   * @param col
   * @return
   */
  public char getChar(int row, int col) {
    int offset = computeOffset(row, col);
    return byteBuffer.getChar(offset);
  }

  /**
   *
   * @param row
   * @param col
   * @return
   */
  public short getShort(int row, int col) {
    int offset = computeOffset(row, col);
    return byteBuffer.getShort(offset);
  }

  /**
   *
   * @param row
   * @param col
   * @return
   */
  public int getInt(int row, int col) {
    assert getColumnSizes()[col] == 4;
    int offset = computeOffset(row, col);
    return byteBuffer.getInt(offset);
  }

  /**
   *
   * @param row
   * @param col
   * @return
   */
  public long getLong(int row, int col) {
    assert getColumnSizes()[col] == 8;
    int offset = computeOffset(row, col);
    return byteBuffer.getLong(offset);
  }

  /**
   *
   * @param row
   * @param col
   * @return
   */
  public float getFloat(int row, int col) {
    assert getColumnSizes()[col] == 4;
    int offset = computeOffset(row, col);
    return byteBuffer.getFloat(offset);
  }

  /**
   * Reads the double at row,col
   * @param row
   * @param col
   * @return
   */
  public double getDouble(int row, int col) {
    assert getColumnSizes()[col] == 8;
    int offset = computeOffset(row, col);
    return byteBuffer.getDouble(offset);
  }

  /**
   * Returns the string value, NOTE: It expects all String values in the file to be of same length
   * @param row
   * @param col
   * @return
   */
  public String getString(int row, int col) {
    return new String(get(row, col));
  }

  /**
   * Generic method to read the raw bytes
   * @param row
   * @param col
   * @return
   */
  public byte[] get(int row, int col) {
    int length = getColumnSizes()[col];
    byte[] dst = new byte[length];
    int offset = computeOffset(row, col);
    byteBuffer.position(offset);
    byteBuffer.get(dst, 0, length);
    return dst;
  }

  public int getNumberOfRows() {
    return rows;
  }

  public int getNumberOfCols() {
    return rows;
  }

  public int[] getColumnSizes() {
    return columnSizes;
  }

  public void close() {
    IOUtils.closeQuietly(file);
    MmapUtils.unloadByteBuffer(byteBuffer);
    byteBuffer = null;
  }
}


text:
from django.conf.urls.defaults import *

urlpatterns = patterns(
    'txtlocal.views',
    url(r'^$', 'sms_response', name='sms_response'),
)


text:
<title>WorldViews Experimental Server</title>

WorldViews TeleViewer

FXPAL


text:
FOUNDATION_EXPORT double RxSwiftFormsVersionNumber;

//! Project version string for RxSwiftForms.
FOUNDATION_EXPORT const unsigned char RxSwiftFormsVersionString[];

// In this header, you should import all the public headers of your framework using statements like #import <RxSwiftForms/PublicHeader.h>


text:
<?php
namespace Poll\PollBundle\Entity\Text;

use Poll\PollBundle\Entity\QuestionImpl;
use Poll\PollBundle\Service\ObjectFactory;

/**
 * Implementace otazky s textovou odpovedi
 * @author kadleto2
 */
class TextQuestionImpl extends QuestionImpl implements TextQuestion {

    public function __construct() {
        parent::__construct();
        $this->questionType = ObjectFactory::TEXT_QUESTION;
    }
}


text:
package vip.kernel.application;

import javax.ejb.Local;

import br.ufes.inf.nemo.jbutler.ejb.application.CrudService;
import vip.kernel.domain.VipConfiguration;

@Local
public interface ManageConfigurationService extends CrudService<VipConfiguration> {

}


text:
package commands

import (
	"fmt"
	"sort"

	. "github.com/cloudfoundry/cli/cf/i18n"
	"github.com/cloudfoundry/cli/flags"
	"github.com/cloudfoundry/cli/flags/flag"

	"github.com/cloudfoundry/cli/cf/api"
	"github.com/cloudfoundry/cli/cf/api/app_instances"
	"github.com/cloudfoundry/cli/cf/command_registry"
	"github.com/cloudfoundry/cli/cf/configuration/core_config"
	"github.com/cloudfoundry/cli/cf/manifest"
	"github.com/cloudfoundry/cli/cf/models"
	"github.com/cloudfoundry/cli/cf/requirements"
	"github.com/cloudfoundry/cli/cf/terminal"
)

type CreateAppManifest struct {
	ui               terminal.UI
	config           core_config.Reader
	appSummaryRepo   api.AppSummaryRepository
	appInstancesRepo app_instances.AppInstancesRepository
	appReq           requirements.ApplicationRequirement
	manifest         manifest.AppManifest
}

func init() {
	command_registry.Register(&CreateAppManifest{})
}

func (cmd *CreateAppManifest) MetaData() command_registry.CommandMetadata {
	fs := make(map[string]flags.FlagSet)
	fs["p"] = &cliFlags.StringFlag{Name: "p", Usage: T("Specify a path for file creation. If path not specified, manifest file is created in current working directory.")}

	return command_registry.CommandMetadata{
		Name:        "create-app-manifest",
		Description: T("Create an app manifest for an app that has been pushed successfully."),
		Usage:       T("CF_NAME create-app-manifest APP_NAME [-p /path/to/<app-name>-manifest.yml ]"),
		Flags:       fs,
	}
}

func (cmd *CreateAppManifest) Requirements(requirementsFactory requirements.Factory, fc flags.FlagContext) (reqs []requirements.Requirement, err error) {
	if len(fc.Args()) != 1 {
		cmd.ui.Failed(T("Incorrect Usage. Requires APP_NAME as argument\n\n") + command_registry.Commands.CommandUsage("create-app-manifest"))
	}

	cmd.appReq = requirementsFactory.NewApplicationRequirement(fc.Args()[0])

	reqs = []requirements.Requirement{
		requirementsFactory.NewLoginRequirement(),
		requirementsFactory.NewTargetedSpaceRequirement(),
		cmd.appReq,
	}
	return
}

func (cmd *CreateAppManifest) SetDependency(deps command_registry.Dependency, pluginCall bool) command_registry.Command {
	cmd.ui = deps.Ui
	cmd.config = deps.Config
	cmd.appSummaryRepo = deps.RepoLocator.GetAppSummaryRepository()
	cmd.manifest = deps.AppManifest
	return cmd
}

func (cmd *CreateAppManifest) Execute(c flags.FlagContext) {
	app := cmd.appReq.GetApplication()

	application, apiErr := cmd.appSummaryRepo.GetSummary(app.Guid)

	if apiErr != nil {
		cmd.ui.Failed(T("Error getting application summary: ") + apiErr.Error())
	}

	cmd.ui.Say(T("Creating an app manifest from current settings of app ") + application.Name + " ...")
	cmd.ui.Say("")

	savePath := "./" + application.Name + "_manifest.yml"

	if c.String("p") != "" {
		savePath = c.String("p")
	}

	cmd.createManifest(application, savePath)
}

func (cmd *CreateAppManifest) createManifest(app models.Application, savePath string) error {
	cmd.manifest.FileSavePath(savePath)
	cmd.manifest.Memory(app.Name, app.Memory)
	cmd.manifest.Instances(app.Name, app.InstanceCount)

	if app.Command != "" {
		cmd.manifest.StartCommand(app.Name, app.Command)
	}

	if app.BuildpackUrl != "" {
		cmd.manifest.BuildpackUrl(app.Name, app.BuildpackUrl)
	}

	if len(app.Services) > 0 {
		for _, service := range app.Services {
			cmd.manifest.Service(app.Name, service.Name)
		}
	}

	if app.HealthCheckTimeout > 0 {
		cmd.manifest.HealthCheckTimeout(app.Name, app.HealthCheckTimeout)
	}

	if len(app.EnvironmentVars) > 0 {
		sorted := sortEnvVar(app.EnvironmentVars)
		for _, envVarKey := range sorted {
			switch app.EnvironmentVars[envVarKey].(type) {
			default:
				cmd.ui.Failed(T("Failed to create manifest, unable to parse environment variable: ") + envVarKey)
			case float64:
				//json.Unmarshal turn all numbers to float64
				value := int(app.EnvironmentVars[envVarKey].(float64))
				cmd.manifest.EnvironmentVars(app.Name, envVarKey, fmt.Sprintf("%d", value))
			case bool:
				cmd.manifest.EnvironmentVars(app.Name, envVarKey, fmt.Sprintf("%t", app.EnvironmentVars[envVarKey].(bool)))
			case string:
				cmd.manifest.EnvironmentVars(app.Name, envVarKey, "\""+app.EnvironmentVars[envVarKey].(string)+"\"")
			}
		}
	}

	if len(app.Routes) > 0 {
		for i := 0; i < len(app.Routes); i++ {
			cmd.manifest.Domain(app.Name, app.Routes[i].Host, app.Routes[i].Domain.Name)
		}
	}

	err := cmd.manifest.Save()
	if err != nil {
		cmd.ui.Failed(T("Error creating manifest file: ") + err.Error())
	}

	cmd.ui.Ok()
	cmd.ui.Say(T("Manifest file created successfully at ") + savePath)
	cmd.ui.Say("")

	return nil
}

func sortEnvVar(vars map[string]interface{}) []string {
	var varsAry []string
	for k, _ := range vars {
		varsAry = append(varsAry, k)
	}
	sort.Strings(varsAry)

	return varsAry
}


text:
package org.artifactory.storage.db.aql.parser;

import com.google.common.collect.Lists;
import org.artifactory.storage.db.aql.parser.elements.ParserElement;
import org.artifactory.util.Pair;

import java.util.List;

/**
 * Each element in The parser peels off a part from the query string.
 * The ParserElementResultContainer contains the the leftover part of the query string
 * and the components that has been used to peel of the query string until this element
 *
 * @author Gidi Shabat
 */
public class ParserElementResultContainer {
    /**
     * Remainder of the original query strong to parse.
     */
    private final String queryRemainder;
    /**
     * The current element peeled off (can be empty)
     */
    private final String element;
    /**
     * The query element path leading to this intermediate result. In reverse order.
     */
    private final List<Pair<ParserElement, String>> list = Lists.newArrayList();

    public ParserElementResultContainer(String queryRemainder, String element) {
        this.queryRemainder = queryRemainder;
        this.element = element;
    }

    public String getQueryRemainder() {
        return queryRemainder;
    }

    public String getElement() {
        return element;
    }

    public void add(ParserElement element, String part) {
        list.add(new Pair<>(element, part));
    }

    public List<Pair<ParserElement, String>> getAll() {
        return list;
    }

}


text:
using Llvm.NET.Types;

namespace Llvm.NET.DebugInfo
{
    /// Binding between a <see cref="DIDerivedType"/> and an <see cref="IPointerType"/>
    public class DebugPointerType
        : DebugType<IPointerType, DIDerivedType>
        , IPointerType
    {
        /// Constructs a new <see cref="DebugPointerType"/>
        /// <param name="debugElementType">Debug type of the pointee</param>
        /// <param name="module"><see cref="NativeModule"/> used for creating the pointer type and debug information</param>
        /// <param name="addressSpace">Target address space for the pointer [Default: 0]</param>
        /// <param name="name">Name of the type [Default: null]</param>
        public DebugPointerType( IDebugType<ITypeRef, DIType> debugElementType, NativeModule module, uint addressSpace = 0, string name = null )
            : this( debugElementType.VerifyArgNotNull( nameof( debugElementType ) ).NativeType
                  , module
                  , debugElementType.VerifyArgNotNull( nameof( debugElementType ) ).DIType
                  , addressSpace
                  , name
                  )
        {
        }

        /// Constructs a new <see cref="DebugPointerType"/>
        /// <param name="llvmElementType">Native type of the pointee</param>
        /// <param name="module"><see cref="NativeModule"/> used for creating the pointer type and debug information</param>
        /// <param name="elementType">Debug type of the pointee</param>
        /// <param name="addressSpace">Target address space for the pointer [Default: 0]</param>
        /// <param name="name">Name of the type [Default: null]</param>
        public DebugPointerType( ITypeRef llvmElementType, NativeModule module, DIType elementType, uint addressSpace = 0, string name = null )
            : this( llvmElementType.VerifyArgNotNull( nameof( llvmElementType ) ).CreatePointerType( addressSpace ), module, elementType, name )
        {
        }

        /// Constructs a new <see cref="DebugPointerType"/>
        /// <param name="llvmPtrType">Native type of the pointer</param>
        /// <param name="module"><see cref="NativeModule"/> used for creating the pointer type and debug information</param>
        /// <param name="elementType">Debug type of the pointee</param>
        /// <param name="name">Name of the type [Default: null]</param>
        public DebugPointerType( IPointerType llvmPtrType, NativeModule module, DIType elementType, string name = null )
            : this( llvmPtrType
                  , module.VerifyArgNotNull( nameof( module ) )
                          .DIBuilder
                          .CreatePointerType( elementType
                                            , name
                                            , module.VerifyArgNotNull( nameof( module ) ).Layout.BitSizeOf( llvmPtrType )
                                            , module.VerifyArgNotNull( nameof( module ) ).Layout.AbiBitAlignmentOf( llvmPtrType )
                                            )
                  )
        {
        }

        /// Constructs a new <see cref="DebugPointerType"/>
        /// <param name="llvmPtrType">Native type of the pointer</param>
        /// <param name="debugType">Debug type for the pointer</param>
        /// <remarks>
        /// This constructor is typically used when building typedefs to a basic type
        /// to provide namespace scoping for the typedef for languages that support
        /// such a concept. This is needed because basic types don't have any namespace
        /// information in the LLVM Debug information (they are implicitly in the global
        /// namespace)
        /// </remarks>
        public DebugPointerType( IPointerType llvmPtrType, DIDerivedType debugType )
            : base( llvmPtrType, debugType )
        {
        }

        /// <inheritdoc/>
        public uint AddressSpace => NativeType.AddressSpace;

        /// <inheritdoc/>
        public ITypeRef ElementType => NativeType.ElementType;
    }
}


text:
<title>ChangeSysTrayIcon</title>

ChangeSysTrayIcon()

Syntax

ChangeSysTrayIcon(#SysTrayIcon, ImageID)

Description

Changes the specified icon in the SysTray area.

Parameters

#SysTrayIcon

The systray icon to change.

ImageID

The new image to use for the systray icon. Only icon image type (.ico) are supported on Windows, for Linux and OS X it is advised to use a PNG image
(in order to have a transparency layer). ImageID() may be used to get this ID easily.

Return value

None.

See Also

AddSysTrayIcon()

Supported OS
All

<- AddSysTrayIcon() - SysTray Index - IsSysTrayIcon() ->


text: <extends:resources.style/>


text:
With the validation problem space well understood, Strickland sets out to achieve many challenging design goals.

1. Remain decoupled from the UI
2. Take no dependencies on other libraries
3. Utilize plain old JavaScript objects and values
4. Apply universal, functional JavaScript patterns
5. Supply only primitive built-in validators
6. Enable consumers to easily create their own validators
7. Provide simple composition features for complex validation logic
8. Maintain a low concept count
9. Permit both synchronous and asynchronous validators
10. Support any possible interaction model
11. Allow boundless extensibility for any application scenario

## Decoupled from the UI

Strickland is built with pure JavaScript. There are no features or concepts coupled to any UI libraries or any rendering concepts at all. Strickland can work just as well for a RESTful API service as it can for a web application with large UI forms.

With this model, Strickland validation can be reused across the server and client. If you have a Node backend and a JavaScript frontend, you can build your validation rules into a shared package.

## No Dependencies

Strickland does not have any dependencies on other libraries.

## Plain Old JavaScript Objects

Strickland is not a type system that forces you to construct and manipulate your data unnaturally. Instead, Strickland works with plain old JavaScript objects and values.

## Universal, Functional JavaScript

Strickland can be executed in any JavaScript environment including the browser and Node. Many functional programming patterns are applied throughout Strickland to yield a friendly yet flexible API. Strickland is also entirely stateless, ensuring your application's architecture is not compromised.

## Primitive Built-In Validators

Strickland does not aim to be a bloated collection of validators. Only the most primitive validators are built-in so that Strickland remains a lightweight framework.

## Ease of Validator Creation

Strickland makes it easy to create your own validators. A single-line arrow function can be used to start, but the programming model scales with your application. As your validators become more complex, Strickland gives you the flexibility you need.

## Composition is Critical

Strickland provides features to compose your validators together. As your collection of validators grows, you will be able to reuse them throughout your applications without any friction.

## Low Concept Count

Strickland is powerful yet its concept count remains very low. Validators define rules; validation executes validators against values; validation results are returned.

## Synchronous and Asynchronous Validation

Strickland lets you quite simply introduce asynchronous validation into your application, without having to drastically change your programming model or alter how synchronous validation is performed.

## Any Interaction Model

Strickland is unaware of how your users are interacting with your system. Because Strickland is completely stateless, you can invoke validation whenever and however you'd like. You can invoke UI form validation on keypress, after an idle timeout, on field blur, on form submit, or any combination of these events. You can build server-side validation using the same validator code and execution patterns.

## Boundless Extensibility

A validator can easily execute other validators, which is demonstrated with arrays of validators and object validation.

Dynamic validators can be created using validator factories.

Validators can receive props using objects or functions that return objects. Those functions can receive validation-time context so that application state can be used within validation rules.

Validators can return booleans, objects, Promises that resolve to booleans or objects, or functions that return Promises that resolve to booleans or objects. Strickland normalizes all of these into consistent and predictable validation results.

Your application is responsible for providing all of the validation result properties, even validation messages. This approach ensures that your application can extend Strickland to meet any functional requirements. Localized messages, warning-level validation results, async progress indicators, UI rendering hints, or any other functionality specific to your platform or application can be applied as a first-class feature.


text:
package core

import (
	"fmt"
	"os"
	"path/filepath"
	"syscall"

	"github.com/Sirupsen/logrus"
)

// DestFile describes a destination file.
type DestFile struct {
	DeviceName string
	Path       string
	Size       uint64
	StartByte  uint64
	EndByte    uint64
	Sha1Sum    string
	err        error // Used to record errors that occurr when creating or writing to the dest file.
	done       bool  // When set to true, the file has been copied and verified at the destination
}

// NewDestFile will return a new destination file with the UUID dest path set. If df is not nil, then the start and end bytes
// of the new dest file will be based off the start and end bytes of the previous dest file (pvf).
func NewDestFile(f *File, d *Device, pvf *DestFile, df *DestFile) *DestFile {
	fp := &DestFile{
		DeviceName: d.Name,
		Size:       f.Size,
		EndByte:    f.Size,
	}
	if pvf != nil {
		fp.StartByte = pvf.EndByte
	}
	fp.generateDestPath(d.MountPoint)
	return fp
}

// generateDestPath will generate a new UUID destination path for the destination file using mp as the mount point.
func (df *DestFile) generateDestPath(mp string) (err error) {
	gid, err := NewID()
	if err != nil {
		return
	}
	df.Path = filepath.Join(mp, gid)
	return
}

// setMetaData sets permissions of the destination file.
func (df *DestFile) setMetaData(f *File) error {
	var err error
	mTimeval := syscall.NsecToTimespec(f.ModTime.UnixNano())
	times := []syscall.Timespec{
		mTimeval,
		mTimeval,
	}
	// err = os.Chown(f.Source.Path, f.Source.Owner, f.Source.Group)
	err = os.Chown(df.Path, f.Owner, f.Group)
	if err == nil {
		Log.WithFields(logrus.Fields{"owner": f.Owner, "group": f.Group}).Debugln("Set owner")
		// Change the modtime of a symlink without following it
		err = LUtimesNano(df.Path, times)
		if err == nil {
			Log.WithFields(logrus.Fields{"modTime": f.ModTime}).Debugln("Set modification time")
		}
	}
	if err != nil {
		return fmt.Errorf("setMetaData: %s", err.Error())
	}
	return nil
}

// createFile is a helper function for creating directories, symlinks, and regular files. If it encounters errors creating
// these files, the error is sent on the cerr buffered error channel.
func (df *DestFile) createFile(f *File) {
	var err error
	if f.Owner != os.Getuid() && os.Getuid() != 0 {
		df.err = SyncIncorrectOwnershipError{f.Path, f.Owner, os.Getuid()}
		Log.Errorf("createFile: %s", df.err)
		return
	}
	var oFile *os.File
	if _, lerr := os.Stat(df.Path); lerr != nil {
		oFile, err = os.Create(df.Path)
		err = oFile.Close()
		if err == nil {
			Log.WithFields(logrus.Fields{"name": f.Name}).Debugln("Created empty file")
		}
	}
	if err == nil {
		err = df.setMetaData(f)
		if err != nil {
			df.err = fmt.Errorf("createFile: %s", err.Error())
		}
	}
}

// source returns the parent file of the destination file
func (df *DestFile) source(fi *FileIndex) *File {
	for _, f := range *fi {
		for _, df2 := range f.DestFiles {
			if df == df2 {
				return f
			}
		}
	}
	return nil
}


text:
<?php

declare (strict_types = 1);

namespace Dumplie\Inventory\Application\Command;

use Dumplie\SharedKernel\Application\Command\Command;
use Dumplie\SharedKernel\Application\Command\CommandSerialize;

final class RemoveProductFromStock implements Command
{
    use CommandSerialize;

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

    /**
     * RemoveProductFromStock constructor.
     *
     * @param string $sku
     */
    public function __construct(string $sku)
    {
        $this->sku = $sku;
    }

    /**
     * @return string
     */
    public function sku(): string
    {
        return $this->sku;
    }
}


text:
<!DOCTYPE html>

<meta charset="utf-8"/>
<title>GPX簡易編集ツール</title>

GPXファイル: <input type="file" id="gpx_files" />
<input type="checkbox" id="gpx_join" value="1つのtrkrtに結合" checked />
<input type="checkbox" id="gpx_join" value="日付でtrkrtを分割" checked />
<input type="checkbox" id="gpx_add_elevation" value="子要素を削除" checked />
<input type="checkbox" id="gpx_add_elevation" value="標高を追加" checked />
<button onclick="execute()">実行</button>

<textarea id="gpx_before" style="width:100%; height:200px;" readonly></textarea>
<textarea id="gpx_after" style="width:100%; height:200px;" readonly></textarea>


text:
(function (app) {
  'use strict';

  app.registerModule('submissions');
})(ApplicationConfiguration);


text:
layout: default
description: The document section offers a editor which let you edit documents and edges of a collection
---
Document
========

The document section offers a editor which let you edit documents and edges of a collection.

![Document](images/documentView.png)

Functions:

 - Edit document
 - Save document
 - Delete docment
 - Switch between Tree/Code - Mode
 - Create a new document

Information:

 - Displays: _id, _rev, _key properties


text:
package com.gravity.goose

import images.Image
import junit.framework.Assert._
import com.gravity.goose.extractors.AdditionalDataExtractor
import org.jsoup.nodes.Element

/**
 * Created by Jim Plush
 * User: jim
 * Date: 8/19/11
 */

object TestUtils {

  val staticHtmlDir = "/com/gravity/goose/statichtml/"
  private val NL = '\n';
  private val TAB = "\t\t";
  val articleReport = new StringBuilder("=======================::. ARTICLE REPORT .::======================\n");

  val DEFAULT_CONFIG: Configuration = new Configuration
  val NO_IMAGE_CONFIG: Configuration = new Configuration
  NO_IMAGE_CONFIG.enableImageFetching = false

  object additionalExt extends AdditionalDataExtractor {
    override def extract(rootElement: Element) = {
      println()
      println("ADDITIONAL DATA EXTRACTOR CALLED")
      println()
      Map("test" -> "success")
    }
  }

  val ADDITIONAL_DATA_CONFIG = new Configuration
  ADDITIONAL_DATA_CONFIG.setAdditionalDataExtractor(additionalExt)

  /**
  * returns an article object from a crawl
  */
  def getArticle(url: String, rawHTML: String = null)(implicit config: Configuration): Article = {
    val goose = new Goose(config)
    val article = goose.extractContent(url, rawHTML)
//    goose.shutdownNetwork()
    article
  }

  def runArticleAssertions(article: Article, expectedTitle: String = null, expectedStart: String = null, expectedImage: String = null, expectedDescription: String = null, expectedKeywords: String = null): Unit = {
    articleReport.append("URL:      ").append(TAB).append(article.finalUrl).append(NL)
    articleReport.append("TITLE:    ").append(TAB).append(article.title).append(NL)
    articleReport.append("IMAGE:    ").append(TAB).append(article.topImage.getImageSrc).append(NL)
    articleReport.append("IMGKIND:  ").append(TAB).append(article.topImage.imageExtractionType).append(NL)
    articleReport.append("CONTENT:  ").append(TAB).append(article.cleanedArticleText.replace("\n", "    ")).append(NL)
    articleReport.append("METAKW:   ").append(TAB).append(article.metaKeywords).append(NL)
    articleReport.append("METADESC: ").append(TAB).append(article.metaDescription).append(NL)
    articleReport.append("DOMAIN:   ").append(TAB).append(article.domain).append(NL)
    articleReport.append("LINKHASH: ").append(TAB).append(article.linkhash).append(NL)
    articleReport.append("MOVIES:   ").append(TAB).append(article.movies).append(NL)
    articleReport.append("TAGS:     ").append(TAB).append(article.tags).append(NL)
    articleReport.append("PUBDATE:  ").append(TAB).append(article.publishDate).append(NL)

    assertNotNull("Resulting article was NULL!", article)

    if (expectedTitle != null) {
      val title: String = article.title
      assertNotNull("Title was NULL!", title)
      assertEquals("Expected title was not returned!", expectedTitle, title)
    }
    if (expectedStart != null) {
      val articleText: String = article.cleanedArticleText
      assertNotNull("Resulting article text was NULL!", articleText)
      assertTrue("Article text was not as long as expected beginning!", expectedStart.length <= articleText.length)
      val actual: String = articleText.substring(0, expectedStart.length)
      assertEquals("The beginning of the article text was not as expected!", expectedStart, actual)
    }
    if (expectedImage != null) {
      val image: Image = article.topImage
      assertNotNull("Top image was NULL!", image)
      val src: String = image.getImageSrc
      assertNotNull("Image src was NULL!", src)
      assertEquals("Image src was not as expected!", expectedImage, src)
    }
    if (expectedDescription != null) {
      val description: String = article.metaDescription
      assertNotNull("Meta Description was NULL!", description)
      assertEquals("Meta Description was not as expected!", expectedDescription, description)
    }
    if (expectedKeywords != null) {
      val keywords: String = article.metaDescription
      assertNotNull("Meta Keywords was NULL!", keywords)
      assertEquals("Meta Keywords was not as expected!", expectedKeywords, keywords)
    }
  }

  def printReport() {
    println(articleReport)
  }
}


text:
require 'beaker-rspec/spec_helper'
require 'beaker-rspec/helpers/serverspec'

unless ENV['RS_PROVISION'] == 'no'
  # This will install the latest available package on el and deb based
  # systems fail on windows and osx, and install via gem on other *nixes
  foss_opts = { :default_action => 'gem_install' }

  if default.is_pe?; then install_pe; else install_puppet( foss_opts ); end

  hosts.each do |host|
    if host['platform'] =~ /debian/
      on host, 'echo \'export PATH=/var/lib/gems/1.8/bin/:${PATH}\' >> ~/.bashrc'
    end

    on host, "mkdir -p #{host['distmoduledir']}"
  end
end

UNSUPPORTED_PLATFORMS = ['Ubuntu','windows','AIX']

RSpec.configure do |c|
  # Project root
  proj_root = File.expand_path(File.join(File.dirname(__FILE__), '..'))

  # Readable test descriptions
  c.formatter = :documentation
  c.order     = :defined

  # Configure all nodes in nodeset
  c.before :suite do
    # Install module and dependencies

    copy_module_to(master, :source => proj_root, :module_name => 'oracle')

    unless ENV['BEAKER_provision'] == 'no'
      modules = [
        'hajee-easy_type',
        'biemond-oradb',
        'erwbgy-limits',
        'fiddyspence-sysctl',
        'puppetlabs-stdlib',
      ]

      modules.each do  |module_name |
        on(default, puppet('module', 'install', module_name), :acceptable_exit_codes => [0,1] )
      end
      on(default, 'mkdir /software')
      files = (1..3).collect {|no| "#{proj_root}/.vendor/p13390677_112040_Linux-x86-64_#{no}of7.zip"}
      files.each {|f| scp_to default, f, '/software'}
      manifest = File.read("#{proj_root}/spec/acceptance/manifests/database.pp")
      apply_manifest manifest, { :catch_failures => true }
    end

  end
end


text:
import luigi
import sciluigi

import pyannote_workflows.tasks.speech
import pyannote_workflows.tasks.face
import pyannote_workflows.tasks.evaluation
import pyannote_workflows.tasks.tvd_dataset
import pyannote_workflows.tasks.propagation
import pyannote_workflows.utils
from pyannote.core import Segment, Annotation
import pyannote.core.json
from pprint import pprint

class _Openface(sciluigi.ExternalTask):

    workdir = luigi.Parameter()
    series = luigi.Parameter()
    season = luigi.IntParameter()
    episode = luigi.IntParameter()

    def out_put(self):
        TEMPLATE = '{workdir}/external/openface/{episode}.txt'
        path = TEMPLATE.format(
            workdir=self.workdir,
            episode=pyannote_workflows.tasks.tvd_dataset.get_episode(self))
        return sciluigi.TargetInfo(self, path)

class OneFace(sciluigi.WorkflowTask):

    workdir = luigi.Parameter(default='/work')
    tvddir = luigi.Parameter(default='/tvd')
    series = luigi.Parameter(default='GameOfThrones')
    season = luigi.IntParameter(default=1)
    episode = luigi.IntParameter(default=1)
    language = luigi.Parameter(default='en')

    faceClustering__threshold = luigi.FloatParameter(default=0.4)

    bicClusteringFeatures__e = luigi.BoolParameter(default=True)
    bicClusteringFeatures__De = luigi.BoolParameter(default=False)
    bicClusteringFeatures__DDe = luigi.BoolParameter(default=False)
    bicClusteringFeatures__coefs = luigi.IntParameter(default=12)
    bicClusteringFeatures__D = luigi.BoolParameter(default=False)
    bicClusteringFeatures__DD = luigi.BoolParameter(default=False)

    bicClustering__penalty_coef = luigi.FloatParameter(default=3.5)
    bicClustering__covariance_type = luigi.Parameter(default='full')

    hyperopt = luigi.Parameter(default=None)

    def workflow(self):

        # =====================================================================
        # FACE CLUSTERING
        # =====================================================================

        openface = self.new_task(
            'openface',
            _Openface,
            workdir=self.workdir,
            series=self.series,
            season=self.season,
            episode=self.episode)

        precomputeFaceClustering = self.new_task(
            'precomputeFaceClustering',
            pyannote_workflows.tasks.face.PrecomputeClustering)

        precomputeFaceClustering.in_openface = openface.out_put

        faceClustering = self.new_task(
            'faceClustering',
            pyannote_workflows.tasks.face.Clustering,
            threshold=self.faceClustering__threshold)

        faceClustering.in_precomputed = precomputeFaceClustering.out_put

        # =====================================================================
        # SPEECH / NON-SPEECH
        # =====================================================================

        audio = self.new_task(
            'audio',
            pyannote_workflows.tasks.tvd_dataset.Audio,
            tvddir=self.tvddir,
            series=self.series,
            season=self.season,
            episode=self.episode,
            language=self.language)

        speakerReference = self.new_task(
            'speakerReference',
            pyannote_workflows.tasks.tvd_dataset.Speaker,
            workdir=self.workdir,
            tvddir=self.tvddir,
            series=self.series,
            season=self.season,
            episode=self.episode)

        speech = self.new_task(
            'speechReference',
            pyannote_workflows.tasks.tvd_dataset.Speech,
            to_annotation=True)

        speech.in_wav = audio.out_put
        speech.in_speaker = speakerReference.out_put

        # =====================================================================
        # MERGE SPEECH TURNS SHARING SAME UNIQUE FACE CLUSTER
        # =====================================================================

        conservativeDirectTagging = self.new_task(
            'conservativeDirectTagging',
            pyannote_workflows.tasks.propagation.ConservativeDirectTagging)

        conservativeDirectTagging.in_source = faceClustering.out_put
        conservativeDirectTagging.in_target = speech.out_put

        # =====================================================================
        # BIC CLUSTERING
        # =====================================================================

        bicClusteringFeatures = self.new_task(
            'bicClusteringFeatures',
            pyannote_workflows.tasks.speech.MFCC,
            e=self.bicClusteringFeatures__e,
            De=self.bicClusteringFeatures__De,
            DDe=self.bicClusteringFeatures__DDe,
            coefs=self.bicClusteringFeatures__coefs,
            D=self.bicClusteringFeatures__D,
            DD=self.bicClusteringFeatures__DD)

        bicClusteringFeatures.in_audio = audio.out_put

        bicClustering = self.new_task(
            'bicClustering',
            pyannote_workflows.tasks.speech.BICClustering,
            penalty_coef=self.bicClustering__penalty_coef,
            covariance_type=self.bicClustering__covariance_type)

        bicClustering.in_segmentation = conservativeDirectTagging.out_put
        bicClustering.in_features = bicClusteringFeatures.out_put

        # =====================================================================
        # EVALUATION
        # =====================================================================

        evaluateDiarization = self.new_task(
            'evaluateDiarization',
            pyannote_workflows.tasks.evaluation.EvaluateDiarizationFast)

        evaluateDiarization.in_hypothesis = bicClustering.out_put
        evaluateDiarization.in_reference = speakerReference.out_put

        if hasattr(self, 'auto_output'):
            pprint(self.auto_output)

        if self.hyperopt is not None:
            hyperopt = self.new_task(
                'hyperopt',
                pyannote_workflows.utils.Hyperopt,
                temp=self.hyperopt)
            hyperopt.in_evaluation = evaluateDiarization.out_put
            return hyperopt

        else:
            return evaluateDiarization


text:
workflow = context.portal_workflow
# Note: Also used by profiles/default/types/AnalysisRequest.xml

# Can't do anything to the object if it's cancelled
if workflow.getInfoFor(context, 'cancellation_state', "active") == "cancelled":
    return False

return True