text:
#ifndef _I_META_TABLE_H_
#define _I_META_TABLE_H_

#include "gnuc_defines.h"
#include <wchar.h>
#include "Api.h"
#include "CMemoryStore.h"

//! A Lua/Rgd variable
/*!
	Represents a variable found in a lua/rgd file.
*/
class RAINMAN_API IMetaNode
{
public:
	//! Constructor
	IMetaNode();

	//! Destructor
	virtual ~IMetaNode();

	//! RGD data types
	/*!
		The various types of data found in RGD files.
		Numbers match up to the type ID used in RGD files.
	*/
	enum eDataTypes
	{
		//! Floating point numeric data [float]
		DT_Float = 0,
		//! Interger numberic data (used in CoH for string references) [unsigned long]
		DT_Integer = 1,
		//! Boolean data [bool]
		DT_Bool = 2,
		//! ASCII text data [char*]
		DT_String = 3,
		//! Unicode text data [wchar_t*]
		DT_WString = 4,
		//! Table data
		DT_Table = 100,
		//! No data (not read or written to RGD, or unknown data type)
		DT_NoData = 254, // Hope Relic doesn't use 254 :)
	};

	//! Data for a Lua/Rgd table variable
	/*!
		The data for a IMetaNode that represents a table.
	*/
	class RAINMAN_API IMetaTable
	{
	public:
		//! Constructor
		IMetaTable(void);

		//! Destructor
		virtual ~IMetaTable(void);

		//! Get the number of children
		/*!
			\return Returns the number of children the table has. May throw a CRainmanException
		*/
		virtual unsigned long VGetChildCount() = 0;

		//! Get a specified child
		/*!
			\param[in] iIndex Range is 0 to VGetChildCount() - 1 (inclusive)
			\return Returns a valid pointer or throws a CRainmanException. You need to delete this pointer when you are done using it.
		*/
		virtual IMetaNode* VGetChild(unsigned long iIndex) = 0;

		//! Get the data type of the reference string
		/*!
			If the table has a Reference([[somefile]]) or Inherit([[somefile]]) then "somefile" is called the reference string
			The reference string can be a IMetaNode::DT_String, a IMetaNode::DT_WString, or there isn't one, it is IMetaNode::DT_NoData.
			\return Returns IMetaNode::DT_String, IMetaNode::DT_WString, IMetaNode::DT_NoData or throws a CRainmanException on error
		*/
		virtual IMetaNode::eDataTypes VGetReferenceType() = 0;

		//! Set the data type of the reference string
		/*!
			\param[in] eType The data type to set the reference to (IMetaNode::DT_String, IMetaNode::DT_WString or IMetaNode::DT_NoData)
			\return Returns nothing, but will throw a CRainmanException on error
			\see VGetReferenceType()
		*/
		virtual void VSetReferenceType(IMetaNode::eDataTypes eType) = 0;

		//! Get the reference string
		/*!
			Use only if VGetReferenceType() returns IMetaNode::DT_String
			\return Returns a valid pointer or throws a CRainmanException
			\see VGetReferenceWString()
		*/
		virtual const char* VGetReferenceString() = 0;

		//! Set the reference string
		/*!
			Make sure to set the data type to IMetaNode::DT_String before
			calling or the call may fail.
			\param[in] sValue The new reference string
			\return Returns nothing, but will throw a CRainmanException on error
			\see VGetReferenceType()
			\see VGetReferenceString()
		*/
		virtual void VSetReferenceString(const char* sValue) = 0;

		//! Get the reference string (unicode)
		/*!
			Use only if VGetReferenceType() returns IMetaNode::DT_WString
			\return Returns a valid pointer or throws a CRainmanException
			\see VGetReferenceType()
			\see VGetReferenceString()
		*/
		virtual const wchar_t* VGetReferenceWString() = 0;

		//! Set the reference string (unicode)
		/*!
			Make sure to set the data type to IMetaNode::DT_WString before
			calling or the call may fail.
			\param[in] wsValue The new reference string
			\return Returns nothing, but will throw a CRainmanException on error
			\see VGetReferenceType()
			\see VGetReferenceWString()
		*/
		virtual void VSetReferenceWString(const wchar_t* wsValue) = 0;

		//! Add a child to the table
		/*!
			The index of the new child need not be VGetChildCount() - 1
			If two IMetaTable objects both refer to the same table, and
			a child is added to one of them, then the other will also become
			aware of the existance of the child.
			\param[in] sName The name of the new child (cannot be the same as an existing child)
			\return A pointer to the newly created child, throws a CRainmanException on error. You need to delete this pointer when you are done using it (
		*/
		virtual IMetaNode* VAddChild(const char* sName) = 0;

		//! Delete a specified child
		/*!
			If two IMetaTable objects both refer to the same table, and a
			child is removed from one of them, then the other will also
			be updated.
			\param[in] iIndex Range is 0 to VGetChildCount() - 1 (inclusive)
			\return Returns nothing, but will throw a CRainmanException on error
		*/
		virtual void VDeleteChild(unsigned long iIndex) = 0;

		virtual bool VSupportsRefresh();
		virtual void VDoRefresh();
	};

	//! Get the data type of the variable
	/*!
		\return Returns the data type of the variabe, will throw a CRainmanException on error
	*/
	virtual eDataTypes VGetType() = 0;

	//! Set the data type of the variable
	/*!
		\param[in] eType The type to set the variable to
		The variable will be converted to the specified data type
		\return Returns nothing, but will throw a CRainmanException on error
	*/
	virtual void VSetType(eDataTypes eType) = 0;

	//! Get the name of the variable
	/*!
		Some variables have a hash, some have a name, some have both. Try this first, and then the hash.
		\return Will return an ASCII string, or return 0. If it returns 0, then
		you should try VGetNameHash() to get the hash of the name.
	*/
	virtual const char* VGetName() = 0;

	//! Set the name of the variable
	/*!
		Will set the name of the variable. If VSetName() throws an exception
		then you should try VSetNameHash() instead.
	*/
	virtual void VSetName(const char* sName) = 0;

	//! Get the hash of the name of the varialbe
	/*!
		RGDs store the hash of the name, and any hash values not
		found in the dictionary will not have an ASCII name. In
		this case you should use the name hash. Luas store the
		name, and not the hash, so use VGetName() for Luas.

		In conclusion, use VGetName() first, and if it returns 0
		then try this.
	*/
	virtual unsigned long VGetNameHash();

	//! Set the hash of the name of the variable
	/*!
		Lua files cannot have a name set by hash, whereas Rgd files can.
		Use VSetName() before you try and use this, as a hash can be obtained from a name but no vice verca
		\param[in] iHash The hash to set the name to
		\return Returns no values, but throws a CRainmanException on error
		\see VGetNameHash()
	*/
	virtual void VSetNameHash(unsigned long iHash);

	// Floats, Bools, Strings , WStrings

	//! Get the value of the variable as a floating point number
	/*!
		Use only if VGetType() returns IMetaNode::DT_Float
		\return Returns the value, or throws a CRainmanException
	*/
	virtual float VGetValueFloat() = 0;

	//! Set the value of the variable to a floating point number
	/*!
		Make sure that the data type is set to IMetaNode::DT_Float
		using VSetType() before calling.
		\param[in] fValue The value
		\return Returns no value, but throws a CRainmanException on error
	*/
	virtual void VSetValueFloat(float fValue) = 0;

	//! Get the value of the variable as an integer number
	/*!
		Use only if VGetType() returns IMetaNode::DT_Integer
		\return Returns the value, or throws a CRainmanException
	*/
	virtual unsigned long VGetValueInteger() = 0;

	//! Set the value of the variable to an integer number
	/*!
		Make sure that the data type is set to IMetaNode::DT_Integer
		using VSetType() before calling.
		\param[in] iValue The value
		\return Returns no value, but throws a CRainmanException on error
	*/
	virtual void VSetValueInteger(unsigned long iValue) = 0;

	//! Get the value of the variable as a boolean
	/*!
		Use only if VGetType() returns IMetaNode::DT_Bool
		\return Returns the value, or throws a CRainmanException
	*/
	virtual bool VGetValueBool() = 0;

	//! Set the value of the variable to a boolean
	/*!
		Make sure that the data type is set to IMetaNode::DT_Bool
		using VSetType() before calling.
		\param[in] bValue The value
		\return Returns no value, but throws a CRainmanException on error
	*/
	virtual void VSetValueBool(bool bValue) = 0;

	//! Get the value of the variable as an ASCII string
	/*!
		Use only if VGetType() returns IMetaNode::DT_String
		\return Returns the value, or throws a CRainmanException
	*/
	virtual const char* VGetValueString() = 0;

	//! Set the value of the variable to an ASCII string
	/*!
		Make sure that the data type is set to IMetaNode::DT_String
		using VSetType() before calling.
		\param[in] sValue The value
		\return Returns no value, but throws a CRainmanException on error
	*/
	virtual void VSetValueString(const char* sValue) = 0;

	//! Get the value of the variable as a unicode string
	/*!
		Use only if VGetType() returns IMetaNode::DT_WString
		\return Returns the value, or throws a CRainmanException
	*/
	virtual const wchar_t* VGetValueWString() = 0;

	//! Set the value of the variable to a unicode string
	/*!
		Make sure that the data type is set to IMetaNode::DT_WString
		using VSetType() before calling.
		\param[in] wsValue The value
		\return Returns no value, but throws a CRainmanException on error
	*/
	virtual void VSetValueWString(const wchar_t* wsValue) = 0;

	//! Get the value of the variable as a table
	/*!
		A variable cannot be set to a metatable (eg. there is no VSetValueMetatable() ), instead you set the data type
		to IMetaNode::DT_Table, do a VGetValueMetatable() and then manipulate the returned pointer.
		\return Will throw an exception or return a valid pointer
		\attention You must delete the return value when you are finished using it
	*/
	virtual IMetaTable* VGetValueMetatable() = 0;

	//! Write this node as application/x-rainman-rgd psuedo mime type
	/*!
		To allow Metanodes to be copy & pasted around, they have to have a common format for interchange.
		This function must be implemented as to return a stream of data which is "application/x-rainman-rgd".
		Format for this data is:

		<4 bytes unsigned> NameHash

		<4 bytes unsigned> NameLen (set to 0 = name unknown; must have a valid hash in this case)

		<N bytes> Name

		<1 byte> DataType

		<4 bytes unsigned> DataLength (for string: strlen, for wstring: wcslen, for table: number of children)

		<N bytes> Data

		For tables, data looks like:

		Child 1

		Child 2

		...
		\return A fresh memory output stream which will be later deleted by the calling code. May throw a CRainmanException, but will otherwise return a valid pointer
	*/
	virtual CMemoryStore::COutStream* VGetNodeAsRainmanRgd() = 0;

	//! Set this node from a application/x-rainman-rgd psuedo mime type
	/*!
		\see VGetNodeAsRainmanRgd()
	*/
	virtual void SGetNodeFromRainmanRgd(IFileStore::IStream* pInput, bool bSetName = false) = 0;
};

#endif


text:
beep_on_error(1);
warning("error",'Octave:divide-by-zero');

