text:
import { Component, Inject, OnInit } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/throttleTime';
import 'rxjs/add/observable/fromEvent';
import { ReactiveFormsModule } from '@angular/forms';

import { UserService } from '../../services/user.service';

import { User } from '../../models/user';

@Component({
    selector: 'users',
    templateUrl: './users.component.html',
    providers: [UserService]
})

export class UsersComponent {
    errorMessage: string;
    filterInput = new FormControl();
    filterText: string;
    filterPlaceholder: string;
    users: User[] = [];

    constructor(private userService: UserService) {
    }

    ngOnInit() {
        this.initializeFilter();
        this.getUsersFromApi();
    }

    private getUsersFromApi() {
        this.userService
            .getAllUsers()
            .then(users => {
                this.errorMessage = "";
                this.users = users;
            })
            .catch((error) => {
                this.errorMessage = error;
                console.log(error);
            });
    }

    private initializeFilter() {
        this.filterText = "";
        this.filterPlaceholder = "Filter...";

        this.filterInput
            .valueChanges
            .debounceTime(200)
            .subscribe(term => {
                this.filterText = <string>(term);
                console.log(term);
            });
    }
}


text:
package org.jboss.jdeparser;

import javax.lang.model.element.ExecutableElement;

/**
 * A block of code, to which statements may be added.
 *
 * @author David M. Lloyd
 */
public interface JBlock extends JStatement, JCommentable {

    /**
     * Insert a blank line at this point.
     *
     * @return this block
     */
    JBlock blankLine();

    /**
     * Create a nested sub-block at this point.
     *
     * @param braces the rule for adding braces
     * @return the nested block
     */
    JBlock block(Braces braces);

    // program flow

    /**
     * Insert an {@code if} statement at this point.
     *
     * @param cond the {@code if} condition
     * @return the {@code if} statement
     */
    JIf _if(JExpr cond);

    /**
     * Insert a {@code while} statement at this point.
     *
     * @param cond the {@code while} condition
     * @return the {@code while} statement
     */
    JBlock _while(JExpr cond);

    /**
     * Insert a {@code do}/{@code while} statement at this point.
     *
     * @param cond the {@code while} condition
     * @return the {@code while} statement
     */
    JBlock _do(JExpr cond);

    /**
     * Add a label at this point, which may be used for future branch instructions.
     *
     * @param name the label name
     * @return the label
     */
    JLabel label(String name);

    /**
     * Add a label at this point whose unique name is automatically generated.
     *
     * @return the label
     */
    JLabel anonLabel();

    /**
     * Create a forward label that can be named and attached later.
     *
     * @return the forward label
     */
    JLabel forwardLabel();

    /**
     * Name and attach a forward label.
     *
     * @param label the label to name and attach
     * @param name the label name
     * @return the attached label
     */
    JLabel label(JLabel label, String name);

    /**
     * Name and attach a forward label as anonymous.
     *
     * @param label the label to name and attach
     * @return the attached label
     */
    JLabel anonLabel(JLabel label);

    /**
     * Insert a {@code continue} statement at this point.
     *
     * @return the statement
     */
    JStatement _continue();

    /**
     * Insert a labelled {@code continue} statement at this point.
     *
     * @param label the label
     * @return the statement
     */
    JStatement _continue(JLabel label);

    /**
     * Insert a {@code break} statement at this point.
     *
     * @return the statement
     */
    JStatement _break();

    /**
     * Insert a labelled {@code break} statement at this point.
     *
     * @param label the label
     * @return the statement
     */
    JStatement _break(JLabel label);

    /**
     * Insert a "for-each" style {@code for} loop at this point.
     *
     * @param mods the item variable modifiers
     * @param type the item variable type
     * @param name the item variable name
     * @param iterable the iterable or array expression
     * @return the body of the {@code for} loop
     */
    JBlock forEach(int mods, String type, String name, JExpr iterable);

    /**
     * Insert a "for-each" style {@code for} loop at this point.
     *
     * @param mods the item variable modifiers
     * @param type the item variable type
     * @param name the item variable name
     * @param iterable the iterable or array expression
     * @return the body of the {@code for} loop
     */
    JBlock forEach(int mods, JType type, String name, JExpr iterable);

    /**
     * Insert a "for-each" style {@code for} loop at this point.
     *
     * @param mods the item variable modifiers
     * @param type the item variable type
     * @param name the item variable name
     * @param iterable the iterable or array expression
     * @return the body of the {@code for} loop
     */
    JBlock forEach(int mods, Class<?> type, String name, JExpr iterable);

    /**
     * Insert a {@code for} loop at this point.
     *
     * @return the {@code for} loop
     */
    JFor _for();

    /**
     * Insert a {@code switch} statement at this point.
     *
     * @param expr the {@code switch} expression
     * @return the {@code switch} statement
     */
    JSwitch _switch(JExpr expr);

    /**
     * Insert a {@code return} statement at this point.
     *
     * @param expr the expression to return
     * @return the statement
     */
    JStatement _return(JExpr expr);

    /**
     * Insert a {@code void} {@code return} statement at this point.
     *
     * @return the statement
     */
    JStatement _return();

    // assert

    /**
     * Insert an {@code assert} statement at this point.
     *
     * @param expr the expression to assert
     * @return the statement
     */
    JStatement _assert(JExpr expr);

    /**
     * Insert an {@code assert} statement at this point with a message.
     *
     * @param expr the expression to assert
     * @param message the assertion message
     * @return the statement
     */
    JStatement _assert(JExpr expr, JExpr message);

    // constructor invocations

    /**
     * Insert a {@code this()} call at this point.
     *
     * @return the call
     */
    JCall callThis();

    /**
     * Insert a {@code super()} call at this point.
     *
     * @return the call
     */
    JCall callSuper();

    // expression

    /**
     * Insert an expression statement at this point.  Expressions which are invalid statements may generate an
     * error at the time this method is called, or at compile time.
     *
     * @param expr the expression to add
     * @return the statement
     */
    JStatement add(JExpr expr);

    // invocations

    /**
     * Insert a method invocation at this point.
     *
     * Note that these two invocations are identical:
     *
     *
{@code
    block.call(element);
    block.add(JExprs.call(element));
}

     *
     * @param element the program element whose name to use
     * @return the method call
     */
    JCall call(ExecutableElement element);

    /**
     * Insert a method invocation at this point.
     *
     * @param obj the expression upon which to invoke
     * @param element the program element whose name to use
     * @return the method call
     */
    JCall call(JExpr obj, ExecutableElement element);

    /**
     * Insert a method invocation at this point.
     *
     * Note that these two invocations are identical:
     *
     *
{@code
    block.call(methodName);
    block.add(JExprs.call(methodName));
}

     *
     * @param name the method name
     * @return the method call
     */
    JCall call(String name);

    /**
     * Insert a method invocation at this point.
     *
     * @param obj the expression upon which to invoke
     * @param name the method name
     * @return the method call
     */
    JCall call(JExpr obj, String name);

    /**
     * Insert a type-qualified static method invocation at this point.
     *
     * @param element the program element whose name and type to use
     * @return the method call
     */
    JCall callStatic(ExecutableElement element);

    /**
     * Insert a type-qualified static method invocation at this point.
     *
     * @param type the type upon which to invoke
     * @param name the method name
     * @return the method call
     */
    JCall callStatic(String type, String name);

    /**
     * Insert a type-qualified static method invocation at this point.
     *
     * @param type the type upon which to invoke
     * @param name the method name
     * @return the method call
     */
    JCall callStatic(JType type, String name);

    /**
     * Insert a type-qualified static method invocation at this point.
     *
     * @param type the type upon which to invoke
     * @param name the method name
     * @return the method call
     */
    JCall callStatic(Class<?> type, String name);

    // raw construction

    /**
     * Insert an object construction statement at this point.
     *
     * @param type the type to instantiate
     * @return the constructor call
     */
    JCall _new(String type);

    /**
     * Insert an object construction statement at this point.
     *
     * @param type the type to instantiate
     * @return the constructor call
     */
    JCall _new(JType type);

    /**
     * Insert an object construction statement at this point.
     *
     * @param type the type to instantiate
     * @return the constructor call
     */
    JCall _new(Class<?> type);

    /**
     * Insert an object construction statement for an anonymous class at this point.
     *
     * @param type the type to instantiate
     * @return the anonymous class definition
     */
    JAnonymousClassDef _newAnon(String type);

    /**
     * Insert an object construction statement for an anonymous class at this point.
     *
     * @param type the type to instantiate
     * @return the anonymous class definition
     */
    JAnonymousClassDef _newAnon(JType type);

    /**
     * Insert an object construction statement for an anonymous class at this point.
     *
     * @param type the type to instantiate
     * @return the anonymous class definition
     */
    JAnonymousClassDef _newAnon(Class<?> type);

    // local class definition

    /**
     * Insert a local class definition at this point.
     *
     * @param mods the class modifiers
     * @param name the local class name
     * @return the local class definition
     */
    JClassDef _class(int mods, String name);

    // synch

    /**
     * Insert a {@code synchronized} block at this point.
     *
     * @param synchExpr the lock expression
     * @return the {@code synchronized} block
     */
    JBlock _synchronized(JExpr synchExpr);

    // assignment

    /**
     * Insert an assignment ({@code =}) expression at this point.
     *
     * @param target the assignment target
     * @param e1 the expression to apply
     * @return the statement
     */
    JStatement assign(JAssignableExpr target, JExpr e1);

    /**
     * Insert an assignment ({@code +=}) expression at this point.
     *
     * @param target the assignment target
     * @param e1 the expression to apply
     * @return the statement
     */
    JStatement addAssign(JAssignableExpr target, JExpr e1);

    /**
     * Insert an assignment ({@code -=}) expression at this point.
     *
     * @param target the assignment target
     * @param e1 the expression to apply
     * @return the statement
     */
    JStatement subAssign(JAssignableExpr target, JExpr e1);

    /**
     * Insert an assignment ({@code *=}) expression at this point.
     *
     * @param target the assignment target
     * @param e1 the expression to apply
     * @return the statement
     */
    JStatement mulAssign(JAssignableExpr target, JExpr e1);

    /**
     * Insert an assignment ({@code /=}) expression at this point.
     *
     * @param target the assignment target
     * @param e1 the expression to apply
     * @return the statement
     */
    JStatement divAssign(JAssignableExpr target, JExpr e1);

    /**
     * Insert an assignment ({@code %=}) expression at this point.
     *
     * @param target the assignment target
     * @param e1 the expression to apply
     * @return the statement
     */
    JStatement modAssign(JAssignableExpr target, JExpr e1);

