text:
GREEN="$(tput setaf 10)"
RED="$(tput setaf 9)"
ORANGE="$(tput setaf 220)"
PURPLE="$(tput setaf 93)"
BLUE="$(tput setaf 21)"
RESET="$(tput sgr0)"

LOG_LEVEL=${LOG_LEVEL:-INFO}

gitBranch() {
	cd $1; git branch | grep "*" | cut -d " " -f 2; cd - &> /dev/null
}

# Write a debug to stderr
debug() {
	if [[ $LOG_LEVEL != "DEBUG" ]] ; then
		return 0
	fi

    local MSG=$1
    echo "${BLUE}$MSG${RESET}" 1>&2
}

# Write an info to stderr
info() {
	if [[ $LOG_LEVEL != "INFO" ]] && [[ $LOG_LEVEL != "DEBUG" ]] ; then
		return 0
	fi

    local MSG=$1
    echo "${GREEN}$MSG${RESET}" 1>&2
}

# Write a warning to stderr
warning() {
	if [[ $LOG_LEVEL != "INFO" ]] && [[ $LOG_LEVEL != "DEBUG" ]] && [[ $LOG_LEVEL != "WARNING" ]] ; then
		return 0
	fi

    local MSG=$1
    echo "${ORANGE}$MSG${RESET}" 1>&2
}

# Write an error to stderr
error() {
    local MSG=$1
    echo "${RED}$MSG${RESET}" 1>&2
}

LOG_LEVEL="`toUpper $LOG_LEVEL`"
if [[ $LOG_LEVEL != "INFO" ]] && [[ $LOG_LEVEL != "DEBUG" ]] && [[ $LOG_LEVEL != "WARNING" ]] && [[ $LOG_LEVEL != "ERROR" ]]; then
	echo "INVALID LOG LEVEL: $LOG_LEVEL"
	echo "MUST BE ONE OF [DEBUG, INFO, WARNING, ERROR]"
	kill 0
fi

ensureAWSCli() {
    if ! which aws > /dev/null ; then
        warning "AWS cli not found. Installing prerequisite AWS cli using brew"
        brew install awscli || {
            error "An error occurred using brew to install AWS cli. If not on mac osx install AWS cli manually."
            kill 0
        }
    fi

    if ! aws configure get aws_access_key_id > /dev/null ; then
        warning "AWS cli not configured. Starting configuration wizard"
        aws configure || {
            error "An error occurred configuring AWS cli."
            kill 0
        }
    fi
}

ensureJQ() {
    if ! which jq > /dev/null ; then
        warning "jq not found. Installing prerequisite jq using brew"
        brew install jq || {
            error "An error occurred using brew to install jq. If not on mac osx install jq manually: https://stedolan.github.io/jq/"
            kill 0
        }
    fi
}


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/photos/library/v1/photos_library.proto

package com.google.photos.library.v1.proto;

public interface DateFilterOrBuilder
    extends
    // @@protoc_insertion_point(interface_extends:google.photos.library.v1.DateFilter)
    com.google.protobuf.MessageOrBuilder {

  /**
   *
   *
   *

   * List of dates that match the media items' creation date. A maximum of
   * 5 dates can be included per request.
   *

   *
   * repeated .google.type.Date dates = 1;
   */
  java.util.List<com.google.type.Date> getDatesList();
  /**
   *
   *
   *

   * List of dates that match the media items' creation date. A maximum of
   * 5 dates can be included per request.
   *

   *
   * repeated .google.type.Date dates = 1;
   */
  com.google.type.Date getDates(int index);
  /**
   *
   *
   *

   * List of dates that match the media items' creation date. A maximum of
   * 5 dates can be included per request.
   *

   *
   * repeated .google.type.Date dates = 1;
   */
  int getDatesCount();
  /**
   *
   *
   *

   * List of dates that match the media items' creation date. A maximum of
   * 5 dates can be included per request.
   *

   *
   * repeated .google.type.Date dates = 1;
   */
  java.util.List<? extends com.google.type.DateOrBuilder> getDatesOrBuilderList();
  /**
   *
   *
   *

   * List of dates that match the media items' creation date. A maximum of
   * 5 dates can be included per request.
   *

   *
   * repeated .google.type.Date dates = 1;
   */
  com.google.type.DateOrBuilder getDatesOrBuilder(int index);

  /**
   *
   *
   *

   * List of dates ranges that match the media items' creation date. A
   * maximum of 5 dates ranges can be included per request.
   *

   *
   * repeated .google.photos.types.DateRange ranges = 2;
   */
  java.util.List<com.google.photos.types.proto.DateRange> getRangesList();
  /**
   *
   *
   *

   * List of dates ranges that match the media items' creation date. A
   * maximum of 5 dates ranges can be included per request.
   *

   *
   * repeated .google.photos.types.DateRange ranges = 2;
   */
  com.google.photos.types.proto.DateRange getRanges(int index);
  /**
   *
   *
   *

   * List of dates ranges that match the media items' creation date. A
   * maximum of 5 dates ranges can be included per request.
   *

   *
   * repeated .google.photos.types.DateRange ranges = 2;
   */
  int getRangesCount();
  /**
   *
   *
   *

   * List of dates ranges that match the media items' creation date. A
   * maximum of 5 dates ranges can be included per request.
   *

   *
   * repeated .google.photos.types.DateRange ranges = 2;
   */
  java.util.List<? extends com.google.photos.types.proto.DateRangeOrBuilder>
      getRangesOrBuilderList();
  /**
   *
   *
   *

   * List of dates ranges that match the media items' creation date. A
   * maximum of 5 dates ranges can be included per request.
   *

   *
   * repeated .google.photos.types.DateRange ranges = 2;
   */
  com.google.photos.types.proto.DateRangeOrBuilder getRangesOrBuilder(int index);
}

redpajama_set_name: RedPajamaGithub


text:
<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light">
        <!-- Customize your theme here. -->
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
        <item name="android:windowNoTitle">true</item>

    </style>
</resources>


text:
@interface FZH_BaiduMapView ()

@property (nonatomic) FZHBaiduMapView  *baiduView;

@end

@implementation FZH_BaiduMapView

- (UIView *)GetMapView
{
    return _baiduView;
}

-(instancetype)initWithFrame:(CGRect)frame{

    if (self = [super init]) {
        _baiduView = [[FZHBaiduMapView alloc] initWithFrame:frame];
    }
    return self;
}

@end