% mybasedir='/Users/hasanogul/jaakkos_files/synergy/mlprojects/';
% h3k4me3dir='/Users/hasanogul/jaakkos_files/synergy/synergy_data/H3K4me3/Mapping_results/'
% pol2dir='/Users/hasanogul/jaakkos_files/synergy/synergy_data/PolII/Mapping_results/'
% analysisdir='/Users/hasanogul/jaakkos_files/synergy/analyses/'

mybasedir='~/synergy_data/tempcodebranch/';
h3k4me3dir='~/synergy_data/H3K4me3/Mapping_results/'
pol2dir='~/synergy_data/PolII/Mapping_results/'
rnadir='~/synergy_data/RNA/Mapping_results/'
analysisdir='~/synergy_data/analyses/'

% for kernel-level computations
path1=[mybasedir 'kern/matlab/jaakko_testversion/']
% for model-level computations
path2=[mybasedir 'gpsim/matlab/jaakko_testversion/'];
% for optimiDefaultConstraint.m
path3=[mybasedir 'optimi/matlab/jaakko_testversion/'];
% for lnDiffErfs.m
path4=[mybasedir 'ndlutil/matlab/'];
% for addPrior.m
path5=[mybasedir 'prior/matlab/'];
% for dist2.m
path6=[mybasedir 'matlab/netlab/NETLAB3p3/'];
% for modelTieParam.m
path7=[mybasedir 'mltools/matlab/'];
% for various experiment things
path8=[mybasedir 'pol2rnaseq/matlab/'];

addpath(path1,path2,path3,path4,path5,path6,path7,path8)

cd(pol2dir)
load pol2_for_matti_ver3.mat   % provides variable bininfo

load all_gene_pol2bins.mat  % provides: pol2bins
load all_empty_pol2bins.mat % provides: allemptybins emptybininfo
n_timepoints=10;

%  bininfo(i,1)=line_chrindex;                    % chromosome index
%  bininfo(i,2)=str2double(genetemp{3}(2:end-1)); % start location
%  bininfo(i,3)=str2double(genetemp{4}(2:end-1)); % end location
%  bininfo(i,4)=i;                                % file line number
%  bininfo(i,5)=geneids(i);                       % ensembl id
%  bininfo(i,6)=genestrands(i);                   % strand sign (+1 or -1)

binlengths=zeros(size(pol2bins,1),1);
for k=1:size(pol2bins,1),
  binlengths(k)=length(pol2bins{k,1});
end;

%-----------------------------------------------------------------
% Read in exon information
%-----------------------------------------------------------------
fprintf(1,'Reading in exons\n');

cd(rnadir);
exonfile=read_stringfile('exons.txt',[32 9 10 13]);
firstexonstarts=ones(size(bininfo,1),1)*nan;
for k=1:(length(exonfile)-1)/4,
  if mod(k,100)==0,
    k
  end;

  ensemblid=str2double(exonfile{(k-1)*4+2}{1}(5:end));
  for l=1:length(exonfile{(k-1)*4+3}),
    exonstarts(l)=str2double(exonfile{(k-1)*4+4}{l});
  end;
  for l=1:length(exonfile{(k-1)*4+4}),
    exonends(l)=str2double(exonfile{(k-1)*4+5}{l});
  end;
  % all we actually need for now is the start of the first exon
  firstexonstart=min(exonstarts);

  % find the index in bininfo that corresponds to this ensembl-id
  gene_index=find(bininfo(:,5)==ensemblid);
  if length(gene_index)==1,
    firstexonstarts(gene_index)=firstexonstart;
  end;
end;

% find the bin corresponding to the exon start
firstexonbins=ones(size(bininfo,1),1)*nan;
nextexonbins=ones(size(bininfo,1),1)*nan;
for k=1:size(bininfo,1),
  if mod(k,100)==0,
    k
  end;

  if ~isnan(firstexonstarts(k)),
    % start of the first exon -30bp
    differencefromend=bininfo(k,3)-(firstexonstarts(k)-30);
    firstexonbins(k)=1+floor(differencefromend/200);
    if firstexonbins(k)>binlengths(k), firstexonbins(k)=binlengths(k);end;

    % start of first exon + 20% towards the end
    differencefromend=floor(0.8*(bininfo(k,3)-firstexonstarts(k)));
    if differencefromend < -200,
      nextexonbins(k)=-100;
    elseif differencefromend < 0,
      nextexonbins(k)=0;
    else
      nextexonbins(k)=1+floor(differencefromend/200);
    end;
    if nextexonbins(k)==0, nextexonbins(k)=1;end;

  else
    % just take the start of the gene
    firstexonbins(k)=binlengths(k);
    if firstexonbins(k)>binlengths(k), firstexonbins(k)=binlengths(k);end;

    % start of the gene + 20% towards the end
    differencefromend=floor(0.8*(bininfo(k,3)-bininfo(k,2)));
    if differencefromend < -200,
      nextexonbins(k)=-100;
    elseif differencefromend < 0,
      nextexonbins(k)=0;
    else
      nextexonbins(k)=1+floor(differencefromend/200);
    end;
    if nextexonbins(k)==0, nextexonbins(k)=1;end;
  end;
end;

%-----------------------------------------------------------------
% Perform noise thresholding
%-----------------------------------------------------------------