    /**
     * Insert an assignment ({@code &=}) expression at this point.
     *
     * @param target the assignment target
     * @param e1 the expression to apply
     * @return the statement
     */
    JStatement andAssign(JAssignableExpr target, JExpr e1);

    /**
     * Insert an assignment ({@code |=}) expression at this point.
     *
     * @param target the assignment target
     * @param e1 the expression to apply
     * @return the statement
     */
    JStatement orAssign(JAssignableExpr target, JExpr e1);

    /**
     * Insert an assignment ({@code ^=}) expression at this point.
     *
     * @param target the assignment target
     * @param e1 the expression to apply
     * @return the statement
     */
    JStatement xorAssign(JAssignableExpr target, JExpr e1);

    /**
     * Insert an assignment ({@code >>=}) expression at this point.
     *
     * @param target the assignment target
     * @param e1 the expression to apply
     * @return the statement
     */
    JStatement shrAssign(JAssignableExpr target, JExpr e1);

    /**
     * Insert an assignment ({@code >>>=}) expression at this point.
     *
     * @param target the assignment target
     * @param e1 the expression to apply
     * @return the statement
     */
    JStatement lshrAssign(JAssignableExpr target, JExpr e1);

    /**
     * Insert an assignment ({@code <<=}) expression at this point.
     *
     * @param target the assignment target
     * @param e1 the expression to apply
     * @return the statement
     */
    JStatement shlAssign(JAssignableExpr target, JExpr e1);

    // inc/dec

    /**
     * Insert a postfix {@code ++} expression at this point.
     *
     * @param target the target expression
     * @return the statement
     */
    JStatement postInc(JAssignableExpr target);

    /**
     * Insert a postfix {@code --} expression at this point.
     *
     * @param target the target expression
     * @return the statement
     */
    JStatement postDec(JAssignableExpr target);

    /**
     * Insert a prefix {@code ++} expression at this point.
     *
     * @param target the target expression
     * @return the statement
     */
    JStatement preInc(JAssignableExpr target);

    /**
     * Insert a prefix {@code --} expression at this point.
     *
     * @param target the target expression
     * @return the statement
     */
    JStatement preDec(JAssignableExpr target);

    // empty

    /**
     * Insert an empty statement at this point (just a semicolon).
     *
     * @return the statement
     */
    JStatement empty();

    // exceptions

    /**
     * Insert a {@code throw} statement at this point.
     *
     * @param expr the expression to throw
     * @return the statement
     */
    JStatement _throw(JExpr expr);

    /**
     * Insert a {@code try} block at this point.
     *
     * @return the {@code try} block
     */
    JTry _try();

    // declarations

    /**
     * Insert a local variable declaration at this point.
     *
     * @param mods the variable modifiers
     * @param type the local variable type
     * @param name the local variable name
     * @param value the local variable's initializer expression
     * @return the local variable declaration
     */
    JVarDeclaration var(int mods, String type, String name, JExpr value);

    /**
     * Insert a local variable declaration at this point.
     *
     * @param mods the variable modifiers
     * @param type the local variable type
     * @param name the local variable name
     * @param value the local variable's initializer expression
     * @return the local variable declaration
     */
    JVarDeclaration var(int mods, JType type, String name, JExpr value);

    /**
     * Insert a local variable declaration at this point.
     *
     * @param mods the variable modifiers
     * @param type the local variable type
     * @param name the local variable name
     * @param value the local variable's initializer expression
     * @return the local variable declaration
     */
    JVarDeclaration var(int mods, Class<?> type, String name, JExpr value);

    /**
     * Insert a local variable declaration at this point.
     *
     * @param mods the variable modifiers
     * @param type the local variable type
     * @param name the local variable name
     * @return the local variable declaration
     */
    JVarDeclaration var(int mods, String type, String name);

    /**
     * Insert a local variable declaration at this point.
     *
     * @param mods the variable modifiers
     * @param type the local variable type
     * @param name the local variable name
     * @return the local variable declaration
     */
    JVarDeclaration var(int mods, JType type, String name);

    /**
     * Insert a local variable declaration at this point.
     *
     * @param mods the variable modifiers
     * @param type the local variable type
     * @param name the local variable name
     * @return the local variable declaration
     */
    JVarDeclaration var(int mods, Class<?> type, String name);

    /**
     * Insert a local variable declaration at this point with a generated name.
     *
     * @param type the local variable type
     * @param value the local variable's initializer expression
     * @return the local variable expression
     */
    JExpr tempVar(String type, JExpr value);

    /**
     * Insert a local variable declaration at this point with a generated name.
     *
     * @param type the local variable type
     * @param value the local variable's initializer expression
     * @return the local variable expression
     */
    JExpr tempVar(JType type, JExpr value);

    /**
     * Insert a local variable declaration at this point with a generated name.
     *
     * @param type the local variable type
     * @param value the local variable's initializer expression
     * @return the local variable expression
     */
    JExpr tempVar(Class<?> type, JExpr value);

    /**
     * Generate a temporary variable name.
     *
     * @return the generated name
     */
    String tempName();

    /**
     * Braces mode.
     */
    enum Braces {
        /**
         * Braces are optional and won't be rendered unless forced.
         */
        OPTIONAL,
        /**
         * Braces are only required if the block contains more or less than one statement.
         */
        IF_MULTILINE,
        /**
         * Braces should always be used.
         */
        REQUIRED,
        ;
    }
}

redpajama_set_name: RedPajamaGithub


text:
package main

import (
	"errors"
	"github.com/gocql/gocql"
	"regexp"
	"strconv"
	"strings"
)

// Constants for Alert entity
const (
	ACTIVE                                           = 1
	DEACTIVE                                         = 2
	MAX_LENGTH_FOR_CRITERIA                          = 140
	MAX_LENGTH_FOR_NAME                              = 32
	MAX_THRESHOLD_VALUE                              = 1000000
	VALIDATION_MESSAGE_NAME_EMPTY                    = "Alert name cannot be null"
	VALIDATION_MESSAGE_NAME_LENGTH                   = "Alert name length must be smaller than "
	VALIDATION_MESSAGE_NAME_ALPHANUMERIC             = "Alert name must be all alphanumerical characters"
	VALIDATION_MESSAGE_REQUIRED_CRITERIA_EMPTY       = "Must included criteria cannot be null"
	VALIDATION_MESSAGE_REQUIRED_CRITERIA_LENGTH      = "Required criteria length must be smaller than "
	VALIDATION_MESSAGE_NICE_TO_HAVE_CRITERIA_LENGTH  = "Optional criteria length must be smaller than "
	VALIDATION_MESSAGE_EXCLUDED_CRITERIA_LENGTH      = "Excluded criteria length must be smaller than "
	VALIDATION_MESSAGE_CRITERIA_PHRASES_ALPHANUMERIC = "Criteria phrases must be alphanumerical!"
	VALIDATION_MESSAGE_THRESHOLD                     = "Threshold must be positive number, it cannot be null, zero or negative number!"
	VALIDATION_MESSAGE_OWNER_ID                      = "Validation failed: ownerId!"
)

var alphanumericRegex = regexp.MustCompile("^[a-zA-Z0-9şŞıİçÇöÖüÜğĞ_\\s]*$")
var validationMessage string

// Alert is the primary entity of this microservice
type Alert struct {
	ID                 gocql.UUID `cql:"id" json:"id"`
	OwnerID            int        `cql:"owner_id" json:"owner_id"`
	Name               string     `cql:"name" json:"name"`
	RequiredCriteria   string     `cql:"required_criteria" json:"required_criteria"`
	NiceToHaveCriteria string     `cql:"nice_to_have_criteria" json:"nice_to_have_criteria"`
	ExcludedCriteria   string     `cql:"excluded_criteria" json:"excluded_criteria"`
	Threshold          int        `cql:"threshold" json:"threshold"`
	Status             int        `cql:"status" json:"status"`
}

func (a *Alert) validate() error {
	err := validateName(a)
	if err != nil {
		return err
	}
	err = validateRequiredCriteria(a)
	if err != nil {
		return err
	}
	err = validateNiceToHaveCriteria(a.NiceToHaveCriteria)
	if err != nil {
		return err
	}
	err = validateExcludedCriteria(a.ExcludedCriteria)
	if err != nil {
		return err
	}
	err = validateThreshold(a.Threshold)
	if err != nil {
		return err
	}
	err = validateOwnerID(a.OwnerID)
	if err != nil {
		return err
	}
	return nil
}

func validateName(a *Alert) error {
	if a.Name == "" {
		return errors.New(VALIDATION_MESSAGE_NAME_EMPTY)
	}
	if len(a.Name) > MAX_LENGTH_FOR_NAME {
		return errors.New(VALIDATION_MESSAGE_NAME_LENGTH + strconv.Itoa(MAX_LENGTH_FOR_NAME))
	}
	if !alphanumericRegex.MatchString(a.Name) {
		return errors.New(VALIDATION_MESSAGE_NAME_ALPHANUMERIC)
	}
	return nil
}

func validateRequiredCriteria(a *Alert) error {
	if a.RequiredCriteria == "" {
		return errors.New(VALIDATION_MESSAGE_REQUIRED_CRITERIA_EMPTY)
	}
	s := strings.Replace(a.RequiredCriteria, ",", "", -1)
	if len(s) > MAX_LENGTH_FOR_CRITERIA {
		return errors.New(VALIDATION_MESSAGE_REQUIRED_CRITERIA_LENGTH + strconv.Itoa(MAX_LENGTH_FOR_CRITERIA))
	}
	return validateCriteriaPhrases(a.RequiredCriteria)
}

func validateNiceToHaveCriteria(a string) error {
	if a == "" {
		return nil
	}
	s := strings.Replace(a, ",", "", -1)
	if len(s) > MAX_LENGTH_FOR_CRITERIA {
		return errors.New(VALIDATION_MESSAGE_NICE_TO_HAVE_CRITERIA_LENGTH + strconv.Itoa(MAX_LENGTH_FOR_CRITERIA))
	}
	return validateCriteriaPhrases(a)
}

func validateExcludedCriteria(a string) error {
	if a == "" {
		return nil
	}
	s := strings.Replace(a, ",", "", -1)
	if len(s) > MAX_LENGTH_FOR_CRITERIA {
		return errors.New(VALIDATION_MESSAGE_EXCLUDED_CRITERIA_LENGTH + strconv.Itoa(MAX_LENGTH_FOR_CRITERIA))
	}
	return validateCriteriaPhrases(a)
}

func validateCriteriaPhrases(a string) error {
	phrases := strings.Split(a, ",")
	var b = true
	for _, phrase := range phrases {
		if !(alphanumericRegex.MatchString(phrase)) {
			b = false
			break
		}
	}
	if !b {
		return errors.New(VALIDATION_MESSAGE_CRITERIA_PHRASES_ALPHANUMERIC)
	}
	return nil
}