text:
var grunt = require('../grunt').grunt();
var path = require('path');
var atInPackaging = require('../ATInPackaging');
var alreadyGeneratedRegExp = /^\s*Aria\.classDefinition\(/;

var classGeneratorsByExtension = {
    'tpl' : 'aria.templates.TplClassGenerator',
    'tpl.css' : 'aria.templates.CSSClassGenerator',
    'tml' : 'aria.templates.TmlClassGenerator',
    'tpl.txt' : 'aria.templates.TxtClassGenerator',
    'cml' : 'aria.templates.CmlClassGenerator'
};

var getExtension = function (file) {
    var baseName = path.basename(file);
    var dot = baseName.indexOf('.');
    if (dot > -1) {
        return baseName.substring(dot + 1);
    }
};

var ATCompiledTemplate = {

    getClassGeneratorFromLogicalPath : function (logicalPath) {
        var extension = getExtension(logicalPath);
        if (!classGeneratorsByExtension.hasOwnProperty(extension)) {
            return null;
        }
        return classGeneratorsByExtension[extension];
    },

    getTextContent : function (inputFile) {
        return inputFile.contentATCompiledTemplate;
    },

    getCompiledTemplate : function (inputFile, fileContent, logicalPath) {
        if (!inputFile.contentATCompiledTemplate) {
            this.compile(inputFile, fileContent, logicalPath);
        }
        return inputFile.contentATCompiledTemplate;
    },

    compile : function (inputFile, fileContent, logicalPath) {
        if (logicalPath == null) {
            logicalPath = inputFile.logicalPath;
        }
        var classGenerator = this.getClassGeneratorFromLogicalPath(logicalPath);
        if (!classGenerator) {
            grunt.log.error("Cannot compile " + logicalPath.yellow + " as a template.");
            return;
        }
        if (fileContent == null) {
            fileContent = inputFile.getTextContent();
        }
        if (alreadyGeneratedRegExp.test(fileContent)) {
            // should already be an Aria class
            return;
        }
        var compiledTemplate;
        var atContext = atInPackaging.getATContext(inputFile.packaging);
        atContext.Aria.load({
            classes : [classGenerator],
            oncomplete : function () {
                var generator = atContext.Aria.getClassRef(classGenerator);
                generator.parseTemplate(fileContent, true, function (res) {
                    if (res.classDef) {
                        compiledTemplate = res.classDef;
                    }
                });
            }
        });
        atContext.execTimeouts();
        inputFile.contentATCompiledTemplate = compiledTemplate;
    }
};

module.exports = ATCompiledTemplate;


text:
import cv2, numpy as np

# initialize the input video
vid = cv2.VideoCapture('input.mp4')
ret, frame = vid.read()

# video to write the flipped input video to
out = cv2.VideoWriter('output.avi', cv2.cv.CV_FOURCC(*'XVID'), 20.0, (1280,720))

while ret:
    frame = cv2.flip(frame,-1)  # flip frame on both axes
    out.write(frame)            # write it out
    cv2.imshow('frame',frame)   # show for debugging

    ret, frame = vid.read()     # read in a new frame

    if cv2.waitKey(1) & 0xFF == ord('q'):
        break


text:
from optparse import make_option

from fabric.context_managers import settings

from woven.api import deploy
from woven.virtualenv import activate
from woven.management.base import WovenCommand

class Command(WovenCommand):
    """
    Deploy your project to a host and activate

    Basic Usage:
    ``python manage.py deploy [user]@[hoststring]``

    Examples:
    ``python manage.py deploy woven@192.168.188.10``
    ``python manage.py deploy woven@host.example.com``

    For just the current user
    ``python manage.py deploy host.example.com``

    """
    option_list = WovenCommand.option_list + (
        make_option('-m', '--migration',
            default='', #use south default run all migrations
            help="Specify a specific migration to run"
        ),
        make_option('--fake',
            action='store_true',
            default=False,
            help="Fake the south migration. Useful when converting an app"
        ),
        make_option('--nomigration',
            action='store_true',
            default=False,
            help="Do not run any migration"
        ),
        make_option('--manualmigration',
            action='store_true',
            default=False,
            help="Manage the database migration manually"
        ),
        make_option('--overwrite',
            action='store_true',
            default=False,
            help="Overwrite an existing installation"
        ),

    )
    help = "Deploy the current version of your project"
    requires_model_validation = False

    def handle_host(self,*args, **options):
        self.validate()
        deploy(overwrite=options.get('overwrite'))

        with settings(nomigration = options.get('nomigration'),
                      migration = options.get('migration'),
                      manualmigration = options.get('manualmigration')):
            activate()


text:
<?php

namespace ZendPdf\Resource\Image;

use ZendPdf as Pdf;
use ZendPdf\Exception;

/**
 * \ZendPdf\Resource\Image\ImageFactory
 *
 * Helps manage the diverse set of supported image file types.
 *
 * @package    Zend_PDF
 * @subpackage Zend_PDF_Image
 * @todo       Use Zend_Mime not file extension for type determination.
 */
class ImageFactory
{
    public static function factory($filename)
    {
        if(!is_file($filename)) {
            throw new Exception\IOException("Cannot create image resource. File not found.");
        }
        $extension = pathinfo($filename, PATHINFO_EXTENSION);
        /*
         * There are plans to use Zend_Mime and not file extension. In the mean time, if you need to
         * use an alternate file extension just spin up the right processor directly.
         */
        switch (strtolower($extension)) {
            case 'tif':
                //Fall through to next case;
            case 'tiff':
                return new Tiff($filename);
                break;
            case 'png':
                return new Png($filename);
                break;
            case 'jpg':
                //Fall through to next case;
            case 'jpe':
                //Fall through to next case;
            case 'jpeg':
                return new Jpeg($filename);
                break;
            default:
                throw new Exception\InvalidArgumentException('Cannot create image resource. File extension not known or unsupported type.');
                break;
        }
    }
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
null

#### Original name
Epidendrum vagans Ames

### Remarks
null


text:
FROM phacnml/galaxy-irida-20.09:base

# Add test tool configs
ADD ./galaxy/tool_conf_irida.xml /galaxy-central/config/tool_conf.xml

# Set up proper admin users
RUN sed -i -e 's/^\(.*\)#admin_users: .*/\1admin_users: admin@galaxy.org,workflowUser@irida.corefacility.ca/' /etc/galaxy/galaxy.yml

# Add custom Irida tools to Galaxy
ADD ./galaxy/assembly_annotation_pipeline_outputs.xml /galaxy-central/tools/irida/assembly_annotation_pipeline_outputs.xml
ADD ./galaxy/collection_list_paired.xml /galaxy-central/tools/irida/collection_list_paired.xml
ADD ./galaxy/core_pipeline_outputs.xml /galaxy-central/tools/irida/core_pipeline_outputs.xml
ADD ./galaxy/core_pipeline_outputs_paired.xml /galaxy-central/tools/irida/core_pipeline_outputs_paired.xml
ADD ./galaxy/core_pipeline_outputs_paired_with_multi_level_parameters.xml /galaxy-central/tools/irida/core_pipeline_outputs_paired_with_multi_level_parameters.xml
ADD ./galaxy/core_pipeline_outputs_paired_with_parameters.xml /galaxy-central/tools/irida/core_pipeline_outputs_paired_with_parameters.xml
ADD ./galaxy/core_pipeline_outputs_single_paired.xml /galaxy-central/tools/irida/core_pipeline_outputs_single_paired.xml
ADD ./galaxy/sleep.xml /galaxy-central/tools/irida/sleep.xml


text:
package v1

import (
	"k8s.io/api/core/v1"
	networkingv1 "k8s.io/api/networking/v1"
	"k8s.io/apimachinery/pkg/runtime"
)

func addDefaultingFuncs(scheme *runtime.Scheme) error {
	return RegisterDefaults(scheme)
}

func SetDefaults_NetworkPolicyPort(obj *networkingv1.NetworkPolicyPort) {
	// Default any undefined Protocol fields to TCP.
	if obj.Protocol == nil {
		proto := v1.ProtocolTCP
		obj.Protocol = &proto
	}
}

func SetDefaults_NetworkPolicy(obj *networkingv1.NetworkPolicy) {
	if len(obj.Spec.PolicyTypes) == 0 {
		// Any policy that does not specify policyTypes implies at least "Ingress".
		obj.Spec.PolicyTypes = []networkingv1.PolicyType{networkingv1.PolicyTypeIngress}
		if len(obj.Spec.Egress) != 0 {
			obj.Spec.PolicyTypes = append(obj.Spec.PolicyTypes, networkingv1.PolicyTypeEgress)
		}
	}
}


text:
set -e

for i in 1 2 3 4; do

    docker-machine create -d virtualbox swarm-$i

    eval $(docker-machine env swarm-$i)

    docker pull mongo

    docker pull vfarcic/go-demo

    docker pull alpine

    docker pull consul

    docker pull vfarcic/docker-flow-proxy

    docker pull vfarcic/go-demo:1.1

    docker pull dockersamples/visualizer

done


text:
=================
Crunchmail Client
=================

Basic usage
===========

Creating a simple client is easy:

.. code-block:: php

    use Crunchmail\Client;

    $config = array(
        'base_uri'    => 'https://api.crunchmail.net/v1/',
        'token_uri'   => 'https://api.crunchmail.net/api-token-auth',
        'auth'        => array( 'api', 'key-supersecret' )
    );
    $client = new Client($config);

The configuration uses the format used by
`Guzzle <https://github.com/guzzle/guzzle>`_, so you can use any of the
parameters that Guzzle offers. Just be careful not to use parameters that would
not be compatible with the Crunchmail API, like 'http_errors'.

Example of Guzzle additionnal parameters:

.. code-block:: php

    $config = array(
        'base_uri'    => 'https://api.crunchmail.net/v1/',
        'token_uri'   => 'https://api.crunchmail.net/api-token-auth',
        'auth'        => array( 'api', 'key-supersecret' ),
        'timeout'     => 2.0,
        // echo a bunch of logs for debug
        'debug'       => true
    );

Certificate file
================

You should never use the Client without the SSL ``verify`` parameter set to
``true`` (default).

You can specify the certificate in the configuration:

.. code-block:: php

    // add the parameter to an existing configuration
    $config['verify'] = '/path/to/certificate.pem';
    $client = new Client($config);

Raw Guzzle request
==================

At one point you may need to directlty request the API, without the abstraction
offered by the client. And it would be a shame to have to use another tool for
that. Hopefully you can request the API via the Guzzle Client registered in the
Client. (in fact the Crunchmail PHP Client extends the Guzzle\Client class).

Be careful, as you will NOT get an entity or a collection, but a raw Guzzle
object. See `Guzzle documentation <http://docs.guzzlephp.org/en/latest/>`_ for
more details about the parameters for each methods.

.. code-block:: php

    $this->client->get('/path/to/the/resource');
    $this->client->post('/path/to/the/resource', $values);
    $this->client->delete('/path/to/the/resource');

Get JWT token from API key
--------------------------

:Method: ``getToken()``
:Summary: Request a new token from the configured gAPI key
:Return: token

.. code-block:: php

    // refresh the message
    $client = new Client($config);
    $token = $client->getTokenFromApiKey('my-api-key');

Get JWT token from credentials
------------------------------

:Method: ``getTokenFromCredentials()``
:Summary: Request a new token from the given credentials
:Parameters:
    - ``String $identifier`` your login
    - ``String $password`` your password
:Return: token

.. code-block:: php

    // refresh the message
    $client = new Client($config);
    $token = $client->getTokenFromCredentials('mylogin', 'mypassword');


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

namespace KrishiKit
{
    class FarmerProfile
    {
        private static string request, response;

    }
}


text:
using System;
using System.Text;
using System.Text.RegularExpressions;

namespace Meebey.SmartIrc4net
{
    /// <summary>
    ///
    /// </summary>
    /// <threadsafety static="true" instance="true" />
    public sealed class Rfc2812
    {
        // nickname   =  ( letter / special ) *8( letter / digit / special / "-" )
        // letter     =  %x41-5A / %x61-7A       ; A-Z / a-z
        // digit      =  %x30-39                 ; 0-9
        // special    =  %x5B-60 / %x7B-7D
        //                  ; "[", "]", "\", "`", "_", "^", "{", "|", "}"
        private static Regex _NicknameRegex = new Regex(@"^[A-Za-z\[\]\\`_^{|}][A-Za-z0-9\[\]\\`_\-^{|}]+$", RegexOptions.Compiled);

        private Rfc2812()
        {
        }

        /// <summary>
        /// Checks if the passed nickname is valid according to the RFC
        ///
        /// Use with caution, many IRC servers are not conform with this!
        /// </summary>
        public static bool IsValidNickname(string nickname)
        {
            if ((nickname != null) &&
                (nickname.Length > 0) &&
                (_NicknameRegex.Match(nickname).Success)) {
                return true;
            }

            return false;
        }

        public static string Pass(string password)
        {
            return "PASS "+password;
        }

        public static string Nick(string nickname)
        {
            return "NICK "+nickname;
        }

        public static string User(string username, int usermode, string realname)
        {
            return "USER "+username+" "+usermode.ToString()+" * :"+realname;
        }

        public static string Oper(string name, string password)
        {
            return "OPER "+name+" "+password;
        }

        public static string Privmsg(string destination, string message)
        {
            return "PRIVMSG "+destination+" :"+message;
        }

        public static string Notice(string destination, string message)
        {
            return "NOTICE "+destination+" :"+message;
        }

        public static string Join(string channel)
        {
            return "JOIN "+channel;
        }

        public static string Join(string[] channels)
        {
            string channellist = String.Join(",", channels);
            return "JOIN "+channellist;
        }

        public static string Join(string channel, string key)
        {
            return "JOIN "+channel+" "+key;
        }

        public static string Join(string[] channels, string[] keys)
        {
            string channellist = String.Join(",", channels);
            string keylist = String.Join(",", keys);
            return "JOIN "+channellist+" "+keylist;
        }

        public static string Part(string channel)
        {
            return "PART "+channel;
        }

        public static string Part(string[] channels)
        {
            string channellist = String.Join(",", channels);
            return "PART "+channellist;
        }

        public static string Part(string channel, string partmessage)
        {
            return "PART "+channel+" :"+partmessage;
        }

        public static string Part(string[] channels, string partmessage)
        {
            string channellist = String.Join(",", channels);
            return "PART "+channellist+" :"+partmessage;
        }

        public static string Kick(string channel, string nickname)
        {
            return "KICK "+channel+" "+nickname;
        }

        public static string Kick(string channel, string nickname, string comment)
        {
            return "KICK "+channel+" "+nickname+" :"+comment;
        }

        public static string Kick(string[] channels, string nickname)
        {
            string channellist = String.Join(",", channels);
            return "KICK "+channellist+" "+nickname;
        }

        public static string Kick(string[] channels, string nickname, string comment)
        {
            string channellist = String.Join(",", channels);
            return "KICK "+channellist+" "+nickname+" :"+comment;
        }

        public static string Kick(string channel, string[] nicknames)
        {
            string nicknamelist = String.Join(",", nicknames);
            return "KICK "+channel+" "+nicknamelist;
        }

        public static string Kick(string channel, string[] nicknames, string comment)
        {
            string nicknamelist = String.Join(",", nicknames);
            return "KICK "+channel+" "+nicknamelist+" :"+comment;
        }

        public static string Kick(string[] channels, string[] nicknames)
        {
            string channellist = String.Join(",", channels);
            string nicknamelist = String.Join(",", nicknames);
            return "KICK "+channellist+" "+nicknamelist;
        }

        public static string Kick(string[] channels, string[] nicknames, string comment)
        {
            string channellist = String.Join(",", channels);
            string nicknamelist = String.Join(",", nicknames);
            return "KICK "+channellist+" "+nicknamelist+" :"+comment;
        }

        public static string Motd()
        {
            return "MOTD";
        }

        public static string Motd(string target)
        {
            return "MOTD "+target;
        }

        [Obsolete("use Lusers() method instead")]
        public static string Luser()
        {
            return Lusers();
        }

        public static string Lusers()
        {
            return "LUSERS";
        }

        [Obsolete("use Lusers(string) method instead")]
        public static string Luser(string mask)
        {
            return Lusers(mask);
        }

        public static string Lusers(string mask)
        {
            return "LUSER "+mask;
        }

        [Obsolete("use Lusers(string, string) method instead")]
        public static string Luser(string mask, string target)
        {
            return Lusers(mask, target);
        }

        public static string Lusers(string mask, string target)
        {
            return "LUSER "+mask+" "+target;
        }

        public static string Version()
        {
            return "VERSION";
        }

        public static string Version(string target)
        {
            return "VERSION "+target;
        }

        public static string Stats()
        {
            return "STATS";
        }

        public static string Stats(string query)
        {
            return "STATS "+query;
        }

        public static string Stats(string query, string target)
        {
            return "STATS "+query+" "+target;
        }

        public static string Links()
        {
            return "LINKS";
        }

        public static string Links(string servermask)
        {
            return "LINKS "+servermask;
        }

        public static string Links(string remoteserver, string servermask)
        {
            return "LINKS "+remoteserver+" "+servermask;
        }

        public static string Time()
        {
            return "TIME";
        }

        public static string Time(string target)
        {
            return "TIME "+target;
        }

        public static string Connect(string targetserver, string port)
        {
            return "CONNECT "+targetserver+" "+port;
        }

        public static string Connect(string targetserver, string port, string remoteserver)
        {
            return "CONNECT "+targetserver+" "+port+" "+remoteserver;
        }

        public static string Trace()
        {
            return "TRACE";
        }

        public static string Trace(string target)
        {
            return "TRACE "+target;
        }

        public static string Admin()
        {
            return "ADMIN";
        }

        public static string Admin(string target)
        {
            return "ADMIN "+target;
        }

        public static string Info()
        {
            return "INFO";
        }

        public static string Info(string target)
        {
            return "INFO "+target;
        }

        public static string Servlist()
        {
            return "SERVLIST";
        }

        public static string Servlist(string mask)
        {
            return "SERVLIST "+mask;
        }

        public static string Servlist(string mask, string type)
        {
            return "SERVLIST "+mask+" "+type;
        }

        public static string Squery(string servicename, string servicetext)
        {
            return "SQUERY "+servicename+" :"+servicetext;
        }

        public static string List()
        {
            return "LIST";
        }

        public static string List(string channel)
        {
            return "LIST "+channel;
        }

        public static string List(string[] channels)
        {
            string channellist = String.Join(",", channels);
            return "LIST "+channellist;
        }

        public static string List(string channel, string target)
        {
            return "LIST "+channel+" "+target;
        }

        public static string List(string[] channels, string target)
        {
            string channellist = String.Join(",", channels);
            return "LIST "+channellist+" "+target;
        }

        public static string Names()
        {
            return "NAMES";
        }

        public static string Names(string channel)
        {
            return "NAMES "+channel;
        }

        public static string Names(string[] channels)
        {
            string channellist = String.Join(",", channels);
            return "NAMES "+channellist;
        }

        public static string Names(string channel, string target)
        {
            return "NAMES "+channel+" "+target;
        }

        public static string Names(string[] channels, string target)
        {
            string channellist = String.Join(",", channels);
            return "NAMES "+channellist+" "+target;
        }

        public static string Topic(string channel)
        {
            return "TOPIC "+channel;
        }

        public static string Topic(string channel, string newtopic)
        {
            return "TOPIC "+channel+" :"+newtopic;
        }

        public static string Mode(string target)
        {
            return "MODE "+target;
        }

        public static string Mode(string target, string newmode)
        {
            return "MODE "+target+" "+newmode;
        }

        public static string Mode(string target, string[] newModes, string[] newModeParameters)
        {
            if (newModes == null) {
                throw new ArgumentNullException("newModes");
            }
            if (newModeParameters == null) {
                throw new ArgumentNullException("newModeParameters");
            }
            if (newModes.Length != newModeParameters.Length) {
                throw new ArgumentException("newModes and newModeParameters must have the same size.");
            }

            StringBuilder newMode = new StringBuilder(newModes.Length);
            StringBuilder newModeParameter = new StringBuilder();
            // as per RFC 3.2.3, maximum is 3 modes changes at once
            int maxModeChanges = 3;
            if (newModes.Length > maxModeChanges) {
                throw new ArgumentOutOfRangeException(
                    "newModes.Length",
                    newModes.Length,
                    String.Format("Mode change list is too large (> {0}).", maxModeChanges)
                );
            }

            for (int i = 0; i <= newModes.Length; i += maxModeChanges) {
                for (int j = 0; j < maxModeChanges; j++) {
                    if (i + j >= newModes.Length) {
                        break;
                    }
                    newMode.Append(newModes[i + j]);
                }

                for (int j = 0; j < maxModeChanges; j++) {
                    if (i + j >= newModeParameters.Length) {
                        break;
                    }
                    newModeParameter.Append(newModeParameters[i + j]);
                    newModeParameter.Append(" ");
                }
            }
            if (newModeParameter.Length > 0) {
                // remove trailing space
                newModeParameter.Length--;
                newMode.Append(" ");
                newMode.Append(newModeParameter.ToString());
            }

            return Mode(target, newMode.ToString());
        }

        public static string Service(string nickname, string distribution, string info)
        {
            return "SERVICE "+nickname+" * "+distribution+" * * :"+info;
        }

        public static string Invite(string nickname, string channel)
        {
            return "INVITE "+nickname+" "+channel;
        }

        public static string Who()
        {
            return "WHO";
        }

        public static string Who(string mask)
        {
            return "WHO "+mask;
        }

        public static string Who(string mask, bool ircop)
        {
            if (ircop) {
                return "WHO "+mask+" o";
            } else {
                return "WHO "+mask;
            }
        }

        public static string Whois(string mask)
        {
            return "WHOIS "+mask;
        }

        public static string Whois(string[] masks)
        {
            string masklist = String.Join(",", masks);
            return "WHOIS "+masklist;
        }

        public static string Whois(string target, string mask)
        {
            return "WHOIS "+target+" "+mask;
        }

        public static string Whois(string target, string[] masks)
        {
            string masklist = String.Join(",", masks);
            return "WHOIS "+target+" "+masklist;
        }

        public static string Whowas(string nickname)
        {
            return "WHOWAS "+nickname;
        }

        public static string Whowas(string[] nicknames)
        {
            string nicknamelist = String.Join(",", nicknames);
            return "WHOWAS "+nicknamelist;
        }

        public static string Whowas(string nickname, string count)
        {
            return "WHOWAS "+nickname+" "+count+" ";
        }

        public static string Whowas(string[] nicknames, string count)
        {
            string nicknamelist = String.Join(",", nicknames);
            return "WHOWAS "+nicknamelist+" "+count+" ";
        }

        public static string Whowas(string nickname, string count, string target)
        {
            return "WHOWAS "+nickname+" "+count+" "+target;
        }

        public static string Whowas(string[] nicknames, string count, string target)
        {
            string nicknamelist = String.Join(",", nicknames);
            return "WHOWAS "+nicknamelist+" "+count+" "+target;
        }

        public static string Kill(string nickname, string comment)
        {
            return "KILL "+nickname+" :"+comment;
        }

        public static string Ping(string server)
        {
            return "PING "+server;
        }

        public static string Ping(string server, string server2)
        {
            return "PING "+server+" "+server2;
        }

        public static string Pong(string server)
        {
            return "PONG "+server;
        }

        public static string Pong(string server, string server2)
        {
            return "PONG "+server+" "+server2;
        }

        public static string Error(string errormessage)
        {
            return "ERROR :"+errormessage;
        }

        public static string Away()
        {
            return "AWAY";
        }

        public static string Away(string awaytext)
        {
            return "AWAY :"+awaytext;
        }

        public static string Rehash()
        {
            return "REHASH";
        }

        public static string Die()
        {
            return "DIE";
        }

        public static string Restart()
        {
            return "RESTART";
        }

        public static string Summon(string user)
        {
            return "SUMMON "+user;
        }

        public static string Summon(string user, string target)
        {
            return "SUMMON "+user+" "+target;
        }

        public static string Summon(string user, string target, string channel)
        {
            return "SUMMON "+user+" "+target+" "+channel;
        }

        public static string Users()
        {
            return "USERS";
        }

        public static string Users(string target)
        {
            return "USERS "+target;
        }

        public static string Wallops(string wallopstext)
        {
            return "WALLOPS :"+wallopstext;
        }

        public static string Userhost(string nickname)
        {
            return "USERHOST "+nickname;
        }

        public static string Userhost(string[] nicknames)
        {
            string nicknamelist = String.Join(" ", nicknames);
            return "USERHOST "+nicknamelist;
        }

        public static string Ison(string nickname)
        {
            return "ISON "+nickname;
        }

        public static string Ison(string[] nicknames)
        {
            string nicknamelist = String.Join(" ", nicknames);
            return "ISON "+nicknamelist;
        }

        public static string Quit()
        {
            return "QUIT";
        }

        public static string Quit(string quitmessage)
        {
            return "QUIT :"+quitmessage;
        }

        public static string Squit(string server, string comment)
        {
            return "SQUIT "+server+" :"+comment;
        }
    }
}


text:
package gis.iwacu_new.rit.edu.main.gps.map;

import java.util.LinkedList;

public class SmoothZoomEngine {

	public static SmoothZoomEngine zoomEngine;

	private LinkedList<Integer> scaleQueue = new LinkedList<Integer>();

	private volatile Float scaleFactor = 1000f;

	private AbstractCommand updateScreen;

	private AbstractCommand reloadMap;

	public static boolean stop = false;

	public static SmoothZoomEngine getInstance() {
		if (zoomEngine == null) {
			zoomEngine = new SmoothZoomEngine();
		}
		return zoomEngine;
	}

	public void setUpdateScreenCommand(final AbstractCommand updateScreen) {
		this.updateScreen = updateScreen;
	}

	public void setReloadMapCommand(final AbstractCommand reloadMap) {
		this.reloadMap = reloadMap;
	}

	public void nullScaleFactor() {
		synchronized (scaleFactor) {
			scaleFactor = 1000f;
		}
	}

	private SmoothZoomEngine() {
		createQueue();
	}

	private void createQueue() {
		new Thread("SmoothZoomEngine") {

			@Override
			public void run() {
				boolean isEmpty = true;
				if (updateScreen != null) {
					updateScreen.execute();
				}
				double endScaleFactor;
				while (true) {
					if (scaleQueue.size() > 0) {
//						System.out.println("scaleQueue=" + scaleQueue);
						isEmpty = false;
						int scaleDirection = scaleQueue.removeFirst();
						endScaleFactor = (scaleDirection == -1
											? scaleFactor / 2
											: scaleFactor * 2);
						int z = PhysicMap.getZoomLevel();
						if ((scaleDirection == -1 && z < 17) || (scaleDirection == 1 && z > -2)) {
							if (!(endScaleFactor > 8000 || endScaleFactor < 125)) {
//								System.out.println("smooth scaling");
								synchronized (zoomEngine) {
									synchronized (scaleFactor) {
										do {
											try {
//												Thread.sleep(5);
//												scaleFactor = scaleFactor + (scaleDirection) * 25;
												scaleFactor = (float) endScaleFactor;
												updateScreen.execute(scaleFactor / 1000);
											} catch (Exception e) {
												e.printStackTrace();
											}
										} while (scaleFactor != endScaleFactor);
									}
								}
							}
						}

						if (!isEmpty && scaleQueue.size() == 0) {
//							System.out.println("reload");
							isEmpty = true;
							try {
//								Thread.sleep(5);
								reloadMap.execute(new Float(scaleFactor / 1000));
								// semaphore.release();
							} catch (Exception e) {
								e.printStackTrace();
							}
						}

					} // end [ if (scaleQueue.size() > 0) ]

					// avoid Thread still running while quitting the application
					if (stop) {
						break;
					}
					// avoid busy waiting
					try {
						Thread.sleep(5);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}

				} // end while
			} // end run()

		}.start();
	}

	public void addToScaleQ(int direction) {
		synchronized(scaleQueue) {
			scaleQueue.addLast( direction );
		}
	}

}


text:
#include "e.h"

/* PROTOTYPES - same all the time */
static void *_create_data(E_Config_Dialog *cfd);
static void _free_data(E_Config_Dialog *cfd, E_Config_Dialog_Data *cfdata);
static int _basic_apply(E_Config_Dialog *cfd, E_Config_Dialog_Data *cfdata);
static int _basic_check_changed(E_Config_Dialog *cfd, E_Config_Dialog_Data *cfdata);
static Evas_Object *_basic_create(E_Config_Dialog *cfd, Evas *evas, E_Config_Dialog_Data *cfdata);
static void _cb_disable_check_list(void *data, Evas_Object *obj);

/* Actual config data we will be playing with whil the dialog is active */
struct _E_Config_Dialog_Data
{
   int use_resist;
   int desk_resist;
   int window_resist;
   int gadget_resist;
   int geometry_auto_resize_limit;
   int geometry_auto_move;
   struct
     {
        double timeout;
        struct
          {
             int dx;
          } move;
        struct
          {
             int dx;
          } resize;
     } border_keyboard;
   struct {
      int    move;
      int    resize;
      int    raise;
      int    lower;
      int    layer;
      int    desktop;
      int    iconify;
   } transient;
   int maximize_policy;
   int maximize_direction;
   int maximized_allow_manip;
   int border_fix_on_shelf_toggle;
   int    allow_above_fullscreen;
   Eina_List *resistance_list;
};

E_Config_Dialog *
e_int_config_window_geometry(E_Container *con, const char *params __UNUSED__)
{
   E_Config_Dialog *cfd;
   E_Config_Dialog_View *v;

   if (e_config_dialog_find("E", "windows/window_geometry")) return NULL;
   v = E_NEW(E_Config_Dialog_View, 1);

   /* methods */
   v->create_cfdata = _create_data;
   v->free_cfdata = _free_data;
   v->basic.apply_cfdata = _basic_apply;
   v->basic.create_widgets = _basic_create;
   v->basic.check_changed = _basic_check_changed;

   /* create config diaolg for NULL object/data */
   cfd = e_config_dialog_new(con, _("Window Geometry"),
			     "E", "windows/window_geometry",
			     "preferences-window-geometry", 0, v, NULL);
   return cfd;
}

static void *
_create_data(E_Config_Dialog *cfd __UNUSED__)
{
   E_Config_Dialog_Data *cfdata = E_NEW(E_Config_Dialog_Data, 1);
   if (!cfdata) return NULL;
   cfdata->use_resist = e_config->use_resist;
   cfdata->desk_resist = e_config->desk_resist;
   cfdata->window_resist = e_config->window_resist;
   cfdata->gadget_resist = e_config->gadget_resist;
   cfdata->geometry_auto_resize_limit = e_config->geometry_auto_resize_limit;
   cfdata->geometry_auto_move = e_config->geometry_auto_move;
   cfdata->border_keyboard.timeout = e_config->border_keyboard.timeout;
   cfdata->border_keyboard.move.dx = e_config->border_keyboard.move.dx;
   cfdata->border_keyboard.resize.dx = e_config->border_keyboard.resize.dx;
   cfdata->transient.move = e_config->transient.move;
   cfdata->transient.resize = e_config->transient.resize;
   cfdata->transient.raise = e_config->transient.raise;
   cfdata->transient.lower = e_config->transient.lower;
   cfdata->transient.layer = e_config->transient.layer;
   cfdata->transient.desktop = e_config->transient.desktop;
   cfdata->transient.iconify = e_config->transient.iconify;
   cfdata->maximize_policy = (e_config->maximize_policy & E_MAXIMIZE_TYPE);
   cfdata->allow_above_fullscreen = e_config->allow_above_fullscreen;
   if (cfdata->maximize_policy == E_MAXIMIZE_NONE)
     cfdata->maximize_policy = E_MAXIMIZE_FULLSCREEN;
   cfdata->maximize_direction =
     (e_config->maximize_policy & E_MAXIMIZE_DIRECTION);
   if (!cfdata->maximize_direction)
     cfdata->maximize_direction = E_MAXIMIZE_BOTH;
   cfdata->maximized_allow_manip = e_config->allow_manip;
   cfdata->border_fix_on_shelf_toggle = e_config->border_fix_on_shelf_toggle;
   return cfdata;
}

static void
_free_data(E_Config_Dialog *cfd __UNUSED__, E_Config_Dialog_Data *cfdata)
{
   eina_list_free(cfdata->resistance_list);
   E_FREE(cfdata);
}

static int
_basic_apply(E_Config_Dialog *cfd __UNUSED__, E_Config_Dialog_Data *cfdata)
{
   e_config->use_resist = cfdata->use_resist;
   e_config->desk_resist = cfdata->desk_resist;
   e_config->window_resist = cfdata->window_resist;
   e_config->gadget_resist = cfdata->gadget_resist;
   e_config->geometry_auto_resize_limit = cfdata->geometry_auto_resize_limit;
   e_config->geometry_auto_move = cfdata->geometry_auto_move;
   e_config->border_keyboard.timeout = cfdata->border_keyboard.timeout;
   e_config->border_keyboard.move.dx = cfdata->border_keyboard.move.dx;
   e_config->border_keyboard.move.dy = cfdata->border_keyboard.move.dx;
   e_config->border_keyboard.resize.dx = cfdata->border_keyboard.resize.dx;
   e_config->border_keyboard.resize.dy = cfdata->border_keyboard.resize.dx;
   e_config->transient.move = cfdata->transient.move;
   e_config->transient.resize = cfdata->transient.resize;
   e_config->transient.raise = cfdata->transient.raise;
   e_config->transient.lower = cfdata->transient.lower;
   e_config->transient.layer = cfdata->transient.layer;
   e_config->transient.desktop = cfdata->transient.desktop;
   e_config->transient.iconify = cfdata->transient.iconify;
   e_config->maximize_policy =
     (cfdata->maximize_policy | cfdata->maximize_direction);
   e_config->allow_manip = cfdata->maximized_allow_manip;
   e_config->border_fix_on_shelf_toggle = cfdata->border_fix_on_shelf_toggle;
   e_config->allow_above_fullscreen = cfdata->allow_above_fullscreen;
   e_config_save_queue();
   return 1; /* Apply was OK */
}

static int
_basic_check_changed(E_Config_Dialog *cfd __UNUSED__, E_Config_Dialog_Data *cfdata)
{
   return ((e_config->use_resist != cfdata->use_resist) ||
	   (e_config->desk_resist != cfdata->desk_resist) ||
	   (e_config->window_resist != cfdata->window_resist) ||
	   (e_config->gadget_resist != cfdata->gadget_resist) ||
	   (e_config->geometry_auto_resize_limit != cfdata->geometry_auto_resize_limit) ||
           (e_config->geometry_auto_move != cfdata->geometry_auto_move) ||
	   (e_config->border_keyboard.timeout != cfdata->border_keyboard.timeout) ||
	   (e_config->border_keyboard.move.dx != cfdata->border_keyboard.move.dx) ||
	   (e_config->border_keyboard.move.dy != cfdata->border_keyboard.move.dx) ||
	   (e_config->border_keyboard.resize.dx != cfdata->border_keyboard.resize.dx) ||
	   (e_config->border_keyboard.resize.dy != cfdata->border_keyboard.resize.dx) ||
           (e_config->transient.move != cfdata->transient.move) ||
           (e_config->transient.resize != cfdata->transient.resize) ||
           (e_config->transient.raise != cfdata->transient.raise) ||
           (e_config->transient.lower != cfdata->transient.lower) ||
           (e_config->transient.layer != cfdata->transient.layer) ||
           (e_config->transient.desktop != cfdata->transient.desktop) ||
           (e_config->transient.iconify != cfdata->transient.iconify) ||
           (e_config->maximize_policy != (cfdata->maximize_policy | cfdata->maximize_direction)) ||
           (e_config->allow_manip != cfdata->maximized_allow_manip) ||
           (e_config->border_fix_on_shelf_toggle != cfdata->border_fix_on_shelf_toggle) ||
           (e_config->allow_above_fullscreen != cfdata->allow_above_fullscreen));
}

static Evas_Object *
_basic_create(E_Config_Dialog *cfd __UNUSED__, Evas *evas, E_Config_Dialog_Data *cfdata)
{
   Evas_Object *otb, *ol, *of, *ow, *oc;
   E_Radio_Group *rg;

   otb = e_widget_toolbook_add(evas, (24 * e_scale), (24 * e_scale));

   /* Resistance */
   ol = e_widget_list_add(evas, 0, 0);
   oc = e_widget_check_add(evas, _("Resist obstacles"), &(cfdata->use_resist));
   e_widget_list_object_append(ol, oc, 1, 0, 0.5);
   ow = e_widget_label_add(evas, _("Other windows"));
   e_widget_disabled_set(ow, !cfdata->use_resist);
   cfdata->resistance_list = eina_list_append (cfdata->resistance_list, ow);
   e_widget_list_object_append(ol, ow, 1, 0, 0.5);
   ow = e_widget_slider_add(evas, 1, 0, _("%2.0f pixels"), 0, 64.0, 1.0, 0,
                            NULL, &(cfdata->window_resist), 100);
   cfdata->resistance_list = eina_list_append (cfdata->resistance_list, ow);
   e_widget_disabled_set(ow, !cfdata->use_resist);
   e_widget_list_object_append(ol, ow, 1, 0, 0.5);
   ow = e_widget_label_add(evas, _("Edge of the screen"));
   cfdata->resistance_list = eina_list_append (cfdata->resistance_list, ow);
   e_widget_disabled_set(ow, !cfdata->use_resist);
   e_widget_list_object_append(ol, ow, 1, 0, 0.5);
   ow = e_widget_slider_add(evas, 1, 0, _("%2.0f pixels"), 0, 64.0, 1.0, 0,
                            NULL, &(cfdata->desk_resist), 100);
   cfdata->resistance_list = eina_list_append (cfdata->resistance_list, ow);
   e_widget_disabled_set(ow, !cfdata->use_resist);
   e_widget_list_object_append(ol, ow, 1, 0, 0.5);
   ow = e_widget_label_add(evas, _("Desktop gadgets"));
   cfdata->resistance_list = eina_list_append (cfdata->resistance_list, ow);
   e_widget_disabled_set(ow, !cfdata->use_resist);
   e_widget_list_object_append(ol, ow, 1, 0, 0.5);
   ow = e_widget_slider_add(evas, 1, 0, _("%2.0f pixels"), 0, 64.0, 1.0, 0,
                            NULL, &(cfdata->gadget_resist), 100);
   cfdata->resistance_list = eina_list_append (cfdata->resistance_list, ow);
   e_widget_disabled_set(ow, !cfdata->use_resist);
   e_widget_list_object_append(ol, ow, 1, 0, 0.5);
   e_widget_on_change_hook_set(oc, _cb_disable_check_list,
                               cfdata->resistance_list);
   e_widget_toolbook_page_append(otb, NULL, _("Resistance"), ol,
                                 1, 0, 1, 0, 0.5, 0.0);

   /* Maximization */
   ol = e_widget_list_add(evas, 0, 0);
   of = e_widget_framelist_add(evas, _("Policy"), 0);
   rg = e_widget_radio_group_new(&(cfdata->maximize_policy));
   ow = e_widget_radio_add(evas, _("Fullscreen"), E_MAXIMIZE_FULLSCREEN, rg);
   e_widget_framelist_object_append(of, ow);
   /* FIXME smart is nothing else than expand - dont confuse users */
   ow = e_widget_radio_add(evas, _("Smart expansion"), E_MAXIMIZE_SMART, rg);
   e_widget_framelist_object_append(of, ow);
   /* ob = e_widget_radio_add(evas, _("Expand the window"), E_MAXIMIZE_EXPAND, rg);
    * e_widget_list_object_append(o, ob, 1, 1, 0.5); */
   ow = e_widget_radio_add(evas, _("Fill available space"), E_MAXIMIZE_FILL, rg);
   e_widget_framelist_object_append(of, ow);
   e_widget_list_object_append(ol, of, 1, 0, 0.5);
   of = e_widget_framelist_add(evas, _("Direction"), 0);
   rg = e_widget_radio_group_new(&(cfdata->maximize_direction));
   ow = e_widget_radio_add(evas, _("Horizontal"), E_MAXIMIZE_HORIZONTAL, rg);
   e_widget_framelist_object_append(of, ow);
   ow = e_widget_radio_add(evas, _("Vertical"), E_MAXIMIZE_VERTICAL, rg);
   e_widget_framelist_object_append(of, ow);
   ow = e_widget_radio_add(evas, _("Both"), E_MAXIMIZE_BOTH, rg);
   e_widget_framelist_object_append(of, ow);
   e_widget_list_object_append(ol, of, 1, 0, 0.5);
   of = e_widget_framelist_add(evas, _("Manipulation"), 0);
   ow = e_widget_check_add(evas, _("Allow manipulation of maximized windows"),
                           &(cfdata->maximized_allow_manip));
   e_widget_framelist_object_append(of, ow);
   ow = e_widget_check_add(evas, _("Allow windows above fullscreen window"),
                           &(cfdata->allow_above_fullscreen));
   e_widget_framelist_object_append(of, ow);
   e_widget_list_object_append(ol, of, 1, 0, 0.5);
   e_widget_toolbook_page_append(otb, NULL, _("Maximization"), ol,
                                 1, 0, 1, 0, 0.5, 0.0);

   /* Keyboard Move and resize */
   ol = e_widget_list_add(evas, 0, 0);
   ow = e_widget_label_add(evas, _("Automatically accept changes after:"));
   e_widget_list_object_append(ol, ow, 1, 0, 0.5);
   ow = e_widget_slider_add(evas, 1, 0, _("%1.1f s"), 0.0, 9.9, 0.1, 0,
                            &(cfdata->border_keyboard.timeout), NULL, 100);
   e_widget_list_object_append(ol, ow, 1, 0, 0.5);
   ow = e_widget_label_add(evas, _("Move by"));
   e_widget_list_object_append(ol, ow, 1, 0, 0.5);
   ow = e_widget_slider_add(evas, 1, 0, _("%2.0f pixels"), 1, 255, 1, 0, NULL,
                            &(cfdata->border_keyboard.move.dx), 100);
   e_widget_list_object_append(ol, ow, 1, 0, 0.5);
   ow = e_widget_label_add(evas, _("Resize by"));
   e_widget_list_object_append(ol, ow, 1, 0, 0.5);
   ow = e_widget_slider_add(evas, 1, 0, _("%2.0f pixels"), 1, 255, 1, 0, NULL,
                            &(cfdata->border_keyboard.resize.dx), 100);
   e_widget_list_object_append(ol, ow, 1, 0, 0.5);
   e_widget_toolbook_page_append(otb, NULL, _("Keyboard"), ol,
                                 1, 0, 1, 0, 0.5, 0.0);

   /* Automatic Move and resize */
   ol = e_widget_list_add(evas, 0, 0);
   ow = e_widget_check_add(evas, _("Limit resize to useful geometry"),
                           &(cfdata->geometry_auto_resize_limit));
   e_widget_list_object_append(ol, ow, 1, 0, 0.5);
   ow = e_widget_check_add(evas, _("Move after resize"),
                           &(cfdata->geometry_auto_move));
   e_widget_list_object_append(ol, ow, 1, 0, 0.5);
   ow = e_widget_check_add(evas, _("Adjust windows on shelf hide"),
                           &(cfdata->border_fix_on_shelf_toggle));
   e_widget_list_object_append(ol, ow, 1, 0, 0.5);
   e_widget_toolbook_page_append(otb, NULL, _("Automatic"), ol,
                                 1, 0, 1, 0, 0.5, 0.0);

   /* Transient  */
   ol = e_widget_list_add(evas, 0, 0);
   ow = e_widget_check_add(evas, _("Follow Move"),
                           &(cfdata->transient.move));
   e_widget_list_object_append(ol, ow, 1, 0, 0.5);
   ow = e_widget_check_add(evas, _("Follow Resize"),
                           &(cfdata->transient.resize));
   e_widget_list_object_append(ol, ow, 1, 0, 0.5);
   ow = e_widget_check_add(evas, _("Follow Raise"),
                           &(cfdata->transient.raise));
   e_widget_list_object_append(ol, ow, 1, 0, 0.5);
   ow = e_widget_check_add(evas, _("Follow Lower"),
                           &(cfdata->transient.lower));
   e_widget_list_object_append(ol, ow, 1, 0, 0.5);
   ow = e_widget_check_add(evas, _("Follow Layer"),
                           &(cfdata->transient.layer));
   e_widget_list_object_append(ol, ow, 1, 0, 0.5);
   ow = e_widget_check_add(evas, _("Follow Desktop"),
                           &(cfdata->transient.desktop));
   e_widget_list_object_append(ol, ow, 1, 0, 0.5);
   ow = e_widget_check_add(evas, _("Follow Iconify"),
                           &(cfdata->transient.iconify));
   e_widget_list_object_append(ol, ow, 1, 0, 0.5);

   e_widget_toolbook_page_append(otb, NULL, _("Transients"), ol,
                                 1, 0, 1, 0, 0.5, 0.0);

   e_widget_toolbook_page_show(otb, 0);
   return otb;
}

static void
_cb_disable_check_list(void *data, Evas_Object *obj)
{
   const Eina_List *list = data;
   const Eina_List *l;
   Evas_Object *o;
   Eina_Bool disable = !e_widget_check_checked_get(obj);

   EINA_LIST_FOREACH(list, l, o)
     e_widget_disabled_set(o, disable);
}


text:
require 'spec_helper'

shared_examples_for '#process' do
  describe 'simple element route' do
    subject do
      c = 0
      source.process { c += 1 }
    end
    its(:first) { should == source.first }
    its(:element_type) { should == :vertex }
  end

  describe 'with extensions' do
    let(:extended) { source.add_extensions([Tackle::SimpleMixin]) }
    let(:exts) { Set[] }

    subject { extended.process { |v| exts << v.extensions } }

    its('first.extensions') { should == [Tackle::SimpleMixin] }

    it 'should have the right extensions in the block' do
      subject.first
      exts.first.should == [Tackle::SimpleMixin]
    end
  end
end

Run.tg :read_only do
  use_pacer_graphml_data :read_only

  context 'on route' do
    it_uses '#process' do
      let(:source) { graph.v }
    end
  end

  context 'on element' do
    it_uses '#process' do
      let(:source) { pangloss }
    end
  end
end


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

using System;
using System.Text;
using Hazelcast.Core;

namespace Hazelcast.Serialization
{
    /// <summary>
    /// Implements <see cref="IData"/> on the heap.
    /// </summary>
    internal sealed class HeapData : IData
    {
        // structure is:
        // partition-hash (4 bytes) | type (4 bytes) | data (byte[])

        internal const int PartitionHashOffset = 0;
        internal const int TypeOffset = 4;
        internal const int DataOffset = 8;

        private const int HeapDataOverHead = DataOffset;

        private const int ArrayHeaderSizeInBytes = 16;

        private readonly byte[] _bytes;

        /// <summary>
        /// Initializes a new empty instance of the <see cref="HeapData"/> class.
        /// </summary>
        public HeapData()
        { }

        /// <summary>
        /// Initializes a new instance of the <see cref="HeapData"/> class.
        /// </summary>
        /// <param name="bytes">The data bytes.</param>
        public HeapData(byte[] bytes)
        {
            //??
            // will use a byte to store partition_hash bit
            // array (12: array header, 4: length)

            // type and partition hash are always written with BIG_ENDIAN byte order
            // either we don't have bytes, or we have enough bytes
            if (bytes != null && bytes.Length > 0 && bytes.Length < HeapDataOverHead)
                throw new ArgumentException($"Data should either be empty or contain at least {HeapDataOverHead} bytes.");

            // TODO: HeapData bytes should in fact never be null, we can simplify all this

            _bytes = bytes;
        }

        /// <inheritdoc />
        public int DataSize => Math.Max(TotalSize - HeapDataOverHead, 0);

        /// <inheritdoc />
        public int TotalSize => _bytes?.Length ?? 0;

        /// <inheritdoc />
        public int PartitionHash
        {
            get
            {
                int hash;
                return _bytes != null &&
                       _bytes.Length >= HeapDataOverHead &&
                       (hash = _bytes.ReadInt(PartitionHashOffset, Endianness.BigEndian)) != 0
                    ? hash
                    : GetHashCode();
            }
        }

        public bool HasPartitionHash
            => _bytes != null &&
               _bytes.Length >= HeapDataOverHead &&
               _bytes.ReadInt(PartitionHashOffset, Endianness.BigEndian) != 0;

        /// <inheritdoc />
        public byte[] ToByteArray() => _bytes ?? Array.Empty<byte>();

        /// <inheritdoc />
        public int TypeId
            => TotalSize == 0 ? SerializationConstants.ConstantTypeNull : _bytes.ReadInt(TypeOffset, Endianness.BigEndian);

        /// <inheritdoc />
        public int HeapCost
            // where does this come from?
            => BytesExtensions.SizeOfInt + (_bytes != null ? ArrayHeaderSizeInBytes + _bytes.Length : 0);

        /// <inheritdoc />
        public bool IsPortable
            => SerializationConstants.ConstantTypePortable == TypeId;

        /// <inheritdoc />
        public override bool Equals(object o)
        {
            if (this == o)
                return true;

            if (!(o is IData data))
                return false;

            if (TypeId != data.TypeId)
                return false;

            var dataSize = DataSize;
            if (dataSize != data.DataSize)
                return false;

            return dataSize == 0 || Equals(_bytes, data.ToByteArray());
        }

        /// <inheritdoc />
        public override int GetHashCode()
        {
            return Murmur3HashCode.Hash(_bytes, DataOffset, DataSize);
        }

        /// <inheritdoc />
        public override string ToString()
        {
            var sb = new StringBuilder("DefaultData{");
            sb.Append("type=").Append(TypeId);
            sb.Append(", hashCode=").Append(GetHashCode());
            sb.Append(", partitionHash=").Append(PartitionHash);
            sb.Append(", totalSize=").Append(TotalSize);
            sb.Append(", dataSize=").Append(DataSize);
            sb.Append(", heapCost=").Append(HeapCost);
            sb.Append('}');
            return sb.ToString();
        }

        // Same as Arrays.equals(byte[] a, byte[] a2) but loop order is reversed.
        private static bool Equals(byte[] data1, byte[] data2)
        {
            if (data1 == data2)
                return true;

            if (data1 == null || data2 == null)
                return false;

            var length = data1.Length;
            if (data2.Length != length)
                return false;

            unchecked
            {
                for (var i = length - 1; i >= DataOffset; i--)
                {
                    if (data1[i] != data2[i])
                        return false;
                }
            }

            return true;
        }
    }
}


text:
module Lolita
  module Controllers
    # This module is included in all controllers and views. UrlHelper provide methods to generate lolita
    # resource paths. As all resources goes to one controller (by default), than it is very difficult to
    # generate url with :controller and :action.
    # There are four methods for path:
    # * lolita_resources_path - goes to index action
    # * lolita_resource_path - goes to create, destroy or show, it depends what kind of method is used
    # * new_lolita_resource_path - goes to new action
    # * edit_lolita_resource_path - goes to edit action
    # All of those methods accept mapping as a first argument and optional options that
    # will be passed to path gererator. It is possible to pass only options, than current mapping will be used.
    # ====Example
    #     # lets say, that current mapping is for posts
    #     edit_lolita_resource_path(:id=>4) #=> /lolita/posts/4/edit
    #     edit_lolita_resource_path(comment_mapping,:id=>1,:parent_id=>2) #=> /lolita/comments/1/edit?parent_id=2
    # For custom actions there are method #lolita_resource_name that make it easier to generate custom method.
    # All other methods use that for real resource path method generation.
    module UrlHelpers

      def self.included(model_klass)
        model_klass.class_eval do

          # Overrides url_for when controller or view uses this helper.
          # It catches hash options and replaces with lolita named route
          # Without this method routes always looks like /lolita/rest/[method]
          # ====Example
          #     # in routes.rb
          #     lolita_for :posts
          #     # GET /lolita/posts
          #     # in view
          #     url_for #=> /lolita/posts
          #     url_for(:controller=>"/posts",:action=>:index) #=> /posts
          #     # GET /posts
          #     url_for #=> /posts
          def url_for_with_lolita options = {}
            if request && options.is_a?(Hash) && !options[:use_route] && self.respond_to?(:lolita_mapping) && self.lolita_mapping
              controller = options[:controller].to_s
              if Lolita.mappings[lolita_mapping.name].controllers.values.include?(controller)
                resource_type = {
                  :index => :lolita_resources_path,
                  :new => :new_lolita_resource_path,
                  :edit => :edit_lolita_resource_path,
                  :create => :lolita_resources_path
                }
                action = (options[:action] || params[:action]).to_sym
                options = self.send(resource_type[action] || :lolita_resource_path,options)
              end
            end

            url_for_without_lolita(options)
          end
          alias_method :url_for_without_lolita, :url_for
          alias_method :url_for, :url_for_with_lolita

        end
      end

      protected

      # Path for index.
      def lolita_resources_path(*args)
        options=args.extract_options!
        mapping=args[0]
        send(lolita_resource_name(:mapping=>mapping,:plural=>true),options)
      end

      # Path for show, create and destroy
      def lolita_resource_path(*args)
        options=args.extract_options!
        mapping=args[0]
        send(lolita_resource_name(:mapping=>mapping),options)
      end

      # Path for new.
      def new_lolita_resource_path(*args)
        options=args.extract_options!
        mapping=args[0]
        send(lolita_resource_name(:mapping=>mapping,:action=>:new),options)
      end

      # Path for edit.
      def edit_lolita_resource_path(*args)
        options=args.extract_options!
        options[:id]||=resource.id if resource
        #raise "Can edit resource without id." unless options[:id]
        mapping=args[0]
        send(lolita_resource_name(:mapping=>mapping,:action=>:edit),options)
      end

      # It return symbol, that represents named route method for path, like lolita_posts_path and so on.
      # It accepts those options:
      # * <tt>:mapping</tt> - Lolita::Mapping object, that is used to detect name of named route.
      # by default it uses Lolita::InternalHelpers#lolita_mapping.
      # * <tt>:plural</tt> - What kind of named route should use, plural or singular.
      # * <tt>:action</tt> - Action is used to put before named route like :edit.
      # ====Example
      #     # current mapping is for posts
      #     lolita_resource_name(:action=>:edit) #=> :edit_lolita_post_path
      #     lolita_resource_name(:plural=>true,:action=>:list) #=> :list_lolita_posts_path
      #     # for different mapping
      #     lolita_resource_name(:mapping=>comments_mapping) #=> :lolita_comment_path
      # This methods is very useful to create your own paths in views.
      def lolita_resource_name(options={}) #TODO test if path is right
        options.assert_valid_keys(:mapping,:plural,:action)
        mapping=options[:mapping].respond_to?(:plural) ? options[:mapping] : lolita_mapping
        name=!options[:plural] ? mapping.name : mapping.plural
        name="#{mapping.path}_#{name}"
        addon = if mapping.plural == mapping.singular && options[:plural]
          "_index"
        end
        :"#{options[:action]}#{options[:action] ? "_" : ""}#{name}#{addon}_path"
      end
    end
  end
end


text:
<?php

namespace ContentManagerBundle\ContentManagerBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\File\UploadedFile;

/**
 * class DashboardController
 *
 * @Route("/contentmanager")
 */
class DashboardController extends DefaultController
{
    /**
     * @Route("/dashboard", name="dashboard")
     * @Template()
     */
    public function dashboardAction()
    {
        return array();
    }
}


text:
module Reddit
  ( runReddit
  , runRedditAnon
  , runRedditWith
  , runResumeRedditWith
  , interpretIO
  , RedditOptions(..)
  , defaultRedditOptions
  , LoginMethod(..)
  -- * Re-exports
  , APIError(..)
  , module Reddit.Actions
  , module Reddit.Types
  , module Reddit.Types.Error
  , module Reddit.Types.Reddit ) where

import Reddit.Actions
import Reddit.Login
import Reddit.Types.Error
import Reddit.Types
import Reddit.Types.Reddit hiding (info, should)

import Control.Concurrent
import Control.Monad
import Control.Monad.IO.Class
import Control.Monad.Trans.Free
import Data.ByteString.Char8 (ByteString)
import Data.Default.Class
import Data.Text (Text)
import Data.Text.Encoding (encodeUtf8)
import Network.API.Builder as API
import Network.HTTP.Client
import Network.HTTP.Client.TLS
import Network.HTTP.Types

-- | Options for how we should run the 'Reddit' action.
--
-- - 'rateLimitingEnabled': 'True' if the connection should be automatically rate-limited
--   and should pause when we hit the limit, 'False' otherwise.
--
-- - 'connectionManager': @'Just' x@ if the connection should use the 'Manager' @x@, 'Nothing'
--   if we should create a new one for the connection.
--
-- - 'loginMethod': The method we should use for authentication, described in 'LoginMethod'.
--
-- - 'customUserAgent': @'Just' "string"@ if the connection should use the user agent @"string"@,
--   @'Nothing'@ if it should use the default agent.
data RedditOptions =
  RedditOptions { rateLimitingEnabled :: Bool
                , connectionManager :: Maybe Manager
                , loginMethod :: LoginMethod
                , customUserAgent :: Maybe ByteString }

instance Default RedditOptions where
  def = RedditOptions True Nothing Anonymous Nothing

-- | The default set of options
defaultRedditOptions :: RedditOptions
defaultRedditOptions = def

-- | Should we log in to Reddit? If so, should we use a stored set of credentials
--   or get a new fresh set?
data LoginMethod = Anonymous -- ^ Don't login, instead use an anonymous account
                 | Credentials Text Text -- ^ Login using the specified username and password
                 | StoredDetails LoginDetails -- ^
                 --   Login using a stored set of credentials. Usually the best way to get
                 --   these is to do @'runRedditAnon' $ 'login' user pass@.
  deriving (Show)

instance Default LoginMethod where def = Anonymous

-- | Run a 'Reddit' action (or a 'RedditT' transformer action). This uses the default logged-in settings
--   for 'RedditOptions': rate limiting enabled, default manager, login via username and password, and
--   the default user-agent. You should change the user agent if you're making anything more complex than
--   a basic script, since Reddit's API policy says that you should have a uniquely identifiable user agent.
runReddit :: MonadIO m => Text -> Text -> RedditT m a -> m (Either (APIError RedditError) a)
runReddit user pass = runRedditWith def { loginMethod = Credentials user pass }

-- | Run a 'Reddit' action (or a 'RedditT' transformer action). This uses the default logged-out settings, so
--   you won't be able to do anything that requires authentication (like checking messages or making a post).
--   At the moment, authentication isn't statically checked, so it'll return a runtime error if you try to do
--   anything you don't have permissions for.
runRedditAnon :: MonadIO m => RedditT m a -> m (Either (APIError RedditError) a)
runRedditAnon = runRedditWith def

-- | Run a 'Reddit' or 'RedditT' action with custom settings. You probably won't need this function for
--   most things, but it's handy if you want to persist a connection over multiple 'Reddit' sessions or
--   use a custom user agent string.
runRedditWith :: MonadIO m => RedditOptions -> RedditT m a -> m (Either (APIError RedditError) a)
runRedditWith opts reddit = liftM dropResume $ runResumeRedditWith opts reddit

-- | Run a 'Reddit' or 'RedditT' action with custom settings. You probably won't need this function for
--   most things, but it's handy if you want to persist a connection over multiple 'Reddit' sessions or
--   use a custom user agent string.
runResumeRedditWith :: MonadIO m => RedditOptions -> RedditT m a -> m (Either (APIError RedditError, Maybe (RedditT m a)) a)
runResumeRedditWith (RedditOptions rl man lm _ua) reddit = do
  manager <- case man of
    Just m -> return m
    Nothing -> liftIO $ newManager tlsManagerSettings
  loginCreds <- case lm of
    Anonymous -> return $ Right Nothing
    StoredDetails ld -> return $ Right $ Just ld
    Credentials user pass -> liftM (fmap Just) $ interpretIO (RedditState loginBaseURL rl manager [] Nothing) $ login user pass
  case loginCreds of
    Left (err, _) -> return $ Left (err, Just reddit)
    Right lds ->
      interpretIO
        (RedditState mainBaseURL rl manager [("User-Agent", "reddit-haskell dev version")] lds) reddit

interpretIO :: MonadIO m => RedditState -> RedditT m a -> m (Either (APIError RedditError, Maybe (RedditT m a)) a)
interpretIO rstate (RedditT r) =
  runFreeT r >>= \case
    Pure x -> return $ Right x
    Free (WithBaseURL u x n) ->
      interpretIO (rstate { currentBaseURL = u }) x >>= \case
        Left (err, Just resume) ->
          return $ Left (err, Just $ resume >>= RedditT . n)
        Left (err, Nothing) -> return $ Left (err, Nothing)
        Right res -> interpretIO rstate $ RedditT $ n res
    Free (FailWith x) -> return $ Left (x, Nothing)
    Free (Nest x n) ->
      interpretIO rstate $ RedditT $ wrap $ NestResuming x (n . dropResume)
    Free (NestResuming x n) -> do
      res <- interpretIO rstate x
      interpretIO rstate $ RedditT $ n res
    Free (RunRoute route n) ->
      interpretIO rstate $ RedditT $ wrap $ ReceiveRoute route (n . unwrapJSON)
    Free (ReceiveRoute route n) ->
      handleReceive route rstate >>= \case
        Left err@(APIError (RateLimitError secs _)) ->
          if rateLimit rstate
            then do
              liftIO $ threadDelay $ fromInteger secs * 1000 * 1000
              interpretIO rstate $ RedditT $ wrap $ ReceiveRoute route n
            else return $ Left (err, Just $ RedditT $ wrap $ ReceiveRoute route n)
        Left err -> return $ Left (err, Just $ RedditT $ wrap $ ReceiveRoute route n)
        Right x -> interpretIO rstate $ RedditT $ n x

dropResume :: Either (APIError RedditError, Maybe (RedditT m a)) a -> Either (APIError RedditError) a
dropResume (Left (x, _)) = Left x
dropResume (Right x) = Right x

handleReceive :: (MonadIO m, Receivable a) => Route -> RedditState -> m (Either (APIError RedditError) a)
handleReceive r rstate = do
  (res, _, _) <- runAPI (builderFromState rstate) (connMgr rstate) () $
    API.runRoute r
  return res

builderFromState :: RedditState -> Builder
builderFromState (RedditState burl _ _ hdrs (Just (LoginDetails (Modhash mh) cj))) =
  Builder "Reddit" burl addAPIType $
    \req -> addHeaders (("X-Modhash", encodeUtf8 mh):hdrs) req { cookieJar = Just cj }
builderFromState (RedditState burl _ _ hdrs Nothing) =
  Builder "Reddit" burl addAPIType (addHeaders hdrs)

addHeaders :: [Header] -> Request -> Request
addHeaders xs req = req { requestHeaders = requestHeaders req ++ xs }

data RedditState =
  RedditState { currentBaseURL :: Text
              , rateLimit :: Bool
              , connMgr :: Manager
              , _extraHeaders :: [Header]
              , _creds :: Maybe LoginDetails }


text:
const reactModules = [
  'react',
  'react/addons',
  'react-native',
  'proptypes',
  'prop-types',
];

/**
 * Takes a module name (string) and returns true if it refers to a root react
 * module name.
 */
export default function isReactModuleName(moduleName: string): boolean {
  return reactModules.includes(moduleName.toLowerCase());
}


text:
package org.tiatus.entity;

import com.fasterxml.jackson.annotation.JsonGetter;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.hibernate.annotations.GenericGenerator;

import javax.persistence.*;
import java.io.Serializable;
import java.sql.Timestamp;

/**
 * Created by johnreynolds on 12/11/2016.
 */
@Entity
@Table(name = "penalty")
public class Penalty implements Serializable {
    private static final long serialVersionUID = 8109059549918473345L;

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "entry_id")
    private Entry entry;

    @Column(name = "note")
    private String note;

    @Column(name = "comment")
    private String comment;

    @Column(name = "time")
    private Timestamp time;

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY, generator = "UseExistingOrGenerateIdGenerator")
    @GenericGenerator(name="UseExistingOrGenerateIdGenerator",
            strategy="org.tiatus.entity.UseExistingOrGenerateIdGenerator",
            parameters = {
                    @org.hibernate.annotations.Parameter(name = "sequence_name", value = "penalty_id_sequence")
            })
    @Column(name = "id")
    private Long id;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @JsonGetter("entry")
    public Long getEntryId() {
        return entry.getId();
    }

    public Entry getEntry() {
        return entry;
    }

    public void setEntry(Entry entry) {
        this.entry = entry;
    }

    public String getNote() {
        return note;
    }

    public void setNote(String note) {
        this.note = note;
    }

    public String getComment() {
        return comment;
    }

    public void setComment(String comment) {
        this.comment = comment;
    }

    public Timestamp getTime() {
        return time;
    }

    public void setTime(Timestamp time) {
        this.time = time;
    }

    @Override
    public int hashCode() {
        return new HashCodeBuilder()
                .append(this.id)
                .toHashCode();
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }

        if (!(o instanceof Penalty)) {
            return false;
        }

        Penalty penalty = (Penalty) o;
        return new EqualsBuilder()
                .append(this.id, penalty.id)
                .isEquals();
    }
}