% For each time point, compute a noise level (average activity per
% bin in hand-picked 'empty regions'. Note that the empty regions
% have been hand-picked based on POL2 activity from chromosome 1 only.
emptysums=zeros(n_timepoints,1);nemptybins=zeros(n_timepoints,1);
for k=1:n_timepoints,
  k
  for l=1:74,
    emptysums(k)=emptysums(k)+sum(allemptybins{l,k});
    nemptybins(k)=nemptybins(k)+length(allemptybins{l,k});
  end;
end;
noiselevels=emptysums./nemptybins;

apply_noisethreshold=1;
if apply_noisethreshold,
  %---------------------------------------------------
  % Substract noise level,
  % thresholding values below noise level to zero.
  %---------------------------------------------------
  for l=1:n_timepoints,
    l
    for k=1:size(pol2bins,1),
      pol2bins{k,l}=pol2bins{k,l}-noiselevels(l);
      I=find(pol2bins{k,l}<0);
      pol2bins{k,l}(I)=0;
    end;
  end;
end;

%-----------------------------------------------------------------
% Compute geometric mean - median based normalization factors for
% time points
%-----------------------------------------------------------------

% find genes that have a sufficient level above noise in all time points
genemeans=zeros(size(pol2bins,1),n_timepoints);
for k=1:size(pol2bins,1),
  if mod(k,1000)==0,
    k
  end;

  for l=1:n_timepoints,
    if length(pol2bins{k,l})>0,
      genemeans(k,l)=mean(pol2bins{k,l});
    end;
  end;
end;
readthreshold=5*200;
enoughdata=genemeans>readthreshold;

% compute geommeanmedian normalization from the above selected genes, using sum over whole gene
tempgeommeans=zeros(size(pol2bins,1),1);
for i=1:size(pol2bins,1),
  if mod(i,1000)==0,
    i
  end;
  % find the time points of this gene that have enough data,
  % excluding the first time point
  Igeommean=find(enoughdata(i,2:n_timepoints)==1)+1;

  % compute geometric mean of the selected time points for this gene
  if length(Igeommean>0),
    tempgeommeans(i)=exp(mean(log(genemeans(i,Igeommean))));
  end;
end;
% compute the normalization factors for the time points as a median
% normalization factor across genes.
Imedians=find(tempgeommeans>0);
tempmedians=zeros(1,n_timepoints);
tempmedians(1)=1;
for j=2:n_timepoints,
  tempmedians(j)=median(genemeans(Imedians,j)./tempgeommeans(Imedians));
end;

%-----------------------------------------------------------------
% Create POL2 summary series
%-----------------------------------------------------------------

% Version 3: sum of last few bins (fixed fraction of gene length,
% towards the end of the gene), normalized by total length of those bins
polsummaryfraction=0.2;
% polsummaryoffsetfraction=0;
pol2_summaryseries_start=nan*ones(size(pol2bins,1),n_timepoints);
pol2_summaryseries_middle=nan*ones(size(pol2bins,1),n_timepoints);
pol2_summaryseries_end=nan*ones(size(pol2bins,1),n_timepoints);
for i=1:size(pol2bins,1),
  if mod(i,100)==0,
    i
  end;

  % summarize by first bins
  % (note that first bins = bins closest to transcription end)
  polsummarylength=ceil(binlengths(i)*polsummaryfraction);
  % polsummaryoffset=ceil(binlengths(i)*polsummaryoffsetfraction);

  start_begin=firstexonbins(i);
  middle_begin=nextexonbins(i);
  end_begin=polsummarylength;
  start_length=start_begin-middle_begin;
  middle_length=middle_begin-end_begin;
  end_length=end_begin;

  if (binlengths(i)>=start_begin) && (start_begin>middle_begin) && (middle_begin>end_begin) && (end_begin>=1),
    for j=1:n_timepoints,
      pol2_summaryseries_start(i,j)=sum(pol2bins{i,j}(middle_begin+1:start_begin))/(start_length*200);
      pol2_summaryseries_middle(i,j)=sum(pol2bins{i,j}(end_begin+1:middle_begin))/(middle_length*200);
      pol2_summaryseries_end(i,j)=sum(pol2bins{i,j}(1:end_begin))/(end_length*200);
    end;
  end;
end;

%---------------------------------------------------
% normalize H3K4me3 time points by noise levels estimated
% from geommean procedure earlier.
%---------------------------------------------------
for j=1:n_timepoints,
  pol2_summaryseries_start(:,j)=pol2_summaryseries_start(:,j)/tempmedians(j);
  pol2_summaryseries_middle(:,j)=pol2_summaryseries_middle(:,j)/tempmedians(j);
  pol2_summaryseries_end(:,j)=pol2_summaryseries_end(:,j)/tempmedians(j);
end;

beep();

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Maruamyu\Core;

/**
 * 乱数生成系のユーティリティ
 */
class Randomizer
{
    /**
     * @param int $min
     * @param int $max
     * @return int
     * @see random_int()
     * @see mt_rand()
     */
    public static function randomInt($min, $max)
    {
        if (function_exists('random_int')) {
            try {
                return random_int($min, $max);
            } catch (\Exception $exception) {
                # do nothing...
            }
        }
        return mt_rand($min, $max);
    }

    /**
     * @param int $length
     * @return string
     * @see random_bytes()
     * @see openssl_random_pseudo_bytes()
     */
    public static function randomBytes($length)
    {
        if (function_exists('random_bytes')) {
            try {
                return random_bytes($length);
            } catch (\Exception $exception) {
                # do nothing...
            }
        }

        if (function_exists('openssl_random_pseudo_bytes')) {
            return openssl_random_pseudo_bytes($length);
        }

        $randomBytes = '';
        for ($i = 0; $i < $length; $i++) {
            $randomBytes .= chr(mt_rand(0, 255));
        }
        return $randomBytes;
    }

    /**
     * @param int $length
     * @return string
     */
    public static function generateToken($length = 32)
    {
        $randomBytes = static::randomBytes($length);
        return substr(strtr(base64_encode($randomBytes), '+/', '-_'), 0, $length);
    }

    /**
     * @return string
     */
    public static function generateUuid()
    {
        return Uuid::generate();
    }

    /**
     * @return string
     */
    public static function generateUlid()
    {
        return Ulid::generate();
    }

    /**
     * constructor (private)
     */
    private function __construct()
    {
    }
}


text:
using System;
using System.ComponentModel;

#if WINDOWS_UWP

namespace Xamarin.Forms.Platform.UWP
#else

namespace Xamarin.Forms.Platform.WinRT
#endif
{
	public class StepperRenderer : ViewRenderer<Stepper, StepperControl>
	{
		protected override void OnElementChanged(ElementChangedEventArgs<Stepper> e)
		{
			base.OnElementChanged(e);

			if (e.NewElement != null)
			{
				if (Control == null)
				{
					SetNativeControl(new StepperControl());
					Control.ValueChanged += OnControlValue;
				}

				UpdateMaximum();
				UpdateMinimum();
				UpdateValue();
				UpdateIncrement();
			}
		}

		protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
		{
			base.OnElementPropertyChanged(sender, e);

			if (e.PropertyName == Stepper.ValueProperty.PropertyName)
				UpdateValue();
			else if (e.PropertyName == Stepper.MaximumProperty.PropertyName)
				UpdateMaximum();
			else if (e.PropertyName == Stepper.MinimumProperty.PropertyName)
				UpdateMinimum();
			else if (e.PropertyName == Stepper.IncrementProperty.PropertyName)
				UpdateIncrement();
		}

		void OnControlValue(object sender, EventArgs e)
		{
			Element.SetValueCore(Stepper.ValueProperty, Control.Value);
		}

		void UpdateIncrement()
		{
			Control.Increment = Element.Increment;
		}

		void UpdateMaximum()
		{
			Control.Maximum = Element.Maximum;
		}

		void UpdateMinimum()
		{
			Control.Minimum = Element.Minimum;
		}

		void UpdateValue()
		{
			Control.Value = Element.Value;
		}
	}
}


text: test cookbook


text:
/* Created by yegor on 9/20/16. */

package ws.epigraph.types;

import org.jetbrains.annotations.Nullable;
import ws.epigraph.annotations.Annotations;
import ws.epigraph.names.TypeName;
import org.jetbrains.annotations.NotNull;

import java.util.List;

abstract class MapTypeImpl extends DatumTypeImpl implements MapType {

  public final @NotNull DatumType keyType;
  public final @NotNull DataType valueType;

  protected MapTypeImpl(
      @NotNull TypeName name,
      @NotNull List<@NotNull ? extends MapType> immediateSupertypes,
      @NotNull DatumType keyType,
      @NotNull DataType valueType,
      @Nullable DatumType declaredMetaType,
      @NotNull Annotations annotations
  ) {
    super(name, immediateSupertypes, declaredMetaType, annotations);
    this.keyType = keyType;
    this.valueType = valueType;
    if (keyType.metaType() != null) throw new IllegalArgumentException(
        String.format(
            "Map type '%s' key type '%s' should not have a meta-type",
            name, keyType.name()
        )
    );
  }

  @Override
  public final @NotNull TypeKind kind() { return TypeKind.MAP; }

  @Override
  @SuppressWarnings("unchecked")
  public @NotNull List<@NotNull ? extends MapType> immediateSupertypes() {
    return (List<? extends MapType>) super.immediateSupertypes();
  }

  @Override
  @SuppressWarnings("unchecked")
  public @NotNull List<@NotNull ? extends MapType> supertypes() {
    return (List<? extends MapType>) super.supertypes();
  }

  @Override
  public @NotNull DatumType keyType() { return keyType; }

  @Override
  public @NotNull DataType valueType() { return valueType; }

}


text:
<!DOCTYPE html>

    <title>Overhead - Results - overhead main load_test</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link href="/css/bootstrap.min.css" rel="stylesheet" media="screen">
    <link href="/css/repose.css" rel="stylesheet" media="screen">

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

      </button>
      Overhead

Running Tests

Applications

Results

Home

Results

main

load_test

Test Results

        <form method="POST">

                Name
                Description
                Started
                ART overhead
                Throughput overhead
                Error overhead
                Plugins
                Status
                Compare

                jenkins-repose-pt-static-adhoc-231
                adhoc test with performance flavor #1 with Repose
                2013-11-06T19:01:13+00:00
                26.0 ms
                -11.899999999999977 rps
                -3000160 total errors

                    SysstatsPlugin

CPU metrics

Kernel metrics

Memory Swap metrics

Memory page metrics

Memory utilization metrics

TCP Failure metrics

TCP

IP Failure metrics

IP metrics

Device Network metrics

Device Disk metrics

Device Network Failure metrics

                    ReposeJmxPlugin

Filter breakdown

Garbage Collection

JVM Memory

JVM Threads

Repose logs

    Completed

                      <input type="checkbox" name="compare[]" value="some-random-string+some-random2-string">

                jenkins-repose-pt-static-adhoc-231
                adhoc test with performance flavor #1 with Repose
                2013-11-06T19:01:13+00:00
                45 ms
                795.9 rps
                9 total errors

                    SysstatsPlugin

CPU metrics

Kernel metrics

Memory Swap metrics

Memory page metrics

Memory utilization metrics

TCP Failure metrics

TCP

IP Failure metrics

IP metrics

Device Network metrics

Device Disk metrics

Device Network Failure metrics

                    ReposeJmxPlugin

Filter breakdown

Garbage Collection

JVM Memory

JVM Threads

Repose logs

    In Progress

                      <input type="checkbox" name="compare[]" value="some-other-string">

                  <button type="submit" class="btn btn-primary">Compare Tests</button>

        </form>

Average Response Time

Error Count

Average Throughput

© Rackspace Hosting 2013


text:
package com.tracker.servlet.schedule;

import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.tracker.util.TaskUtil;

@SuppressWarnings("serial")
public class ScheduleStatComputation extends HttpServlet {

	private static final long DAY_IN_MILLIS = 1000*60*60*24;
	private static final long MIN_IN_MILLIS = 60*1000;

	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {

	    String date_param = req.getParameter("date");
	    Integer date = Integer.parseInt(date_param);

	    String duration_param = req.getParameter("duration");
	    Integer duration = Integer.parseInt(duration_param);

	    Calendar cal = Calendar.getInstance();
	    cal.setTime(new Date());
	    cal.set(Calendar.HOUR_OF_DAY, 0);
	    cal.set(Calendar.MINUTE, 0);
	    cal.set(Calendar.SECOND, 0);
	    cal.set(Calendar.MILLISECOND, 0);
	    cal.add(Calendar.DATE, -date);
	    for(long t = cal.getTimeInMillis(); t<cal.getTimeInMillis() + DAY_IN_MILLIS; t+=duration*MIN_IN_MILLIS) {
	        Map<String, String> params = new HashMap<String, String>();
	        params.put("diff", duration_param);
	        params.put("from", String.valueOf(t));
	        params.put("to", String.valueOf(t + duration*MIN_IN_MILLIS));
	        TaskUtil.queueTask("/computeArrivalCompletions", params);
	    }
	}

}


text: SELECT ROW_COUNT() FROM db_root;


text:
<?xml version="1.0" encoding="UTF-8"?>

<chapter xml:id="KEW_Reporting" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns="http://docbook.org/ns/docbook" version="5.0">
    <title>Reporting Guide</title>

        <title>Reporting Features</title>
        <para>KEW provides various options for reporting on and simulation of routing scenarios.
            There is a GUI for performing these reporting functions as well as an API that you
            can use to run routing reports against the system.</para>

        <title>The Routing Report Screen</title>
        <para>From the Rice main menu there is a link to the <emphasis role="bold">Routing
            Report</emphasis> screen. From this set of screens you can enter various
            criteria for running reports against the routing engine. The output of this
            reporting is a simulated view of the <emphasis role="bold">Route Log</emphasis>,
            displaying the result of the report.</para>

        <title>The Report APIs</title>
        <para>The KEW client API also provides facilities for running reports against the
            routing engine. At the core of KEW is a <emphasis role="bold">Simulation
                Engine</emphasis> that is responsible for running these types of reports. The
            method for executing these reports is on the Workflow Info object that is part of
            the client API. The method is defined:</para>
        <programlisting>public DocumentDetailVO routingReport(ReportCriteriaVO reportCriteria) throws WorkflowException;</programlisting>
        <para>This method takes the report criteria and returns the results of the routing
            report.</para>

        <title>Report Criteria</title>
        <para>The routing report operates under two basic modes:<orderedlist>
            <listitem>
                <para>Reports that run against existing Documents </para>
            </listitem>
            <listitem>
                <para>Reports that simulate a Document from a Document Type </para>
            </listitem>
        </orderedlist></para>
        <para>In each these cases there are certain properties that you need to set on the
            ReportCriteriaVO to obtain the desired results.</para>
        <para>In the first case, the report runs against a document that has already been
            created in the system. This document already has a Document Id and may be en route.
            Using this style of reporting, you can run simulations to determine where the
            document will go in future route nodes. For example, to run a simulation against an
            existing document to determine to whom it will route in the future, execute this
            code:</para>

            <title>Routing Report against a Document</title>
            <programlisting>WorkflowInfo info = new WorkflowInfo();
RoutingReportCriteriaVO criteria = new ReportCriteriaVO(new Long(1234));
DocumentDetailVO results = info.routingReport(criteria);
// examine results...
</programlisting>
            <para>This runs a report against the document with ID 1234, starting at the active
                nodes of the document and continuing to the terminal nodes of the document. The
                DocumentDetailVO will contain the Action Requests generated during the report
                simulation.</para>
            <para>You can also stop the report at a particular node or once Rice generates a
                request for a particular user. For example, to stop the report simulation at a
                node or when Rice generates a certain user's request, configure the report
                criteria like this:</para>

            <title>Terminate Report at Node or User</title>
            <programlisting>WorkflowInfo info = new WorkflowInfo();

RoutingReportCriteriaVO criteria = new ReportCriteriaVO(new Long(1234), "MyNodeName");
criteria.setTargetUsers(new UserIdVO[] { new NetworkIdVO("ewestfal") });

DocumentDetailVO results = info.routingReport(criteria);
</programlisting>
            <para>This executes the report until it reaches a node named <emphasis role="bold"
                >MyNodeName</emphasis> or a request is generated for user <emphasis
                    role="bold">ewestfal</emphasis>.</para>
            <para>In the second style of reporting, the report is run against an arbitrary
                Document Type and the simulation engine creates a temporary document against
                which to run the report. When setting up the report criteria for these
                scenarios, you usually populate the XML content of the document on the criteria
                (provided that the routing of that document evaluates the XML). Also, the
                criteria need to be configured with the valid node names (or rule templates)
                against which the report should be run. For example, to run a Document Type
                report, you can invoke the routing report this way:</para>

            <title>Report against a Document Type</title>
            <programlisting>WorkflowInfo info = new WorkflowInfo();
RouteReportCriteriaVO criteria = new ReportCriteriaVO("MyDocumentType");

criteria.setXmlContent("<accountNumber>1234</accountNumber>");

criteria.setNodeNames(new String[] { "MyNodeName" });
DocumentDetailVO results = info.routingReport(criteria);
</programlisting>
            <para>The code above simulates the generation of requests for <emphasis role="bold"
                >MyDocumentType</emphasis> at the <emphasis role="bold"
                    >MyNodeName</emphasis> node with the XML given. This sort of reporting is
                especially useful if you simply need to determine what rules in the rule system
                will fire and generate action requests under a particular scenario.</para>
            <para>As an alternative to specifying the node names, you can also specify rule
                template names. This is simply another way to target a specific node in the
                document. It searches the Document Type definition for nodes with the specified
                rule templates and then runs the report against those nodes. Currently, the rule
                template must exist on a node in the Document Type definition or an error will
                be thrown. In the case of our previous example, you could simply change the line
                that sets the node names on the criteria to:</para>
            <programlisting>criteria.setRuleTemplateNames(new String[] { "MyRuleTemplate" });</programlisting>
            <para>As above, this is primarily useful for determining who will have requests
                generated to them from the KEW rule system.</para>

        <title>Interpreting Report Results</title>
        <para>As we've seen, the object returned by the Routing Report is an instance of
            DocumentDetailVO. This object extends RouteHeaderVO and provides three more pieces
            of data along with it:<orderedlist>
                <listitem>
                    <para>An array of ActionRequestVO objects representing the action requests
                        on the document </para>
                </listitem>
                <listitem>
                    <para>An array of ActionTakenVO objects representing the actions that have
                        been performed against the document </para>
                </listitem>
                <listitem>
                    <para>An array of RouteNodeInstanceVO objects that represent nodes in the
                        document path </para>
                </listitem>
            </orderedlist></para>
        <para>For reporting, the most important piece of data here is typically the
            ActionRequestVO objects. After running a report, this array contains the Action
            Requests that were generated as the result of the simulation. So, for example, in
            the example above where we run a document type report against the <emphasis
                role="bold">MyRuleTemplate</emphasis> rule template, this array contains all of
            the Action Requests that were generated to users or workgroups during the report
            simulation.</para>

</chapter>


text:
								Ingresar

								Registro

								<form id="login-form" role="form" style="display: block;">

										<input type="text" name="username" id="username" tabindex="1" class="form-control" placeholder="Username" value="">

										<input type="password" name="password" id="password" tabindex="2" class="form-control" placeholder="Password">

										<input type="checkbox" tabindex="3" class="" name="remember" id="remember">
										 Remember Me

												<input type="submit" name="login-submit" id="login-submit" tabindex="4" class="form-control btn btn-login" value="Log In">

													Forgot Password?

								</form>

								<form id="register-form" action="<?php echo base_url()?>login_controller/usuario_agregar/" method="POST" style="display: none;">

										<input type="text" name="Nombre" id="Nombre" tabindex="1" class="form-control" placeholder="Nombre" value="">

										<input type="text" name="Apellido" id="Apellido" tabindex="1" class="form-control" placeholder="Apellido" value="">

										<input type="email" name="Email" id="email" tabindex="1" class="form-control" placeholder="Email" value="">

										<input type="email" name="Email2" id="email2" tabindex="1" class="form-control" placeholder="Confirmar email" value="">

										<input type="password" name="Clave" id="password" tabindex="2" class="form-control" placeholder="Clave">

										<input type="password" name="Clave2" id="confirm-password" tabindex="2" class="form-control" placeholder="Confirmar clave">

												<input type="submit" name="register-submit" id="register-submit" tabindex="4" class="form-control btn btn-register" value="Registrarse">

								</form>


text:
- Basic (words)
- [Twokenizer](https://github.com/brendano/ark-tweet-nlp/blob/master/src/cmu/arktweetnlp/Twokenize.java)

# Feature extractors
- unigrams
- n-grams
- unordered n-grams
- subsequnces


text:
(function(){
	"use strict";
	/*jshint maxstatements: 350*/

	var ruled;

	var scale = {
		first: function(min){
			return Math.floor(min / 10) * 10;
		},
		next: function(previous){
			return previous + 10;
		},
		label: function(value){
			return value;
		}
	};

	var formattedScale = {
		first: function(min){
			return Math.floor(min / 10) * 10;
		},
		next: function(previous){
			return previous + 10;
		},
		format: function(tick, startValue, endValue){
			if (startValue % (2 * 10) && endValue > 0) {
				tick.addClass("formatterTestClass");
			}
		},
		label: function(value){
			return value;
		}
	};

	var el = function(){return $("#test") };

	var ctorTest = new TestCase(
		"Ruler default ctor",
		function(){
			ruled = $("<div />").appendTo(el());
			ruled.ruler();
		},
		function(){
			QUnit.ok(ruled.hasClass("ui-ruler"), "ui-ruler class should have been added");
			ruled.remove();
		}
	);

	var dtorTest = new TestCase(
		"Ruler destructor",
		function(){
			ruled = $("<div />").appendTo(el());
			ruled.ruler({
				min: 0,
				max: 100,
				scales: [scale]
			});

			ruled.ruler("destroy");
		},
		function(){
			QUnit.ok(!ruled.hasClass("ui-ruler"), "ui-ruler class should have been removed");
			QUnit.equal(ruled.find("*").length, 0, "destroy should empty the element");
			ruled.remove();
			ruled = null;
		}
	);

	var ctorWithOneScale = new TestCase(
		"Ctor with one scale",
		function(){
			ruled = $("<div />").appendTo(el());
			ruled.ruler({
				min: 0,
				max: 10,
				scales: [scale]
			});
		},
		function(){
			var scale = ruled.find(".ui-ruler-scale"),
				tick = scale.find(".ui-ruler-tick"),
				label = tick.find(".ui-ruler-tick-label");

			QUnit.equal(scale.length, 1, "Should have created one scale");
			QUnit.equal(tick.length, 1, "Should have created one tick");
			QUnit.equal(label.length, 1, "Should have created one label");
			QUnit.equal(label.text(), "0", "Label text should be correct");
			QUnit.ok(scale.hasClass("ui-ruler-scale0"), "Class should have been initialized for first ruler");
			QUnit.ok(tick.attr("style") && tick.attr("style").indexOf("width: 100%") >= 0, "Width should be 100%: " + tick.attr("style"));

			ruled.ruler("destroy");
			ruled.detach();
		}
	);

	var formattedScaleWith4Ticks = new TestCase(
		"Formatting ticks with one scale of 4 ticks",
		function(){
			ruled = $("<div />").appendTo(el());
			ruled.ruler({
				min: 0,
				max: 40,
				scales: [formattedScale]
			});
		},
		function(){
			var scale = ruled.find(".ui-ruler-scale"),
				tick = scale.find(".ui-ruler-tick"),
				label = tick.find(".ui-ruler-tick-label"),
				formattedTick = scale.find(".formatterTestClass");

			QUnit.equal(scale.length, 1, "Should have created one scale");
			QUnit.equal(tick.length, 4, "Should have created four ticks");
			QUnit.equal(label.length, 4, "Should have created four labels");
			QUnit.equal(formattedTick.length, 2, "Should have created two labels");
			QUnit.ok(scale.hasClass("ui-ruler-scale0"), "Class should have been initialized for first ruler");
			QUnit.ok($(tick[0]).attr("style") && $(tick[0]).attr("style").indexOf("width: 25%") >= 0, "Width should be 25%: " + $(tick[0]).attr("style"));

			ruled.ruler("destroy");
			ruled.detach();
		}
	);

	var scaleStartingAfter = new TestCase(
		"Shifted scale starting after min",
		function(){
			ruled = $("<div />").appendTo(el());

			var shifted = $.extend({}, scale, {
				first: function(){
					return 10;
				}
			});

			ruled.ruler({
				min: 0,
				max: 20,
				scales: [shifted]
			});

		},
		function(){
			var scale = ruled.find(".ui-ruler-scale"),
				tick = scale.find(".ui-ruler-tick"),
				tickStyle = tick.attr("style");

			QUnit.equal(tick.length, 1, "Tick should have been created");
			QUnit.ok(tickStyle.indexOf("width: 50%") >= 0, "Width should be 50% " + tickStyle);
			QUnit.ok(tickStyle.indexOf("margin-left: 50%") >= 0, "Margin-left should be 50% " + tickStyle);

			ruled.ruler("destroy");
			ruled.detach();
		}
	);

	var lasttick = new TestCase(
		"Last tick should have been generated",
		function(){
			ruled = $("<div />").appendTo(el());

			ruled.ruler({
				min: 0,
				max: 25,
				scales: [scale]
			});
		},
		function(){
			var scale = ruled.find(".ui-ruler-scale"),
				tick = scale.find(".ui-ruler-tick"),
				tickStyle = scale.find(".ui-ruler-tick:last").attr("style");

			QUnit.equal(tick.length, 3, "Last tick should have been created");
			QUnit.ok(tickStyle.indexOf("width: 20%") >= 0, "Last tick should be shrinked: " + tickStyle);

			ruled.remove();
		}
	);

	var tickStop = new TestCase(
		"tests test stop",
		function(){
			ruled = $("<div />").appendTo(el());

			var scaleStop = $.extend({}, scale, {
					stop: function(value){
						return value === 30;
					}
				});

			ruled.ruler({
				min: 0,
				max: 100,
				scales: [scaleStop]
			});
		},
		function(){
			var scaleStop = ruled.find(".ui-ruler-scale"),
				ticks = scaleStop.find(".ui-ruler-tick");

			QUnit.equal(ticks.length, 3, "Should have stopped on false");

			ruled.remove();
		});

	var setMinOption = new TestCase(
		"Set min option after construction",
		function(){
			ruled = $("<div />").appendTo(el());
			ruled.ruler({
				min: 0,
				max: 100,
				scales: [scale]
			});

			ruled.ruler("option", "min", 50);
		},
		function(){
			var scale = ruled.find(".ui-ruler-scale"),
				ticks = scale.find(".ui-ruler-tick");

			QUnit.equal(ticks.length, 5, "Ruler should have been regenerated");

			ruled.remove();
		});

	var setMaxOption = new TestCase(
		"Set max option after construction",
		function(){
			ruled = $("<div />").appendTo(el());
			ruled.ruler({
				min: 0,
				max: 100,
				scales: [scale]
			});

			ruled.ruler("option", "max", 60);
		},
		function(){
			var scale = ruled.find(".ui-ruler-scale"),
				ticks = scale.find(".ui-ruler-tick");

			QUnit.equal(ticks.length, 6, "Ruler should have been regenerated");

			ruled.remove();
		});

	var setScalesOption = new TestCase(
		"Set scales options after construction",
		function(){
			ruled = $("<div />").appendTo(el());
			ruled.ruler({
				min: 0,
				max: 100,
				scales: [scale]
			});

			ruled.ruler("option", "scales", [scale, scale]);
		},
		function(){
			var scales = ruled.find(".ui-ruler-scale");

			QUnit.equal(scales.length, 2, "Ruler should have been regenerated");
			ruled.remove();
		});

	var dateRuler = new TestCase(
		"Ruler with dates",
		function(){
			var scale = {
				next: function(previous){
					var next = new Date(previous);
					return new Date(next.setDate(previous.getDate() + 2));
				},
				label: function(val){
					return val.toString();
				}
			}
			ruled = $("<div />").appendTo(el());
			ruled.ruler({
				min: new Date(2012, 0, 1),
				max: new Date(2012, 0, 6),
				scales: [scale]
			});
		},
		function(){
			var ticks = ruled.find(".ui-ruler-tick"),
				lasttick = ruled.find(".ui-ruler-tick:last"),
				style = ticks.attr("style"),
				lastStyle = lasttick.attr("style");

			QUnit.equal(ticks.length, 3, "ticks should have been created, even with dates");
			QUnit.ok(style.indexOf("width: 40%") >= 0, "ticks should have been correctly dimensionned: " + style);
			QUnit.ok(lastStyle.indexOf("width: 20%") >= 0, "Last tick should have been correctly shrinked: " + lastStyle);

			ruled.remove();
		});

	testRunner.add("ruler", [ctorTest, dtorTest,
		ctorWithOneScale,
		formattedScaleWith4Ticks,
		scaleStartingAfter,
		lasttick,
		tickStop,
		setMinOption, setMaxOption, setScalesOption,
		dateRuler]);
}());


text:
using System.Net;
using System.Net.Http;
using System.Web.Http.Filters;
using biz.dfch.CS.Commons.Diagnostics;

namespace biz.dfch.CS.Web.Utilities.Http
{
    public class CatchallExceptionFilterAttribute : ExceptionFilterAttribute
    {
        private static bool _suppressStackTrace = false;

        private static readonly TraceSource _traceSource = Logger.Get("biz.dfch.CS.Web.Utilities");

        public CatchallExceptionFilterAttribute()
        {
            // N/A
        }

        public CatchallExceptionFilterAttribute(bool suppressStackTrace)
        {
            _suppressStackTrace = suppressStackTrace;
        }

        public override void OnException(HttpActionExecutedContext context)
        {
            if (null == context || null == context.Exception)
            {
                return;
            }

            var ex = context.Exception;
            var message = string.Format(
                "{0}-EX {1}"
                ,
                context.ActionContext.Request.GetCorrelationId()
                ,
                ex.Message
                );

            _traceSource.TraceException(ex, message);

            if(_suppressStackTrace)
            {
                context.Response = context.Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex.Message);
            }
        }
    }
}


text:
package com.google.android.apps.iosched.io.model;

public class EventSlots {

    public Day[] day;
}


text:
"""Checks third-party licenses for the purposes of the Android WebView build.

The Android tree includes a snapshot of Chromium in order to power the system
WebView.  This tool checks that all code uses open-source licenses compatible
with Android, and that we meet the requirements of those licenses. It can also
be used to generate an Android NOTICE file for the third-party code.

It makes use of src/tools/licenses.py and the README.chromium files on which
it depends. It also makes use of a data file, third_party_files_whitelist.txt,
which whitelists indicidual files which contain third-party code but which
aren't in a third-party directory with a README.chromium file.
"""

import optparse
import os
import re
import subprocess
import sys
import textwrap

REPOSITORY_ROOT = os.path.abspath(os.path.join(
    os.path.dirname(__file__), '..', '..'))

sys.path.append(os.path.join(REPOSITORY_ROOT, 'tools'))
import licenses

import known_issues

def GetIncompatibleDirectories():
  """Gets a list of third-party directories which use licenses incompatible
  with Android. This is used by the snapshot tool.
  Returns:
    A list of directories.
  """

  whitelist = [
    'Apache( Version)? 2(\.0)?',
    '(New )?BSD( [23]-Clause)?( with advertising clause)?',
    'L?GPL ?v?2(\.[01])?( or later)?',
    'MIT(/X11)?(-like)?',
    'MPL 1\.1 ?/ ?GPL 2(\.0)? ?/ ?LGPL 2\.1',
    'MPL 2(\.0)?',
    'Microsoft Limited Public License',
    'Microsoft Permissive License',
    'Public Domain',
    'SGI Free Software License B',
    'X11',
  ]
  regex = '^(%s)$' % '|'.join(whitelist)
  result = []
  for directory in _FindThirdPartyDirs():
    if directory in known_issues.KNOWN_ISSUES:
      result.append(directory)
      continue
    try:
      metadata = licenses.ParseDir(directory, REPOSITORY_ROOT,
                                   require_license_file=False)
    except licenses.LicenseError as e:
      print 'Got LicenseError while scanning ' + directory
      raise
    if metadata.get('License Android Compatible', 'no').upper() == 'YES':
      continue
    license = re.split(' [Ll]icenses?$', metadata['License'])[0]
    tokens = [x.strip() for x in re.split(' and |,', license) if len(x) > 0]
    for token in tokens:
      if not re.match(regex, token, re.IGNORECASE):
        result.append(directory)
        break
  return result

class ScanResult(object):
  Ok, Warnings, Errors = range(3)

def _CheckLicenseHeaders(excluded_dirs_list, whitelisted_files):
  """Checks that all files which are not in a listed third-party directory,
  and which do not use the standard Chromium license, are whitelisted.
  Args:
    excluded_dirs_list: The list of directories to exclude from scanning.
    whitelisted_files: The whitelist of files.
  Returns:
    ScanResult.Ok if all files with non-standard license headers are whitelisted
    and the whitelist contains no stale entries;
    ScanResult.Warnings if there are stale entries;
    ScanResult.Errors if new non-whitelisted entries found.
  """

  excluded_dirs_list = [d for d in excluded_dirs_list if not 'third_party' in d]
  # Using a commond pattern for third-partyies makes the ignore regexp shorter
  excluded_dirs_list.append('third_party')
  # VCS dirs
  excluded_dirs_list.append('.git')
  excluded_dirs_list.append('.svn')
  # Build output
  excluded_dirs_list.append('out/Debug')
  excluded_dirs_list.append('out/Release')
  # 'Copyright' appears in license agreements
  excluded_dirs_list.append('chrome/app/resources')
  # This is a test output directory
  excluded_dirs_list.append('chrome/tools/test/reference_build')
  # This is tests directory, doesn't exist in the snapshot
  excluded_dirs_list.append('content/test/data')
  # This is a test output directory
  excluded_dirs_list.append('data/dom_perf')
  # Histogram tools, doesn't exist in the snapshot
  excluded_dirs_list.append('tools/histograms')
  # Arm sysroot tools, doesn't exist in the snapshot
  excluded_dirs_list.append('arm-sysroot')

  args = ['android_webview/tools/find_copyrights.pl',
          '.'
          ] + excluded_dirs_list
  p = subprocess.Popen(args=args, cwd=REPOSITORY_ROOT, stdout=subprocess.PIPE)
  lines = p.communicate()[0].splitlines()

  offending_files = []
  allowed_copyrights = '^(?:\*No copyright\*' \
      '|20[0-9][0-9](?:-20[0-9][0-9])? The Chromium Authors\. ' \
      'All rights reserved.*)$'
  allowed_copyrights_re = re.compile(allowed_copyrights)
  for l in lines:
    entries = l.split('\t')
    if entries[1] == "GENERATED FILE":
      continue
    copyrights = entries[1].split(' / ')
    for c in copyrights:
      if c and not allowed_copyrights_re.match(c):
        offending_files.append(os.path.normpath(entries[0]))
        break

  unknown = set(offending_files) - set(whitelisted_files)
  if unknown:
    print 'The following files contain a third-party license but are not in ' \
          'a listed third-party directory and are not whitelisted. You must ' \
          'add the following files to the whitelist.\n%s' % \
          '\n'.join(sorted(unknown))

  stale = set(whitelisted_files) - set(offending_files)
  if stale:
    print 'The following files are whitelisted unnecessarily. You must ' \
          ' remove the following files from the whitelist.\n%s' % \
          '\n'.join(sorted(stale))

  if unknown:
    return ScanResult.Errors
  elif stale:
    return ScanResult.Warnings
  else:
    return ScanResult.Ok

def _ReadFile(path):
  """Reads a file from disk.
  Args:
    path: The path of the file to read, relative to the root of the repository.
  Returns:
    The contents of the file as a string.
  """

  return open(os.path.join(REPOSITORY_ROOT, path), 'rb').read()

def _FindThirdPartyDirs():
  """Gets the list of third-party directories.
  Returns:
    The list of third-party directories.
  """

  # Please don't add here paths that have problems with license files,
  # as they will end up included in Android WebView snapshot.
  # Instead, add them into known_issues.py.
  prune_paths = [
    # Placeholder directory, no third-party code.
    os.path.join('third_party', 'adobe'),
    # Apache 2.0 license. See
    # https://code.google.com/p/chromium/issues/detail?id=140478.
    os.path.join('third_party', 'bidichecker'),
    # Isn't checked out on clients
    os.path.join('third_party', 'gles2_conform'),
    # The llvm-build doesn't exist for non-clang builder
    os.path.join('third_party', 'llvm-build'),
    # Binaries doesn't apply to android
    os.path.join('third_party', 'widevine'),
  ]
  third_party_dirs = licenses.FindThirdPartyDirs(prune_paths, REPOSITORY_ROOT)
  return licenses.FilterDirsWithFiles(third_party_dirs, REPOSITORY_ROOT)

def _Scan():
  """Checks that license meta-data is present for all third-party code and
     that all non third-party code doesn't contain external copyrighted code.
  Returns:
    ScanResult.Ok if everything is in order;
    ScanResult.Warnings if there are non-fatal problems (e.g. stale whitelist
      entries)
    ScanResult.Errors otherwise.
  """

  third_party_dirs = _FindThirdPartyDirs()

  # First, check designated third-party directories using src/tools/licenses.py.
  all_licenses_valid = True
  for path in sorted(third_party_dirs):
    try:
      licenses.ParseDir(path, REPOSITORY_ROOT)
    except licenses.LicenseError, e:
      if not (path in known_issues.KNOWN_ISSUES):
        print 'Got LicenseError "%s" while scanning %s' % (e, path)
        all_licenses_valid = False

  # Second, check for non-standard license text.
  files_data = _ReadFile(os.path.join('android_webview', 'tools',
                                      'third_party_files_whitelist.txt'))
  whitelisted_files = []
  for line in files_data.splitlines():
    match = re.match(r'([^#\s]+)', line)
    if match:
      whitelisted_files.append(match.group(1))
  licenses_check = _CheckLicenseHeaders(third_party_dirs, whitelisted_files)

  return licenses_check if all_licenses_valid else ScanResult.Errors

def GenerateNoticeFile():
  """Generates the contents of an Android NOTICE file for the third-party code.
  This is used by the snapshot tool.
  Returns:
    The contents of the NOTICE file.
  """

  third_party_dirs = _FindThirdPartyDirs()

  # Don't forget Chromium's LICENSE file
  content = [_ReadFile('LICENSE')]

  # We provide attribution for all third-party directories.
  # TODO(steveblock): Limit this to only code used by the WebView binary.
  for directory in third_party_dirs:
    metadata = licenses.ParseDir(directory, REPOSITORY_ROOT,
                                 require_license_file=False)
    license_file = metadata['License File']
    if license_file and license_file != licenses.NOT_SHIPPED:
      content.append(_ReadFile(license_file))

  return '\n'.join(content)

def main():
  class FormatterWithNewLines(optparse.IndentedHelpFormatter):
    def format_description(self, description):
      paras = description.split('\n')
      formatted_paras = [textwrap.fill(para, self.width) for para in paras]
      return '\n'.join(formatted_paras) + '\n'

  parser = optparse.OptionParser(formatter=FormatterWithNewLines(),
                                 usage='%prog [options]')
  parser.description = (__doc__ +
                       '\nCommands:\n' \
                       '  scan  Check licenses.\n' \
                       '  notice Generate Android NOTICE file on stdout')
  (options, args) = parser.parse_args()
  if len(args) != 1:
    parser.print_help()
    return ScanResult.Errors

  if args[0] == 'scan':
    scan_result = _Scan()
    if scan_result == ScanResult.Ok:
      print 'OK!'
    return scan_result
  elif args[0] == 'notice':
    print GenerateNoticeFile()
    return ScanResult.Ok

  parser.print_help()
  return ScanResult.Errors

if __name__ == '__main__':
  sys.exit(main())


text:
using ACE.Demo.Model.Accounts;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dapper;

namespace ACE.Demo.Repositories
{
    public class AccountRepository : BaseRepository, IAccountRepository
    {
        public Account Get(int id)
        {
            using (IDbConnection connection = OpenConnection())
            {
                return connection.Query<Account>("SELECT AccountId, Amount FROM ace_demo_account WHERE AccountId = @AccountId;",
                    new { AccountId = id }).SingleOrDefault();
            }
        }
    }
}


text: Hablo is a simple web messenger


text:
name 'macosx_accessibility_test'
maintainer 'Dennis Hoer'
maintainer_email 'dennis.hoer@gmail.com'
license 'MIT'
description 'Mac OS X Accessibility Test'
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version '0.1.0'

depends 'macosx_accessibility'


text:
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace Platformer
{
    public class Tile : GameObject
    {
        public const int Size = 64;

        public Point Position;
        public Point SourcePos;

        public bool IsBlock;
        public bool IsEmpty;

        public Rectangle Bounds => new Rectangle(Position.X, Position.Y, Size, Size);

        private Rectangle SourceBounds => new Rectangle(SourcePos.X, SourcePos.Y, Size, IsBlock ? Size : Size / 4 * 3);

        public Tile(Point position, int sourcePos, bool isBlock)
        {
            const float scale = Game1.BackBufferWidth / (float)20;
            Position = new Point((int)(position.X * scale), (int)(position.Y * scale));
            IsBlock = isBlock;

            if (sourcePos >= 0)
                SourcePos = new Point(Game1.Instance.Rand.Next(5) * 64, sourcePos);
            else
                IsEmpty = true;
        }

        public override void Update(List<GameObject> objects)
        {

        }

        public override void Draw(SpriteBatch sb)
        {
            sb.Draw(IsBlock ? TextureManager.Instance.GetTexture("BlockSheet") : IsEmpty ? TextureManager.Instance.GetTexture("EmptyBlock") : TextureManager.Instance.GetTexture("PlatformSheet"), Bounds, SourceBounds, Color.White);
        }
    }
}


text:
package ec.steadystate;
import ec.simple.*;
import ec.*;
import ec.util.Parameter;
import java.util.*;
import ec.eval.MasterProblem;

public class SteadyStateEvaluator extends SimpleEvaluator
    {
    LinkedList queue = new LinkedList();

    /** Holds the subpopulation currently being evaluated.  */
    int subpopulationBeingEvaluated = -1;

    /** Our problem. */
    SimpleProblemForm problem;

    public void setup(final EvolutionState state, final Parameter base)
        {
        super.setup(state,base);
        }

    public void prepareToEvaluate(EvolutionState state, int thread)
        {
        problem = (SimpleProblemForm)p_problem.clone();

        /*
           We only call prepareToEvaluate during Asynchronous Evolution.
        */
        if (problem instanceof MasterProblem)
            ((MasterProblem)problem).prepareToEvaluate(state, thread);
        }

    /** Submits an individual to be evaluated by the Problem, and adds it and its subpopulation to the queue. */
    public void evaluateIndividual(final EvolutionState state, Individual ind, int subpop)
        {
        problem.evaluate(state, ind, subpop, 0);
        queue.addLast(new QueueIndividual(ind, subpop));
        }

    /** Returns true if we're ready to evaluate an individual.  Ordinarily this is ALWAYS true,
        except in the asynchronous evolution situation, where we may not have a processor ready yet. */
    public boolean canEvaluate()
        {
        if (problem instanceof MasterProblem)
            return ((MasterProblem)problem).canEvaluate();
        else return true;
        }

    /** Returns an evaluated individual is in the queue and ready to come back to us.
        Ordinarily this is ALWAYS true at the point that we call it, except in the asynchronous
        evolution situation, where we may not have a job completed yet, in which case NULL is
        returned. Once an individual is returned by this function, no other individual will
        be returned until the system is ready to provide us with another one.  NULL will
        be returned otherwise.  */
    public Individual getNextEvaluatedIndividual()
        {
        QueueIndividual qind = null;

        if (problem instanceof MasterProblem)
            {
            if (((MasterProblem)problem).evaluatedIndividualAvailable())
                qind = ((MasterProblem)problem).getNextEvaluatedIndividual();
            }
        else
            {
            qind = (QueueIndividual)(queue.removeFirst());
            }

        if (qind == null) return null;

        subpopulationBeingEvaluated = qind.subpop;
        return qind.ind;
        }

    /** Returns the subpopulation of the last evaluated individual returned by getNextEvaluatedIndividual, or potentially -1 if
        getNextEvaluatedIndividual was never called or hasn't returned an individual yet. */
    public int getSubpopulationOfEvaluatedIndividual()
        {
        return subpopulationBeingEvaluated;
        }
    }


text:
@implementation RACModel

@end


text:
package com.equalinformation.poc.akka.scala.track1.wordcount.actors

import akka.actor.Actor
import scala.collection.immutable.Map
import scala.collection.mutable.HashMap

import com.equalinformation.poc.akka.scala.track1.wordcount._

/**
  * Created by bpupadhyaya on 2/10/16.
  */
class AggregateActor extends Actor {
  val finalReducedMap = new HashMap[String, Int]
  def receive: Receive = {
    case ReduceData(reduceDataMap) =>
      aggregateInMemoryReduce(reduceDataMap)
    case Result =>
      sender ! finalReducedMap.toString()
  }
  def aggregateInMemoryReduce(reducedList: Map[String, Int]): Unit = {
    for ((key,value) <- reducedList) {
      if (finalReducedMap contains key)
        finalReducedMap(key) = (value + finalReducedMap.get(key).get)
      else
        finalReducedMap += (key -> value)
    }
  }
}


text:
namespace dart {

class MaybeOnStackBuffer {
 public:
  explicit MaybeOnStackBuffer(intptr_t size) {
    if (size > kOnStackBufferCapacity) {
      p_ = reinterpret_cast<char*>(malloc(size));
    } else {
      p_ = &buffer_[0];
    }
  }
  ~MaybeOnStackBuffer() {
    if (p_ != &buffer_[0]) free(p_);
  }

  char* p() { return p_; }

 private:
  static const intptr_t kOnStackBufferCapacity = 4096;
  char* p_;
  char buffer_[kOnStackBufferCapacity];
};

JSONWriter::JSONWriter(intptr_t buf_size)
    : open_objects_(0), buffer_(buf_size) {}

void JSONWriter::AppendSerializedObject(const char* serialized_object) {
  PrintCommaIfNeeded();
  buffer_.AddString(serialized_object);
}

void JSONWriter::AppendSerializedObject(const uint8_t* buffer,
                                        intptr_t buffer_length) {
  buffer_.AddRaw(buffer, buffer_length);
}

void JSONWriter::AppendSerializedObject(const char* property_name,
                                        const char* serialized_object) {
  PrintCommaIfNeeded();
  PrintPropertyName(property_name);
  buffer_.AddString(serialized_object);
}

void JSONWriter::Clear() {
  buffer_.Clear();
  open_objects_ = 0;
}

void JSONWriter::OpenObject(const char* property_name) {
  PrintCommaIfNeeded();
  open_objects_++;
  if (property_name != NULL) {
    PrintPropertyName(property_name);
  }
  buffer_.AddChar('{');
}

void JSONWriter::UncloseObject() {
  intptr_t len = buffer_.length();
  ASSERT(len > 0);
  ASSERT(buffer_.buffer()[len - 1] == '}');
  open_objects_++;
  buffer_.set_length(len - 1);
}

void JSONWriter::CloseObject() {
  ASSERT(open_objects_ > 0);
  open_objects_--;
  buffer_.AddChar('}');
}

void JSONWriter::OpenArray(const char* property_name) {
  PrintCommaIfNeeded();
  if (property_name != NULL) {
    PrintPropertyName(property_name);
  }
  open_objects_++;
  buffer_.AddChar('[');
}

void JSONWriter::CloseArray() {
  ASSERT(open_objects_ > 0);
  open_objects_--;
  buffer_.AddChar(']');
}

void JSONWriter::PrintValueNull() {
  PrintCommaIfNeeded();
  buffer_.Printf("null");
}

void JSONWriter::PrintValueBool(bool b) {
  PrintCommaIfNeeded();
  buffer_.Printf("%s", b ? "true" : "false");
}

void JSONWriter::PrintValue(intptr_t i) {
  EnsureIntegerIsRepresentableInJavaScript(static_cast<int64_t>(i));
  PrintCommaIfNeeded();
  buffer_.Printf("%" Pd "", i);
}

void JSONWriter::PrintValue64(int64_t i) {
  EnsureIntegerIsRepresentableInJavaScript(i);
  PrintCommaIfNeeded();
  buffer_.Printf("%" Pd64 "", i);
}

void JSONWriter::PrintValue(double d) {
  // Max length of a double in characters (including \0).
  // See double_conversion.cc.
  const size_t kBufferLen = 25;
  char buffer[kBufferLen];
  DoubleToCString(d, buffer, kBufferLen);
  PrintCommaIfNeeded();
  buffer_.Printf("%s", buffer);
}

static const char base64_digits[65] =
    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
static const char base64_pad = '=';

void JSONWriter::PrintValueBase64(const uint8_t* bytes, intptr_t length) {
  PrintCommaIfNeeded();
  buffer_.AddChar('"');

  intptr_t odd_bits = length % 3;
  intptr_t even_bits = length - odd_bits;
  for (intptr_t i = 0; i < even_bits; i += 3) {
    intptr_t triplet = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2];
    buffer_.AddChar(base64_digits[triplet >> 18]);
    buffer_.AddChar(base64_digits[(triplet >> 12) & 63]);
    buffer_.AddChar(base64_digits[(triplet >> 6) & 63]);
    buffer_.AddChar(base64_digits[triplet & 63]);
  }
  if (odd_bits == 1) {
    intptr_t triplet = bytes[even_bits] << 16;
    buffer_.AddChar(base64_digits[triplet >> 18]);
    buffer_.AddChar(base64_digits[(triplet >> 12) & 63]);
    buffer_.AddChar(base64_pad);
    buffer_.AddChar(base64_pad);
  } else if (odd_bits == 2) {
    intptr_t triplet = (bytes[even_bits] << 16) | (bytes[even_bits + 1] << 8);
    buffer_.AddChar(base64_digits[triplet >> 18]);
    buffer_.AddChar(base64_digits[(triplet >> 12) & 63]);
    buffer_.AddChar(base64_digits[(triplet >> 6) & 63]);
    buffer_.AddChar(base64_pad);
  }

  buffer_.AddChar('"');
}

void JSONWriter::PrintValue(const char* s) {
  PrintCommaIfNeeded();
  buffer_.AddChar('"');
  AddEscapedUTF8String(s);
  buffer_.AddChar('"');
}

bool JSONWriter::PrintValueStr(const String& s,
                               intptr_t offset,
                               intptr_t count) {
  PrintCommaIfNeeded();
  buffer_.AddChar('"');
  bool did_truncate = AddDartString(s, offset, count);
  buffer_.AddChar('"');
  return did_truncate;
}

void JSONWriter::PrintValueNoEscape(const char* s) {
  PrintCommaIfNeeded();
  buffer_.Printf("%s", s);
}

void JSONWriter::PrintfValue(const char* format, ...) {
  va_list args;
  va_start(args, format);
  VPrintfValue(format, args);
  va_end(args);
}

void JSONWriter::VPrintfValue(const char* format, va_list args) {
  PrintCommaIfNeeded();

  va_list measure_args;
  va_copy(measure_args, args);
  intptr_t len = Utils::VSNPrint(NULL, 0, format, measure_args);
  va_end(measure_args);

  MaybeOnStackBuffer mosb(len + 1);
  char* p = mosb.p();

  va_list print_args;
  va_copy(print_args, args);
  intptr_t len2 = Utils::VSNPrint(p, len + 1, format, print_args);
  va_end(print_args);
  ASSERT(len == len2);

  buffer_.AddChar('"');
  AddEscapedUTF8String(p, len);
  buffer_.AddChar('"');
}

void JSONWriter::PrintPropertyBool(const char* name, bool b) {
  PrintPropertyName(name);
  PrintValueBool(b);
}

void JSONWriter::PrintProperty(const char* name, intptr_t i) {
  PrintPropertyName(name);
  PrintValue(i);
}

void JSONWriter::PrintProperty64(const char* name, int64_t i) {
  PrintPropertyName(name);
  PrintValue64(i);
}

void JSONWriter::PrintProperty(const char* name, double d) {
  PrintPropertyName(name);
  PrintValue(d);
}

void JSONWriter::PrintProperty(const char* name, const char* s) {
  PrintPropertyName(name);
  PrintValue(s);
}

void JSONWriter::PrintPropertyBase64(const char* name,
                                     const uint8_t* b,
                                     intptr_t len) {
  PrintPropertyName(name);
  PrintValueBase64(b, len);
}

bool JSONWriter::PrintPropertyStr(const char* name,
                                  const String& s,
                                  intptr_t offset,
                                  intptr_t count) {
  PrintPropertyName(name);
  return PrintValueStr(s, offset, count);
}

void JSONWriter::PrintPropertyNoEscape(const char* name, const char* s) {
  PrintPropertyName(name);
  PrintValueNoEscape(s);
}

void JSONWriter::PrintfProperty(const char* name, const char* format, ...) {
  va_list args;
  va_start(args, format);
  VPrintfProperty(name, format, args);
  va_end(args);
}

void JSONWriter::VPrintfProperty(const char* name,
                                 const char* format,
                                 va_list args) {
  PrintPropertyName(name);

  va_list measure_args;
  va_copy(measure_args, args);
  intptr_t len = Utils::VSNPrint(NULL, 0, format, measure_args);
  va_end(measure_args);

  MaybeOnStackBuffer mosb(len + 1);
  char* p = mosb.p();

  va_list print_args;
  va_copy(print_args, args);
  intptr_t len2 = Utils::VSNPrint(p, len + 1, format, print_args);
  va_end(print_args);
  ASSERT(len == len2);

  buffer_.AddChar('"');
  AddEscapedUTF8String(p, len);
  buffer_.AddChar('"');
}

void JSONWriter::Steal(char** buffer, intptr_t* buffer_length) {
  ASSERT(buffer != NULL);
  ASSERT(buffer_length != NULL);
  *buffer_length = buffer_.length();
  *buffer = buffer_.Steal();
}

void JSONWriter::PrintPropertyName(const char* name) {
  ASSERT(name != NULL);
  PrintCommaIfNeeded();
  buffer_.AddChar('"');
  AddEscapedUTF8String(name);
  buffer_.AddChar('"');
  buffer_.AddChar(':');
}

void JSONWriter::PrintNewline() {
  buffer_.AddChar('\n');
}

void JSONWriter::PrintCommaIfNeeded() {
  if (NeedComma()) {
    buffer_.AddChar(',');
  }
}

bool JSONWriter::NeedComma() {
  const char* buffer = buffer_.buffer();
  intptr_t length = buffer_.length();
  if (length == 0) {
    return false;
  }
  char ch = buffer[length - 1];
  return (ch != '[') && (ch != '{') && (ch != ':') && (ch != ',');
}

void JSONWriter::EnsureIntegerIsRepresentableInJavaScript(int64_t i) {
#ifdef DEBUG
  if (!Utils::IsJavascriptInt(i)) {
    OS::PrintErr(
        "JSONWriter::EnsureIntegerIsRepresentableInJavaScript failed on "
        "%" Pd64 "\n",
        i);
    UNREACHABLE();
  }
#endif
}

void JSONWriter::AddEscapedUTF8String(const char* s) {
  if (s == NULL) {
    return;
  }
  intptr_t len = strlen(s);
  AddEscapedUTF8String(s, len);
}

void JSONWriter::AddEscapedUTF8String(const char* s, intptr_t len) {
  if (s == NULL) {
    return;
  }
  const uint8_t* s8 = reinterpret_cast<const uint8_t*>(s);
  intptr_t i = 0;
  for (; i < len;) {
    // Extract next UTF8 character.
    int32_t ch = 0;
    int32_t ch_len = Utf8::Decode(&s8[i], len - i, &ch);
    ASSERT(ch_len != 0);
    buffer_.EscapeAndAddCodeUnit(ch);
    // Move i forward.
    i += ch_len;
  }
  ASSERT(i == len);
}

bool JSONWriter::AddDartString(const String& s,
                               intptr_t offset,
                               intptr_t count) {
  intptr_t length = s.Length();
  ASSERT(offset >= 0);
  if (offset > length) {
    offset = length;
  }
  if (!Utils::RangeCheck(offset, count, length)) {
    count = length - offset;
  }
  intptr_t limit = offset + count;
  for (intptr_t i = offset; i < limit; i++) {
    uint16_t code_unit = s.CharAt(i);
    if (Utf16::IsTrailSurrogate(code_unit)) {
      buffer_.EscapeAndAddUTF16CodeUnit(code_unit);
    } else if (Utf16::IsLeadSurrogate(code_unit)) {
      if (i + 1 == limit) {
        buffer_.EscapeAndAddUTF16CodeUnit(code_unit);
      } else {
        uint16_t next_code_unit = s.CharAt(i + 1);
        if (Utf16::IsTrailSurrogate(next_code_unit)) {
          uint32_t decoded = Utf16::Decode(code_unit, next_code_unit);
          buffer_.EscapeAndAddCodeUnit(decoded);
          i++;
        } else {
          buffer_.EscapeAndAddUTF16CodeUnit(code_unit);
        }
      }
    } else {
      buffer_.EscapeAndAddCodeUnit(code_unit);
    }
  }
  // Return value indicates whether the string is truncated.
  return (offset > 0) || (limit < length);
}

}  // namespace dart