func validateThreshold(a int) error {
	if a > MAX_THRESHOLD_VALUE || a <= 0 {
		return errors.New(VALIDATION_MESSAGE_THRESHOLD)
	}
	return nil
}

func validateOwnerID(ownerID int) error {
	if ownerID < 0 {
		return errors.New(VALIDATION_MESSAGE_OWNER_ID)
	}
	return nil
}

func GenerateAlertId() gocql.UUID {
	return gocql.TimeUUID()
}


text:
<?php

declare(strict_types=1);

namespace DesignPatterns\Behavioral\NullObject\Tests;

use DesignPatterns\Behavioral\NullObject\NullLogger;
use DesignPatterns\Behavioral\NullObject\PrintLogger;
use DesignPatterns\Behavioral\NullObject\Service;
use PHPUnit\Framework\TestCase;

class LoggerTest extends TestCase
{
    public function testNullObject()
    {
        $service = new Service(new NullLogger());
        $this->expectOutputString('');
        $service->doSomething();
    }

    public function testStandardLogger()
    {
        $service = new Service(new PrintLogger());
        $this->expectOutputString('We are in DesignPatterns\Behavioral\NullObject\Service::doSomething');
        $service->doSomething();
    }
}


text:
import os
import six
import stat
import uuid
import time
import logging
import tarfile
import tempfile

from .. import utils

class SshTarballTransferMixin(object):
    """
    Transfers resources and recipes by packing them to tar.gz and
    copying it via ssh.
    """
    def _transfer(self, pack_path, pack_dest, res_dir):
        node = self.node
        args = locals()
        # copy and extract tarball
        script = utils.ScriptRunner()
        script.append("scp %(pack_path)s root@%(node)s:%(pack_dest)s"
                      % args)
        script.append("ssh -o StrictHostKeyChecking=no "
                      "-o UserKnownHostsFile=/dev/null root@%(node)s "
                      "tar -C %(res_dir)s -xpzf %(pack_dest)s" % args)
        try:
            script.execute()
        except ScriptRuntimeError as ex:
            # TO-DO: change to appropriate exception
            raise RuntimeError('Failed to copy resources to node %s. '
                               'Reason: %s' % (node, ex))

    def _pack_resources(self):
        randpart = uuid.uuid4().hex[:8]
        pack_path = os.path.join(self.local_tmpdir,
                                 'res-%s.tar.gz' % randpart)
        pack = tarfile.open(pack_path, mode='w:gz')
        os.chmod(pack_path, stat.S_IRUSR | stat.S_IWUSR)
        for path, dest in self._resources:
            if not dest:
                dest = os.path.basename(path)
            pack.add(path,
                     arcname=os.path.join(dest, os.path.basename(path)))
        pack.close()
        return pack_path

    def _copy_resources(self):
        pack_path = self._pack_resources()
        pack_dest = os.path.join(self.remote_tmpdir,
                                 os.path.basename(pack_path))
        self._transfer(pack_path, pack_dest, self.resource_dir)

    def _pack_recipes(self):
        randpart = uuid.uuid4().hex[:8]
        pack_path = os.path.join(self.local_tmpdir,
                                 'rec-%s.tar.gz' % randpart)
        pack = tarfile.open(pack_path, mode='w:gz')
        os.chmod(pack_path, stat.S_IRUSR | stat.S_IWUSR)
        if self.recipe_dir.startswith(self.resource_dir):
            dest = self.recipe_dir[len(self.resource_dir):].lstrip('/')
        else:
            dest = ''
        for marker, recipes in six.iteritems(self._recipes):
            for path in recipes:
                _dest = os.path.join(dest, os.path.basename(path))
                pack.add(path, arcname=_dest)
        pack.close()
        return pack_path

    def _copy_recipes(self):
        pack_path = self._pack_recipes()
        pack_dest = os.path.join(self.remote_tmpdir,
                                 os.path.basename(pack_path))
        if self.recipe_dir.startswith(self.resource_dir):
            extr_dest = self.resource_dir
        else:
            extr_dest = self.recipe_dir
        self._transfer(pack_path, pack_dest, extr_dest)

class DroneObserver(object):
    """
    Base class for listening messages from drones.
    """
    def applying(self, drone, recipe):
        """
        Drone is calling this method when it starts applying recipe.
        """
        # subclass must implement this method
        raise NotImplementedError()

    def checking(self, drone, recipe):
        """
        Drone is calling this method when it starts checking if recipe
        has been applied.
        """
        # subclass must implement this method
        raise NotImplementedError()

    def finished(self, drone, recipe):
        """
        Drone is calling this method when it's finished with recipe
        application.
        """
        # subclass must implement this method
        raise NotImplementedError()

class Drone(object):
    """
    Base class used to apply installation recipes to nodes.
    """
    def __init__(self, node, resource_dir=None, recipe_dir=None,
                 local_tmpdir=None, remote_tmpdir=None):
        self._recipes = utils.SortedDict()
        self._resources = []
        self._applied = set()
        self._running = set()
        self._observer = None

        # remote host IP or hostname
        self.node = node
        # working directories on remote host
        self.resource_dir = (resource_dir or
                             '/tmp/drone%s' % uuid.uuid4().hex[:8])
        self.recipe_dir = (recipe_dir or
                           os.path.join(self.resource_dir, 'recipes'))
        # temporary directories
        self.remote_tmpdir = (remote_tmpdir or
                              '/tmp/drone%s' % uuid.uuid4().hex[:8])
        self.local_tmpdir = (local_tmpdir or
                             tempfile.mkdtemp(prefix='drone'))

    def init_node(self):
        """
        Initializes node for manipulation.
        """
        created = []
        server = utils.ScriptRunner(self.node)
        for i in (self.resource_dir, self.recipe_dir,
                  self.remote_tmpdir):
            server.append('mkdir -p %s' % os.path.dirname(i))
            server.append('mkdir --mode 0700 %s' % i)
            created.append('%s:%s' % (self.node, i))
        server.execute()

        # TO-DO: complete logger name when logging will be setup correctly
        logger = logging.getLogger()
        logger.debug('Created directories: %s' % ','.join(created))

    @property
    def recipes(self):
        for i in self._recipes.itervalues():
            for y in i:
                yield y

    @property
    def resources(self):
        for i in self._resources:
            yield i[0]

    def add_recipe(self, path, marker=None):
        """
        Registers recipe for application on node. Recipes will be
        applied in order they where added to drone. Multiple recipes can
        be applied in paralel if they have same marker.
        """
        marker = marker or uuid.uuid4().hex[:8]
        self._recipes.setdefault(marker, []).append(path)

    def add_resource(self, path, destination=None):
        """
        Registers resource. Destination will be relative from resource
        directory on node.
        """
        dest = destination or ''
        self._resources.append((path, dest))

    def _copy_resources(self):
        """
        Copies all local files registered in self._resources to their
        appropriate destination on self.node. If tmpdir is given this
        method can operate only in this directory.
        """
        # subclass must implement this method
        raise NotImplementedError()

    def _copy_recipes(self):
        """
        Copies all local files registered in self._recipes to their
        appropriate destination on self.node. If tmpdir is given this
        method can operate only in this directory.
        """
        # subclass must implement this method
        raise NotImplementedError()

    def prepare_node(self):
        """
        Copies all local resources and recipes to self.node.
        """
        # TO-DO: complete logger name when logging will be setup correctly
        logger = logging.getLogger()
        logger.debug('Copying drone resources to node %s: %s'
                     % (self.node, self.resources))
        self._copy_resources()
        logger.debug('Copying drone recipes to node %s: %s'
                     % (self.node, [i[0] for i in self.recipes]))
        self._copy_recipes()

    def _apply(self, recipe):
        """
        Starts application of single recipe given as path to the recipe
        file in self.node. This method should not wait until recipe is
        applied.
        """
        # subclass must implement this method
        raise NotImplementedError()

    def _finished(self, recipe):
        """
        Returns True if given recipe is applied, otherwise returns False
        """
        # subclass must implement this method
        raise NotImplementedError()

    def _wait(self):
        """
        Waits until all started applications of recipes will be finished
        """
        while self._running:
            _run = list(self._running)
            for recipe in _run:
                if self._observer:
                    self._observer.checking(self, recipe)
                if self._finished(recipe):
                    self._applied.add(recipe)
                    self._running.remove(recipe)
                    if self._observer:
                        self._observer.finished(self, recipe)
                else:
                    time.sleep(3)
                    continue

    def set_observer(self, observer):
        """
        Registers an observer. Given object should be subclass of class
        DroneObserver.
        """
        for attr in ('applying', 'checking', 'finished'):
            if not hasattr(observer, attr):
                raise ValueError('Observer object should be a subclass '
                                 'of class DroneObserver.')
        self._observer = observer

    def apply(self, marker=None, name=None, skip=None):
        """
        Applies recipes on node. If marker is specified, only recipes
        with given marker are applied. If name is specified only recipe
        with given name is applied. Skips recipes with names given
        in list parameter skip.
        """
        # TO-DO: complete logger name when logging will be setup correctly
        logger = logging.getLogger()
        skip = skip or []
        lastmarker = None
        for mark, recipelist in six.iteritems(self._recipes):
            if marker and marker != mark:
                logger.debug('Skipping marker %s for node %s.' %
                             (mark, self.node))
                continue
            for recipe in recipelist:
                base = os.path.basename(recipe)
                if (name and name != base) or base in skip:
                    logger.debug('Skipping recipe %s for node %s.' %
                                 (recipe, self.node))
                    continue

                # if the marker has changed then we don't want to
                # proceed until all of the previous puppet runs have
                # finished
                if lastmarker and lastmarker != mark:
                    self._wait()
                lastmarker = mark

                logger.debug('Applying recipe %s to node %s.' %
                             (base, self.node))
                rpath = os.path.join(self.recipe_dir, base)
                if self._observer:
                    self._observer.applying(self, recipe)
                self._running.add(rpath)
                self._apply(rpath)
        self._wait()

    def cleanup(self, resource_dir=True, recipe_dir=True):
        """
        Removes all directories created by this drone.
        """
        shutil.rmtree(self.local_tmpdir, ignore_errors=True)
        server = utils.ScriptRunner(self.node)
        server.append('rm -fr %s' % self.remote_tmpdir)
        if recipe_dir:
            server.append('rm -fr %s' % self.recipe_dir)
        if resource_dir:
            server.append('rm -fr %s' % self.resource_dir)
        server.execute()

