text:
import os
import json
from random import randint
from random import choice
import mysql.connector
from mysql.connector import errorcode

conn = mysql.connector.connect(user='lucas', password='ohjustpoutthen',
        host='localhost', database='it478')

tables = {}

tables['users'] = ("create table users (idUser bigint not null primary key, gender char(1) not null, age datetime not null, zipcode int(5) not null, city varchar(45) not null)")

tables['tweets'] = ("create table tweets (idUser bigint not null, tweetText varchar(140) not null, tweetDate datetime not null, retweetCount smallint not null, idTweet bigint not null primary key, sentimentScore double not null, constraint fk_tweets_user foreign key (idUser) references users (idUser))")

tables['sentiment_staging_users'] = ("create table sentiment_staging_users (idUser bigint not null primary key, gender char(1) not null, age datetime not null, zipcode int(5) not null, city varchar(45) not null, status varchar(45) null)")

tables['sentiment_staging_tweets'] = ("create table sentiment_staging_tweets (Sentiment_Staging_User_idUser bigint not null, tweetText varchar(140) not null, tweetDate datetime not null, retweetCount smallint not null, idTweet bigint not null primary key, sentimentScore double null, status varchar(45) null, constraint fk_tweets_staging_user foreign key (Sentiment_Staging_User_idUser) references sentiment_staging_users (idUser))")

cursor = conn.cursor()

for name, ddl in tables.items():
    try:
        print("Creating table {}: ".format(name), end='')
        cursor.execute(ddl)
    except mysql.connector.Error as err:
        if err.errno == errorcode.ER_TABLE_EXISTS_ERROR:
            print("already exists.")
        else:
            print(err.msg)
    else:
        print("OK")

cursor.execute('create index fk_Tweets_User_idx on tweets (idUser asc)')
cursor.execute('create index fk_Sentiment_Staging_Tweets_Sentiment_Staging_User1_idx on sentiment_staging_tweets (Sentiment_Staging_User_idUser asc)')

def getUserIDs(path):
    user_list = os.listdir(path)
    return user_list

def setGender():
    # Simulate a coin flip as for whether a user will be male or female
    coin = randint(0,1)
    gender = 'F'
    if coin == 0:
        gender = 'M'
    return gender

def setAge():
    month = str(randint(1, 12))
    day = str(randint(1, 28))
    year = str(randint(1979, 1996))
    birthday = year+'-'+month+'-'+day
    return birthday

def setZip():
    zips = {    '61701':'Bloomington',
                '61702':'Bloomington',
                '61704':'Bloomington',
                '61705':'Bloomington',
                '61709':'Bloomington',
                '61710':'Bloomington',
                '61791':'Bloomington',
                '61799':'Bloomington',
                '61761':'Normal',
                '61790':'Normal'        }

    randzip = choice(list(zips.keys()))
    return [randzip, zips[randzip]]

def processUsers(user_list):
    for user in user_list:
        with open('collected_tweets/'+user, 'r') as user_file:
            tweets = json.load(user_file)
            if len(tweets) == 0:
                print('skipping user: empty tweets')
            else:
                gender = setGender()
                rzip = setZip()
                age = setAge()
                cursor.execute('insert into sentiment_staging_users (idUser, gender, age, zipcode, city) values (%s,%s,%s,%s,%s)', (user, gender, age, rzip[0], rzip[1]))
                for tweet in tweets:
                    row = (user, tweet['text'], str('0'), tweet['retweet_count'], tweet['id_str'], 'LOADED' )
                    cursor.execute('insert into sentiment_staging_tweets (Sentiment_Staging_User_idUser, tweetText, tweetDate, retweetCount, idTweet, status) values (%s, %s, %s, %s, %s)', row)
        conn.commit()

userlist = getUserIDs('collected_tweets')
processUsers(userlist)

cursor.close()
conn.close()


text:
package org.commonjava.indy.bind.jaxrs;

import io.undertow.servlet.api.DeploymentInfo;

import javax.ws.rs.core.Application;
import java.util.Collections;
import java.util.Set;

public abstract class IndyDeploymentProvider
{

    public abstract DeploymentInfo getDeploymentInfo( final String contextRoot, final Application application );

    public Set<Class<?>> getAdditionalClasses()
    {
        return Collections.emptySet();
    }

}

redpajama_set_name: RedPajamaGithub


text:
'use strict';

var isNumeric = require('fast-isnumeric');

var Lib = require('../../lib');
var Axes = require('../../plots/cartesian/axes');

var binFunctions = require('./bin_functions');
var normFunctions = require('./norm_functions');
var doAvg = require('./average');

module.exports = function calc(gd, trace) {
    // ignore as much processing as possible (and including in autorange) if bar is not visible
    if(trace.visible !== true) return;

    // depending on orientation, set position and size axes and data ranges
    // note: this logic for choosing orientation is duplicated in graph_obj->setstyles
    var pos = [],
        size = [],
        i,
        pa = Axes.getFromId(gd,
            trace.orientation==='h' ? (trace.yaxis || 'y') : (trace.xaxis || 'x')),
        maindata = trace.orientation==='h' ? 'y' : 'x',
        counterdata = {x: 'y', y: 'x'}[maindata];

    // prepare the raw data
    var pos0 = pa.makeCalcdata(trace, maindata);
    // calculate the bins
    if((trace['autobin' + maindata]!==false) || !(maindata + 'bins' in trace)) {
        trace[maindata + 'bins'] = Axes.autoBin(pos0, pa, trace['nbins' + maindata]);

        // copy bin info back to the source data.
        trace._input[maindata + 'bins'] = trace[maindata + 'bins'];
    }

    var binspec = trace[maindata + 'bins'],
        allbins = typeof binspec.size === 'string',
        bins = allbins ? [] : binspec,
        // make the empty bin array
        i2,
        binend,
        n,
        inc = [],
        counts = [],
        total = 0,
        norm = trace.histnorm,
        func = trace.histfunc,
        densitynorm = norm.indexOf('density')!==-1,
        extremefunc = func==='max' || func==='min',
        sizeinit = extremefunc ? null : 0,
        binfunc = binFunctions.count,
        normfunc = normFunctions[norm],
        doavg = false,
        rawCounterData;

    if(Array.isArray(trace[counterdata]) && func!=='count') {
        rawCounterData = trace[counterdata];
        doavg = func==='avg';
        binfunc = binFunctions[func];
    }

    // create the bins (and any extra arrays needed)
    // assume more than 5000 bins is an error, so we don't crash the browser
    i = binspec.start;
    // decrease end a little in case of rounding errors
    binend = binspec.end +
        (binspec.start - Axes.tickIncrement(binspec.start, binspec.size)) / 1e6;
    while(i<binend && pos.length<5000) {
        i2 = Axes.tickIncrement(i, binspec.size);
        pos.push((i + i2) / 2);
        size.push(sizeinit);
        // nonuniform bins (like months) we need to search,
        // rather than straight calculate the bin we're in
        if(allbins) bins.push(i);
        // nonuniform bins also need nonuniform normalization factors
        if(densitynorm) inc.push(1 / (i2 - i));
        if(doavg) counts.push(0);
        i = i2;
    }

    var nMax = size.length;
    // bin the data
    for(i=0; i<pos0.length; i++) {
        n = Lib.findBin(pos0[i], bins);
        if(n>=0 && n<nMax) total += binfunc(n, i, size, rawCounterData, counts);
    }

    // average and/or normalize the data, if needed
    if(doavg) total = doAvg(size, counts);
    if(normfunc) normfunc(size, total, inc);

    var serieslen = Math.min(pos.length, size.length),
        cd = [],
        firstNonzero = 0,
        lastNonzero = serieslen-1;
    // look for empty bins at the ends to remove, so autoscale omits them
    for(i=0; i<serieslen; i++) {
        if(size[i]) {
            firstNonzero = i;
            break;
        }
    }
    for(i=serieslen-1; i>firstNonzero; i--) {
        if(size[i]) {
            lastNonzero = i;
            break;
        }
    }

    // create the "calculated data" to plot
    for(i=firstNonzero; i<=lastNonzero; i++) {
        if((isNumeric(pos[i]) && isNumeric(size[i]))) {
            cd.push({p: pos[i], s: size[i], b: 0});
        }
    }

    return cd;
};


text:
ifconfig | awk '/inet addr/{print substr($2,6)}' | grep 172 > /data/service-load-balancer.dat

echo "[${HOSTNAME}] Initialized successfully."


text:
Version v3.0.1 - August 11, 2015
================================================================================

Fixed
--------------------------------------------------------------------------------
  * Parameter errors not being converted properly

Version v3.0.0 - August 11, 2015
================================================================================

Changed
--------------------------------------------------------------------------------
  * VerifiableModel to VerifiableResource and simplified
  * HumanError to be uninstantiable
  * RescuableResource so it doesn't need called
  * RescuableResource's rescue_froms to be simpler
  * Configuration into a singleton
  * Switch from building URLs to using error URL mappings
  * codes to use underscores between words
  * To use the new JSON API format
  * Rename customer_support_uri
  * Rename developer_documentation_uri to url
  * error code into the error's key
  * Moved as_json into main module
  * Moved common accessors into main module
  * Rename developer_message to details
  * Rename developer_details to source
  * Move base_message_key to base module

Added
--------------------------------------------------------------------------------
  * UnpermittedParametersError
  * ParameterMissingError
  * resource name methods to RescuableResource
  * Default source information
  * Default error detail text
  * Default HTTP status
  * id to the error
  * title to the error
  * .ctags configuration file

Removed
--------------------------------------------------------------------------------
  * Unneeded requires
  * via as an option from RescuableResource
  * 'from' as an option from RescuableResource
  * Anything having to do with building URLs
  * Unneeded rescue
  * RequestError superclass
  * friendly message
  * message keys

Version v2.0.0 - April 10, 2015
================================================================================

Removed
--------------------------------------------------------------------------------
  * No longer needed require statement
  * HumanError::Persistable

Changed
--------------------------------------------------------------------------------
  * VerifiableModel to pass the action name
  * VerifiableModel to always return an ID array
  * VerifiableModel to allow the lookup library to be passed in
  * RescuableResource to always rescue HumanErrors
  * HumanError#raise to use build instead of fetch

Fixed
--------------------------------------------------------------------------------
  * HumanError is a class not a module
  * Requiring VerifiableModel
  * Resource name sent to errors
  * raise to use the new version of fetch

Added
--------------------------------------------------------------------------------
  * RecordInvalid and RecordNotValid to convertable errors
  * HumanError#build
  * VerifiableModel from Coadjutor
  * ResourcePersistenceError.convert
  * ResourceNotFoundError.convert
  * AssociationError.convert

Version v1.13.4 - March 26, 2015
================================================================================

Added
--------------------------------------------------------------------------------
  * Deploy script
  * Rubygems settings

Version v1.13.3 - February 17, 2015
================================================================================

Fixed
--------------------------------------------------------------------------------
  * Another missed rescue variable

Version v1.13.2 - February 17, 2015
================================================================================

Fixed
--------------------------------------------------------------------------------
  * Accidentally removed too many raise errors

Version v1.13.1 - February 17, 2015
================================================================================

Fixed
--------------------------------------------------------------------------------
  * resource name in developer details needs to be underscored

Feature
--------------------------------------------------------------------------------
  * Allow ResourceNotFoundError to have a default action
  * Add Apill::Errors::InvalidSubdomainError
  * Switch to CircleCI

Bugfix
--------------------------------------------------------------------------------
  * Override the CircleCI test command

Version v1.12.0 - June 30, 2014
================================================================================

Bugfix
--------------------------------------------------------------------------------
  * RescuableResource was moved without Drew's changes