text:
United States Senate voting records data from the 106th Congress (1999-2000)

Source: https://www.senate.gov/legislative/LIS/roll_call_lists/vote_menu_106_1.htm

The data set contains 100 variables, which correspond to 100 senators. Each of the 542 samples is a bill that was put to a vote. The votes are recorded as 0 for a No vote and 1 for a Yes vote.


text:
namespace SuperheroesUniverse.Importer.Dto
{
    using System.Collections.Generic;

    public class Superhero
    {
        public string Name { get; set; }
        public string SecretIdentity { get; set; }
        public string Alignment { get; set; }
        public string Story { get; set; }
        public City City { get; set; }
        public ICollection<string> Powers { get; set; }
        public ICollection<string> Fractions { get; set; }
    }
}


text:
3F5Caches
=========

Some utilities written by Devang Agrawal for the 3F5 Caches Lab

Run the tester.sh program from the same folder as your compiled blocking program

The blocking code was edited to take the blocking factor as a parameter, these changes can be copied over to your code from the first few lines of the blocking.cc file to be able to use this tester properly


text:
require 'helper'

class TestPagination < Test::Unit::TestCase
  should "respond to #paginate" do
    assert_respond_to Pagination, :paginate
  end

  context "since we're assume OhmAdapter by default" do
    should "at minimum accept a collection" do
      assert_nothing_raised do
        Pagination.paginate([])
      end
    end
  end

  context "given an empty collection" do
    setup do
      @collection = Pagination.paginate([])
    end

    should "default to page 1" do
      assert_equal 1, @collection.page
    end

    should "be current?(1)" do
      assert @collection.current?(1)
    end

    should "default to 15 per page" do
      assert_equal 15, @collection.per_page
    end

    should "have no prev page sinced it's page 1" do
      assert_nil @collection.prev_page
    end

    should "have no next page since the collection passed was empty" do
      assert_nil @collection.next_page
    end

    should "not render" do
      assert ! @collection.render?
    end
  end

  context "given 2 items, page 1, per_page 1" do
    setup do
      @collection = Pagination.paginate(['first', 'second'], :per_page => 1)
    end

    should "have no prev page" do
      assert_nil @collection.prev_page
    end

    should "have a next page of 2" do
      assert_equal 2, @collection.next_page
    end

    context 'when we set page to 2' do
      setup do
        @collection = Pagination.paginate(['f', 's'], :page => 2, :per_page => 1)
      end

      should "have a prev page of 1" do
        assert_equal 1, @collection.prev_page
      end

      should "have no next page" do
        assert_nil @collection.next_page
      end
    end
  end

  context "given we have 100 pages and we're at pages 1 to 6" do
    should "have 1 to 10 of displayed_pages" do
      (1..6).each do |p|
        collection = Pagination.paginate((1..100).to_a, :per_page => p)
        assert_equal (1..10).to_a, collection.displayed_pages
      end
    end
  end

  context "given we have 100 pages and we're at page 7" do
    setup do
      @collection = Pagination.paginate((1..100).to_a, :per_page => 1, :page => 7)
    end

    should "have 2 to 11 of displayed_pages" do
      assert_equal (2..11).to_a, @collection.displayed_pages
    end
  end

  context "given we have 100 pages and we're at page 50" do
    setup do
      @collection = Pagination.paginate((1..100).to_a, :per_page => 1, :page => 50)
    end

    should "have 45 to 54 of displayed_pages" do
      assert_equal (45..54).to_a, @collection.displayed_pages
    end
  end

  context "given we have 100 pages and we're at page 94" do
    should "start with 89 and end with 98" do
      collection = Pagination.paginate((1..100).to_a, :per_page => 1, :page => 94)
      assert_equal (89..98).to_a, collection.displayed_pages
    end
  end

  context "given we have 100 pages and we're at page 95" do
    should "start with 90 and end with 99" do
      collection = Pagination.paginate((1..100).to_a, :per_page => 1, :page => 95)
      assert_equal (90..99).to_a, collection.displayed_pages
    end
  end

  context "given we have 100 pages and we're at pages 96 up to 100" do
    should "start with 91 and end with 100" do
      (96..100).each do |p|
        collection = Pagination.paginate((1..100).to_a, :per_page => 1, :page => p)
        assert_equal (91..100).to_a, collection.displayed_pages
      end
    end
  end

  context "given we have 5 pages and we're at page 2 up to 5" do
    should "always display the 5 pages" do
      (1..5).each do |p|
        collection = Pagination.paginate((1..100).to_a, :per_page => 20, :page => p)
        assert_equal (1..5).to_a, collection.displayed_pages
      end

    end
  end