class PackstackDrone(SshTarballTransferMixin, Drone):
    """
    This drone uses Puppet and it's manifests to manipulate node.
    """
    # XXX: Since this implementation is Packstack specific (_apply
    #      method), it should be moved out of installer when
    #      Controller and plugin system will be refactored and installer
    #      will support projects.
    def __init__(self, *args, **kwargs):
        kwargs['resource_dir'] = ('/var/tmp/packstack/drone%s'
                                  % uuid.uuid4().hex[:8])
        kwargs['recipe_dir'] = '%s/manifests' % kwargs['resource_dir']
        kwargs['remote_tmpdir'] = '%s/temp' % kwargs['resource_dir']

        super(PackstackDrone, self).__init__(*args, **kwargs)

        self.module_dir = os.path.join(self.resource_dir, 'modules')
        self.fact_dir = os.path.join(self.resource_dir, 'facts')

    def init_node(self):
        """
        Initializes node for manipulation.
        """
        super(PackstackDrone, self).init_node()
        server = utils.ScriptRunner(self.node)
        for pkg in ("puppet", "openssh-clients", "tar"):
            server.append("rpm -q --whatprovides %(pkg)s || "
                          "yum install -y %(pkg)s" % locals())
        server.execute()

    def add_resource(self, path, resource_type=None):
        """
        Resource type should be module, fact or resource.
        """
        resource_type = resource_type or 'resource'
        dest = '%ss' % resource_type
        super(PackstackDrone, self).add_resource(path, destination=dest)

    def _finished(self, recipe):
        recipe_base = os.path.basename(recipe)
        log = os.path.join(self.recipe_dir,
                           recipe_base.replace(".finished", ".log"))
        local = utils.ScriptRunner()
        local.append('scp -o StrictHostKeyChecking=no '
                     '-o UserKnownHostsFile=/dev/null '
                     'root@%s:%s %s' % (self.node, recipe, log))
        try:
            # once a remote puppet run has finished, we retrieve
            # the log file and check it for errors
            local.execute(log=False)
            # if we got to this point the puppet apply has finished
            return True
        except utils.ScriptRuntimeError as e:
            # the test raises an exception if the file doesn't exist yet
            return False

    def _apply(self, recipe):
        running = "%s.running" % recipe
        finished = "%s.finished" % recipe

        server = utils.ScriptRunner(self.node)
        server.append("touch %s" % running)
        server.append("chmod 600 %s" % running)

        # XXX: This is terrible hack, but unfortunatelly the apache
        # puppet module doesn't work if we set FACTERLIB
        # https://github.com/puppetlabs/puppetlabs-apache/pull/138
        for bad_word in ('horizon', 'nagios', 'apache'):
            if bad_word in recipe:
                break
        else:
            server.append("export FACTERLIB=$FACTERLIB:%s" %
                          self.fact_dir)
        server.append("export PACKSTACK_VAR_DIR=%s" % self.resource_dir)

        # TO-DO: complete logger name when logging will be setup correctly
        logger = logging.getLogger()
        loglevel = logger.level <= logging.DEBUG and '--debug' or ''
        rdir = self.resource_dir
        mdir = self._module_dir
        server.append(
            "( flock %(rdir)s/ps.lock "
            "puppet apply %(loglevel)s --modulepath %(mdir)s "
            "%(recipe)s > %(running)s 2>&1 < /dev/null; "
            "mv %(running)s %(finished)s ) "
            "> /dev/null 2>&1 < /dev/null &" % locals())
        server.execute()


text:
package com.external.volley.http;

/**
 * LoadListener special for ByteArrayLoadControler
 *
 * @author steven-pan
 *
 */
public interface LoadListener {

	void onStart();

	void onSuccess(byte[] data, String url, int actionId);

	void onError(String errorMsg, String url, int actionId);
}


text:
""" Each new term in the Fibonacci sequence is
generated by adding the previous two terms.
By starting with 1 and 2, the first 10 terms will be:

1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...

By considering the terms in the Fibonacci sequence
whose values do not exceed four million,
find the sum of the even-valued terms.  """

def fib_even_sum(number):
	if number == 0: return 0
	if number == 1: return 0
	if number == 2: return 2
	if number > 4000000:
		return "Number cannot exceed 4 million"

	#number is greater than 2 (error check done)

	#set sum to 2
	sum = 2

	#sum initial fibonacci values
	fib0 = 0
	fib1 = 1
	fib2 = 2

	#counter to sum only every third entry
	counter = 0;

	while (fib2 <= number):
		if(counter == 3):
			#add even number to sum bucket
			sum = sum + fib2

			#reset counter
			counter = 0

		#Move to the next 3 set of numbers starting from fib2
		fib0 = fib1
		fib1 = fib2
		fib2 = fib0 + fib1
		counter = counter + 1

	#return total sum
	return sum

	#Test
print(fib_even_sum(4000000))


text:
#include <jni.h>
#include <leveldb/db.h>
#include <jnihelper.h>

leveldb::Options convertOptions(jobject options);
leveldb::Options convertWriteOptions(jobject options);
leveldb::Options convertReadOptions(jobject options);

jobject convertStatus(JNIEnv* env,leveldb::Status status){
	jobject jstatus;

	bool is_dbopen_ok = status.ok();
	std::string strStatus =status.ToString();
    const char * charStatus = strStatus.c_str();
    jstring jstrStatus = env->NewStringUTF(charStatus);

	jclass jstatuscls = env->FindClass("product/miyabi/android/leveldb/db/Status");
//	jclass jstatuscls = env->FindClass("Lproduct/miyabi/android/leveldb/db/Status;");
	jmethodID jmethodIdInit;
	if (jstatuscls==NULL ){
		return NULL;
	}
	/*
	jmethodIdInit =  env->GetMethodID(jstatuscls,"factory","(Ljava/lang/String;)Lproduct/miyabi/android/leveldb/db/Status");
	jstatus = env->CallStaticObjectMethod(jstatuscls,jmethodIdInit,jstrStatus);
	*/
	jmethodIdInit =  env->GetMethodID(jstatuscls,"<init>","(Ljava/lang/String;)V");
	if(jmethodIdInit==NULL){
		return NULL;
	}
	jstatus = env->NewObject(jstatuscls,jmethodIdInit,jstrStatus);
	return jstatus;
}


text:
namespace igloo {

  class TestResultsOutput
  {
    protected:
      std::ostream& output;
    public:
      TestResultsOutput(std::ostream& outstream = std::cout) : output(outstream) {}
      virtual void PrintResult(const TestResults& results) const = 0;
  };
}

#endif


text:
(function (global, factory) {
  if (typeof define === "function" && define.amd) {
    define(["exports"], factory);
  } else if (typeof exports !== "undefined") {
    factory(exports);
  } else {
    var mod = {
      exports: {}
    };
    factory(mod.exports);
    global.actual = mod.exports;
  }
})(this, function (_exports) {
  "use strict";

  _exports.__esModule = true;
  _exports.bar = _exports.foo = void 0;
  var foo, bar;
  _exports.bar = bar;
  _exports.foo = foo;
});


text:
package com.westglenn.www.pitchcounter;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;

import java.util.ArrayList;

public class AddPitcherActivity extends Activity {
    private StateSingleton stateInstance;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Get the message from the intent
        Intent intent = getIntent();

        //list = intent.getParcelableArrayListExtra(PitcherListActivity.PITCHER_LIST);
        stateInstance = StateSingleton.getInstance();

        Integer count = stateInstance.getList().size() + 1;
        String pitcherName = String.format("Pitcher %d", count);

        // Set the text view as the activity layout
        setContentView(R.layout.activity_add_pitcher);
        EditText editText = (EditText)findViewById(R.id.edit_addPlayer);
        editText.setText(pitcherName);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.add_pitcher, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        switch (item.getItemId()) {
            case R.id.action_accept:
                EditText editText = (EditText)findViewById(R.id.edit_addPlayer);
                String pitcherName = editText.getText().toString();
                Intent intent = new Intent();
                intent.putExtra("newpitchername", pitcherName );
                setResult(RESULT_OK, intent);
                finish();

                return true;
            case R.id.action_settings:
                intent = new Intent(this, SettingsActivity.class);
                startActivity(intent);
                return true;
            case R.id.action_help:
                intent = new Intent(this, HelpActivity.class);
                startActivity(intent);
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }

    }
}


text:
//Copyright © 2014 Sony Computer Entertainment America LLC. See License.txt.

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;

namespace Sce.Atf.Controls.Timelines.Direct2D
{
    ///
    /// A timeline manipulator for moving IEvent objects, such as markers, keys, and intervals
    public class D2dMoveManipulator
    {
        ///
        /// Constructor that permanently attaches to the given TimelineControl by subscribing to its
        /// events
        /// <param name="owner">The timeline control that we are permanently attached to</param>
        public D2dMoveManipulator(D2dTimelineControl owner)
        {
            m_owner = owner;
            m_owner.MouseDownPicked += owner_MouseDownPicked;
            m_owner.MouseMovePicked += owner_MouseMovePicked;
            m_owner.MouseMove += owner_MouseMove;
            m_owner.MouseDown += owner_MouseDown;
            m_owner.MouseUp += owner_MouseUp;
            m_owner.DrawingD2d += owner_DrawingD2d;
            m_owner.KeyDown += owner_KeyDown;
            m_owner.DragOver += owner_DragOver;
            m_owner.DragEnter += owner_DragEnter;
            m_owner.DragLeave += owner_DragLeave;
            m_owner.DragDrop += owner_DragDrop;
        }

        ///
        /// Gets the timeline control that we are permanently attached to
        protected D2dTimelineControl Owner
        {
            get { return m_owner; }
        }

        ///
        /// Gets the layout information for showing timeline objects that are currently being dragged.
        /// Is null if the IsMovingSelection property is false.
        protected GhostInfo[] Ghosts
        {
            get { return m_ghosts; }
        }

        ///
        /// Gets whether or not the user has dragged a selection set past a small threshold and thus
        /// ghost objects should be drawn
        protected bool IsMovingSelection
        {
            get
            {
                if (m_isDragDropping)
                    return true;
                return
                    m_mouseMoveHitRecord != null &&
                    DragOverThreshold &&
                    !m_owner.IsUsingMouse;
            }
        }