Version v1.11.0 - June 28, 2014
================================================================================

Version v1.10.0 - June 25, 2014
================================================================================

Feature
--------------------------------------------------------------------------------
  * Allow UUIDs and GUIDs for id column values

Version v1.9.0 - June 10, 2014
================================================================================

Bugfix
--------------------------------------------------------------------------------
  * Remove end-of-string anchors from error message regexes

Feature
--------------------------------------------------------------------------------
  * Default CRUD error action to 'persist'

Version v1.8.2 - June 6, 2014
================================================================================

Version v1.8.1 - June 5, 2014
================================================================================

Bugfix
--------------------------------------------------------------------------------
  * Make find a class method instead of an instance method

Version v1.8.0 - June 5, 2014
================================================================================

Feature
--------------------------------------------------------------------------------
  * Add HumanError::Persistable

Version v1.7.1 - May 28, 2014
================================================================================

Bugfix
--------------------------------------------------------------------------------
  * Rework the 'message' and 'to_s' methods on Error

Version v1.7.0 - May 22, 2014
================================================================================

Feature
--------------------------------------------------------------------------------
  * Add to_s to base Error module

Version v1.6.1 - May 22, 2014
================================================================================

Bugfix
--------------------------------------------------------------------------------
  * Require the association_error file

Version v1.6.0 - May 22, 2014
================================================================================

Bugfix
--------------------------------------------------------------------------------
  * Remove a manual reference to `knowledgebase_article_id`

Feature
--------------------------------------------------------------------------------
  * Add AssociationError

Version v1.5.0 - May 20, 2014
================================================================================

Feature
--------------------------------------------------------------------------------
  * Allow HumanError::Errors to have messages explicitly set

Uncategorized
--------------------------------------------------------------------------------
  * Upgrade rspectacular

Version v1.4.0 - May 6, 2014
================================================================================

Feature
--------------------------------------------------------------------------------
  * Allow HumanError instances to both lookup and raise errors
  * Values passed in when looking up errors override local config
  * Allow local configuration to be passed to looked up errors
  * Allow a HumanError instance to 'look up' an error by name
  * Add Configuration#to_h
  * Allow HumanError to be instantiated with a configuration

Version v1.3.0 - May 6, 2014
================================================================================

Feature
--------------------------------------------------------------------------------
  * Add a DuplicateAuthenticationError

Version v1.2.0 - April 15, 2014
================================================================================

  * Add options as an argument to to_json since that's the standard
    implementation
  * Move developer_documentation_uri into HumanError::Error since all its
    dependencies are in that file

Version v1.1.0 - April 15, 2014
================================================================================

  * Add errors.rb to load all the errors files
  * Add Apill::Errors::InvalidApiRequestError to the ErrorCodeDirectory
  * Since the customer support URI now depends exclusively on items in
    HumanError::Error, we can move it up
  * Extract Knowledgebase ID into KnowledgebaseIdDirectory similarly to how we
    did the ErrorCodeDirectory
  * Errors should be able to convert themselves to JSON
  * Human Error only runs on Ruby 2.x

Version v1.0.0 - April 15, 2014
================================================================================

  * Remove Gemfile.lock from git ignored files
  * Massive refactoring with extra Matrix awesomesauce
  * Add badges
  * Add Travis Integration
  * Add CodeClimate test reporter

Version v0.0.1 - March 24, 2014
================================================================================

  * Initial commit


text:
from google.cloud import iap_v1

def sample_delete_tunnel_dest_group():
    # Create a client
    client = iap_v1.IdentityAwareProxyAdminServiceClient()

    # Initialize request argument(s)
    request = iap_v1.DeleteTunnelDestGroupRequest(
        name="name_value",
    )

    # Make the request
    client.delete_tunnel_dest_group(request=request)

# [END iap_v1_generated_IdentityAwareProxyAdminService_DeleteTunnelDestGroup_sync]


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
    Copyright 2012 Facebook

    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.
-->

<resources>
    <string name="app_name">ProfilePictureSample</string>
    <string name="description">Sample app demonstrating the use of ProfilePictureView</string>
    <string name="cropping_label">Show cropped version</string>
    <string name="crop_original_button_text">Original</string>
    <string name="crop_square_button_text">Square</string>
    <string name="user_chris_name">Chris</string>
    <string name="user_michael_name">Michael</string>
    <string name="user_karthik_name">Karthik</string>
    <string name="user_random_name">Random</string>
    <string name="user_none_name">None</string>
    <string name="smaller_button_text">-</string>
    <string name="larger_button_text">+</string>
    <string name="large_image_size">Large</string>
    <string name="normal_image_size">Normal</string>
    <string name="small_image_size">Small</string>
    <string name="preset_size_button_text">Use preset size</string>
    <string name="custom_size_button_text">Use custom size</string>
</resources>


text:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ProjectileSpawner : MonoBehaviour {

	int i;

	// Use this for initialization
	void Start () {

	}

	// Update is called once per frame
	void Update () {
		if (i++ % 60 == 0) {
			Instantiate(Resources.Load("Prefabs/Projectiles/Test"), new Vector2(this.transform.position.x, this.transform.position.y), Quaternion.identity);
		}
	}
}


text:
package io.quarkus.test.junit.buildchain;

import java.util.function.Consumer;

import org.jboss.jandex.Index;

import io.quarkus.builder.BuildChainBuilder;

/**
 * Implementation of this class have the ability to add build items
 */
public interface TestBuildChainCustomizerProducer {

    Consumer<BuildChainBuilder> produce(Index testClassesIndex);
}


text:
package griffon.plugins.domain.orm;

import griffon.exceptions.GriffonException;

/**
 * An exception thrown when an error occurs visiting a criteria closure
 *
 * @author Andres Almiray
 */
public class CriteriaVisitException extends GriffonException {
    public CriteriaVisitException() {
        super();
    }

    public CriteriaVisitException(String arg0, Throwable arg1) {
        super(arg0, arg1);
    }

    public CriteriaVisitException(String arg0) {
        super(arg0);
    }

    public CriteriaVisitException(Throwable arg0) {
        super(arg0);
    }
}


text:
function ind2run(rle::RLEVector, i::Integer)
  re = rle.runends
  n = length(re)
  run = searchsortedfirst(re,i,1,n)
  run <= n || throw(BoundsError())  # Can't be < 1
  return(run)
end

function ind2run(rle::RLEVector,i::UnitRange)
  re = rle.runends
  n = length(re)
  left_run = searchsortedfirst(re,first(i),1,n)
  right_run = searchsortedfirst(re,last(i),left_run,n)
  right_run <= n || throw(BoundsError())  # Can't be < 1
  return( left_run:right_run )
end

function ind2run(rle::RLEVector, i::AbstractArray)
  re = rle.runends
  n = length(re)
  runs = searchsortedfirst(re,i,1,n)
  maximum(runs) <= n || throw(BoundsError())  # Can't be < 1
  return(runs)
end

# get index of the run corresponding to the i'th value in the expanded runs, index in run and remainder of run
#  (runindex, index_in_run, values_in_run_after_i)
function ind2runcontext(rle::RLEVector, i::Integer)
  run = ind2run(rle, i)
  runend = rle.runends[run]
  ind_in_run = run == 1 ? i : i - rle.runends[run-1]
  (run, ind_in_run, runend - i)
end

function ind2runcontext(rle::RLEVector, i::UnitRange)
  s = start(i)
  e = last(i)
  n = length(rle)
  runs = ind2run(rle, i)
  left_run = start(runs)
  right_run = last(runs)
  runend = rle.runends[right_run]
  ind_in_run = left_run == 1 ? s : s - rle.runends[left_run-1]
  (left_run, right_run, ind_in_run, runend - e)
end

function setrun!(rle::RLEVector, value, i::Int)
  run = ind2run(rle,i)
  rle.runvalues[run] = value
  return(rle)
end

## Just enough for AbstractArray
Base.linearindexing{T<:RLEVector}(::Type{T}) = Base.LinearFast()

endof(rle::RLEVector) = length(rle)

function Base.getindex(rle::RLEVector, i::Int)
    run = ind2run(rle,i)
    return( rle.runvalues[run] )
end

function Base.setindex!(rle::RLEVector, value, i::Int)
  run = ind2run(rle,i)
  runvalue = rle.runvalues[run]
  runend = rle.runends[run]
  value == runvalue && return rle # replace with same value, no-op
  previous_run = run - 1
  next_run = run + 1
  at_start_of_run = (previous_run > 0 && i == rle.runends[previous_run] + 1) || i == 1
  at_end_of_run = i == runend
  match_left = run > 1 && rle.runvalues[previous_run] == value
  match_right = run < nrun(rle) && rle.runvalues[next_run] == value
  if at_end_of_run
    if at_start_of_run # in a run of length 1
      if match_right && match_left
        splice!(rle.runvalues, previous_run:run)
        splice!(rle.runends, previous_run:run)
      elseif match_right
        splice!(rle.runvalues,run)
        splice!(rle.runends,run)
      elseif match_left
        splice!(rle.runvalues,run)
        splice!(rle.runends,previous_run)
      else
        rle.runvalues[run] = value
      end
    else # end of a run longer than 1
      if match_right
        rle.runends[run] = runend - 1
      else
        insert!(rle.runvalues, next_run, value)
        insert!(rle.runends, run, runend - 1)
      end
    end
  elseif at_start_of_run
    if match_left
      rle.runends[previous_run] = rle.runends[previous_run] + 1
    else
      insert!(rle.runvalues, run, value)
      insert!(rle.runends, run, i)
    end
 else # middle of a run, average case
    splice!(rle.runvalues, run, [runvalue,value,runvalue])
    splice!(rle.runends, run, [i-1,i,runend])
  end
  return(rle)
end

function Base.getindex(rle::RLEVector, ind::Array{Bool, 1})
    rle[ find(ind) ]
end

function Base.setindex!(rle::RLEVector, value::AbstractArray, ind::Array{Bool, 1})
    rle[ find(ind) ] = value
end

## Indexing optimizations
function Base.getindex(rle::RLEVector, ind::UnitRange)
    runs = ind2run(rle,collect(ind)) # OPTIMIZE ME: ind2runcontext
    rv = rle.runvalues[runs]
    return(rv)
end

#function Base.slice(rle::RLEVector, indices::UnitRange)
#    runs = ind2run(rle,indices)
#    rv = rle.runvalues[runs]
#    nrun = length(runs)
#    re = similar(rle.runends, nrun)
#    offset = start(indices) - 1
#    @inbounds for (i,r) in enumerate( start(runs):(last(runs) - 1) )
#        re[i] = rle.runends[r] - offset
#    end
#    re[nrun] = last(indices) - offset # length(indices)
#    rval = RLEVector{eltype(rv),eltype(re)}(rv,re)
#    return(rval)
#end

function Base.getindex(rle::RLEVector, ind::AbstractVector)
    run_indices = ind2run(rle, ind)
    return( RLEVector( rle.runvalues[ run_indices ] ) )
end