text:
<?php

session_start();
header( 'Location: index.html' );

?>


text:
/* eslint-disable */
import * as Types from '../graphqlTypes.generated';

import { gql } from '@apollo/client';
import { TagCategoryFragmentDoc } from '../TagCategories/TagCategoryFragment.generated';
import * as Apollo from '@apollo/client';
const defaultOptions = {};
export type TagFragment = {
  __typename: 'Tag';
  id: string;
  name: string;
  tagCategory?: Types.Maybe<{
    __typename: 'TagCategory';
    id: string;
    name: string;
    color?: Types.Maybe<string>;
    textColor?: Types.Maybe<string>;
    icon?: Types.Maybe<string>;
  }>;
};

export type TagAutocompleteQueryVariables = Types.Exact<{
  queryString?: Types.Maybe<Types.Scalars['String']>;
}>;

export type TagAutocompleteQueryData = {
  __typename: 'Query';
  tags: {
    __typename: 'TagConnection';
    edges: Array<{
      __typename: 'TagEdge';
      node: {
        __typename: 'Tag';
        id: string;
        name: string;
        tagCategory?: Types.Maybe<{
          __typename: 'TagCategory';
          id: string;
          name: string;
          color?: Types.Maybe<string>;
          textColor?: Types.Maybe<string>;
          icon?: Types.Maybe<string>;
        }>;
      };
    }>;
  };
};