        ///
        /// Moves the objects represented by the current ghosts to be at the position of
        /// the ghosts
        protected virtual void MoveSelection()
        {
            // To avoid setting the dirty bit in custom applications.
            // http://sf.ship.scea.com/sf/go/artf22506
            PointF dragOffset = GetDragOffset();
            if (!m_isDragDropping &&
                (dragOffset.X == 0.0f) &&
                (dragOffset.Y == 0.0f))
                return;

            // If we're dragging up, then don't create new tracks
            if (dragOffset.Y < 0)
                foreach (GhostInfo ghost in m_ghosts)
                    if (!ghost.Valid)
                        return;

            if (m_isDragDropping)
            {
                // No transaction for drag-drop; this is the responsibility of the timeline context, for example.
                // Also, the timeline context will create tracks and groups as necessary.
                // All we really need to do is to update the position of the selected objects so that
                //  snapping is correct.
                _MoveSelection(false, false);
            }
            else
            {
                // If Control key is being held down, then we're in copy mode.
                bool tryToCopy = (Control.ModifierKeys == Keys.Control);

                m_owner.TransactionContext.DoTransaction(
                    () => _MoveSelection(tryToCopy, true),
                    "Move Events".Localize("Move Manipulator's undo / redo description for moving timeline events"));
            }
        }

        private void _MoveSelection(bool tryToCopy, bool createTracksAndGroups)
        {
            ITimeline timeline = m_owner.TimelineDocument.Timeline;
            Dictionary<ITrack, ITrack> newTrackMap = new Dictionary<ITrack, ITrack>();
            List<Sce.Atf.Pair<ITrack, IEvent>> toAdd = new List<Sce.Atf.Pair<ITrack, IEvent>>();

            for (int i = 0; i < m_ghosts.Length; i++)
            {
                GhostInfo ghost = m_ghosts[i];

                ITimelineObject ghostCopy = null;
                if (tryToCopy)
                {
                    ICloneable cloneable = ghost.Object as ICloneable;
                    if (cloneable != null)
                        ghostCopy = cloneable.Clone() as ITimelineObject;
                }

                ITimelineReference reference = ghost.Object as ITimelineReference;
                if (reference != null)
                {
                    if (ghostCopy != null)
                        reference = (ITimelineReference)ghostCopy;
                    reference.Start = ghost.Start;
                    if (ghostCopy != null && timeline is IHierarchicalTimelineList)
                        ((IHierarchicalTimelineList)timeline).References.Add(reference);
                    continue;
                }

                IInterval interval = ghost.Object as IInterval;
                if (interval != null)
                {
                    if (ghostCopy != null)
                        interval = (IInterval)ghostCopy;
                    interval.Start = ghost.Start;
                    interval.Length = ghost.Length;
                    ITrack target = (ITrack)ghost.Target;
                    if (target != interval.Track && createTracksAndGroups)
                    {
                        if (target == null)
                            target = CreateTargetTrack(interval.Track, newTrackMap);
                        if (ghostCopy == null)
                            interval.Track.Intervals.Remove(interval);
                        toAdd.Add(new Sce.Atf.Pair<ITrack, IEvent>(target, interval));
                    }
                    continue;
                }

                IKey key = ghost.Object as IKey;
                if (key != null)
                {
                    if (ghostCopy != null)
                        key = (IKey)ghostCopy;
                    key.Start = ghost.Start;
                    ITrack target = (ITrack)ghost.Target;
                    if (target != key.Track && createTracksAndGroups)
                    {
                        if (target == null)
                            target = CreateTargetTrack(key.Track, newTrackMap);
                        if (ghostCopy == null)
                            key.Track.Keys.Remove(key);
                        toAdd.Add(new Sce.Atf.Pair<ITrack, IEvent>(target, key));
                    }
                    continue;
                }

                IMarker marker = ghost.Object as IMarker;
                if (marker != null)
                {
                    if (ghost.Valid &&
                        marker.Start != ghost.Start)
                    {
                        if (ghostCopy != null)
                        {
                            IMarker markerCopy = (IMarker)ghostCopy;
                            markerCopy.Start = ghost.Start;
                            marker.Timeline.Markers.Add(markerCopy);
                        }
                        else
                            marker.Start = ghost.Start;
                    }
                    continue;
                }

                ITrack track = ghost.Object as ITrack;
                if (track != null)
                {
                    var targetTrack = ghost.Target as ITrack;
                    if (targetTrack != null &&
                        targetTrack != track)
                    {
                        if (ghostCopy != null)
                            track = (ITrack)ghostCopy;
                        int index = targetTrack.Group.Tracks.IndexOf(targetTrack);
                        if (ghostCopy == null)
                            track.Group.Tracks.Remove(track);
                        targetTrack.Group.Tracks.Insert(index, track);
                    }
                    else
                    {
                        var targetGroup = ghost.Target as IGroup;
                        if (targetGroup != null)
                        {
                            // the track was dragged to an empty group. http://tracker.ship.scea.com/jira/browse/WWSATF-1371
                            if (ghostCopy != null)
                                track = (ITrack)ghostCopy;
                            else
                                track.Group.Tracks.Remove(track);
                            targetGroup.Tracks.Insert(0, track);
                        }
                    }
                    continue;
                }

                IGroup group = ghost.Object as IGroup;
                if (group != null)
                {
                    IGroup target = (IGroup)ghost.Target;
                    if (target != null &&
                        target != group)
                    {
                        if (ghostCopy != null)
                            group = (IGroup)ghostCopy;
                        int index = m_owner.TimelineDocument.Timeline.Groups.IndexOf(target);
                        if (ghostCopy == null)
                            m_owner.TimelineDocument.Timeline.Groups.Remove(group);
                        m_owner.TimelineDocument.Timeline.Groups.Insert(index, group);
                    }
                    continue;
                }
            }

            // So that when multiple intervals from multiple tracks are relocated to a different
            //  set of tracks, we need to remove them all and then add them all. If the remove and
            //  adds are done in pairs, one by one, then the events can step on each other. artf32260
            foreach (Sce.Atf.Pair<ITrack, IEvent> trackEventPair in toAdd)
            {
                if (trackEventPair.Second is IInterval)
                    trackEventPair.First.Intervals.Add((IInterval)trackEventPair.Second);
                else
                    trackEventPair.First.Keys.Add((IKey)trackEventPair.Second);
            }
        }

        // get start and y offsets in timeline space
        private PointF GetDragOffset()
        {
            if (!m_isDragDropping)
                return m_owner.GetDragOffset();
            PointF dragOffset = GdiUtil.InverseTransformVector(m_owner.Transform, DragDelta);
            dragOffset.X = m_owner.ConstrainFrameOffset(dragOffset.X);
            return dragOffset;
        }

        ///
        /// Gets the delta between current and drag points
        private Point DragDelta
        {
            get
            {
                if (!m_isDragDropping)
                    return m_owner.DragDelta;
                Point dragPoint = DragPoint;
                return new Point(dragPoint.X - m_firstPoint.X, dragPoint.Y - m_firstPoint.Y);
            }
        }

        ///
        /// Gets whether or not mouse movement passed the DragThreshold in x or y
        private bool DragOverThreshold
        {
            get
            {
                if (!m_isDragDropping)
                    return m_owner.DragOverThreshold;
                return m_isDragging && m_dragOverThreshold;
            }
        }

        ///
        /// Gets the first mouse point, or current mouse point if drag has passed the
        /// drag threshold
        private Point DragPoint
        {
            get { return m_dragOverThreshold ? m_currentPoint : m_firstPoint; }
        }

        ///
        /// Creates a target track if it doesn't already exist as a value in the 'newTrackMap' dictionary. New
        /// tracks are added to 'newTrackMap', with 'original' as the key.
        /// <param name="original">The key in the 'newTrackMap' dictionary</param>
        /// <param name="newTrackMap">Dictionary that maps original tracks to new tracks</param>
        /// <returns>The new track, equal to newTrackMap[original]</returns>
        private ITrack CreateTargetTrack(ITrack original, Dictionary<ITrack, ITrack> newTrackMap)
        {
            ITrack target;
            if (!newTrackMap.TryGetValue(original, out target))
            {
                ITimeline timeline = m_owner.TimelineDocument.Timeline;
                IGroup newGroup = m_owner.Create(original.Group);
                timeline.Groups.Add(newGroup);
                target = m_owner.Create(original);
                newGroup.Tracks.Add(target);
                newTrackMap.Add(original, target);
            }
            return target;
        }

        private void owner_MouseDownPicked(object sender, HitEventArgs e)
        {
            if (e.MouseEvent.Button == MouseButtons.Left &&
                !m_owner.IsUsingMouse)
            {
                m_mouseMoveHitRecord = null;

                HitRecord hitRecord = e.HitRecord;
                if (m_owner.IsEditable(hitRecord.HitPath))
                {
                    switch (e.HitRecord.Type)
                    {
                        case HitType.GroupMove:
                        case HitType.TrackMove:
                        case HitType.Interval:
                        case HitType.Key:
                        case HitType.Marker:
                            m_mouseMoveHitRecord = hitRecord;
                            break;
                    }
                }

                m_owner.IsMovingSelection = m_mouseMoveHitRecord != null; //obsolete
            }
        }

        private void owner_MouseMovePicked(object sender, HitEventArgs e)
        {
            if (e.MouseEvent.Button == MouseButtons.None &&
                !m_owner.IsUsingMouse)
            {
                HitRecord hitRecord = e.HitRecord;
                if (m_owner.IsEditable(hitRecord.HitPath))
                {
                    switch (hitRecord.Type)
                    {
                        case HitType.Interval:
                        case HitType.Key:
                        case HitType.Marker:
                            m_owner.Cursor = Cursors.SizeAll;
                            break;

                        default:
                            break;
                    }
                }
            }
        }

        // mouse move events aren't issued during a drag-over
        private void owner_DragOver(object sender, DragEventArgs e)
        {
            //MouseMove(e.X, e.Y);
            IEnumerable<ITimelineObject> dragDropObjects = m_owner.DragDropObjects;
            if (dragDropObjects == null)
                return;

            m_firstPoint.X = m_currentPoint.X = e.X;
            m_firstPoint.Y = m_currentPoint.Y = e.Y;
            float clientWindowX = m_owner.PointToClient(new Point(e.X, e.Y)).X;
            float worldX = GdiUtil.InverseTransform(m_owner.Transform, clientWindowX);
            foreach (ITimelineObject obj in dragDropObjects)
            {
                var _event = obj as IEvent;
                if (_event != null)
                    _event.Start = worldX;
            }
            MouseMove(e.X, e.Y);
        }

        private void owner_MouseMove(object sender, MouseEventArgs e)
        {
            MouseMove(e.X, e.Y);
        }

        private void MouseMove(int x, int y)
        {
            m_currentPoint = new Point(x, y);
            int xDelta = Math.Abs(m_currentPoint.X - m_firstPoint.X);
            int yDelta = Math.Abs(m_currentPoint.Y - m_firstPoint.Y);
            if (m_isDragging &&
                !m_dragOverThreshold &&
                (xDelta > m_dragThreshold || yDelta > m_dragThreshold))
            {
                m_dragOverThreshold = true;
            }

            if (IsMovingSelection)
            {
                m_ghosts = GetMoveGhostInfo(m_owner.Transform, m_owner.GetLayout());
                if (Control.ModifierKeys == Keys.Control)
                    m_owner.Cursor = Cursors.PanNW; //to indicate copy operation
                else
                    m_owner.Cursor = Cursors.SizeAll;
            }
        }