function Base.setindex!{T1,T2}(rle::RLEVector{T1,T2}, value::T1, indices::UnitRange)
  runs = ind2run(rle,indices)
  left_run = first(runs)
  right_run = last(runs)
  left_runvalue = rle.runvalues[left_run]
  right_runvalue = rle.runvalues[right_run]
  left_runend = rle.runends[left_run]
  right_runend = rle.runends[right_run]
  left_i = start(indices)
  right_i = last(indices)
  previous_run = left_run - 1
  next_run = right_run + 1
  at_start_of_run = (previous_run > 0 && left_i == rle.runends[previous_run] + 1) || left_i == 1
  at_end_of_run = right_i == right_runend
  match_left = left_run > 1 && rle.runvalues[previous_run] == value
  match_right = right_run < nrun(rle) && rle.runvalues[next_run] == value
  adjusted_runvalues = Array(typeof(left_runvalue),0)
  adjusted_runends = Array(typeof(left_runend),0)
  if at_end_of_run
    if at_start_of_run # in a run of length 1
      if match_right && match_left
        left_run = previous_run
      elseif match_right
        # do nothing
      elseif match_left
        rle.runends[previous_run] = right_runend
      else
        rle.runvalues[right_run] = value
        right_run = right_run - 1
      end
    else
      if match_right
        rle.runends[left_run] = left_i - 1
        left_run = left_run + 1
      else
        adjusted_runvalues = [left_runvalue,value]
        adjusted_runends = [left_i-1,right_i]
      end
    end
  elseif at_start_of_run
    if match_left
      rle.runends[previous_run] = last(indices)
      right_run = right_run - 1
    else
      adjusted_runvalues = [value,right_runvalue]
      adjusted_runends = [right_i,right_runend]
    end
  else # middle of a run, average case
    adjusted_runvalues = [left_runvalue,value,right_runvalue]
    adjusted_runends = [left_i-1,right_i,right_runend]
  end
  adjusted_runs = left_run:right_run
  splice!(rle.runvalues,adjusted_runs,adjusted_runvalues)
  splice!(rle.runends,adjusted_runs,adjusted_runends)
  return(rle)
end

## Getter shortcuts
function head(x::RLEVector,l::Integer=6)
    collect(x[ 1:l ])
end

function tail(x::RLEVector,l::Integer=6)
    collect( x[ length(x)-(l-1):end ] )
end

## Iterators
function start(rle::RLEVector)
  (1,1)
end

function next(rle::RLEVector, state)
  if state[2] == rle.runends[ state[1] ]
    newstate = (state[1] + 1, state[2] + 1)
  else
    newstate = (state[1],state[2] + 1)
  end
  return( (rle.runvalues[state[1]], newstate) )
end

function done(rle::RLEVector, state)
  state[1] > nrun(rle)
end

# Iterator for ranges based on RLE e.g. (value, start, end)
immutable RLEEachIterator{T1,T2}
    rle::RLEVector{T1,T2}
end
each(x::RLEVector) = RLEEachIterator(x)

function start(x::RLEEachIterator)
    1
end

function next(x::RLEEachIterator, state)
    newstate = state + 1
    first = rfirst(x.rle,state)
    last = rlast(x.rle)[state]
    ( (rvalue(x.rle)[state], first:last ), newstate )
end

function done(x::RLEEachIterator, state)
    state > nrun(x.rle)
end


text:
import attributes from './attributes';

let action;

describe('attributes reducer', () => {
  describe('when receiving an UPDATE_ATTRIBUTE action', () => {
    beforeEach(() => { action = { type: 'UPDATE_ATTRIBUTE', attributeName: 'foo', value: 'bar' } });

    describe('and the state doesn\'t yet contain the attributeName in it', () => {
      it('records the action\'s attributeName and value to its state object', () => {
        expect(attributes(undefined, action)).toEqual({ foo: 'bar' });
      });
    });

    describe('and the state already contain the attributeName in it', () => {
      it('updates the value attributed to attributeName', () => {
        const previousState = { foo: 'some bar' };
        expect(attributes(previousState, action)).toEqual({ foo: 'bar' });
      });
    });
  });
});


text:
'use strict';

const EmberAddon = require('ember-cli/lib/broccoli/ember-addon');

module.exports = function (defaults) {
  let project = defaults.project;
  let options = {
    'ember-fetch': {
      preferNative: true,
    },
    vendorFiles: {
      'app-shims.js': null,
    },
  };

  if (project.findAddonByName('ember-native-dom-event-dispatcher')) {
    options.vendorFiles['jquery.js'] = null;
  }

  options.autoImport = {
    webpack: {
      node: {
        global: true,
      },
    },
  };

  // Code snippets for ember-cli-addon-docs
  options.snippetExtensions = ['css', 'hbs', 'js', 'json', 'ts', 'yaml'];

  let app = new EmberAddon(defaults, options);

  /*
    This build file specifies the options for the dummy test app of this
    addon, located in `/tests/dummy`
    This build file does *not* influence how the addon or the app using it
    behave. You most likely want to be modifying `./index.js` or app's build file
  */

  const { maybeEmbroider } = require('@embroider/test-setup');
  return maybeEmbroider(app, {
    skipBabel: [
      {
        package: 'qunit',
      },
    ],
  });
};


text:
"""
Kind of unit tests for CoAP messages.
"""

from ..code_registry import OptionNumber, MessageType, MethodCode
from ..message import CoapMessage, CoapOption

def verify_coap_option(bin_data, option_number, option_value):
    """ Helper function to verify CoapOption works for the given arguments.
    """

    #Build an option with given arguments and verify it
    option = CoapOption(option_number=option_number, option_value=option_value)
    assert option.build() == bin_data

    #Parse the given binary data and verify it matches
    option = CoapOption.parse(bin_data)
    assert option.value == option_value
    assert option.length != 15
    length = option.length
    if option.length == 13:
        length = 13 + option.length_extended
    elif option.length == 14:
        length = 269 + option.length_extended
    assert length == len(option_value)

    calc_opt_number = option.delta
    if option.delta == 13:
        calc_opt_number = 13 + option.delta_extended
    elif option.delta == 14:
        calc_opt_number = 269 + option.delta_extended
    assert calc_opt_number == option_number

def test_coap_option_basic():
    # Basic test case to verify CoAP option for URI path works.
    verify_coap_option('\xb4test', OptionNumber.uri_path, 'test')
    verify_coap_option('\xcbtext/plain;', OptionNumber.content_format, 'text/plain;')

def test_coap_option_long_uri():
    # This test will build an option with very long value and verifies length_extended field is used.
    verify_coap_option('\xbd\x0fthis_is_a_very_long_uri_path', OptionNumber.uri_path, 'this_is_a_very_long_uri_path')

def test_coap_option_two_byte_number():
    # This test will build an option with option number > 12 to test delta_extended field.
    verify_coap_option('\xda\x07correct_me', OptionNumber.location_query, 'correct_me')

def test_coap_option_two_byte_value():
    # This test will build an option with option number > 12 to test delta_extended field.
    verify_coap_option('\xdd\x07\x02very_long_value', OptionNumber.location_query, 'very_long_value')

    verify_coap_option('\x61\x00', OptionNumber.observe, '\x00')

def verify_coap_message(bin_data, message_type, message_id, class_code, class_detail, token, options, payload):
    """ Helper function to verify CoapMessage works for the given arguments.
    """
    if token is None:
        token = ''
    token_length = len(token)
    #Build an option with given arguments and verify it
    msg = CoapMessage(version=1, message_type=message_type, message_id=message_id, class_code=class_code,
                      class_detail=class_detail, token=token, token_length=token_length, options=options, payload=payload)
    assert msg.build() == bin_data

    #Parse the given binary data and verify it matches
    msg = CoapMessage.parse(bin_data)
    assert msg.version == 1
    assert msg.type == message_type
    assert msg.message_id == message_id
    assert msg.class_code == class_code
    assert msg.class_detail == class_detail
    assert msg.token_length == token_length
    if len(options) > 0:
        msg_options = msg.coap_option
        assert len(msg_options) == len(options)
        for idx, opt in enumerate(options):
            assert msg_options[idx] == opt
    assert msg.payload.value == payload or (msg.payload.value == '' and payload is None)

def test_coap_message_ack():
    #acknowledgment with empty message.
    verify_coap_message('`\x01\xab\xcd',
                        message_type=MessageType.acknowledgment, message_id=0xabcd, class_code=0, class_detail=MethodCode.get,
                        token='', payload=None, options=[])

def test_coap_message_get():
    #simple GET request
    verify_coap_message('@\x01\x01\x00\xb5hello',
                        message_type=MessageType.confirmable, message_id=0x100, class_code=0, class_detail=MethodCode.get,
                        token='', payload=None,
                        options=[CoapOption(option_number=OptionNumber.uri_path, option_value='hello')])

def test_coap_message_put():
    #simple PUT request with payload
    verify_coap_message('@\x01\x01\x00\xb5hello\xffworld',
                        message_type=MessageType.confirmable, message_id=0x100, class_code=0, class_detail=MethodCode.get,
                        token='', payload='world',
                        options=[CoapOption(option_number=OptionNumber.uri_path, option_value='hello')])

def test_coap_message_token():
    #simple GET request with token
    verify_coap_message('H\x01\x01\x001234abcd\xbd\x01check_my_token',
                        message_type=MessageType.confirmable, message_id=0x100, class_code=0, class_detail=MethodCode.get,
                        token='1234abcd', payload=None,
                        options=[CoapOption(option_number=OptionNumber.uri_path, option_value='check_my_token')])
    #simple GET request with observe
    verify_coap_message('H\x01\x01\x001234abcd\x61\x00', message_type=MessageType.confirmable,
                        message_id=0x100, class_code=0, class_detail=MethodCode.get,
                        token='1234abcd', payload=None, options=[CoapOption(option_number=OptionNumber.observe,
                                                                            option_value='\x00')])


text:
import os
import sys
import threading
import logging
import toml
import argparse
import queue

import autobot
import autobot.config

LOG = logging.getLogger(__name__)

# TODO: Output formatter system
# TODO: Make dev help and normal help output different things
# TODO: HipChat Plugin
# TODO: Core Admin Plugin
# TODO: Plugin folder scaffolding script
# TODO: Live plugin reloads using inotify
# TODO: Testing using Behave
# TODO: Create fake factory that satisfies the needs of the brain thread
# TODO: Documentation using Sphinx
# TODO: Redis Plugin
# TODO: ACL..?
# TODO: Nicer CLI than logger?

def parse_args():
    parser = argparse.ArgumentParser(
        description='The primary foreground script for the chatbot library '
        'autobot')
    parser.add_argument('--debug', action='store_true',
                        help='Enable debug output')
    parser.add_argument('--config-file', help='The configuration file')
    parser.add_argument('--custom-plugins', help='The folder in which '
                        'to look for custom plugins to execute with.',
                        default=os.curdir)
    return parser.parse_args()

def main():
    args = parse_args()
    if args.debug:
        logging.getLogger('autobot').setLevel(logging.DEBUG)

    f = args.config_file

    config = autobot.config.defaults
    if f and os.path.exists(f):
        LOG.debug('Reading configuration file from %s!', f)
        with open(f) as conf:
            config.update(toml.loads(conf.read()))

    matchers = []
    catchalls = []
    event_callbacks = autobot.event
    workq = queue.Queue()
    messageq = queue.Queue()
    scheduleq = queue.Queue()
    mapping = {
            autobot.Callback: catchalls.append,
            autobot.Matcher: matchers.append,
            autobot.ScheduledCallback: scheduleq.put,
            autobot.EventCallback: event_callbacks.add_handler,
    }

    factory = autobot.Factory(config, mapping)
    LOG.debug('Importing plugins!')
    factory.start()

    brain = autobot.brain.Brain(factory, matchers, catchalls, messageq, workq)
    brain_thread = threading.Thread(name='brain', target=brain.boot)

    scheduler = autobot.scheduler.Scheduler(
        factory, config.get('scheduler_resolution'), scheduleq, workq
    )
    scheduler_thread = threading.Thread(name='timer', target=scheduler.boot)

    worker_pool = autobot.workers.WorkerPool(workq)

    try:
        worker_pool.start()
        brain_thread.start()
        scheduler_thread.start()

        LOG.debug('Starting service listener!')
        service = factory.get_service()
        service.set_message_queue(messageq)
        service.start()

        # Make sure the main thread is blocking so we can catch the interrupt
        brain_thread.join()
        scheduler_thread.join()

    except (KeyboardInterrupt, SystemExit):
        LOG.info('\nI have been asked to quit nicely, and so I will!')
        scheduler.shutdown()
        service.shutdown()
        brain.shutdown()
        worker_pool.shutdown()
        sys.exit()