end


text:
{% extends "arctic/base_list.html" %}

{% load i18n staticfiles arctic_tags %}

{% block scripts_bottom %}
    {{ block.super }}
    {% verbatim %}

    {% endverbatim %}
{% endblock %}


text:
package test.conffailure;

import org.testng.annotations.BeforeSuite;

public class ClassWithFailedBeforeSuite {

  @BeforeSuite
  public void setUpShouldFail() {
    throw new RuntimeException("Failing in setUp");
  }
}


text:
'''
 PID Controll class inspired by the rainbow_dash of the
 CDTM Drone Elective 2015.
 https://github.com/CDTM/Autonomous-Drones/tree/master/rainbow_dash
'''

class PID:
    ''' PID Controller '''
    def __init__(self, Kp=0.25, Kd=0.25, Ki=0.05):
        self.Kp = Kp
        self.Kd = Kd
        self.Ki = Ki
        self.last_error = 0

    def step(self, error):
        nextStep = self.Kp*error + self.Ki*(error+self.last_error) + self.Kd*(error-self.last_error)
        self.last_error = error
        return nextStep


text:
<?xml version="1.0" encoding="UTF-8"?>
<project name="pas_ref_app" default="package">
  <property name="build.dir" value="build"/>
  <property name="build.version" value="0.1"/>

  <property name="dist.file" value="${build.dir}/dist/${ant.project.name}-${build.version}.tar.gz"/>

  <property name="mainapp.dir" value="${build.dir}/${ant.project.name}"/>

  <target name="clean">
    <delete dir="${build.dir}"/>
  </target>

  <target name="mainapp">
    <mkdir dir="${mainapp.dir}"/>
    <copy todir="${mainapp.dir}">
      <fileset dir=".">
        <exclude name="**/.*"/>
        <exclude name="local/**"/>
        <exclude name="build/**"/>
        <exclude name="**/*-gist"/>
        <exclude name="**/*.xcf"/>
        <exclude name="build.*"/>
        <exclude name="default/app.conf"/>
      </fileset>
    </copy>

    <copy todir="${mainapp.dir}/default" file="default/app.conf" verbose="on">
      <filterset>
        <filter token="VERSION" value="${build.version}"/>
      </filterset>
    </copy>
  </target>

  <target name="package" depends="mainapp">
    <mkdir dir="${build.dir}/dist"/>
    <tar destfile="${dist.file}" longfile="gnu" compression="gzip">
      <tarfileset dir="${build.dir}" filemode="755" username="splunk" group="splunk">
        <include name="${ant.project.name}/**"/>
      </tarfileset>
    </tar>
  </target>