export type TagListPageQueryVariables = Types.Exact<{
  after?: Types.Maybe<Types.Scalars['String']>;
}>;

export type TagListPageQueryData = {
  __typename: 'Query';
  tags: {
    __typename: 'TagConnection';
    totalCount: number;
    pageInfo: { __typename: 'PageInfo'; endCursor?: Types.Maybe<string> };
    edges: Array<{
      __typename: 'TagEdge';
      node: {
        __typename: 'Tag';
        id: string;
        name: string;
        tagCategory?: Types.Maybe<{
          __typename: 'TagCategory';
          id: string;
          name: string;
          color?: Types.Maybe<string>;
          textColor?: Types.Maybe<string>;
          icon?: Types.Maybe<string>;
        }>;
      };
    }>;
  };
};

export type EditTagQueryVariables = Types.Exact<{
  id: Types.Scalars['ID'];
}>;

export type EditTagQueryData = {
  __typename: 'Query';
  tag: {
    __typename: 'Tag';
    id: string;
    name: string;
    projects: { __typename: 'ProjectConnection'; totalCount: number };
    tagCategory?: Types.Maybe<{
      __typename: 'TagCategory';
      id: string;
      name: string;
      color?: Types.Maybe<string>;
      textColor?: Types.Maybe<string>;
      icon?: Types.Maybe<string>;
    }>;
  };
};