if __name__ == '__main__':
    main()


text:
#if !defined(LT__DIRENT_H)
#define LT__DIRENT_H 1

#if defined(LT_CONFIG_H)
#  include LT_CONFIG_H
#else
#  include <config.h>
#endif

#include "lt_system.h"

#ifdef HAVE_DIRENT_H
/* We have a fully operational dirent subsystem.  */
#  include <dirent.h>
#  define D_NAMLEN(dirent) (strlen((dirent)->d_name))

#elif defined __WINDOWS__
/* Use some wrapper code to emulate dirent on windows..  */
#  define WINDOWS_DIRENT_EMULATION 1

#  include <windows.h>

#  define D_NAMLEN(dirent)	(strlen((dirent)->d_name))
#  define dirent		lt__dirent
#  define DIR			lt__DIR
#  define opendir		lt__opendir
#  define readdir		lt__readdir
#  define closedir		lt__closedir

LT_BEGIN_C_DECLS

struct dirent
{
  char d_name[LT_FILENAME_MAX];
  int  d_namlen;
};

typedef struct
{
  HANDLE hSearch;
  WIN32_FIND_DATA Win32FindData;
  BOOL firsttime;
  struct dirent file_info;
} DIR;

LT_SCOPE DIR *		opendir		(const char *path);
LT_SCOPE struct dirent *readdir		(DIR *entry);
LT_SCOPE void		closedir	(DIR *entry);

LT_END_C_DECLS

#else /* !defined(__WINDOWS__)*/
ERROR - cannot find dirent
#endif /*!defined(__WINDOWS__)*/

#endif /*!defined(LT__DIRENT_H)*/


text:
/**@file tsip_header_Accept_Language.h
 * @brief SIP header 'Accept-Language'.
 *
 * @author Mamadou Diop <diopmamadou(at)doubango[dot]org>
 *

 */
#ifndef _TSIP_HEADER_ACCEPT_LANGUAGE_H_
#define _TSIP_HEADER_ACCEPT_LANGUAGE_H_

#include "tinysip_config.h"
#include "tinysip/headers/tsip_header.h"

TSIP_BEGIN_DECLS

////////////////////////////////////////////////////////////////////////////////////////////////////
///
/// @brief	SIP header 'Accept-Contact' .
/// @author	Mamadou
/// @date	12/3/2009
///
/// @par ABNF
///
////////////////////////////////////////////////////////////////////////////////////////////////////
typedef struct tsip_header_Accept_Language_s
{
	TSIP_DECLARE_HEADER;
}
tsip_header_Accept_Language_t;

TSIP_END_DECLS

#endif /* _TSIP_HEADER_ACCEPT_LANGUAGE_H_ */


text:
package cluster

import "errors"

// BackendType defines the type of backend used for the cluster
type BackendType int

// Available backend types
const (
	UnspecifiedBackend BackendType = iota // Zero-value
	FilesystemBackend
	MemoryBackend
)

type backend interface {
	WriteMember(m *member) error
	DeleteMember(id MemberID) error

	ReadMember(id MemberID) (*member, error)
	ReadMembers() (map[MemberID]*member, error)
	ReadMemberIDs() (map[MemberID]struct{}, error)
}

func newBackend(conf *Config) (backend, error) {
	switch conf.BackendType {
	case FilesystemBackend:
		return newFilesystemBackend(conf.Directory, conf.TTL*3)
	case MemoryBackend:
		return newMemoryBackend(), nil
	default:
		return nil, errors.New("No backend type configured")
	}
}


text:
Amazon EMR already provides an environment with HDFS, Zookeeper, and YARN. This bootstrap script enables us to deploy Apache Accumulo on top of EMR cluster through docker containers. The main advantage of using docker in this scenario is ability to extend the container, for instance by adding GeoWave or GeoMesa iterator jars and still use the same bootstrap scripts.

## Parameters

The script is parametrized on following arguments:

  - `-i | --image` docker image to be used for accumulo
  - `-s | --accumulo-secret` accumulo secret to be used
  - `-p | --accumulo-password` accumulo password for root account
  - `-n | --instance-name` accumulo instance name
  - `-e | --env` additional environment variables for docker containers

These parameters have default values defined at the top of the bootstrap script.

## Usage

In order to use this bootstrap script it should be copied to an S3 bucket under your control so it accessed by the EMR cluster during the bootstrap phase.

```console
aws emr create-cluster --name "GeoDocker Accumulo" \
--release-label emr-5.0.0 \
--output text \
--use-default-roles \
--ec2-attributes KeyName=geotrellis-cluster \
--applications Name=Hadoop Name=Zookeeper \
--instance-groups \
Name=Master,BidPrice=0.5,InstanceCount=1,InstanceGroupType=MASTER,InstanceType=m3.xlarge \
Name=Workers,BidPrice=0.5,InstanceCount=1,InstanceGroupType=CORE,InstanceType=m3.xlarge \
--bootstrap-actions \
Name=BootstrapGeoWave,Path=s3://geotrellis-test/geodocker/accumulo-0.2/bootstrap-geodocker-accumulo.sh,\
Args=[-i=quay.io/geodocker/accumulo:latest,-n=gis,-p=secret,\
-e=TSERVER_XMX=10G,-e=TSERVER_CACHE_DATA_SIZE=6G,-e=TSERVER_CACHE_INDEX_SIZE=2G]
```


text:
<project>
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.redhat.bayessian.test</groupId>
  <artifactId>test-5-dependencies-0-cves</artifactId>
  <version>1.0</version>

  <dependencies>
    <dependency>
      <groupId>io.vertx</groupId>
      <artifactId>vertx-core</artifactId>
      <version>3.7.1</version>
    </dependency>

    <dependency>
      <groupId>io.vertx</groupId>
      <artifactId>vertx-jdbc-client</artifactId>
      <version>3.4.1</version>
    </dependency>

    <dependency>
      <groupId>io.vertx</groupId>
      <artifactId>vertx-rx-java</artifactId>
      <version>3.4.1</version>
    </dependency>

    <dependency>
      <groupId>io.vertx</groupId>
      <artifactId>vertx-web-client</artifactId>
      <version>3.4.1</version>
    </dependency>

    <dependency>
      <groupId>io.vertx</groupId>
      <artifactId>vertx-web-templ-freemarker</artifactId>
      <version>3.4.1</version>
    </dependency>

  </dependencies>
</project>