</project>


text:
class GURL;
class PrefRegistrySimple;

namespace policy {

class DlpReportingManager;

#if BUILDFLAG(IS_CHROMEOS_ASH)
class DlpFilesController;
#endif

class DlpRulesManagerImpl : public DlpRulesManager {
 public:
  using RuleId = int;
  using UrlConditionId = base::MatcherStringPattern::ID;

  ~DlpRulesManagerImpl() override;

  // Registers the policy pref.
  static void RegisterPrefs(PrefRegistrySimple* registry);

  // DlpRulesManager:
  Level IsRestricted(const GURL& source,
                     Restriction restriction) const override;
  Level IsRestrictedByAnyRule(const GURL& source,
                              Restriction restriction,
                              std::string* out_source_pattern) const override;
  Level IsRestrictedDestination(
      const GURL& source,
      const GURL& destination,
      Restriction restriction,
      std::string* out_source_pattern,
      std::string* out_destination_pattern) const override;
  Level IsRestrictedComponent(const GURL& source,
                              const Component& destination,
                              Restriction restriction,
                              std::string* out_source_pattern) const override;
  AggregatedDestinations GetAggregatedDestinations(
      const GURL& source,
      Restriction restriction) const override;
  AggregatedComponents GetAggregatedComponents(
      const GURL& source,
      Restriction restriction) const override;
  bool IsReportingEnabled() const override;
  DlpReportingManager* GetReportingManager() const override;

#if BUILDFLAG(IS_CHROMEOS_ASH)
  DlpFilesController* GetDlpFilesController() const override;
#endif