        // mouse move events aren't issued during a drag-over
        void owner_DragEnter(object sender, DragEventArgs e)
        {
            MouseDown(e.X, e.Y);
        }

        private void owner_MouseDown(object sender, MouseEventArgs e)
        {
            MouseDown(e.X, e.Y);
        }

        private void MouseDown(int x, int y)
        {
            m_firstPoint = m_currentPoint = new Point(x, y);
            m_isDragging = true;
            m_isDragDropping = (m_owner.DragDropObjects != null);
        }

        void owner_DragLeave(object sender, EventArgs e)
        {
            CancelDrag();
        }

        ///
        /// Method called when drag and drop ends
        /// <param name="sender">Sender</param>
        /// <param name="e">Event args</param>
        void owner_DragDrop(object sender, DragEventArgs e)
        {
            owner_MouseUp(sender, null);
        }

        private void owner_MouseUp(object sender, MouseEventArgs e)
        {
            if (IsMovingSelection)
            {
                MoveSelection();
                m_owner.Invalidate();
            }
            CancelDrag();
        }

        // draw dragged events
        private void owner_DrawingD2d(object sender, EventArgs e)
        {
            Rectangle clientRectangle = m_owner.ClientRectangle;
            Matrix transform = m_owner.Transform;

            if (IsMovingSelection && m_ghosts != null)
            {
                m_owner.Renderer.DrawGhosts(
                    m_ghosts,
                    GhostType.Move,
                    transform,
                    clientRectangle);

                // raise EventMoving events
                foreach (GhostInfo ghost in m_ghosts)
                {
                    IEvent _event = ghost.Object as IEvent;
                    if (_event != null)
                    {
                        m_owner.MoveEvent(
                            new EventMovedEventArgs(_event, ghost.Start, ghost.Target as ITrack));
                    }
                }
            }
        }

        private void owner_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == m_owner.CancelDragKey)
                CancelDrag();
        }

        private void CancelDrag()
        {
            m_isDragging = false;
            m_dragOverThreshold = false;
            m_isDragDropping = false;

            if (m_mouseMoveHitRecord != null)
            {
                m_mouseMoveHitRecord = null;
                m_ghosts = null;
                m_owner.IsMovingSelection = false;
                m_owner.Cursor = Cursors.Arrow;
                m_owner.Invalidate();
            }
        }

        // gets move information, for drawing ghosts and for performing actual move operation
        private GhostInfo[] GetMoveGhostInfo(Matrix worldToView, TimelineLayout layout)
        {
            // get start and y offsets in timeline space
            PointF dragOffset = GetDragOffset();

            // Get snapping points along the timeline (in world coordinates).
            List<float> movingPoints = new List<float>(2);
            TimelinePath snapperPath;
            if (m_mouseMoveHitRecord != null)
                snapperPath = m_mouseMoveHitRecord.HitPath;//use the last clicked event (interval, key or marker)
            else
                snapperPath = m_owner.Selection.LastSelected as TimelinePath;//moving a group or track, for example
            IEvent snapperEvent = snapperPath != null ? snapperPath.Last as IEvent : null;

            if (snapperEvent != null)
            {
                using (Matrix localToWorld = D2dTimelineControl.CalculateLocalToWorld(snapperPath))
                {
                    float worldStart = GdiUtil.Transform(localToWorld, snapperEvent.Start + dragOffset.X);
                    movingPoints.Add(worldStart);
                    if (snapperEvent.Length > 0.0f)
                        movingPoints.Add(GdiUtil.Transform(localToWorld,
                            snapperEvent.Start + dragOffset.X + snapperEvent.Length));
                }
            }

            // Get the offset from one of the world snap points to the closest non-selected object.
            float snapOffset;
            try
            {
                s_snapOptions.FilterContext = snapperEvent;
                s_snapOptions.Filter = MoveSnapFilter;
                snapOffset = m_owner.GetSnapOffset(movingPoints, s_snapOptions);
            }
            finally
            {
                s_snapOptions.FilterContext = null;
                s_snapOptions.Filter = null;
            }

            // adjust dragOffset to "snap-to" nearest event
            dragOffset.X += snapOffset;

            // get offsets in client space
            float xOffset = dragOffset.X * worldToView.Elements[0];
            float yOffset = dragOffset.Y * worldToView.Elements[3];

            TimelinePath[] targets = GetMoveTargets(layout);

            // Pretend that drag-drop objects are in the TimelineLayout object
            if (m_owner.DragDropObjects != null)
            {
                foreach (ITimelineObject dragDrop in m_owner.DragDropObjects)
                    layout[dragDrop] = GetDragDropBounds(dragDrop);
            }

            GhostInfo[] ghosts = new GhostInfo[targets.Length];
            int i = -1;
            foreach(TimelinePath path in m_owner.Selection.Selection)
            {
                i++;

                ITimelineObject timelineObject = path.Last;
                RectangleF bounds = layout[path];

                TimelinePath targetPath = targets[i];
                ITimelineObject target = targetPath != null ? targetPath.Last : null;

                float start = 0;
                float length = 0;
                bool valid = true;

                IInterval interval = timelineObject as IInterval;
                IKey key = timelineObject as IKey;
                IMarker marker = timelineObject as IMarker;
                ITrack track = timelineObject as ITrack;
                IGroup group = timelineObject as IGroup;
                ITimelineReference reference = timelineObject as ITimelineReference;

                if (interval != null)
                {
                    ITrack targetTrack = target as ITrack;
                    start = interval.Start + dragOffset.X;
                    length = interval.Length;
                    valid = targetTrack != null;
                    valid &= m_owner.Constraints.IsStartValid(interval, ref start);
                    valid &= m_owner.Constraints.IsLengthValid(interval, ref length);

                    if (valid)
                    {
                        ITrack intervalTrack = interval.Track;
                        if (intervalTrack != null)
                            yOffset = layout[target].Y - layout[interval.Track].Y;
                        else
                            yOffset = layout[target].Y - bounds.Y;

                        TimelinePath testPath = new TimelinePath(targetPath);
                        foreach (IInterval other in targetTrack.Intervals)
                        {
                            // skip selected intervals, since they are moving too
                            testPath.Last = other;
                            if (m_owner.Selection.SelectionContains(testPath))
                                continue;

                            if (!m_owner.Constraints.IsIntervalValid(interval, ref start, ref length, other))
                            {
                                valid = false;
                                break;
                            }
                        }
                    }
                }
                else if (reference != null)
                {
                    // don't allow for vertical repositioning yet
                    start = reference.Start + dragOffset.X;
                    valid = true;
                }
                else if (key != null)
                {
                    start = key.Start + dragOffset.X;
                    ITrack targetTrack = target as ITrack;
                    valid = targetTrack != null;
                    valid &= m_owner.Constraints.IsStartValid(key, ref start);

                    if (valid)
                    {
                        ITrack keyTrack = key.Track;
                        if (keyTrack != null)
                            yOffset = layout[targetTrack].Y - layout[key.Track].Y;
                        else
                            yOffset = layout[targetTrack].Y - bounds.Y;
                    }
                }
                else if (marker != null)
                {
                    start = marker.Start + dragOffset.X;
                    yOffset = 0;
                    valid = m_owner.Constraints.IsStartValid(marker, ref start);
                }
                else if (track != null)
                {
                    xOffset = 0;
                    if (target == null)
                    {
                        target =
                            (DragDelta.Y < 0) ? GetLastTrack() : GetFirstTrack();
                    }
                }
                else if (group != null)
                {
                    xOffset = 0;
                    if (target == null)
                    {
                        IList<IGroup> groups = m_owner.TimelineDocument.Timeline.Groups;
                        target = (DragDelta.Y < 0) ? groups[0] : groups[groups.Count - 1];
                    }
                }

                bounds.Offset(xOffset, yOffset);

                ghosts[i] = new GhostInfo(timelineObject, target, start, length, bounds, valid);
            }
            return ghosts;
        }

        // Gets the bounding box in client window coordinates
        private RectangleF GetDragDropBounds(ITimelineObject dragDrop)
        {
            var bounds = new RectangleF();

            var interval = dragDrop as IInterval;
            if (interval != null)
                bounds = m_owner.Renderer.GetBounds(interval, 0, m_owner.Transform, m_owner.ClientRectangle);

            var key = dragDrop as IKey;
            if (key != null)
                bounds = m_owner.Renderer.GetBounds(key, 0, m_owner.Transform, m_owner.ClientRectangle);

            bounds = GdiUtil.Transform(m_owner.Transform, bounds);

            return bounds;
        }

        private ITrack GetFirstTrack()
        {
            foreach (IGroup group in m_owner.TimelineDocument.Timeline.Groups)
                foreach (ITrack track in group.Tracks)
                    return track;

            return null;
        }

        private ITrack GetLastTrack()
        {
            IList<IGroup> groups = m_owner.TimelineDocument.Timeline.Groups;
            for (int i = groups.Count - 1; i >= 0; --i)
            {
                IGroup group = groups[i];
                IList<ITrack> tracks = group.Tracks;
                for (int j = tracks.Count - 1; j >= 0; ) // loop decrement is unreachable code!
                    return tracks[j];
            }

            return null;
        }

        // get track that contains y value (in client window coordinates, aka, screen space)
        private TimelinePath GetTargetTrack(
            float y,
            TimelineLayout layout,
            IList<ITrack> tracks)
        {
            TimelinePath testPath = new TimelinePath((ITimelineObject)null);
            foreach (ITrack track in tracks)
            {
                testPath.Last = track;
                RectangleF targetBounds = layout[testPath];
                if (targetBounds.Top <= y && targetBounds.Bottom >= y)
                    return testPath;
            }

            return null;
        }

        // gets objects of appropriate type that are underneath the moving selected objects
        private TimelinePath[] GetMoveTargets(TimelineLayout layout)
        {
            // get groups and visible tracks
            List<IGroup> groups = new List<IGroup>();
            List<ITrack> visibleTracks = new List<ITrack>();
            foreach (IGroup group in m_owner.TimelineDocument.Timeline.Groups)
            {
                groups.Add(group);

                IList<ITrack> tracks = group.Tracks;
                bool expanded = group.Expanded;
                bool collapsible = tracks.Count > 1;
                bool collapsed = collapsible && !expanded;
                if (!collapsed)
                    foreach (ITrack track in tracks)
                        visibleTracks.Add(track);
            }

            TimelinePath[] targets = new TimelinePath[m_owner.Selection.SelectionCount];
            RectangleF bounds;
            TimelinePath testPath = new TimelinePath((ITimelineObject)null);

            int i = -1;
            foreach(TimelinePath path in m_owner.Selection.Selection)
            {
                i++;

                IGroup group = path.Last as IGroup;
                if (group != null)
                {
                    foreach (IGroup targetGroup in groups)
                    {
                        Point p = DragPoint;
                        testPath.Last = targetGroup;
                        RectangleF targetBounds = layout[testPath];
                        if (targetBounds.Top <= p.Y && targetBounds.Bottom >= p.Y)
                        {
                            targets[i] = new TimelinePath(testPath);
                            break;
                        }
                    }
                    continue;
                }

                ITrack track = path.Last as ITrack;
                if (track != null)
                {
                    foreach (ITrack targetTrack in visibleTracks)
                    {
                        Point p = m_owner.DragPoint;
                        testPath.Last = targetTrack;
                        RectangleF targetBounds = layout[testPath];
                        if (targetBounds.Top <= p.Y && targetBounds.Bottom >= p.Y)
                        {
                            targets[i] = new TimelinePath(testPath);
                            break;
                        }
                    }
                    if (targets[i] == null)
                    {
                        foreach (IGroup targetGroup in groups)
                        {
                            Point p = DragPoint;
                            testPath.Last = targetGroup;
                            RectangleF targetBounds = layout[testPath];
                            if (targetBounds.Top <= p.Y && targetBounds.Bottom >= p.Y)
                            {
                                targets[i] = new TimelinePath(testPath);
                                break;
                            }
                        }
                    }
                    continue;
                }

                IInterval interval = path.Last as IInterval;
                if (interval != null)
                {
                    track = interval.Track;
                    if (track != null)
                    {
                        testPath.Last = track;
                        bounds = layout[testPath];
                        float y = bounds.Top + bounds.Height * 0.5f + DragDelta.Y;
                        targets[i] = GetTargetTrack(y, layout, visibleTracks);
                        continue;
                    }
                    else
                    {
                        float y = m_owner.RectangleToClient(new Rectangle(Cursor.Position, new Size())).Y;
                        targets[i] = GetTargetTrack(y, layout, visibleTracks);
                    }
                }

                IKey key = path.Last as IKey;
                if (key != null)
                {
                    track = key.Track;
                    if (track != null)
                    {
                        testPath.Last = track;
                        bounds = layout[testPath];
                        float y = bounds.Top + bounds.Height * 0.5f + DragDelta.Y;
                        targets[i] = GetTargetTrack(y, layout, visibleTracks);
                        continue;
                    }
                    else
                    {
                        //float y = m_owner.ClientToCanvas(m_owner.DragPoint).Y;
                        float y = m_owner.RectangleToClient(new Rectangle(Cursor.Position, new Size())).Y;
                        targets[i] = GetTargetTrack(y, layout, visibleTracks);
                    }
                }

                // ignore Markers, as they don't hit targets
            }

            return targets;
        }

        private bool MoveSnapFilter(IEvent testEvent, D2dTimelineControl.SnapOptions options)
        {
            ITimelineReference movingReference = options.FilterContext as ITimelineReference;
            if (movingReference == null)
                return true;

            IHierarchicalTimeline movingTimeline = movingReference.Target;
            if (movingTimeline == null)
                return true;

            ITimeline owningTimeline = null;
            if (testEvent is ITimelineReference)
                owningTimeline = ((ITimelineReference)testEvent).Parent;
            else if (testEvent is IInterval)
                owningTimeline = ((IInterval)testEvent).Track.Group.Timeline;
            else if (testEvent is IKey)
                owningTimeline = ((IKey)testEvent).Track.Group.Timeline;
            else if (testEvent is IMarker)
                owningTimeline = ((IMarker)testEvent).Timeline;

            // Is the reference being compared to an object that it owns? Never snap!
            if (owningTimeline == movingTimeline)
                return false;

            // Is the reference being compared against a sibling object? Snap away.
            if (owningTimeline == movingReference.Parent)
                return true;

            // to-do: support a true hierarchy. We can't support directed acyclic graphs because
            //  the Layout implementation uses a Dictionary of ITimelineObjects and the same object
            //  can't have multiple layout rectangles. We could support a tree hierarchy, though.
            //// The test object may be a grandchild of the moving reference. Look for a parent.
            //owningTimeline = owningTimeline.Parent;

            return true;
        }

        private static readonly D2dTimelineControl.SnapOptions s_snapOptions = new D2dTimelineControl.SnapOptions();

        private readonly D2dTimelineControl m_owner;
        private GhostInfo[] m_ghosts;
        private HitRecord m_mouseMoveHitRecord;
        private Point m_firstPoint;
        private Point m_currentPoint;
        private int m_dragThreshold = 3;
        private bool m_dragOverThreshold;
        private bool m_isDragging;
        private bool m_isDragDropping;
    }
}