export const TagFragmentDoc = gql`
  fragment TagFragment on Tag {
    id
    name
    tagCategory {
      id
      ...TagCategoryFragment
    }
  }
  ${TagCategoryFragmentDoc}
`;
export const TagAutocompleteQueryDocument = gql`
  query TagAutocompleteQuery($queryString: String) {
    tags(queryString: $queryString) {
      edges {
        node {
          id
          ...TagFragment
        }
      }
    }
  }
  ${TagFragmentDoc}
`;

/**
 * __useTagAutocompleteQuery__
 *
 * To run a query within a React component, call `useTagAutocompleteQuery` and pass it any options that fit your needs.
 * When your component renders, `useTagAutocompleteQuery` returns an object from Apollo Client that contains loading, error, and data properties
 * you can use to render your UI.
 *
 * @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options;
 *
 * @example
 * const { data, loading, error } = useTagAutocompleteQuery({
 *   variables: {
 *      queryString: // value for 'queryString'
 *   },
 * });
 */
export function useTagAutocompleteQuery(
  baseOptions?: Apollo.QueryHookOptions<TagAutocompleteQueryData, TagAutocompleteQueryVariables>,
) {
  const options = { ...defaultOptions, ...baseOptions };
  return Apollo.useQuery<TagAutocompleteQueryData, TagAutocompleteQueryVariables>(
    TagAutocompleteQueryDocument,
    options,
  );
}
export function useTagAutocompleteQueryLazyQuery(
  baseOptions?: Apollo.LazyQueryHookOptions<
    TagAutocompleteQueryData,
    TagAutocompleteQueryVariables
  >,
) {
  const options = { ...defaultOptions, ...baseOptions };
  return Apollo.useLazyQuery<TagAutocompleteQueryData, TagAutocompleteQueryVariables>(
    TagAutocompleteQueryDocument,
    options,
  );
}
export type TagAutocompleteQueryHookResult = ReturnType<typeof useTagAutocompleteQuery>;
export type TagAutocompleteQueryLazyQueryHookResult = ReturnType<
  typeof useTagAutocompleteQueryLazyQuery