  std::string GetSourceUrlPattern(const GURL& source_url,
                                  Restriction restriction,
                                  Level level) const override;
  size_t GetClipboardCheckSizeLimitInBytes() const override;
  bool IsFilesPolicyEnabled() const override;

 protected:
  friend class DlpRulesManagerFactory;

  explicit DlpRulesManagerImpl(PrefService* local_state);

 private:
  void OnPolicyUpdate();

  // Used to track kDlpRulesList local state pref.
  PrefChangeRegistrar pref_change_registrar_;

  // Map from the components to their configured rules IDs.
  std::map<Component, std::set<RuleId>> components_rules_;

  // Map from the restrictions to their configured rules IDs and levels.
  std::map<Restriction, std::map<RuleId, Level>> restrictions_map_;

  // Vector of source urls conditions.
  url_matcher::URLMatcherConditionSet::Vector src_conditions_;

  // Vector of destination urls conditions.
  url_matcher::URLMatcherConditionSet::Vector dst_conditions_;

  // Used to match the URLs of the sources.
  std::unique_ptr<url_matcher::URLMatcher> src_url_matcher_;

  // Used to match the URLs of the destinations.
  std::unique_ptr<url_matcher::URLMatcher> dst_url_matcher_;

  // Map from the URL matching conditions IDs of the sources to their configured
  // rules IDs.
  std::map<UrlConditionId, RuleId> src_url_rules_mapping_;