text:
MStatus initializePlugin(MObject obj) {
    MFnPlugin plugin(obj, "August Ek & Ramin Assadi", "1.0", "Any");

    MStatus status = plugin.registerCommand("extract", ExtractFaceCommand::creator);
    CHECK_MSTATUS_AND_RETURN_IT(status);

    status = plugin.registerCommand("mesh2particle", GenerateParticleCommand::creator);
    CHECK_MSTATUS_AND_RETURN_IT(status);
    return status;
}

MStatus uninitializePlugin(MObject obj) {
    MFnPlugin plugin(obj);

    MStatus status = plugin.deregisterCommand("extract");
    CHECK_MSTATUS_AND_RETURN_IT(status);

    status = plugin.deregisterCommand("mesh2particle");
    CHECK_MSTATUS_AND_RETURN_IT(status);
    return status;
}

int main(int argc, char** argv) {

    if (argc != 2) return 0;
    return 0;
}


text:
<workflow-app xmlns="uri:oozie:workflow:0.2" name="job-wf">
    <start to="job-node"/>
    <action name="job-node">
    </action>
    <kill name="fail">
        <message>Workflow failed, error message[${wf:errorMessage(wf:lastErrorNode())}]</message>
    </kill>
    <end name="end"/>
</workflow-app>


text:
var Router = Ember.Router.extend({
  location: ENV.locationType
});

Router.map(function() {
	this.resource('lists', { path: '/'} );
});

export default Router;


text:
.. _`Tutorial`:

Tutorial
========

This section contains a few short tutorials about using pywbem. It is intended
to be enough to get people up and going who already know a bit about WBEM and
CIM.

The tutorials in this section are
`Jupyter Notebooks <http://jupyter-notebook-beginner-guide.readthedocs.io/>`_,
and are shown using the online
`Jupyter Notebook Viewer <http://nbviewer.jupyter.org/>`_.
This allows viewing the tutorials without having Jupyter Notebook installed
locally.

In order to view a tutorial, just click on a link in this table:

===================================  ==========================================
Tutorial                             Short description
===================================  ==========================================
None developed to date
===================================  ==========================================

For the following topics, tutorials are not yet available:

* TODO

Executing code in the tutorials
-------------------------------

You cannot directly modify or execute the code in the tutorials using the
Jupyter Notebook Viewer, though. In order to do that, the Jupyter Notebook
Viewer provides a download button at the top right corner of the page.

You must have Jupyter Notebook
`installed <https://jupyter.readthedocs.io/en/latest/install.html>`_,
preferrably in a
`virtual Python environment <http://docs.python-guide.org/en/latest/dev/virtualenvs/>`_,
and you must have pywbem installed.

To see a list of your downloaded notebook files, start Jupyter Notebook as
follows::

    jupyter notebook --notebook-dir={your-notebook-dir}


text:
package es.predictia.util.date;

import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

public class ReducedPrecisionDateTime implements DateProvider, Comparable<ReducedPrecisionDateTime>{

	private final DateTimeFormatter fmt;
	private final DateTime dt;

	public ReducedPrecisionDateTime(DateTimeFormatter fmt, DateTime dt) {
		this.fmt = fmt;
		this.dt = this.fmt.parseDateTime(this.fmt.print(dt));
	}

	public ReducedPrecisionDateTime(Pattern pattern, DateTime dt) {
		this.fmt = pattern.getDateTimeFormatter();
		this.dt = this.fmt.parseDateTime(this.fmt.print(dt));
	}

	public ReducedPrecisionDateTime(String pattern, DateTime dt){
		this.fmt = DateTimeFormat.forPattern(pattern).withZone(DateTimeZone.UTC);
		this.dt = this.fmt.parseDateTime(this.fmt.print(dt));
	}

	public DateTime getDate() {
		return dt;
	}

	public String toString(){
		return fmt.print(dt);
	}

	public int hashCode(){
		return toString().hashCode();
	}

	public boolean equals(Object o){
		if(o instanceof ReducedPrecisionDateTime){
			return ((ReducedPrecisionDateTime) o).toString().equals(this.toString());
		}
		return false;
	}

	public int compareTo(ReducedPrecisionDateTime o) {
		return getDate().compareTo(o.getDate());
	}

}