>;
export type TagAutocompleteQueryQueryResult = Apollo.QueryResult<
  TagAutocompleteQueryData,
  TagAutocompleteQueryVariables
>;
export const TagListPageQueryDocument = gql`
  query TagListPageQuery($after: String) {
    tags(first: 25, after: $after) {
      pageInfo {
        endCursor
      }
      totalCount
      edges {
        node {
          id
          ...TagFragment
        }
      }
    }
  }
  ${TagFragmentDoc}
`;

/**
 * __useTagListPageQuery__
 *
 * To run a query within a React component, call `useTagListPageQuery` and pass it any options that fit your needs.
 * When your component renders, `useTagListPageQuery` returns an object from Apollo Client that contains loading, error, and data properties
 * you can use to render your UI.
 *
 * @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options;
 *
 * @example
 * const { data, loading, error } = useTagListPageQuery({
 *   variables: {
 *      after: // value for 'after'
 *   },
 * });
 */
export function useTagListPageQuery(
  baseOptions?: Apollo.QueryHookOptions<TagListPageQueryData, TagListPageQueryVariables>,
) {
  const options = { ...defaultOptions, ...baseOptions };
  return Apollo.useQuery<TagListPageQueryData, TagListPageQueryVariables>(
    TagListPageQueryDocument,
    options,
  );
}
export function useTagListPageQueryLazyQuery(
  baseOptions?: Apollo.LazyQueryHookOptions<TagListPageQueryData, TagListPageQueryVariables>,
) {
  const options = { ...defaultOptions, ...baseOptions };
  return Apollo.useLazyQuery<TagListPageQueryData, TagListPageQueryVariables>(
    TagListPageQueryDocument,
    options,
  );
}
export type TagListPageQueryHookResult = ReturnType<typeof useTagListPageQuery>;
export type TagListPageQueryLazyQueryHookResult = ReturnType<typeof useTagListPageQueryLazyQuery>;
export type TagListPageQueryQueryResult = Apollo.QueryResult<
  TagListPageQueryData,
  TagListPageQueryVariables