  // Map from the URL matching conditions IDs of the destinations to their
  // configured rules IDs.
  std::map<UrlConditionId, RuleId> dst_url_rules_mapping_;

  // Map from the URL matching conditions IDs of the sources to their string
  // patterns.
  std::map<UrlConditionId, std::string> src_pattterns_mapping_;

  // Map from the URL matching conditions IDs of the destinations to their
  // string patterns.
  std::map<UrlConditionId, std::string> dst_pattterns_mapping_;

  // System-wide singleton instantiated when required by rules configuration.
  std::unique_ptr<DlpReportingManager> reporting_manager_;

#if BUILDFLAG(IS_CHROMEOS_ASH)
  // System-wide singleton instantiated when there are rules involving files.
  std::unique_ptr<DlpFilesController> files_controller_;
#endif
};

}  // namespace policy

#endif  // CHROME_BROWSER_CHROMEOS_POLICY_DLP_DLP_RULES_MANAGER_IMPL_H_


text:
/* global describe it */
import React, { Component } from 'react';
import Enzyme, { mount } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import connect from 'react-tracker-connect';
import { Meteor } from 'meteor/meteor';
import { Tracker } from 'meteor/tracker';
import { ReactiveVar } from 'meteor/reactive-var';
import { chai } from 'meteor/practicalmeteor:chai';