text:
LR Search
========
[![Build Status](https://travis-ci.org/adlnet/LR-Search.png?branch=master)](https://travis-ci.org/adlnet/LR-Search)

This project is a companion to [LR-Data](https://github.com/adlnet/LR-Data) and acts as a set of search and data services for the ElasticSearch built by LR-Data.

# Search API

This is the primary API endpoint for searching the Learning Registry

It is accessible at ```/search```

It supports a number of query string params

| Param | Description                   | Required |
|:------|:-----------------------------|:---------:|
|terms  |phrase to search for, or a Common Core standards ID           |true|
|filter |generic filter for results     |false|
|page   |0 based index for paged results|false|
|contentType|filter specifically for content type|false|
|accessibility|filter for accessibility metadata as defined in LRMI|false|

The response format for the search results is as follows

```json
{
    "count": 1,
    "data": [
        {
            "hasScreenshot": true,
            "url": "http://www.example.com",
            "accessibilityFeature": [ ],
            "description": "Sampel Description for content",
            "_id": "1e4b2d8ec9849beffedef9ddc392f2b1",
            "publisher": "Sample Publisher",
            "title": "Sample Title"
        }
    ]
}
```

# Screenshot API

The ```/screenshot/{id}``` endpoint returns a screenshot of resource linked to the ID parameter

|Status|cause|
|:----:|:---:|
|200|normal|
|404|screenshot not available|

404 errors can occur for a number of reason, the most common being that the image is not cached, and creating the screenshot times out while accessing the remote site

# Standards API

The standards API exposes date concerning Common Core standards

The ```/new/standards``` endpoint returns a list of all the Common Core standards the system knows about

```json
[
    "standard"
]
```

The ```/new/standards/{id}``` endpoint returns all the Common Core standards for the supplied ID

```json
{
    "title": "title",
    "description": "description",
    "id": "id",
    "children": [...]
}
```

Where the contents of ```children``` have the same structure as the parent node

# Data API

If you have the ID for a document in the system you can access it's metadata via the ```/data``` endpoint

You can either supply the ID as ```/data/{id}``` or you can get multiple documents via ```/data?keys={ids}``` where ids is a json encoded
list of IDs

If you request multiple documents the response will be formated as

```json
{
    "count": 1,
    "data": [
        {
            "hasScreenshot": true,
            "url": "http://www.example.com",
            "accessibilityFeature": [ ],
            "description": "Sampel Description for content",
            "_id": "1e4b2d8ec9849beffedef9ddc392f2b1",
            "publisher": "Sample Publisher",
            "title": "Sample Title"
        }
    ]
}
```

If you requests a single ID the response will be formated as

```json
{
    "hasScreenshot": true,
    "url": "http://www.example.com",
    "accessibilityFeature": [ ],
    "description": "Sampel Description for content",
    "_id": "1e4b2d8ec9849beffedef9ddc392f2b1",
    "publisher": "Sample Publisher",
    "title": "Sample Title"
}
```


text:
.. _api-depracated:

Deprecated API Documentation
============================

User Management
---------------

[POST] /users
*************

**Deprecated Fields**
These fields are currently deprecated and support for them will be removed soon.

============================== ==================================================================
education_level_name           (String) Undergraduate, Graduate, Postgraduate. This shows up on their main education on their profile
cumulative_gpa                 (Decimal) The student's cumulative GPA
department_gpa                 (Decimal) Decimal of student's departmental GPA
major_names                    (String Array) An array of major names for this student. These must be majors configured in the school's majors list.
minor_names                    (String Array) An array of minor names for this student. These must be minors configured in the school's minors list.
primary_college_name           (String) The college the student belongs to. Must be one of the colleges configured in the school's college list.
education_start_date           (Date) The date the student started at the school in any standard date format. See references for date formats.
education_end_date             (Date) The date the student graduated or plans to graduate school (can be blank if currently_attending is set). See references for date formats.
education_currently_attending  (Boolean) Should be set to true if education_end_date is blank. This signifies they are currently attending this school.
============================== ==================================================================

Reports
---------

[GET] /report/{id}
******************
Allows administrators to output customized data feeds. Because of the highly customizable nature of these reports, the responses are not guaranteed to be performant and are rate limited.

**Params**
None

**Sample Response**
::

    {
      success: true,
      report: [
        {
          id
          name
          locked
          username: "sgringwe",
          first_name: "Scott",
          …
        },
        {...}, {...}
      ]
      data: [
        [column1, column2, column3], #column list
        [
          {column1: value, column2: value}, #row 1
          {column1: value, column2: value}, #row 2
        ]
      ]
    }


text:
package com.smart.cloud.fire.activity.WebServer;

import android.app.Activity;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;

import fire.cloud.smart.com.smartcloudfire.R;

public class WebServerActivity extends Activity {

    private WebView webView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web_server);

        webView = (WebView) findViewById(R.id.webView);
        //支持javascript
        webView.getSettings().setJavaScriptEnabled(true);
        // 设置可以支持缩放
        webView.getSettings().setSupportZoom(true);
        // 设置出现缩放工具
        webView.getSettings().setBuiltInZoomControls(true);
        //扩大比例的缩放
        webView.getSettings().setUseWideViewPort(true);
        //自适应屏幕
//        webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webView.getSettings().setLoadWithOverviewMode(true);
        webView.setWebViewClient(new WebViewClient()
        {
            //覆盖shouldOverrideUrlLoading 方法
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url)
            {
                view.loadUrl(url);
                return true;
            }
        });
        webView.loadUrl("http://119.29.155.148:51091/fireSystem/welcome.jsp");
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Serilog;
using SQLite;

namespace Cascade {
	public class SqliteDatabase {

		// use withConnection instead of this
		// if you use this directly then locking is your responsibility
		public SQLiteAsyncConnection Connection { get; }

		private readonly bool _debug;

		public SqliteDatabase(
			SQLite.SQLiteAsyncConnection connection,
			bool debug = false
		) {
			Log.Debug("Setup HistoryDatabase with file " + connection.DatabasePath);
			Connection = connection;
			_debug = debug;

			if (_debug) {
				Connection.Tracer = (s) => Log.Debug(s);
				Connection.Trace = true;
				Connection.TimeExecution = true;
			}
		}

		public async Task<T> Create<T>(T model) {
			await Connection.InsertAsync(model);
			return model;
		}

		public async Task<T?> Get<T>(object id) where T : new() {
			return await Connection.FindAsync<T>(id);
		}
		// public async Task<T?> Get<T>(int id) where T : new() {
		// 	return await Connection.FindAsync<T>(id);
		// }
		// public async Task<T?> Get<T>(String id) where T : new() {
		// 	return await Connection.FindAsync<T>(id);
		// }

		public async Task<bool> Update(object obj, bool aEnsure = true) {
			if (obj==null)
				throw new ArgumentNullException();
			//lock (_connection) {
			int rowsAffected = 0;
			try
			{
				rowsAffected = await Connection.UpdateAsync(obj);
				Log.Debug($"HistoryDatabase: Updated {rowsAffected} rows");
			} catch(Exception e) {
				Log.Debug(e.Message);
				throw e;
			}
			var success = rowsAffected > 0;
			if (!success && aEnsure)
				throw new Exception("Record not found to update " + obj.GetType().Name); //+ " " + GetPrimaryKey(obj).ToString());
			return success;
			//}
		}

		public async Task Upsert(object obj) {
			var success = await Update(obj, false);
			if (!success)
				await Connection.InsertAsync(obj);
		}

		// public async Task<T> Update<T>(object id, Dictionary<String, object> changes) {
		//
		//
		//
		// 	//var results = Connection.UpdateAsync(changes);
		// 	var results = Connection.ExecuteAsync("UPDATE ? SET Price = ? Where Id = ?", 1000000, 2);
		//
		//
		// }

		public async Task Delete<Model>(object id) {
			await Connection.DeleteAsync<Model>(id);
		}

		public async Task Delete(object model) {
			await Connection.DeleteAsync(model);
		}

		public async Task<bool> Exists<Model>(object id) {
			bool exists = false;
			try
			{
				exists = await Connection.ExecuteScalarAsync<bool>("SELECT EXISTS(SELECT 1 FROM " + TableName<Model>() + " WHERE ID=?)", id);
			}
			catch (Exception ex)
			{
				exists = false;
			}
			return exists;
		}

		public string TableName<Model>() {
			return Connection.TableMappings.First(m => m.MappedType == typeof(Model)).TableName;
		}

		//public Query<T>("select * from packets where kin=0 and journey_id=? order by timems", aJourney.id);

		// public Task<List<T>> Query<T>(string query, params object[] args) where T : class, new()
		// {
		// 	lock (_connection) {
		// 		return _connection.QueryAsync<T>(query, args);
		// 	}
		// }
		//
		// public Task<int> Execute(string query, params object[] args)
		// {
		// 	lock (_connection) {
		// 		return _connection.ExecuteAsync(query, args);
		// 	}
		// }
		//
		// // public long GetPrimaryKey(object aModel) {
		// // 	var propertyInfo = aModel.GetType().GetPrimaryKey();
		// // 	if (propertyInfo == null)
		// // 		throw new Exception("This model doesn't have a [PrimaryKey] attribute");
		// // 	return Convert.ToInt64(propertyInfo.GetValue(aModel));
		// // }
		//
		// public async Task<bool> Update(object obj, bool aEnsure = true) {
		// 	if (obj==null)
		// 		throw new ArgumentNullException();
		// 	lock (_connection) {
		// 		int rowsAffected = 0;
		// 		try
		// 		{
		// 			rowsAffected = await _connection.UpdateAsync(obj);
		// 			Log.Debug($"HistoryDatabase: Updated {rowsAffected} rows");
		// 		} catch(Exception e) {
		// 			Log.Debug(e.Message);
		// 			throw e;
		// 		}
		// 		var success = rowsAffected > 0;
		// 		if (!success && aEnsure)
		// 			throw new Exception("Record not found to update " + obj.GetType().Name); //+ " " + GetPrimaryKey(obj).ToString());
		// 		return success;
		// 	}
		// }
		//
		// public void Insert(object obj) {
		// 	if (obj==null)
		// 		throw new ArgumentNullException();
		// 	lock (_connection) {
		// 		int rowsAffected = 0;
		// 		// try
		// 		// {
		// 			rowsAffected = _connection.Insert(obj);
		// 			Log.Debug($"HistoryDatabase: Inserted {rowsAffected} rows");
		// 		// }
		// 		// catch (SQLite.SQLiteException e)
		// 		// {
		// 		// 	FreeCommon.reportException(e,new Dictionary<string,string>() {
		// 		// 		{ "model", FreeCommon.Json.Serialize(obj as ModelBase) },
		// 		// 		{ "InnerException", e.InnerException?.ToString()},
		// 		// 		{ "Source", e.Source },
		// 		// 		{	"HelpLink",e.HelpLink }
		// 		// 	});
		// 		// }
		//
		// 		if (rowsAffected == 0)
		// 			throw new Exception("Record failed to insert " + obj.GetType().Name); //+ " " + GetPrimaryKey(obj).ToString());
		// 	}
		// }
		//
		// public void Upsert(object obj)
		// {
		// 	lock (_connection) {
		// 		var success = Update(obj, false);
		// 		if (!success)
		// 			Insert(obj);
		// 	}
		// }
		//
		// // public string tableName<T>()
		// // {
		// // 	var n = typeof(T).Name;
		// // 	switch (n) {
		// // 		case "JourneyLeg":
		// // 			return "journey_legs";
		// // 	}
		// // 	return n.ToLower() + "s";
		// // }

		// public T WithConnection<T>(Func<SQLiteConnection,T> func) {
		// 	lock (Connection) {
		// 		return func(Connection);
		// 	}
		// }
		//
		// public void WithConnection(Action<SQLiteConnection> func) {
		// 	lock (Connection) {
		// 		func(Connection);
		// 	}
		// }

		public Task Close() {
			// if (Connection == null)
			// 	return;
			// lock (Connection) {
				return Connection.CloseAsync();
			// }
		}

		public async Task DropAllTables() {
			foreach (var tm in Connection.TableMappings) {
				await Connection.DropTableAsync(tm);
			}
		}
	}
}