>;
export const EditTagQueryDocument = gql`
  query EditTagQuery($id: ID!) {
    tag(id: $id) {
      id
      ...TagFragment
      projects {
        totalCount
      }
    }
  }
  ${TagFragmentDoc}
`;

/**
 * __useEditTagQuery__
 *
 * To run a query within a React component, call `useEditTagQuery` and pass it any options that fit your needs.
 * When your component renders, `useEditTagQuery` returns an object from Apollo Client that contains loading, error, and data properties
 * you can use to render your UI.
 *
 * @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options;
 *
 * @example
 * const { data, loading, error } = useEditTagQuery({
 *   variables: {
 *      id: // value for 'id'
 *   },
 * });
 */
export function useEditTagQuery(
  baseOptions: Apollo.QueryHookOptions<EditTagQueryData, EditTagQueryVariables>,
) {
  const options = { ...defaultOptions, ...baseOptions };
  return Apollo.useQuery<EditTagQueryData, EditTagQueryVariables>(EditTagQueryDocument, options);
}
export function useEditTagQueryLazyQuery(
  baseOptions?: Apollo.LazyQueryHookOptions<EditTagQueryData, EditTagQueryVariables>,
) {
  const options = { ...defaultOptions, ...baseOptions };
  return Apollo.useLazyQuery<EditTagQueryData, EditTagQueryVariables>(
    EditTagQueryDocument,
    options,
  );
}
export type EditTagQueryHookResult = ReturnType<typeof useEditTagQuery>;
export type EditTagQueryLazyQueryHookResult = ReturnType<typeof useEditTagQueryLazyQuery>;
export type EditTagQueryQueryResult = Apollo.QueryResult<EditTagQueryData, EditTagQueryVariables>;


text:
<?php
    //echo '
Session:
', print_r($_SESSION), '
';
?>

Dashboard

Opret brugersend
Opret Instruktørsend


text:
import { assert, match, SinonStub, stub } from 'sinon';
import TelemetryReporter from 'vscode-extension-telemetry';
import { TelemetryService } from '@src/lib/languageServer/telemetry';
import { beforeEach, afterEach } from 'mocha';

suite('Telemetry', () => {
  let reporter: TelemetryReporter;
  let sendEvent: SinonStub;

  beforeEach(() => {
    reporter = new TelemetryReporter('salesforcedx-vscode', 'v1', 'test567890');
    sendEvent = stub(reporter, 'sendTelemetryEvent');
  });

  afterEach(async () => {
    sendEvent.restore();
    await reporter.dispose();
  });

  test('Should send telemetry data', async () => {
    const telemetryService = TelemetryService.getInstance();
    telemetryService.initializeService(reporter, true);

    telemetryService.sendExtensionActivationEvent([0, 678]);
    assert.calledOnce(sendEvent);
  });

  test('Should not send telemetry data', async () => {
    const telemetryService = TelemetryService.getInstance();
    telemetryService.initializeService(reporter, false);

    telemetryService.sendExtensionActivationEvent([1, 700]);
    assert.notCalled(sendEvent);
  });

  test('Should send correct data format on sendExtensionActivationEvent', async () => {
    const telemetryService = TelemetryService.getInstance();
    telemetryService.initializeService(reporter, true);

    telemetryService.sendExtensionActivationEvent([1, 700]);
    assert.calledOnce(sendEvent);

    const expectedData = {
      extensionName: 'salesforcedx-vscode-apex',
      startupTime: match.string
    };
    assert.calledWith(sendEvent, 'activationEvent', match(expectedData));
  });

  test('Should send correct data format on sendExtensionDeactivationEvent', async () => {
    const telemetryService = TelemetryService.getInstance();
    telemetryService.initializeService(reporter, true);

    telemetryService.sendExtensionDeactivationEvent();
    assert.calledOnce(sendEvent);

    const expectedData = {
      extensionName: 'salesforcedx-vscode-apex'
    };
    assert.calledWith(sendEvent, 'deactivationEvent', expectedData);
  });

  test('Should send correct data format on sendApexLSPActivationEvent', async () => {
    const telemetryService = TelemetryService.getInstance();
    telemetryService.initializeService(reporter, true);

    telemetryService.sendApexLSPActivationEvent([0, 50]);
    assert.calledOnce(sendEvent);

    const expectedData = {
      extensionName: 'salesforcedx-vscode-apex',
      startupTime: match.string
    };
    assert.calledWith(sendEvent, 'apexLSPStartup', match(expectedData));
  });

  test('Should send correct data format on sendApexLSPError', async () => {
    const telemetryService = TelemetryService.getInstance();
    telemetryService.initializeService(reporter, true);
    const errorMsg = 'NullPointerException on Apex LSP';
    telemetryService.sendApexLSPError(errorMsg);
    assert.calledOnce(sendEvent);

    const expectedData = {
      extensionName: 'salesforcedx-vscode-apex',
      errorMsg
    };
    assert.calledWith(sendEvent, 'apexLSPError', expectedData);
  });

  test('Should send correct data format on sendErrorEvent with additionalData', async () => {
    const telemetryService = TelemetryService.getInstance();
    telemetryService.initializeService(reporter, true);

    const additionalData = {
      cancelled: false,
      standardObjects: 1,
      customObjects: 2,
      commandName: 'sobject_refresh_command',
      executionTime: telemetryService.getEndHRTime([0, 678])
    };

    telemetryService.sendErrorEvent(
      { message: 'sample error', stack: 'sample stack' },
      additionalData
    );
    assert.calledOnce(sendEvent);

    const expectedData = {
      extensionName: 'salesforcedx-vscode-apex',
      errorMessage: 'sample error',
      errorStack: 'sample stack',
      cancelled: false,
      standardObjects: 1,
      customObjects: 2,
      commandName: 'sobject_refresh_command',
      executionTime: match.string
    };
    assert.calledWith(sendEvent, 'error', match(expectedData));
  });
});


text:
package Plack::Middleware::Refresh;
use strict;
use parent qw(Plack::Middleware);
use Module::Refresh;
use Plack::Util::Accessor qw(last cooldown);

sub prepare_app {
    my $self = shift;
    $self->cooldown(10) unless defined $self->cooldown;

    Module::Refresh->new;
    $self->last(time - $self->cooldown);
}

sub call {
    my($self, $env) = @_;

    if (time > $self->last + $self->cooldown) {
        Module::Refresh->refresh;
        $self->last(time);
    }

    $self->app->($env);
}

1;

__END__

=head1 NAME

Plack::Middleware::Refresh - Refresh all modules in %INC

=head1 SYNOPSIS

  enable "Refresh", cooldown => 3;
  $app;

=head1 DESCRIPTION

This is I<yet another> approach to refresh modules in C<%INC> during
the development cycle, without the need to have a forking process to
watch for filesystem updates. This middleware, in a request time,
compares the last refresh time and the current time and if the
difference is bigger than I<cooldown> seconds which defaults to 10,
call L<Module::Refresh> to reload all Perl modules in C<%INC> if the
files have been modified.

Note that this only reloads modules and not other files such as
templates.

This middleware is quite similar to what Rack::Reoader does. If you
have issues with this reloading technique, for instance when you have
in-file templates that needs to be recompiled, or Moose classes that
has C<make_immutable>, take a look at L<plackup>'s default -r option
or L<Plack::Loader::Shotgun> instead.

=head1 AUTHOR

Tatsuhiko Miyagawa

=head1 SEE ALSO

L<Module::Refresh> Rack::Reloader

=cut


text:
module Expresspigeon
  module API
    VERSION = "0.1.1"
  end
end


text:
exports.Collection = Thorax.Collection.extend({

});


text:
module AssignmentLogsHelper
end