Enzyme.configure({ adapter: new Adapter() });

if (Meteor.isClient) {
  // client side tests
  describe('Options', () => {
    it('not allowed props should be undefined', () => {
      const reactive = new ReactiveVar(1);
      let runs = 0;

      @connect(({ num, notAllowed }) => {
        runs += 1;
        return { value: reactive.get() * num, typeOfNotAllowed: typeof notAllowed };
      }, {
        allowedProps: ['num'],
      })
      class Foo extends Component {
        constructor() {
          super();
          this.renderCount = 0;
        }
        render() {
          this.renderCount += 1;
          return (

{ this.renderCount }

{ JSON.stringify(this.props || {}) }

          );
        }
      }

      let props;
      const item = mount(<Foo num={10} notAllowed />);
      props = JSON.parse(item.find('.props').text());
      chai.assert.equal(props.value, 10);
      chai.assert.equal(props.notAllowed, true);
      chai.assert.equal(props.typeOfNotAllowed, 'undefined');
      chai.assert.equal(parseInt(item.find('.renderCount').text(), 10), 1);
      chai.assert.equal(runs, 1);

      reactive.set(10);
      Tracker.flush({ _throwFirstError: true });
      props = JSON.parse(item.find('.props').text());
      chai.assert.equal(props.value, 100);
      chai.assert.equal(props.notAllowed, true);
      chai.assert.equal(props.typeOfNotAllowed, 'undefined');
      chai.assert.equal(parseInt(item.find('.renderCount').text(), 10), 2);
      chai.assert.equal(runs, 2);

      item.setProps({ notReactive: 2 });
      Tracker.flush({ _throwFirstError: true });
      props = JSON.parse(item.find('.props').text());
      chai.assert.equal(props.value, 100);
      chai.assert.equal(props.notReactive, 2);
      chai.assert.equal(props.notAllowed, true);
      chai.assert.equal(props.typeOfNotAllowed, 'undefined');
      chai.assert.equal(parseInt(item.find('.renderCount').text(), 10), 3);
      chai.assert.equal(runs, 2);

      item.unmount();
    });
  });
} else {
  // server side tests
}


text:
package ch.bfh.controllers;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;

import java.util.List;
import java.util.stream.Collectors;

import static org.junit.Assert.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@RunWith(SpringRunner.class)
@WebMvcTest(PieChartController.class)
@ComponentScan(basePackages = { "ch.bfh" })
public class PieChartControllerTest {
    @Autowired
    PieChartController pieChartController;

    @Autowired
    private MockMvc mockMvc;

    @Test
    public void shouldreturnaListofanalyse() throws Exception {
        List<String> availableendpoints = pieChartController.analysen.stream().map(a -> a.getName()).collect(Collectors.toList());
        String responsebody = availableendpoints.toString();

        this.mockMvc.perform(get("/api/piechart/list"))
                .andDo(print())
                .andExpect(status().is(200))
                .andExpect(content().json(responsebody));
    }

    @Test
    public void shouldreturnPiecharts() throws Exception{

    }

}