text:
typedef NS_ENUM(NSInteger, {{EnumName}}) {
{{#values}}
  {{EnumName}}_{{originalName}}{{/values|,
}}

};


text:
package com.github.chrisruffalo.silvering.visitor.hierarchy;

/**
 *

 *
 * @author Chris Ruffalo
 */
public class Trunk extends Root implements IChild {
}


text:
import sip
sip.setapi('QString', 2)
sip.setapi('QVariant', 2)

from PyQt4 import QtCore, QtGui

class ScribbleArea(QtGui.QWidget):

    def __init__(self, parent=None):
        super(ScribbleArea, self).__init__(parent)

        self.setAttribute(QtCore.Qt.WA_StaticContents)
        self.modified = False
        self.scribbling = False
        self.myPenWidth = 1
        self.myPenColor = QtCore.Qt.blue
        imageSize = QtCore.QSize(500, 500)
        self.image = QtGui.QImage(imageSize, QtGui.QImage.Format_RGB32)
        self.lastPoint = QtCore.QPoint()

    def openImage(self, fileName):
        loadedImage = QtGui.QImage()
        if not loadedImage.load(fileName):
            return False

        w = loadedImage.width()
        h = loadedImage.height()
        self.mainWindow.resize(w, h)

        self.image = loadedImage
        self.modified = False
        self.update()
        return True

    def saveImage(self, fileName, fileFormat):
        visibleImage = self.image
        self.resizeImage(visibleImage, self.size())

        if visibleImage.save(fileName, fileFormat):
            self.modified = False
            return True
        else:
            return False

    def setPenColor(self, newColor):
        self.myPenColor = newColor

    def setPenWidth(self, newWidth):
        self.myPenWidth = newWidth

    def clearImage(self):
        self.image.fill(QtGui.qRgb(255, 255, 255))
        self.modified = True
        self.update()

    def mousePressEvent(self, event):
        if event.button() == QtCore.Qt.LeftButton:
            self.lastPoint = event.pos()
            self.scribbling = True

    def mouseMoveEvent(self, event):
        if (event.buttons() & QtCore.Qt.LeftButton) and self.scribbling:
            self.drawLineTo(event.pos())

    def mouseReleaseEvent(self, event):
        if event.button() == QtCore.Qt.LeftButton and self.scribbling:
            self.drawLineTo(event.pos())
            self.scribbling = False

    def paintEvent(self, event):
        painter = QtGui.QPainter(self)
        painter.drawImage(event.rect(), self.image)

    def resizeEvent(self, event):

        self.resizeImage(self.image, event.size())

        super(ScribbleArea, self).resizeEvent(event)

    def drawLineTo(self, endPoint):
        painter = QtGui.QPainter(self.image)
        painter.setPen(QtGui.QPen(self.myPenColor, self.myPenWidth,
            QtCore.Qt.SolidLine, QtCore.Qt.RoundCap, QtCore.Qt.RoundJoin))
        painter.drawLine(self.lastPoint, endPoint)
        self.modified = True

        self.update()
        self.lastPoint = QtCore.QPoint(endPoint)

    def resizeImage(self, image, newSize):
        if image.size() == newSize:
            return

        newImage = QtGui.QImage(newSize, QtGui.QImage.Format_RGB32)
        newImage.fill(QtGui.qRgb(255, 255, 255))
        painter = QtGui.QPainter(newImage)
        painter.drawImage(QtCore.QPoint(0, 0), image)

        self.image = newImage

    def print_(self):
        printer = QtGui.QPrinter(QtGui.QPrinter.HighResolution)

        printDialog = QtGui.QPrintDialog(printer, self)
        if printDialog.exec_() == QtGui.QDialog.Accepted:
            painter = QtGui.QPainter(printer)
            rect = painter.viewport()
            size = self.image.size()
            size.scale(rect.size(), QtCore.Qt.KeepAspectRatio)
            painter.setViewport(rect.x(), rect.y(), size.width(), size.height())
            painter.setWindow(self.image.rect())
            painter.drawImage(0, 0, self.image)
            painter.end()

    def isModified(self):
        return self.modified

    def penColor(self):
        return self.myPenColor

    def penWidth(self):
        return self.myPenWidth

class MainWindow(QtGui.QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()

        self.saveAsActs = []

        self.scribbleArea = ScribbleArea(self)
        self.scribbleArea.clearImage()
        self.scribbleArea.mainWindow = self  # maybe not using this?
        self.setCentralWidget(self.scribbleArea)

        self.createActions()
        self.createMenus()

        self.setWindowTitle("My Paint Brush")
        self.resize(500, 500)

    def closeEvent(self, event):
        if self.maybeSave():
            event.accept()
        else:
            event.ignore()

    def open(self):
        if self.maybeSave():
            fileName = QtGui.QFileDialog.getOpenFileName(self, "Open File",
                QtCore.QDir.currentPath())
            if fileName:
                self.scribbleArea.openImage(fileName)

    def save(self):
        action = self.sender()
        fileFormat = action.data()
        self.saveFile(fileFormat)

    def penColor(self):
        newColor = QtGui.QColorDialog.getColor(self.scribbleArea.penColor())
        if newColor.isValid():
            self.scribbleArea.setPenColor(newColor)

    def penWidth(self):
        newWidth, ok = QtGui.QInputDialog.getInteger(self, "Paint Brush",
            "Select pen width:", self.scribbleArea.penWidth(), 1, 50, 1)
        if ok:
            self.scribbleArea.setPenWidth(newWidth)

    def about(self):
        QtGui.QMessageBox.about(self, "About My Paint Brush",
            "
The My Paint Brush example shows how to use "
            "QMainWindow as the base widget for an application, and how "
            "to reimplement some of QWidget's event handlers to receive "
            "the events generated for the application's widgets:
"
            "
 We reimplement the mouse event handlers to facilitate "
            "drawing, the paint event handler to update the application "
            "and the resize event handler to optimize the application's "
            "appearance. In addition we reimplement the close event "
            "handler to intercept the close events before terminating "
            "the application.
"
            "
 The example also demonstrates how to use QPainter to "
            "draw an image in real time, as well as to repaint "
            "widgets.
")

    def createActions(self):
        self.openAct = QtGui.QAction("&Open...", self, shortcut="Ctrl+O",
            triggered=self.open)

        for format in QtGui.QImageWriter.supportedImageFormats():
            format = str(format)

            text = format.upper() + "..."

            action = QtGui.QAction(text, self, triggered=self.save)
            action.setData(format)
            self.saveAsActs.append(action)

        self.printAct = QtGui.QAction("&Print...", self,
            triggered=self.scribbleArea.print_)

        self.exitAct = QtGui.QAction("E&xit", self, shortcut="Ctrl+Q",
            triggered=self.close)

        self.penColorAct = QtGui.QAction("&Pen Color...", self,
            triggered=self.penColor)

        self.penWidthAct = QtGui.QAction("Pen &Width...", self,
            triggered=self.penWidth)

        self.clearScreenAct = QtGui.QAction("&Clear Screen", self,
            shortcut="Ctrl+L", triggered=self.scribbleArea.clearImage)

        self.aboutAct = QtGui.QAction("&About", self, triggered=self.about)

        self.aboutQtAct = QtGui.QAction("About &Qt", self,
            triggered=QtGui.qApp.aboutQt)

    def createMenus(self):
        self.saveAsMenu = QtGui.QMenu("&Save As", self)
        for action in self.saveAsActs:
            self.saveAsMenu.addAction(action)

        fileMenu = QtGui.QMenu("&File", self)
        fileMenu.addAction(self.openAct)
        fileMenu.addMenu(self.saveAsMenu)
        fileMenu.addAction(self.printAct)
        fileMenu.addSeparator()
        fileMenu.addAction(self.exitAct)

        optionMenu = QtGui.QMenu("&Options", self)
        optionMenu.addAction(self.penColorAct)
        optionMenu.addAction(self.penWidthAct)
        optionMenu.addSeparator()
        optionMenu.addAction(self.clearScreenAct)

        helpMenu = QtGui.QMenu("&Help", self)
        helpMenu.addAction(self.aboutAct)
        helpMenu.addAction(self.aboutQtAct)

        self.menuBar().addMenu(fileMenu)
        self.menuBar().addMenu(optionMenu)
        self.menuBar().addMenu(helpMenu)

    def maybeSave(self):
        if self.scribbleArea.isModified():
            ret = QtGui.QMessageBox.warning(self, "Paint Brush",
                "The image has been modified.\n"
                "Do you want to save your changes?",
                QtGui.QMessageBox.Save | QtGui.QMessageBox.Discard |
                QtGui.QMessageBox.Cancel)
            if ret == QtGui.QMessageBox.Save:
                return self.saveFile('png')
            elif ret == QtGui.QMessageBox.Cancel:
                return False

        return True

    def saveFile(self, fileFormat):
        initialPath = QtCore.QDir.currentPath() + '/untitled.' + fileFormat

        fileName = QtGui.QFileDialog.getSaveFileName(self, "Save As",
            initialPath,
            "%s Files (*.%s);;All Files (*)" % (fileFormat.upper(), fileFormat))
        if fileName:
            return self.scribbleArea.saveImage(fileName, fileFormat)

        return False

if __name__ == '__main__':

    import sys

    app = QtGui.QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Tabl. analyt. Fung. France (Paris) 4: 163 (1885)

#### Original name
Clavaria bessonii Pat.

### Remarks
null


text:
using namespace lightstep;

TEST_CASE("ChunkedHttpFraming") {
  std::string header_serialization(ChunkedHttpMaxHeaderSize + 1, ' ');
  WriteHttpChunkHeader(&header_serialization[0], header_serialization.size(),
                       10);
  REQUIRE(header_serialization == " 0000000a\r\n");
}


text:
namespace ash {
namespace test {

namespace {

class BoundsAnimatorWaiter : public views::BoundsAnimatorObserver {
 public:
  explicit BoundsAnimatorWaiter(views::BoundsAnimator* animator)
      : animator_(animator) {
    animator->AddObserver(this);
  }
  ~BoundsAnimatorWaiter() override { animator_->RemoveObserver(this); }

  void Wait() {
    if (!animator_->IsAnimating())
      return;

    run_loop_ = std::make_unique<base::RunLoop>();
    run_loop_->Run();
  }

 private:
  // views::BoundsAnimatorObserver:
  void OnBoundsAnimatorProgressed(views::BoundsAnimator* animator) override {}
  void OnBoundsAnimatorDone(views::BoundsAnimator* animator) override {
    if (run_loop_)
      run_loop_->Quit();
  }

  views::BoundsAnimator* animator_;
  std::unique_ptr<base::RunLoop> run_loop_;

  DISALLOW_COPY_AND_ASSIGN(BoundsAnimatorWaiter);
};

}  // namespace

AppsGridViewTestApi::AppsGridViewTestApi(AppsGridView* view) : view_(view) {}

AppsGridViewTestApi::~AppsGridViewTestApi() {}

views::View* AppsGridViewTestApi::GetViewAtModelIndex(int index) const {
  return view_->view_model_.view_at(index);
}

void AppsGridViewTestApi::LayoutToIdealBounds() {
  if (view_->reorder_timer_.IsRunning()) {
    view_->reorder_timer_.Stop();
    view_->OnReorderTimer();
  }
  if (view_->folder_dropping_timer_.IsRunning()) {
    view_->folder_dropping_timer_.Stop();
    view_->OnFolderDroppingTimer();
  }
  view_->bounds_animator_->Cancel();
  view_->Layout();
}

gfx::Rect AppsGridViewTestApi::GetItemTileRectOnCurrentPageAt(int row,
                                                              int col) const {
  int slot = row * (view_->cols()) + col;
  return view_->GetExpectedTileBounds(
      GridIndex(view_->pagination_model()->selected_page(), slot));
}

void AppsGridViewTestApi::PressItemAt(int index) {
  GetViewAtModelIndex(index)->OnKeyPressed(
      ui::KeyEvent(ui::ET_KEY_PRESSED, ui::VKEY_RETURN, ui::EF_NONE));
}

bool AppsGridViewTestApi::HasPendingPageFlip() const {
  return view_->page_flip_timer_.IsRunning() ||
         view_->pagination_model()->has_transition();
}

int AppsGridViewTestApi::TilesPerPage(int page) const {
  return view_->TilesPerPage(page);
}

int AppsGridViewTestApi::AppsOnPage(int page) const {
  return view_->view_structure_.items_on_page(page);
}

AppListItemView* AppsGridViewTestApi::GetViewAtIndex(GridIndex index) const {
  return view_->GetViewAtIndex(index);
}

views::View* AppsGridViewTestApi::GetViewAtVisualIndex(int page,
                                                       int slot) const {
  const std::vector<std::vector<AppListItemView*>>& view_structure =
      view_->view_structure_.pages();
  if (page >= static_cast<int>(view_structure.size()) ||
      slot >= static_cast<int>(view_structure[page].size())) {
    return nullptr;
  }
  return view_structure[page][slot];
}

gfx::Rect AppsGridViewTestApi::GetItemTileRectAtVisualIndex(int page,
                                                            int slot) const {
  return view_->GetExpectedTileBounds(GridIndex(page, slot));
}

void AppsGridViewTestApi::WaitForItemMoveAnimationDone() {
  BoundsAnimatorWaiter waiter(view_->bounds_animator_.get());
  waiter.Wait();
}

}  // namespace test
}  // namespace ash


text:
package link

// may be other default request func

// OpenTunnelFunc define a func about open tunnel
type OpenTunnelFunc func(proto string, localHost string, localPort int, remoteHost string, remotePort int, reverse bool) error

type tunnelCreateBody struct {
	ID uint32
}


text:
import React from 'react';
import ReactDOM from 'react-dom';

class Box extends React.Component{
	constructor(props){
		super(props);
		this.state = {
		}
		this.onDragStart = this.onDragStart.bind(this);
		this.onDragEnd = this.onDragEnd.bind(this);
	}

	onDragStart(event){
		event.target.style.opacity = '0.4';
		event.dataTransfer.effectAllowed = 'move';

		let classOfBox = event.target.className;
		event.dataTransfer.setData("box", classOfBox);
	}

	onDragEnd(event){
		event.target.style.opacity = '1';
		//event.target.parentNode.removeChild(event.target);
		//this.props.onDropChange(event.target.className);
		// let classOfBox = event.target.className;
		// alert("WYSYŁA: " + classOfBox);
		// event.dataTransfer.setData("box", classOfBox);
	}

	render(){
		var box = [];
		var boxStyle = [];
		var top, left;
		for (var i = 0; i< this.props.tableToSend.length; i++){
			top = 33 + this.props.tableToSend[i].start_hour*100 + this.props.tableToSend[i].start_hour*3 - i*50; //(top: 0) + (startHour*height of td) + (startHour*border of td) - (height of previous boxes)
			left = this.props.tableToSend[i].day_number*100 + this.props.tableToSend[i].day_number*3;
			boxStyle[i] = {top: top+'px', left: left+'px'};
			var boxClass = this.props.tableToSend[i].id;
			box.push(

start hour: {this.props.tableToSend[i].start_hour}

day: {this.props.tableToSend[i].day_number}

			);
		}

		return(

				{box}

		);
	}
}

export default Box;


text:
require 'spec_helper'

describe SingaporeCPFCalculator::Year2014::CitizenOrSPR3::Age60To65ContributionCalculator do

  subject(:calculator) {
    described_class.new ordinary_wages: ordinary_wages,
                        additional_wages: additional_wages
  }

  let(:result) { calculator.calculate }

  let(:additional_wages) { 0.0 }

  describe "#calculate" do

    context "when the total wages amounts to 0.00" do
      let(:ordinary_wages) { 0.00 }
      it { expect(result).to equal_cpf total: 0.00, employee: 0.00, employer: 0.00 }
    end

    context "when the total wages amounts to 50.00" do
      let(:ordinary_wages) { 50.00 }
      it { expect(result).to equal_cpf total: 0.00, employee: 0.00, employer: 0.00 }
    end

    context "when the total wages amounts to 50.01" do
      let(:ordinary_wages) { 50.01 }
      it { expect(result).to equal_cpf total: 4.00, employee: 0.00, employer: 4.00 }
    end

    context "when the total wages amounts to 64.28" do
      let(:ordinary_wages) { 64.28 }
      it { expect(result).to equal_cpf total: 4.00, employee: 0.00, employer: 4.00 }
    end

    context "when the total wages amounts to 504.44" do
      let(:ordinary_wages) { 504.44 }
      it { expect(result).to equal_cpf total: 36.00, employee: 0.00, employer: 36.00 }
    end

    context "when the total wages amounts to 504.45" do
      let(:ordinary_wages) { 504.45 }
      it { expect(result).to equal_cpf total: 36.00, employee: 1.00, employer: 35.00 }
    end

    context "when the total wages amounts to 749.99" do
      let(:ordinary_wages) { 749.99 }
      it { expect(result).to equal_cpf total: 109.00, employee: 56.00, employer: 53.00 }
    end

    context "when the total wages amounts to 750.00" do
      let(:ordinary_wages) { 750.00 }
      it { expect(result).to equal_cpf total: 109.00, employee: 56.00, employer: 53.00 }
    end

    context "when the total wages amounts to 5,000.00" do
      let(:ordinary_wages) { 5_000.00 }
      it { expect(result).to equal_cpf total: 725.00, employee: 375.00, employer: 350.00 }
    end

    context "when the total wages amounts to 10,000.00" do
      let(:ordinary_wages) { 10_000.00 }
      it { expect(result).to equal_cpf total: 725.00, employee: 375.00, employer: 350.00 }
    end

  end

end


text:
module ManageIQ::Providers::Lenovo::PhysicalInfraManager::PhysicalServer::Operations
  extend ActiveSupport::Concern

  include_concern 'ManageIQ::Providers::Lenovo::PhysicalInfraManager::Operations::ComponentAnsibleSender'

  #
  # Makes the provision of a server step-by-step using ansible methods.
  #   A Server provision consists in:
  #     - Update its firmwares;
  #     - Apply a config pattern
  #
  # @param config_pattern_id - the ID of the config pattern that will be used in
  #   provision.
  #
  # @return an array containing the response of all ansible executions.
  #
  def ansible_provision_server(config_pattern_id)
    responses = []
    responses << ansible_update_firmware
    responses << ansible_apply_pattern(config_pattern_id)

    responses
  end

  def ansible_update_firmware
    ansible_run(
      'role_name' => 'lenovo.lxca-config',
      'tags'      => 'update_all_firmware_withpolicy',
      'vars'      => {
        'mode'        => 'immediate',
        'uuid_list'   => uid_ems,
        'lxca_action' => 'apply'
      }
    )
  end

  def ansible_update_firmwares(firmware_names = [])
    ansible_run(
      'role_name' => 'lenovo.lxca-config',
      'tags'      => 'update_firmware',
      'vars'      => {
        'mode'        => 'immediate',
        'server'      => "#{uid_ems},#{firmware_names.join(',')}",
        'lxca_action' => 'apply'
      }
    )
  end

  def ansible_apply_pattern(pattern_id)
    ansible_run(
      'role_name' => 'lenovo.lxca-config',
      'tags'      => 'apply_configpatterns',
      'vars'      => {
        'endpoint' => uid_ems,
        'restart'  => 'immediate',
        'type'     => 'node',
        'id'       => pattern_id
      }
    )
  end
end


text:
package org.tuberlin.de.district_tip;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.DataSet;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.util.Collector;

public class DistrictTip {

    @SuppressWarnings("serial")
    public static void main(String[] args) throws Exception {
        final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();

        DataSet<String> data = env.readTextFile("data/district_tip_testdata.txt");

        DataSet<TaxiTrip> tripData = data.flatMap(new FlatMapFunction<String, TaxiTrip>() {

            @Override
            public void flatMap(String value, Collector<TaxiTrip> collector) throws Exception {
                String[] split = value.split(",");
                TaxiTrip trip = new TaxiTrip();
                trip.setDistrict(split[17]);
                trip.setTip(Double.parseDouble(split[14]));
                collector.collect(trip);
            }
        });

        DataSet<TaxiTrip> reducedData = tripData.groupBy("neighborhood").reduce((t1, t2) -> {
            int sum = t1.getCount() + t2.getCount();
            double sumValue = t1.getTip() + t2.getTip();
            double average = sumValue / sum;
            double roundedAverage = Math.round(average * 100.0) / 100.0;
            TaxiTrip trip = new TaxiTrip();
            trip.setDistrict(t1.getDistrict());
            trip.setCount(sum);
            trip.setTip(sumValue);
            trip.setAverageTip(roundedAverage);
            return trip;
        });

        reducedData.print();

    }

}


text:
/** @jsx React.DOM */
"use strict";

var React = require('react');

var Container 	= require('../Container');
var Component 	= require('../Component');
var FlexBox 	= require('../FlexBox');
var LayoutItem 	= require('../LayoutItem');
var PlaceHolder = require('../PlaceHolder');
var Tabs		= require('../TabbedContainer');

var primaryTypes = require('../../examples/sample-components/types');
var components = require('../../examples/sample-components/components');

var LayoutTypes = {Container, Component, FlexBox, Tabs, TabbedContainer:Tabs,PlaceHolder, LayoutItem};

var Types = {};

function componentFromJSON(json, types){

	Types = types || {};

	var component = _componentFromJSON(json);

	Types = null;

	return component;
}

function _componentFromJSON(json, idx){

	if (Array.isArray(json)){
		return json.map(componentFromJSON);
	}
	else if (json == null){
		return null
	}

	var {type, content, ...props} = json;
	var ReactType, BoxedType, boxedComponent;

	ReactType = LayoutTypes[type];

	if (ReactType === undefined){
		if (React.DOM[type]){
			ReactType = type;
		}
		else if (Types[type]){
			ReactType = Types[type];
		}
		else if (primaryTypes[type]){
			ReactType = primaryTypes[type];
		}
		else {
			ReactType = Component;
			BoxedType = components[type];
			if (BoxedType === undefined){
				throw "componentFromJSON: unknown component type: " + type;
			}
		}
	}

	var children = content ? content.map(_componentFromJSON) : null;
	if (BoxedType){
		boxedComponent = <BoxedType>{children}</BoxedType>;
	}

	return (
		<ReactType key={idx | 0} {...props} json={json}>
			{boxedComponent || children}
		</ReactType>
	);
}

module.exports = componentFromJSON;


text:
package net.sourceforge.myvd.test.router;

import java.util.ArrayList;
import java.util.Properties;

import junit.framework.TestCase;
import net.sourceforge.myvd.chain.AddInterceptorChain;
import net.sourceforge.myvd.chain.BindInterceptorChain;
import net.sourceforge.myvd.chain.CompareInterceptorChain;
import net.sourceforge.myvd.chain.DeleteInterceptorChain;
import net.sourceforge.myvd.chain.ExetendedOperationInterceptorChain;
import net.sourceforge.myvd.chain.ModifyInterceptorChain;
import net.sourceforge.myvd.chain.PostSearchCompleteInterceptorChain;
import net.sourceforge.myvd.chain.PostSearchEntryInterceptorChain;
import net.sourceforge.myvd.chain.RenameInterceptorChain;
import net.sourceforge.myvd.chain.SearchInterceptorChain;
import net.sourceforge.myvd.core.NameSpace;
import net.sourceforge.myvd.inserts.Insert;
import net.sourceforge.myvd.types.Attribute;
import net.sourceforge.myvd.types.Bool;
import net.sourceforge.myvd.types.DistinguishedName;
import net.sourceforge.myvd.types.Entry;
import net.sourceforge.myvd.types.ExtendedOperation;
import net.sourceforge.myvd.types.Filter;
import net.sourceforge.myvd.types.Int;
import net.sourceforge.myvd.types.Password;
import net.sourceforge.myvd.types.Results;

import com.novell.ldap.LDAPAttribute;
import com.novell.ldap.LDAPConstraints;
import com.novell.ldap.LDAPEntry;
import com.novell.ldap.LDAPException;
import com.novell.ldap.LDAPModification;
import com.novell.ldap.LDAPSearchConstraints;

public class TestglobalChain extends TestCase implements Insert {

	public void testdonothing() {

	}

	String name;

	public void configure(String name, Properties props, NameSpace nameSpace)
			throws LDAPException {
		// TODO Auto-generated method stub
		this.name = name;
	}

	public void add(AddInterceptorChain chain, Entry entry,
			LDAPConstraints constraints) throws LDAPException {
		entry = new Entry(new LDAPEntry(entry.getEntry().getDN() + ",c=us",entry.getEntry().getAttributeSet()));
		chain.nextAdd(entry,constraints);

	}

	public void bind(BindInterceptorChain chain, DistinguishedName dn,
			Password pwd, LDAPConstraints constraints) throws LDAPException {

		dn = new DistinguishedName(dn.getDN().toString() + ",c=us");
		chain.nextBind(dn,pwd,constraints);

	}

	public void compare(CompareInterceptorChain chain, DistinguishedName dn,
			Attribute attrib, LDAPConstraints constraints) throws LDAPException {
		dn = new DistinguishedName(dn.getDN().toString() + ",c=us");
		chain.nextCompare(dn,attrib,constraints);

	}

	public void delete(DeleteInterceptorChain chain, DistinguishedName dn,
			LDAPConstraints constraints) throws LDAPException {
		dn = new DistinguishedName(dn.getDN().toString() + ",c=us");
		chain.nextDelete(dn,constraints);

	}

	public void extendedOperation(ExetendedOperationInterceptorChain chain,
			ExtendedOperation op, LDAPConstraints constraints)
			throws LDAPException {
		chain.nextExtendedOperations(op,constraints);

	}

	public void modify(ModifyInterceptorChain chain, DistinguishedName dn,
			ArrayList<LDAPModification> mods, LDAPConstraints constraints)
			throws LDAPException {
		dn = new DistinguishedName(dn.getDN().toString() + ",c=us");
		chain.nextModify(dn,mods,constraints);

	}

	public void search(SearchInterceptorChain chain, DistinguishedName base,
			Int scope, Filter filter, ArrayList<Attribute> attributes,
			Bool typesOnly, Results results, LDAPSearchConstraints constraints)
			throws LDAPException {
		if (base.getDN().getRDNs().size() > 0) {
			base = new DistinguishedName(base.getDN().toString() + ",c=us");
		}

		chain.nextSearch(base,scope,filter,attributes,typesOnly,results,constraints);
	}

	public void rename(RenameInterceptorChain chain, DistinguishedName dn,
			DistinguishedName newRdn, Bool deleteOldRdn,
			LDAPConstraints constraints) throws LDAPException {
		chain.getRequest().put("ISRENAME","ISRENAME");
		dn = new DistinguishedName(dn.getDN().toString() + ",c=us");
		chain.nextRename(dn,newRdn,deleteOldRdn,constraints);

	}

	public void rename(RenameInterceptorChain chain, DistinguishedName dn,
			DistinguishedName newRdn, DistinguishedName newParentDN,
			Bool deleteOldRdn, LDAPConstraints constraints)
			throws LDAPException {
		chain.getRequest().put("ISRENAME","ISRENAME");
		dn = new DistinguishedName(dn.getDN().toString() + ",c=us");
		chain.nextRename(dn,newRdn,newParentDN,deleteOldRdn,constraints);

	}

	public void postSearchEntry(PostSearchEntryInterceptorChain chain,
			Entry entry, DistinguishedName base, Int scope, Filter filter,
			ArrayList<Attribute> attributes, Bool typesOnly,
			LDAPSearchConstraints constraints) throws LDAPException {

		if (! chain.getRequest().containsKey("ISRENAME")) {
			entry.getEntry().getAttributeSet().add(new LDAPAttribute("globalTestAttrib","globalTestVal"));
		}
		chain.nextPostSearchEntry(entry,base,scope,filter,attributes,typesOnly,constraints);

	}

	public void postSearchComplete(PostSearchCompleteInterceptorChain chain,
			DistinguishedName base, Int scope, Filter filter,
			ArrayList<Attribute> attributes, Bool typesOnly,
			LDAPSearchConstraints constraints) throws LDAPException {

		chain.nextPostSearchComplete(base,scope,filter,attributes,typesOnly,constraints);

	}

	public String getName() {
		return this.name;
	}

	public void shutdown() {
		// TODO Auto-generated method stub

	}

}


text:
package org.apache.hcatalog.api;

import java.util.List;
import java.util.Map;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hive.common.JavaUtils;
import org.apache.hadoop.hive.metastore.api.PartitionEventType;
import org.apache.hcatalog.common.HCatException;
import org.apache.hcatalog.data.schema.HCatFieldSchema;

/**
 * The abstract class HCatClient containing APIs for HCatalog DDL commands.
 */
public abstract class HCatClient {

    public enum DropDBMode {RESTRICT, CASCADE}

    public static final String HCAT_CLIENT_IMPL_CLASS = "hcat.client.impl.class";

    /**
     * Creates an instance of HCatClient.
     *
     * @param conf An instance of configuration.
     * @return An instance of HCatClient.
     * @throws HCatException
     */
    public static HCatClient create(Configuration conf) throws HCatException {
        HCatClient client = null;
        String className = conf.get(HCAT_CLIENT_IMPL_CLASS,
            HCatClientHMSImpl.class.getName());
        try {
            Class<? extends HCatClient> clientClass = Class.forName(className,
                true, JavaUtils.getClassLoader()).asSubclass(
                    HCatClient.class);
            client = (HCatClient) clientClass.newInstance();
        } catch (ClassNotFoundException e) {
            throw new HCatException(
                "ClassNotFoundException while creating client class.", e);
        } catch (InstantiationException e) {
            throw new HCatException(
                "InstantiationException while creating client class.", e);
        } catch (IllegalAccessException e) {
            throw new HCatException(
                "IllegalAccessException while creating client class.", e);
        }
        if (client != null) {
            client.initialize(conf);
        }
        return client;
    }

    abstract void initialize(Configuration conf) throws HCatException;

    /**
     * Get all existing databases that match the given
     * pattern. The matching occurs as per Java regular expressions
     *
     * @param pattern  java re pattern
     * @return list of database names
     * @throws HCatException
     */
    public abstract List<String> listDatabaseNamesByPattern(String pattern)
        throws HCatException;

    /**
     * Gets the database.
     *
     * @param dbName The name of the database.
     * @return An instance of HCatDatabaseInfo.
     * @throws HCatException
     */
    public abstract HCatDatabase getDatabase(String dbName) throws HCatException;

    /**
     * Creates the database.
     *
     * @param dbInfo An instance of HCatCreateDBDesc.
     * @throws HCatException
     */
    public abstract void createDatabase(HCatCreateDBDesc dbInfo)
        throws HCatException;

    /**
     * Drops a database.
     *
     * @param dbName The name of the database to delete.
     * @param ifExists Hive returns an error if the database specified does not exist,
     *                 unless ifExists is set to true.
     * @param mode This is set to either "restrict" or "cascade". Restrict will
     *             remove the schema if all the tables are empty. Cascade removes
     *             everything including data and definitions.
     * @throws HCatException
     */
    public abstract void dropDatabase(String dbName, boolean ifExists,
                                      DropDBMode mode) throws HCatException;

    /**
     * Returns all existing tables from the specified database which match the given
     * pattern. The matching occurs as per Java regular expressions.
     * @param dbName The name of the DB (to be searched)
     * @param tablePattern The regex for the table-name
     * @return list of table names
     * @throws HCatException
     */
    public abstract List<String> listTableNamesByPattern(String dbName, String tablePattern)
        throws HCatException;

    /**
     * Gets the table.
     *
     * @param dbName The name of the database.
     * @param tableName The name of the table.
     * @return An instance of HCatTableInfo.
     * @throws HCatException
     */
    public abstract HCatTable getTable(String dbName, String tableName)
        throws HCatException;

    /**
     * Creates the table.
     *
     * @param createTableDesc An instance of HCatCreateTableDesc class.
     * @throws HCatException
     */
    public abstract void createTable(HCatCreateTableDesc createTableDesc) throws HCatException;

    /**
     * Updates the Table's column schema to the specified definition.
     *
     * @param dbName The name of the database.
     * @param tableName The name of the table.
     * @param columnSchema The (new) definition of the column schema (i.e. list of fields).
     *
     */
    public abstract void updateTableSchema(String dbName, String tableName, List<HCatFieldSchema> columnSchema)
        throws HCatException;

    /**
     * Creates the table like an existing table.
     *
     * @param dbName The name of the database.
     * @param existingTblName The name of the existing table.
     * @param newTableName The name of the new table.
     * @param ifNotExists If true, then error related to already table existing is skipped.
     * @param isExternal Set to "true", if table has be created at a different
     *                   location other than default.
     * @param location The location for the table.
     * @throws HCatException
     */
    public abstract void createTableLike(String dbName, String existingTblName,
                                         String newTableName, boolean ifNotExists, boolean isExternal,
                                         String location) throws HCatException;

    /**
     * Drop table.
     *
     * @param dbName The name of the database.
     * @param tableName The name of the table.
     * @param ifExists Hive returns an error if the database specified does not exist,
     *                 unless ifExists is set to true.
     * @throws HCatException
     */
    public abstract void dropTable(String dbName, String tableName,
                                   boolean ifExists) throws HCatException;

    /**
     * Renames a table.
     *
     * @param dbName The name of the database.
     * @param oldName The name of the table to be renamed.
     * @param newName The new name of the table.
     * @throws HCatException
     */
    public abstract void renameTable(String dbName, String oldName,
                                     String newName) throws HCatException;

    /**
     * Gets all the partitions.
     *
     * @param dbName The name of the database.
     * @param tblName The name of the table.
     * @return A list of partitions.
     * @throws HCatException
     */
    public abstract List<HCatPartition> getPartitions(String dbName, String tblName)
        throws HCatException;

    /**
     * Gets all the partitions that match the specified (and possibly partial) partition specification.
     * A partial partition-specification is one where not all partition-keys have associated values. For example,
     * for a table ('myDb.myTable') with 2 partition keys (dt string, region string),
     * if for each dt ('20120101', '20120102', etc.) there can exist 3 regions ('us', 'uk', 'in'), then,
     *  1. Complete partition spec: getPartitions('myDb', 'myTable', {dt='20120101', region='us'}) would return 1 partition.
     *  2. Partial  partition spec: getPartitions('myDb', 'myTable', {dt='20120101'}) would return all 3 partitions,
     *                              with dt='20120101' (i.e. region = 'us', 'uk' and 'in').
     * @param dbName The name of the database.
     * @param tblName The name of the table.
     * @param partitionSpec The partition specification. (Need not include all partition keys.)
     * @return A list of partitions.
     * @throws HCatException
     */
    public abstract List<HCatPartition> getPartitions(String dbName, String tblName, Map<String, String> partitionSpec)
        throws HCatException;

    /**
     * Gets the partition.
     *
     * @param dbName The database name.
     * @param tableName The table name.
     * @param partitionSpec The partition specification, {[col_name,value],[col_name2,value2]}. All partition-key-values
     *                      must be specified.
     * @return An instance of HCatPartitionInfo.
     * @throws HCatException
     */
    public abstract HCatPartition getPartition(String dbName, String tableName,
                                               Map<String, String> partitionSpec) throws HCatException;

    /**
     * Adds the partition.
     *
     * @param partInfo An instance of HCatAddPartitionDesc.
     * @throws HCatException
     */
    public abstract void addPartition(HCatAddPartitionDesc partInfo)
        throws HCatException;

    /**
     * Adds a list of partitions.
     *
     * @param partInfoList A list of HCatAddPartitionDesc.
     * @return The number of partitions added.
     * @throws HCatException
     */
    public abstract int addPartitions(List<HCatAddPartitionDesc> partInfoList)
        throws HCatException;

    /**
     * Drops partition(s) that match the specified (and possibly partial) partition specification.
     * A partial partition-specification is one where not all partition-keys have associated values. For example,
     * for a table ('myDb.myTable') with 2 partition keys (dt string, region string),
     * if for each dt ('20120101', '20120102', etc.) there can exist 3 regions ('us', 'uk', 'in'), then,
     *  1. Complete partition spec: dropPartitions('myDb', 'myTable', {dt='20120101', region='us'}) would drop 1 partition.
     *  2. Partial  partition spec: dropPartitions('myDb', 'myTable', {dt='20120101'}) would drop all 3 partitions,
     *                              with dt='20120101' (i.e. region = 'us', 'uk' and 'in').
     * @param dbName The database name.
     * @param tableName The table name.
     * @param partitionSpec The partition specification, {[col_name,value],[col_name2,value2]}.
     * @param ifExists Hive returns an error if the partition specified does not exist, unless ifExists is set to true.
     * @throws HCatException,ConnectionFailureException
     */
    public abstract void dropPartitions(String dbName, String tableName,
                                        Map<String, String> partitionSpec, boolean ifExists)
        throws HCatException;

    /**
     * List partitions by filter.
     *
     * @param dbName The database name.
     * @param tblName The table name.
     * @param filter The filter string,
     *    for example "part1 = \"p1_abc\" and part2 <= "\p2_test\"". Filtering can
     *    be done only on string partition keys.
     * @return list of partitions
     * @throws HCatException
     */
    public abstract List<HCatPartition> listPartitionsByFilter(String dbName, String tblName,
                                                               String filter) throws HCatException;

    /**
     * Mark partition for event.
     *
     * @param dbName The database name.
     * @param tblName The table name.
     * @param partKVs the key-values associated with the partition.
     * @param eventType the event type
     * @throws HCatException
     */
    public abstract void markPartitionForEvent(String dbName, String tblName,
                                               Map<String, String> partKVs, PartitionEventType eventType)
        throws HCatException;

    /**
     * Checks if a partition is marked for event.
     *
     * @param dbName the db name
     * @param tblName the table name
     * @param partKVs the key-values associated with the partition.
     * @param eventType the event type
     * @return true, if is partition marked for event
     * @throws HCatException
     */
    public abstract boolean isPartitionMarkedForEvent(String dbName, String tblName,
                                                      Map<String, String> partKVs, PartitionEventType eventType)
        throws HCatException;

    /**
     * Gets the delegation token.
     *
     * @param owner the owner
     * @param renewerKerberosPrincipalName the renewer kerberos principal name
     * @return the delegation token
     * @throws HCatException,ConnectionFailureException
     */
    public abstract String getDelegationToken(String owner,
                                              String renewerKerberosPrincipalName) throws HCatException;

    /**
     * Renew delegation token.
     *
     * @param tokenStrForm the token string
     * @return the new expiration time
     * @throws HCatException
     */
    public abstract long renewDelegationToken(String tokenStrForm)
        throws HCatException;

    /**
     * Cancel delegation token.
     *
     * @param tokenStrForm the token string
     * @throws HCatException
     */
    public abstract void cancelDelegationToken(String tokenStrForm)
        throws HCatException;

    /**
     * Retrieve Message-bus topic for a table.
     *
     * @param dbName The name of the DB.
     * @param tableName The name of the table.
     * @return Topic-name for the message-bus on which messages will be sent for the specified table.
     * By default, this is set to <db-name>.<table-name>. Returns null when not set.
     */
    public abstract String getMessageBusTopicName(String dbName, String tableName) throws HCatException;

    /**
     * Close the hcatalog client.
     *
     * @throws HCatException
     */
    public abstract void close() throws HCatException;
}


text:
'use strict';

const electron = require('electron');
// Module to control application life.
const app = electron.app;
// Module to create native browser window.
const BrowserWindow = electron.BrowserWindow;

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow;

function createWindow () {
  // Create the browser window to be full screen. Could also be kiosk: true
  // but requires some further testing.
  mainWindow = new BrowserWindow({
    width: 800,
    height: 600
//    fullscreen: true
  });

  // and load the index.html of the app.
  mainWindow.loadURL('file://' + __dirname + '/index.html');

  // Don't show a menu bar
  mainWindow.setMenuBarVisibility(false);

  // Emitted when the window is closed.
  mainWindow.on('closed', function() {
    // Dereference the window object, usually you would store windows
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.
    mainWindow = null;
  });
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
app.on('ready', createWindow);

// Quit when all windows are closed.
app.on('window-all-closed', function () {
  // On OS X it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('activate', function () {
  // On OS X it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (mainWindow === null) {
    createWindow();
  }
});

const saveResults = formData => {
  console.log('save form');
  console.log(formData);

  var fs = require('fs');
  var stream = fs.createWriteStream("entries.txt", {'flags': 'a'});
  stream.once('open', function(fd) {
    stream.write(formData.name + "\n");
    stream.write(formData.email + "\n");

    for (let i = 0; i < formData.interests.length; i++) {
      stream.write(formData.interests[i] + "\n");
    }

    stream.write("\n----------------------------------------\n\n")
    stream.end();
  });
}

exports.saveResults = saveResults;


text:
<<<<<<< HEAD

package g4p_controls;

import g4p_controls.HotSpot.HSalpha;
import g4p_controls.HotSpot.HSmask;
import processing.core.PApplet;
import processing.core.PImage;

/**
 * Intermediary class for control based on images.
 *
 * It will create an array (minimum size 3) of PImage objects one for each image file.
 *
 * @author Peter Lager
 */
abstract class GImageControl extends GAbstractControl {

	protected PImage[] bimage = null;
	public PImage mask = null;

	public GImageControl(PApplet theApplet, float p0, float p1, float p2, float p3,
			String[] fnames, String fnameMask) {
		super(theApplet, p0, p1, p2, p3);
		// These will be zero if we are to use the image size
		int controlWidth = (int)width, controlHeight = (int)height;
		//=======================================================
		// First of all load images
		bimage = new PImage[3];
		if(fnames == null || fnames.length == 0){
			fnames = new String[] { "err0.png", "err1.png", "err2.png" };
			bimage = new PImage[3];
		}
		else {
			bimage = new PImage[PApplet.max(3, fnames.length)];
		}

		for(int i = 0; i < fnames.length; i++){
			bimage[i] = winApp.loadImage(fnames[i]);
			if(bimage[i] == null)
				bimage[i] = winApp.loadImage("err" + (i%3) + ".png");
		}
		for(int i = fnames.length; i < 3; i++)
			bimage[i] = bimage[i-1];

		// Get mask image if available
		if(fnameMask != null)
			mask = winApp.loadImage(fnameMask);
		//=======================================================
		// So now we need to decide whether to resize the images or control
		if(width > 0 && height > 0){
			// Resize images
			for(int i = 0; i < bimage.length; i++){
				if(bimage[i].width != controlWidth || bimage[i].height != height)
					bimage[i].resize(controlWidth, controlHeight);
			}
			if(mask != null && (mask.width != controlWidth || mask.height != controlHeight))
				mask.resize(controlWidth, controlHeight);
		}
		else {
			// resize control
			width = bimage[0].width;
			height = bimage[0].height;
			halfWidth = width/2;
			halfHeight = height/2;
			// Recalculate corners or centre  depending on contro;_mode
			switch(G4P.control_mode){
			case CORNER:
			case CORNERS:
				x = p0;
				y = p1;
				cx = x + halfWidth;
				cy = y + halfHeight;
				break;
			case CENTER:
				cx = p0;
				cy = p1;
				x = cx - halfWidth;
				y = cy - halfHeight;
				break;
			}
		}
		if(mask != null){	// if we have a mask use it for the hot spot
			hotspots = new HotSpot[]{
					new HSmask(1, mask)
			};
		}
		else {   // no mask then use alpha channel of the OFF image
			hotspots = new HotSpot[]{
					new HSalpha(1, 0, 0, bimage[0], PApplet.CORNER)
			};
		}

	}

}
=======
/*
  Part of the GUI for Processing library
  	http://www.lagers.org.uk/g4p/index.html
	http://gui4processing.googlecode.com/svn/trunk/

  Copyright (c) 2008-13 Peter Lager

  This library is free software; you can redistribute it and/or
  modify it under the terms of the GNU Lesser General Public
  License as published by the Free Software Foundation; either
  version 2.1 of the License, or (at your option) any later version.

  This library is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  Lesser General Public License for more details.

  You should have received a copy of the GNU Lesser General
  Public License along with this library; if not, write to the
  Free Software Foundation, Inc., 59 Temple Place, Suite 330,
  Boston, MA  02111-1307  USA
 */

package g4p_controls;

import g4p_controls.HotSpot.HSalpha;
import g4p_controls.HotSpot.HSmask;
import processing.core.PApplet;
import processing.core.PImage;

/**
 * Intermediary class for control based on images.
 *
 * It will create an array (minimum size 3) of PImage objects one for each image file.
 *
 * @author Peter Lager
 */
abstract class GImageControl extends GAbstractControl {

	protected PImage[] bimage = null;
	public PImage mask = null;

	public GImageControl(PApplet theApplet, float p0, float p1, float p2, float p3,
			String[] fnames, String fnameMask) {
		super(theApplet, p0, p1, p2, p3);
		// These will be zero if we are to use the image size
		int controlWidth = (int)width, controlHeight = (int)height;
		//=======================================================
		// First of all load images
		bimage = new PImage[3];
		if(fnames == null || fnames.length == 0){
			fnames = new String[] { "err0.png", "err1.png", "err2.png" };
			bimage = new PImage[3];
		}
		else {
			bimage = new PImage[PApplet.max(3, fnames.length)];
		}

		for(int i = 0; i < fnames.length; i++){
			bimage[i] = winApp.loadImage(fnames[i]);
			if(bimage[i] == null)
				bimage[i] = winApp.loadImage("err" + (i%3) + ".png");
		}
		for(int i = fnames.length; i < 3; i++)
			bimage[i] = bimage[i-1];

		// Get mask image if available
		if(fnameMask != null)
			mask = winApp.loadImage(fnameMask);
		//=======================================================
		// So now we need to decide whether to resize the images or control
		if(width > 0 && height > 0){
			// Resize images
			for(int i = 0; i < bimage.length; i++){
				if(bimage[i].width != controlWidth || bimage[i].height != height)
					bimage[i].resize(controlWidth, controlHeight);
			}
			if(mask != null && (mask.width != controlWidth || mask.height != controlHeight))
				mask.resize(controlWidth, controlHeight);
		}
		else {
			// resize control
			width = bimage[0].width;
			height = bimage[0].height;
			halfWidth = width/2;
			halfHeight = height/2;
			// Recalculate corners or centre  depending on contro;_mode
			switch(G4P.control_mode){
			case CORNER:
			case CORNERS:
				x = p0;
				y = p1;
				cx = x + halfWidth;
				cy = y + halfHeight;
				break;
			case CENTER:
				cx = p0;
				cy = p1;
				x = cx - halfWidth;
				y = cy - halfHeight;
				break;
			}
		}
		if(mask != null){	// if we have a mask use it for the hot spot
			hotspots = new HotSpot[]{
					new HSmask(1, mask)
			};
		}
		else {   // no mask then use alpha channel of the OFF image
			hotspots = new HotSpot[]{
					new HSalpha(1, 0, 0, bimage[0], PApplet.CORNER)
			};
		}

	}

}
>>>>>>> origin/master


text:
import java.util.*;

/**
 * This class stores an element of a Coxeter group of type A and rank
 * "size" as a permutation, oneLine.  The methods contained in
 * this class can preform elementary operations on the element.
 * @author Tyson Gern (tygern@gmail.com)
 */
class TypeA extends Element{

    /**
     * This constructs an element from a permutation.
     * @param input The permutation
     */
    public TypeA(int[] input) {
        size = input.length;
        rank = input.length - 1;
        oneLine = new int[size];

        boolean[] number = new boolean[size];
        for (int i = 0; i < size; i++) number[i] = false;

        for(int i = 0; i < size; i++) {
            if (input[i] > size || input[i] <= 0 || number[input[i] - 1]) {
                throw new IllegalArgumentException("Invalid permutation");
            }
            oneLine[i] = input[i];
            number[input[i] - 1] = true;
        }
    }

    /**
     * This constructs the identity element of a particular rank.
     * @param rank The rank of the element
     */
    protected TypeA(int rank) {
        this.rank = rank;
        this.size = rank + 1;
        oneLine = new int[size];
        for (int i = 0; i < size; i++) {
            oneLine[i] = i + 1;
        }
    }

    /**
     * This method gets the inverse
     * @return The inverse of element
     */
    public TypeA findInverse() {
        return new TypeA(this.invertPermutation());
    }

    /**
     * This method inverts the element
     * @return Nothing
     */
    public void invert() {
        this.oneLine = findInverse().oneLine;
    }

    /**
     * This method multiplies the element on the right by a generator,
     * s.
     * @param s The generator
     * @return Nothing
     */
    private TypeA rightMultiplyS(int s) {
        if (s <= rank && s >= 1) {
            switchPlaces(s-1, s);
        }
        return this;
    }

    /**
     * This method multiplies the element on the left by a generator,
     * s.
     * @param s The generator
     * @return Nothing
     */
    private TypeA leftMultiplyS(int s) {
        if (s <= rank && s >= 1) {
            switchValues(s,s + 1);
        }

        return this;
    }

    /**
     * This method gets the length of the element
     * @return the length of the element.
     */
    public int length() {
        return countInv();
    }

    /**
     * This method returns true if s is in the right descent set of
     * the element, false otherwise.
     * @return true is s is a descent of the element
     */
    protected boolean isRightDescent(int s) {
        if (s >= 1 && s <= rank) {
            return (oneLine[s - 1] > oneLine[s]);
        }
        return false;
    }

    /**
     * This method creates a TypeAExpression reduced expression from a
     * signed permutation.
     * @return a reduced expression
     */
    public TypeAExpression findRE() {
        ArrayList<Integer> generator = new ArrayList<Integer> ();
        TypeA permutation = new TypeA(oneLine);

        while (permutation.length() != 0) {
            for (int i = permutation.size; i >= 1; i--) {
                if (permutation.isRightDescent(i)) {
                    generator.add(i);
                    permutation.rightMultiplyS(i);
                }
            }
        }

        int length = generator.size();
        int[] genArray = new int[length];
        for (int i = 0; i < length; i++) {
            genArray[length - 1 - i] = generator.get(i).intValue();
        }

        TypeAExpression redExp = new TypeAExpression(genArray, permutation.rank);
        return redExp;

    }

    /**
     * This method multiplies a permutation on the right by another
     * permutation.
     * @param the other element
     * @return the product of this and other
     */
    public TypeA rightMultiply(TypeA other) {
        if (!compatible(other)) return null;
        return new TypeA(rightMultiplyPerm(other));
    }

    /**
     * This method multiplies a permutation on the left by another
     * permutation.
     * @param the other element
     * @return the product of this and other
     */
    public TypeA leftMultiply(TypeA other) {
        return other.rightMultiply(this);
    }
}