text:
import os.path
from functools import lru_cache
from typing import List, Tuple

import requests

from django.core.management.base import BaseCommand
from obj_update import obj_update_or_create
from tqdm import tqdm

from ...models import Location, Receipt

@lru_cache(maxsize=512)
def Location_get(street_address, city, state, zip, name) -> Tuple[Location, bool]:
    """
    Wrapper around Location.objects.get_or_create just to use lru_cache
    """
    return Location.objects.get_or_create(
        street_address=street_address,
        city=city,
        state=state,
        zip=zip,
        defaults=dict(name=name),
    )

def import_data_from_api(data: List[dict]) -> int:
    created_count = 0
    for row in data:
        location, location_created = Location_get(
            street_address=row["taxpayer_address"],
            city=row["location_city"],
            state=row["location_state"],
            zip=row["location_zip"],
            name=row["location_name"],
        )
        if location_created:
            print(f"Created Location: {location.pk} - {location}")
        receipt, created = obj_update_or_create(
            Receipt,
            tabc_permit=row["tabc_permit_number"],
            date=row["obligation_end_date_yyyymmdd"].split("T")[0],
            defaults=dict(
                taxpayer_name=row["taxpayer_name"],
                tax_number=row["taxpayer_number"],
                liquor=row["liquor_receipts"],
                wine=row["wine_receipts"],
                beer=row["beer_receipts"],
                cover=row["cover_charge_receipts"],
                total=row["total_receipts"],
                location_name=row["location_name"],
                location_number=row["location_number"],
                county_code=row["location_county"],
                location=location,
            ),
        )
        if created:
            created_count += 1
    return created_count

class Command(BaseCommand):
    help = "Import from Socrata API"

    def handle(self, *args, **options):
        offset = 0
        while True:
            res = requests.get(
                "https://data.texas.gov/resource/naix-2893.json",
                # What the params do:
                # https://dev.socrata.com/docs/queries/
                params={
                    "$order": "obligation_end_date_yyyymmdd desc",
                    "$offset": offset,
                    "$limit": 2000,  # Default: 1000
                },
            )
            data = res.json()
            print(f"Total rows: {len(data)}")
            print(
                f'Date range: {data[0]["obligation_end_date_yyyymmdd"]} - {data[-1]["obligation_end_date_yyyymmdd"]}'
            )
            created_count = import_data_from_api(data)
            print(f"Created   : {created_count}")
            if created_count:
                offset += len(data)
            else:
                break


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://camel.apache.org/schema/spring
       http://camel.apache.org/schema/spring/camel-spring.xsd">

    <!-- this is an included XML file where we only define the the routeContext -->
    <routeContext id="routes" xmlns="http://camel.apache.org/schema/spring">
        <route>
            <!-- Example for Choice -->
            <from uri="jetty:http://0.0.0.0:8080/?matchOnUriPrefix=true"/>
            <bean ref="loggingThrottleProcessor"/>
            <choice>
                <when>
                    <simple>${in.header.REQ_TYPE} regex '(.*)something(.*)'</simple>
                    <to uri="direct:throttle1"/>
                </when>
                <when>
                    <simple>${in.header.REQ_TYPE} == 'something_else'</simple>
                    <to uri="direct:throttle2"/>
                </when>
                <otherwise>
                    <to uri="direct:throttle1"/>
                </otherwise>

            </choice>

        </route>
        <route id="throttle1">
            <!-- Throttle Example waiting for execution -->
            <from uri="direct:throttle1"/>
            <throttle rejectExecution="false" timePeriodMillis="10000">
                <constant>10</constant>
                <to uri="direct:production"/>
            </throttle>
        </route>
        <route id="throttle2">
            <!-- Throttle Example with rejecting execution of requests -->
            <from uri="direct:throttle2"/>
            <throttle rejectExecution="true" timePeriodMillis="10000" asyncDelayed="true">
                <constant>1</constant>
                <to uri="direct:production"/>
            </throttle>
            <onException>
                <exception>java.lang.Exception</exception>
                <handled>
                    <constant>true</constant>
                </handled>
                <process ref="http503ErrorProcessor"/>
            </onException>
        </route>
        <route>
            <!-- another throttle example with waiting requests -->
            <from uri="direct:throttle3"/>
            <throttle timePeriodMillis="1000">
                <constant>1</constant>
                <to uri="direct:production"/>
            </throttle>
        </route>
        <route>
            <from uri="direct:production"/>
            <to uri="http://localhost:80/?bridgeEndpoint=true&throwExceptionOnFailure=false"/>
        </route>
    </routeContext>
    <bean id="loggingProcessor" class="de.isys.software.camel.processor.LoggingProcessor"/>
    <bean id="loggingThrottleProcessor" class="de.isys.software.camel.processor.LoggingProcessor">
        <property name="logMessage" value="THROTTLING REQUEST ..."/>
        <property name="logHeader" value="TYP"/>
    </bean>
    <bean id="http503ErrorProcessor" class="de.isys.software.camel.processor.HttpStatusCodeProcessor">
        <property name="httpStatusCode" value="503"/>
    </bean>

    <bean id="http200ErrorProcessor" class="de.isys.software.camel.processor.HttpStatusCodeProcessor">
        <property name="httpStatusCode" value="200"/>
    </bean>

</beans>

redpajama_set_name: RedPajamaGithub


text:
<?php
/**
 * ©[2017] SugarCRM Inc.  Licensed by SugarCRM under the Apache 2.0 license.
 */

namespace Sugarcrm\REST\Endpoint\Data\Filters\Expression;

use Sugarcrm\REST\Endpoint\Data\Filters\FilterInterface;
use Sugarcrm\REST\Exception\Filter\UnknownFilterOperator;

/**
 * Class AbstractExpression
 * @package Sugarcrm\REST\Endpoint\Data\Filters\Expression
 * @method AndExpression        and()
 * @method OrExpression         or()
 * @method $this                equals($field,$value)
 * @method $this                notEquals($field,$value)
 * @method $this                starts($field,$value)
 * @method $this                ends($field,$value)
 * @method $this                contains($field,$value)
 * @method $this                in($field,array $value)
 * @method $this                notIn($field,array $value)
 * @method $this                isNull($field)
 * @method $this                notNull($field)
 * @method $this                lt($field,$value)
 * @method $this                lessThan($field,$value)
 * @method $this                lte($field,$value)
 * @method $this                lessThanOrEqualTo($field,$value)
 * @method $this                lessThanOrEquals($field,$value)
 * @method $this                greaterThan($field,$value)
 * @method $this                gte($field,$value)
 * @method $this                greaterThanOrEqualTo($field,$value)
 * @method $this                greaterThanOrEquals($field,$value)
 */
abstract class AbstractExpression implements FilterInterface, ExpressionInterface
{
    /**
     * @var array
     */
    private $filters = array();

    /**
     * @var AbstractExpression
     */
    private $parentExpression;

    /**
     * @var array
     */
    protected $operators = array(
        'equals' => 'Sugarcrm\REST\Endpoint\Data\Filters\Operator\Equals',
        'notEquals' => 'Sugarcrm\REST\Endpoint\Data\Filters\Operator\NotEquals',
        'starts' => 'Sugarcrm\REST\Endpoint\Data\Filters\Operator\Starts',
        'ends' => 'Sugarcrm\REST\Endpoint\Data\Filters\Operator\Ends',
        'contains' => 'Sugarcrm\REST\Endpoint\Data\Filters\Operator\Contains',
        'in' => 'Sugarcrm\REST\Endpoint\Data\Filters\Operator\In',
        'notIn' => 'Sugarcrm\REST\Endpoint\Data\Filters\Operator\NotIn',
        'isNull' => 'Sugarcrm\REST\Endpoint\Data\Filters\Operator\IsNull',
        'notNull' => 'Sugarcrm\REST\Endpoint\Data\Filters\Operator\NotNull',
        'lt' => 'Sugarcrm\REST\Endpoint\Data\Filters\Operator\LessThan',
        'lessThan' => 'Sugarcrm\REST\Endpoint\Data\Filters\Operator\LessThan',
        'lte' => 'Sugarcrm\REST\Endpoint\Data\Filters\Operator\LessThanOrEqual',
        'lessThanOrEqualTo' => 'Sugarcrm\REST\Endpoint\Data\Filters\Operator\LessThanOrEqual',
        'lessThanOrEquals' => 'Sugarcrm\REST\Endpoint\Data\Filters\Operator\LessThanOrEqual',
        'gt' => 'Sugarcrm\REST\Endpoint\Data\Filters\Operator\GreaterThan',
        'greaterThan' => 'Sugarcrm\REST\Endpoint\Data\Filters\Operator\GreaterThan',
        'gte' => 'Sugarcrm\REST\Endpoint\Data\Filters\Operator\GreaterThanOrEqual',
        'greaterThanOrEqualTo' => 'Sugarcrm\REST\Endpoint\Data\Filters\Operator\GreaterThanOrEqual',
        'greaterThanOrEquals' => 'Sugarcrm\REST\Endpoint\Data\Filters\Operator\GreaterThanOrEqual',
    );

    /**
     * @var array
     */
    protected $expressions = array(
        'and' => 'Sugarcrm\REST\Endpoint\Data\Filters\Expression\AndExpression',
        'or' => 'Sugarcrm\REST\Endpoint\Data\Filters\Expression\OrExpression',
    );

    /**
     * @param $name
     * @param $arguments
     * @return AbstractExpression
     * @throws UnknownFilterOperator
     */
    public function __call($name, $arguments)
    {
        if (array_key_exists($name,$this->operators)){
            $Operator = $this->operators[$name];
            $Op = new $Operator($arguments);
            $this->filters[] = $Op;
            return $this;
        }
        if (array_key_exists($name,$this->expressions)){
            $Expression =  $this->expressions[$name];
            $Exp = new $Expression();
            $Exp->setParentExpression($this);
            $this->filters[] = $Exp;
            return $Exp;
        }
        throw new UnknownFilterOperator(array($name));
    }

    /**
     * Sets Parent Expression to allow for nested tree structure
     * @param AbstractExpression $Expression
     * @return $this
     */
    public function setParentExpression(AbstractExpression $Expression){
        $this->parentExpression = $Expression;
        return $this;
    }

    /**
     * Gets the Parent Expression of current Expression
     * @return AbstractExpression
     */
    public function getParentExpression(){
        return $this->parentExpression;
    }

    /**
     * Compiles the Expression based on the stored Filters array
     * @return array
     */
    public function compile()
    {
        $data = array();
        foreach($this->filters as $filter){
            $data[] = $filter->compile();
        }
        return $data;
    }

    public function clear()
    {
        $this->filters = array();
        return $this;
    }

}


text:
- `Mol` data can be now transferred to/from the database as either binary or text, depending on the
  value assigned to the `DJANGO_RDKIT_MOL_SERIALIZATION` settings attribute (allowed values are
  `BINARY` and `TEXT`, defaults to `BINARY`)

## [0.3.2]

### Fixed
- The `MolField` and related lookup expressions were refactored to support
  bulk update operations

## [0.3.1]

### Fixed
- Replaced the deprecated/unsupported `ugettext_lazy` with `gettext_lazy`

## [0.3.0]

### Added
- `mol_to_svg` support

### Removed
- The gist index migration operation was removed (GiST support is available in django)

## [0.2.0]

### Changed
- Updated for Django 3.0
- Support for Python2 was removed

## [Unreleased]

### Added
- README and CHANGELOG files

### Changed
- MolField values are always passed to the database as pickled Mol instances
- MolField supports parsing mol blocks and InChI input in addition to SMILES
- MolField specifies an appropriate default form field input

## [0.1.0] - 2018-08-16


text:
package http

import (
	"encoding/json"
	"github.com/wcong/ants-go/ants/action"
	Http "github.com/wcong/ants-go/ants/http"
	Node "github.com/wcong/ants-go/ants/node"
	"log"
	"net/http"
	"time"
)

type Router struct {
	node        *Node.Node
	mux         map[string]func(http.ResponseWriter, *http.Request)
	reporter    action.Watcher
	distributer action.Watcher
	rpcClient   action.RpcClientAnts
}

func NewRouter(node *Node.Node, reporter, distributer action.Watcher, rpcClient action.RpcClientAnts) *Router {
	mux := make(map[string]func(http.ResponseWriter, *http.Request))
	router := &Router{
		node:        node,
		mux:         mux,
		reporter:    reporter,
		distributer: distributer,
		rpcClient:   rpcClient,
	}
	mux["/"] = router.Welcome
	mux["/cluster"] = router.Cluster
	mux["/spiders"] = router.Spiders
	mux["/crawl"] = router.Crawl
	mux["/crawl/cluster"] = router.CrawlCluster
	mux["/crawl/node"] = router.CrawlNode
	return router
}

func (this *Router) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	url := r.URL.String()
	log.Println("get request:" + url)
	if !this.node.Cluster.IsReady() {
		w.Write([]byte("sorry,cluster not ready,please wait"))
		return
	}
	path := r.URL.Path
	if h, ok := this.mux[path]; ok {
		w.Header().Set(Http.CONTENT_TYPE, Http.JSON_CONTENT_TYPE)
		h(w, r)
		return
	}
	this.Welcome(w, r)
}

func (this *Router) Welcome(w http.ResponseWriter, r *http.Request) {
	now := time.Now().Format("2006-01-02 15:04:05")
	welcome := WelcomeInfo{
		"for crawl",
		"do not panic",
		now,
	}
	encoder, err := json.Marshal(welcome)
	if err != nil {
		log.Println(err)
	}
	w.Write(encoder)
}
func (this *Router) Spiders(w http.ResponseWriter, r *http.Request) {
	spiderList := make([]string, 0, len(this.node.Crawler.SpiderMap))
	for spider := range this.node.Crawler.SpiderMap {
		spiderList = append(spiderList, spider)
	}
	encoder, err := json.Marshal(spiderList)
	if err != nil {
		log.Println(err)
	}
	w.Write(encoder)
}

// try to start spider
// if ok
// *		tell other node start spider
// *		start reporter and distribute in this node
func (this *Router) Crawl(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	spiderName := r.Form["spider"][0]
	now := time.Now().Format("2006-01-02 15:04:05")
	startResult := &StartSpiderResult{}
	result, message := this.node.StartSpider(spiderName)
	if result {
		log.Println("start spider:", spiderName)
		for _, nodeInfo := range this.node.GetAllNode() {
			if !this.node.IsMe(nodeInfo.Name) {
				this.rpcClient.StartSpider(nodeInfo.Name, spiderName)
			}
		}
		go this.reporter.Start()
		go this.distributer.Start()
	}
	startResult.Time = now
	startResult.Success = result
	startResult.Spider = spiderName
	startResult.Message = message
	encoder, err := json.Marshal(startResult)
	if err != nil {
		log.Println(err)
	}
	w.Write(encoder)
}

func (this *Router) Cluster(w http.ResponseWriter, r *http.Request) {
	encoder, err := json.Marshal(this.node.Cluster)
	if err != nil {
		log.Println(err)
	}
	w.Write(encoder)
}

func (this *Router) CrawlCluster(w http.ResponseWriter, r *http.Request) {
	encoder, err := json.Marshal(this.node.Cluster.RequestStatus)
	if err != nil {
		log.Println(err)
	}
	w.Write(encoder)
}

func (this *Router) CrawlNode(w http.ResponseWriter, r *http.Request) {
	encoder, err := json.Marshal(this.node.Cluster.CrawlStatus())
	if err != nil {
		log.Println(err)
	}
	w.Write(encoder)
}


text:
import { APIRequestContext } from "@playwright/test";
import { Report } from "@stryker-mutator/dashboard-common";
import {
  EnableRepositoryResponse,
  PutReportResponse,
  Repository,
} from "@stryker-mutator/dashboard-contract";
import { generateAuthToken } from "../../actions/auth.action";

export class ReportClient {
  private projectApiKeys = new Map<string, Promise<string>>();

  constructor(private request: APIRequestContext) {}

  async enableRepository(slug: string): Promise<string> {
    if (this.projectApiKeys.has(slug)) {
      return this.projectApiKeys.get(slug)!;
    } else {
      this.projectApiKeys.set(
        slug,
        Promise.resolve().then(async () => {
          const patchBody: Partial<Repository> = { enabled: true };
          const authToken = generateAuthToken();
          const response = await this.request.patch(
            `/api/repositories/${slug}`,
            {
              data: patchBody,
              headers: {
                Authorization: `Bearer ${authToken}`,
              },
            }
          );
          const body: EnableRepositoryResponse = await response.json();
          return body.apiKey;
        })
      );
      return this.projectApiKeys.get(slug)!;
    }
  }

  async getUserRepositories(): Promise<Repository[]> {
    const auth = generateAuthToken();
    const response = await this.request.get("api/user/repositories", {
      headers: { Authorization: `Bearer ${auth}` },
    });
    const body = await response.json();
    return body;
  }

  async uploadReport(result: Report): Promise<PutReportResponse> {
    const apiKey = await this.enableRepository(result.projectName);
    const response = await this.request.put(
      `/api/reports/${result.projectName}/${result.version}${
        result.moduleName ? `?module=${result.moduleName}` : ""
      }`,
      {
        data: result,
        headers: {
          ["X-Api-Key"]: apiKey,
        },
      }
    );
    const body = await response.json();
    return body;
  }
}


text:
'use strict';

var request = require('supertest')
	, should = require('should')
	, mongojs = require('mongojs')
	, db = require('../../lib/db')
	, redisService = require('../../lib/redis')
	, app = require('../../spa.acl.server.5002').app;

var url = 'http://localhost:5002'

describe('Test users api\n', function() {

	var url_user_api = '/api/users';
	var url_login = '/public/login';

	describe('Test query users without token: GET->' + url_user_api, function() {
		it('should return 401 without token ', function(done) {
			request(app)
			.get(url_user_api)
			.expect('Content-Type', /json/)
			.expect('Access-Control-Allow-Headers', 'Content-Type, X-Requested-With')
			.expect(401)
			.end(function(err,res){
				should.not.exist(err);
				res.body.should.have.property('message', 'please login');

				if (err) return done(err);
				done();
			});
		});
	});

	describe('Test query users with fake token: GET->' + url_user_api, function() {
		it('should return 401 with fake token ', function(done) {
			request(app)
			.get(url_user_api + '?tid=invalidid')
			.set('SessionToken', 'aabbcc')
			.expect('Content-Type', /json/)
			.expect('Access-Control-Allow-Headers', 'Content-Type, X-Requested-With')
			.expect(401)
			.end(function(err,res){
				should.not.exist(err);
				res.body.should.have.property('message', 'invalid tokenid');
				if (err) return done(err);
				done();
			});
		});
	});

	describe('Test get a list of users: GET->' + url_user_api, function() {
		var token_id;
		it('should return HTTP 200 if authentication success', function(done) {

			var credentials = {
				username: 'mary@demo.org',
				password: 'passwd'
			}
			request(app)
			.post(url_login)
			.send(credentials)
			.expect('Content-Type', /json/)
			.expect('Access-Control-Allow-Headers', 'Content-Type, X-Requested-With')
			.expect(200)
			.end(function(err,res){
				should.not.exist(err);
				//console.log('return from login ' + res.body);
				token_id = res.body['tokenid'];
				token_id.length.should.equal(40);
				done();
			});
		});

		console.log('in client tokenid=' + token_id);
		it('should return 4 users for url ', function(done) {
			request(app)
			.get(url_user_api + '?tid=' + token_id)
			.expect('Content-Type', /json/)
			.expect('Access-Control-Allow-Headers', 'Content-Type, X-Requested-With')
			.expect(200)
			.end(function(err,res){
				should.not.exist(err);
				res.body.should.have.lengthOf(4);
				res.body[0].should.have.property('firstname', 'Dustin');
				if (err) return done(err);

				redisService.remove(token_id, function(err, reply){
					//console.log(reply.toString());
					done();
				});
			});
		});
	});

	describe('Test get user by id: GET-> /api/users/52e9ce56977f8a8b113a09f9', function() {
		var token_id = 'f2cb3e8d653f46008272113c6c72422843901ef3';
		var email = 'mary@demo.org';

		beforeEach(function(done) {
			var record = [token_id, 'uid', '52e9ce56977f8a8b113a09f9', 'email', email];
			redisService.save(token_id, record, function(err, reply){
				//console.log(reply.toString());
				done();
			});
		});

		afterEach(function(done){
			redisService.remove(token_id, function(err, reply){
				//console.log(reply.toString());
				done();
			});
		});

		/**
		 * User should only be able to query it self
		 */
		it('should be able to query user by id ', function(done) {
			request(app)
			.get(url_user_api + '/52e9ce56977f8a8b113a09f9?tid=' + token_id)
			.expect('Content-Type', /json/)
			.expect('Access-Control-Allow-Headers', 'Content-Type, X-Requested-With')
			.expect(200)
			.end(function(err,res){
				should.not.exist(err);

				res.body.should.have.property('firstname', 'Dustin');
				if (err) return done(err);
				done();
			});
		});

	});

	describe('Test add user: POST -> /public/users', function() {

		var url_add_user_api = '/public/users';
		afterEach(function(done) {
			db.remove('user', {'firstname': "Bill"}, true, function(err, numberOfRemovedDocs) {
				should.not.exist(err);
				// console.log('delete %j user', numberOfRemovedDocs);
				done();
			});
		});

		it('should be able to add user ' + url_add_user_api, function(done) {

			var user = {
				"firstname" : "Bill",
				"lastname" : "Gates",
				"email" : "bill@msn.com",
				'password': 'passwd'
			}

			request(app)
			.post(url_add_user_api)
			.send(user)
			.expect('Content-Type', /json/)
			.expect('Access-Control-Allow-Headers', 'Content-Type, X-Requested-With')
			.expect(200)
			.end(function(err,res){
				should.not.exist(err);

				res.body.should.have.property('message', 'user registration success');
				if (err) return done(err);
				done();
			});
		});
	});

	/**
	 * should be only delete user self
	 */
	describe('Test delete user: DELETE -> /api/users/52e9ce56977f8a8b113a09f9', function() {

		var token_id = 'f2cb3e8d653f46008272113c6c72422843901ef3';
		var email = 'mary@demo.org';

		beforeEach(function(done) {
			var record = [token_id, 'uid', '52e9ce56977f8a8b113a09f9', 'email', email];
			redisService.save(token_id, record, function(err, reply){
				//console.log(reply.toString());
				done();
			});
		});

		afterEach(function(done) {

			var user = {
				"_id": new mongojs.ObjectId("52e9ce56977f8a8b113a09f9"),
				'password': '30274c47903bd1bac7633bbf09743149ebab805f',
				'email': 'dustin@demo.org',
				"firstname" : "Dustin",
				"lastname" : "Light"
			}

			db.save('user', user, function(err, numberOfRemovedDocs) {
				should.not.exist(err);
				// console.log('delete %j user', numberOfRemovedDocs);
				redisService.remove(token_id, function(err, reply){
					//console.log(reply.toString());
					done();
				});
			});
		});

		it('should be able to delete user ' + url_user_api, function(done) {

			request(url)
			.del(url_user_api + '/52e9ce56977f8a8b113a09f9?tid='+ token_id)
			.expect('Content-Type', /json/)
			.expect('Access-Control-Allow-Headers', 'Content-Type, X-Requested-With')
			.expect(200)
			.end(function(err,res){
				should.not.exist(err);
				//console.log(res.body);
				res.body.should.be.true;
				//res.body.should.have.lengthOf(3);
				if (err) return done(err);
				done();
			});
		});
	});

});


text:
import { sha256 } from 'sha.js';
import { encode, decode, encodingLength } from 'varuint-bitcoin';
import { Buffer } from '@stacks/common';

// 'Stacks Message Signing:\n'.length //  = 24
// 'Stacks Message Signing:\n'.length.toString(16) //  = 18
const chainPrefix = '\x18Stacks Message Signing:\n';

export function hashMessage(message: string) {
  return new sha256().update(encodeMessage(message)).digest();
}

export function encodeMessage(message: string | Buffer): Buffer {
  const encoded = encode(Buffer.from(message).length);
  return Buffer.concat([Buffer.from(chainPrefix), encoded, Buffer.from(message)]);
}

export function decodeMessage(encodedMessage: Buffer): Buffer {
  // Remove the chain prefix: 1 for the varint and 24 for the length of the string
  // 'Stacks Message Signing:\n'
  const messageWithoutChainPrefix = encodedMessage.subarray(1 + 24);
  const decoded = decode(messageWithoutChainPrefix);
  const varIntLength = encodingLength(decoded);
  // Remove the varint prefix
  return messageWithoutChainPrefix.slice(varIntLength);
}


text:
package apple.carplay;

import apple.NSObject;
import apple.foundation.NSArray;
import apple.foundation.NSCoder;
import apple.foundation.NSMethodSignature;
import apple.foundation.NSSet;
import apple.foundation.protocol.NSSecureCoding;
import apple.uikit.UIImage;
import org.moe.natj.c.ann.FunctionPtr;
import org.moe.natj.general.NatJ;
import org.moe.natj.general.Pointer;
import org.moe.natj.general.ann.Generated;
import org.moe.natj.general.ann.Library;
import org.moe.natj.general.ann.Mapped;
import org.moe.natj.general.ann.NInt;
import org.moe.natj.general.ann.NUInt;
import org.moe.natj.general.ann.Owned;
import org.moe.natj.general.ann.Runtime;
import org.moe.natj.general.ptr.VoidPtr;
import org.moe.natj.objc.Class;
import org.moe.natj.objc.ObjCRuntime;
import org.moe.natj.objc.SEL;
import org.moe.natj.objc.ann.ObjCClassBinding;
import org.moe.natj.objc.ann.ProtocolClassMethod;
import org.moe.natj.objc.ann.Selector;
import org.moe.natj.objc.map.ObjCObjectMapper;

/**
 * [@c] CPNavigationAlert is a banner alert that can display map or navigation-related information to the user.
 */
@Generated
@Library("CarPlay")
@Runtime(ObjCRuntime.class)
@ObjCClassBinding
public class CPNavigationAlert extends NSObject implements NSSecureCoding {
    static {
        NatJ.register();
    }

    @Generated
    protected CPNavigationAlert(Pointer peer) {
        super(peer);
    }

    @Generated
    @Selector("accessInstanceVariablesDirectly")
    public static native boolean accessInstanceVariablesDirectly();

    @Generated
    @Owned
    @Selector("alloc")
    public static native CPNavigationAlert alloc();

    @Owned
    @Generated
    @Selector("allocWithZone:")
    public static native CPNavigationAlert allocWithZone(VoidPtr zone);

    @Generated
    @Selector("automaticallyNotifiesObserversForKey:")
    public static native boolean automaticallyNotifiesObserversForKey(String key);

    @Generated
    @Selector("cancelPreviousPerformRequestsWithTarget:")
    public static native void cancelPreviousPerformRequestsWithTarget(@Mapped(ObjCObjectMapper.class) Object aTarget);

    @Generated
    @Selector("cancelPreviousPerformRequestsWithTarget:selector:object:")
    public static native void cancelPreviousPerformRequestsWithTargetSelectorObject(
            @Mapped(ObjCObjectMapper.class) Object aTarget, SEL aSelector,
            @Mapped(ObjCObjectMapper.class) Object anArgument);

    @Generated
    @Selector("classFallbacksForKeyedArchiver")
    public static native NSArray<String> classFallbacksForKeyedArchiver();

    @Generated
    @Selector("classForKeyedUnarchiver")
    public static native Class classForKeyedUnarchiver();

    @Generated
    @Selector("debugDescription")
    public static native String debugDescription_static();

    @Generated
    @Selector("description")
    public static native String description_static();

    @Generated
    @Selector("duration")
    public native double duration();

    @Generated
    @Selector("encodeWithCoder:")
    public native void encodeWithCoder(NSCoder coder);

    @Generated
    @Selector("hash")
    @NUInt
    public static native long hash_static();

    @Generated
    @Selector("image")
    public native UIImage image();

    @Generated
    @Selector("imageSet")
    public native CPImageSet imageSet();

    @Generated
    @Selector("init")
    public native CPNavigationAlert init();

    @Generated
    @Selector("initWithCoder:")
    public native CPNavigationAlert initWithCoder(NSCoder coder);

    @Generated
    @Selector("initWithTitleVariants:subtitleVariants:image:primaryAction:secondaryAction:duration:")
    public native CPNavigationAlert initWithTitleVariantsSubtitleVariantsImagePrimaryActionSecondaryActionDuration(
            NSArray<String> titleVariants, NSArray<String> subtitleVariants, UIImage image, CPAlertAction primaryAction,
            CPAlertAction secondaryAction, double duration);

    /**
     * Fully specify a @c CPNavigationAlert with a title, image, primary and secondary action,
     * and duration.
     *
     * @param titleVariants    An array of titles. The system will select a title that fits in the available space. The
     *                         variant strings should be provided as localized, displayable content.
     * @param subtitleVariants An array of subtitles. The system will select a subtitle that fits in the available
     *                         space. The variant strings should be provided as localized, displayable content.
     * @param imageSet         An optional @c CPImageSet to display in this navigation alert. Animated images are not
     *                         supported.
     *                         If an animated image is provided, only the first image from each image set will be used.
     * @param primaryAction    The alert must include at least one action button.
     * @param secondaryAction  An optional secondary button to display on the trailing edge of this alert.
     * @param duration         The duration for which this alert should be visible. Specify 0 for an alert
     *                         that displays indefinitely.
     * @return an initialized @c CPNavigationAlert.
     */
    @Generated
    @Selector("initWithTitleVariants:subtitleVariants:imageSet:primaryAction:secondaryAction:duration:")
    public native CPNavigationAlert initWithTitleVariantsSubtitleVariantsImageSetPrimaryActionSecondaryActionDuration(
            NSArray<String> titleVariants, NSArray<String> subtitleVariants, CPImageSet imageSet,
            CPAlertAction primaryAction, CPAlertAction secondaryAction, double duration);

    @Generated
    @Selector("instanceMethodForSelector:")
    @FunctionPtr(name = "call_instanceMethodForSelector_ret")
    public static native NSObject.Function_instanceMethodForSelector_ret instanceMethodForSelector(SEL aSelector);

    @Generated
    @Selector("instanceMethodSignatureForSelector:")
    public static native NSMethodSignature instanceMethodSignatureForSelector(SEL aSelector);

    @Generated
    @Selector("instancesRespondToSelector:")
    public static native boolean instancesRespondToSelector(SEL aSelector);

    @Generated
    @Selector("isSubclassOfClass:")
    public static native boolean isSubclassOfClass(Class aClass);

    @Generated
    @Selector("keyPathsForValuesAffectingValueForKey:")
    public static native NSSet<String> keyPathsForValuesAffectingValueForKey(String key);

    @Generated
    @Owned
    @Selector("new")
    public static native CPNavigationAlert new_objc();

    @Generated
    @Selector("primaryAction")
    public native CPAlertAction primaryAction();

    @Generated
    @Selector("resolveClassMethod:")
    public static native boolean resolveClassMethod(SEL sel);

    @Generated
    @Selector("resolveInstanceMethod:")
    public static native boolean resolveInstanceMethod(SEL sel);

    @Generated
    @Selector("secondaryAction")
    public native CPAlertAction secondaryAction();

    @Generated
    @Selector("setVersion:")
    public static native void setVersion_static(@NInt long aVersion);

    @Generated
    @Selector("subtitleVariants")
    public native NSArray<String> subtitleVariants();

    @Generated
    @Selector("superclass")
    public static native Class superclass_static();

    @Generated
    @Selector("supportsSecureCoding")
    public static native boolean supportsSecureCoding();

    @Generated
    @ProtocolClassMethod("supportsSecureCoding")
    public boolean _supportsSecureCoding() {
        return supportsSecureCoding();
    }

    @Generated
    @Selector("titleVariants")
    public native NSArray<String> titleVariants();

    /**
     * The navigation alert may be updated with new title and subtitle variants, either
     * after it has already been displayed on screen, or before its initial presentation on screen.
     * <p>
     * Updating an alert that has been already been dismissed has no effect.
     *
     * @param newTitleVariants    an updated array of title variants
     * @param newSubtitleVariants an updated array of subtitle variants
     */
    @Generated
    @Selector("updateTitleVariants:subtitleVariants:")
    public native void updateTitleVariantsSubtitleVariants(NSArray<String> newTitleVariants,
            NSArray<String> newSubtitleVariants);

    @Generated
    @Selector("version")
    @NInt
    public static native long version_static();
}


text:
package com.twu.biblioteca.factories;

import com.twu.biblioteca.authentication.Session;
import com.twu.biblioteca.authentication.Users;
import com.twu.biblioteca.helpers.Messages;
import com.twu.biblioteca.main_menu.MainMenu;
import com.twu.biblioteca.models.Library;
import com.twu.biblioteca.user_interface.UserInterface;
import org.junit.Test;

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;

public class GuestUserMainMenuFactoryTest {

    @Test
    public void shouldHaveAMenuForListingBooks() {
        Session session = mock(Session.class);
        Library library = mock(Library.class);
        Messages messages = mock(Messages.class);
        Users users = mock(Users.class);
        UserInterface userInterface = mock(UserInterface.class);
        MainMenu mainMenu = new GuestUserMainMenuFactory().establishMainMenu(session, library, messages, users, userInterface);

        assertEquals(com.twu.biblioteca.menu_items.ListBooksMenuItem.class, mainMenu.getMenu("1").getClass());
    }

    @Test
    public void shouldHaveAMenuForQuitting() {
        Session session = mock(Session.class);
        Library library = mock(Library.class);
        Messages messages = mock(Messages.class);
        Users users = mock(Users.class);
        UserInterface userInterface = mock(UserInterface.class);
        MainMenu mainMenu = new GuestUserMainMenuFactory().establishMainMenu(session, library, messages, users, userInterface);

        assertEquals(com.twu.biblioteca.menu_items.QuitMenuItem.class, mainMenu.getMenu("2").getClass());
    }

    @Test
    public void shouldHaveAMenuForCheckingOutABook() {
        Session session = mock(Session.class);
        Library library = mock(Library.class);
        Messages messages = mock(Messages.class);
        Users users = mock(Users.class);
        UserInterface userInterface = mock(UserInterface.class);
        MainMenu mainMenu = new GuestUserMainMenuFactory().establishMainMenu(session, library, messages, users, userInterface);

        assertEquals(com.twu.biblioteca.menu_items.CheckoutBookMenuItem.class, mainMenu.getMenu("3").getClass());
    }

    @Test
    public void shouldHaveAMenuForReturningABook() {
        Session session = mock(Session.class);
        Library library = mock(Library.class);
        Messages messages = mock(Messages.class);
        Users users = mock(Users.class);
        UserInterface userInterface = mock(UserInterface.class);
        MainMenu mainMenu = new GuestUserMainMenuFactory().establishMainMenu(session, library, messages, users, userInterface);

        assertEquals(com.twu.biblioteca.menu_items.ReturnBookMenuItem.class, mainMenu.getMenu("4").getClass());
    }

    @Test
    public void shouldHaveAMenuForListingMovies() {
        Session session = mock(Session.class);
        Library library = mock(Library.class);
        Messages messages = mock(Messages.class);
        Users users = mock(Users.class);
        UserInterface userInterface = mock(UserInterface.class);
        MainMenu mainMenu = new GuestUserMainMenuFactory().establishMainMenu(session, library, messages, users, userInterface);

        assertEquals(com.twu.biblioteca.menu_items.ListMoviesMenuItem.class, mainMenu.getMenu("5").getClass());
    }

    @Test
    public void shouldHaveAMenuForCheckingOutAMovie() {
        Session session = mock(Session.class);
        Library library = mock(Library.class);
        Messages messages = mock(Messages.class);
        Users users = mock(Users.class);
        UserInterface userInterface = mock(UserInterface.class);
        MainMenu mainMenu = new GuestUserMainMenuFactory().establishMainMenu(session, library, messages, users, userInterface);

        assertEquals(com.twu.biblioteca.menu_items.CheckoutMovieMenuItem.class, mainMenu.getMenu("6").getClass());
    }

    @Test
    public void shouldHaveAMenuForLoggingIn() {
        Session session = mock(Session.class);
        Library library = mock(Library.class);
        Messages messages = mock(Messages.class);
        Users users = mock(Users.class);
        UserInterface userInterface = mock(UserInterface.class);
        MainMenu mainMenu = new GuestUserMainMenuFactory().establishMainMenu(session, library, messages, users, userInterface);

        assertEquals(com.twu.biblioteca.menu_items.LoginMenuItem.class, mainMenu.getMenu("7").getClass());
    }
}


text:
copyright:
 years: 2015 2016

---

# Abilitazione delle applicazioni Android alla ricezione di notifiche di push
{: #tag_based_notifications}

Abilita le applicazioni Android a ricevere notifiche di push e invia notifiche di push ai tuoi dispositivi.

## Installazione del Push SDK client con Gradle
{: #android_install}

Questa sezione descrive come installare e utilizzare il Push SDK client per sviluppare
    ulteriormente le tue applicazioni Android.

Il Push SDK dei servizi mobili Bluemix® può essere aggiunto utilizzando Gradle. Gradle
          scarica automaticamente le risorse dai repository e le rende disponibili alla tua applicazione Android. Assicurati di impostare correttamente
          Android Studio e Android Studio SDK. Per ulteriori informazioni su come impostare il tuo sistema, consulta la [panoramica di Android Studio](https://developer.android.com/tools/studio/index.html). Per informazioni su Gradle, consulta [Configuring Gradle Builds](http://developer.android.com/tools/building/configuring-gradle.html).

1. In Android Studio, dopo aver creato e aperto la tua applicazione mobile, apri il tuo file **build.gradle** dell'applicazione. Quindi aggiungi le seguenti dipendenze alla tua applicazione mobile. Queste istruzioni di importazione sono necessarie per i frammenti di codice:

	```
	import com.ibm.mobilefirstplatform.clientsdk.android.core.api.BMSClient;
	import com.ibm.mobilefirstplatform.clientsdk.android.push.api.MFPPush;
	import com.ibm.mobilefirstplatform.clientsdk.android.push.api.MFPPushException;
	import com.ibm.mobilefirstplatform.clientsdk.android.push.api.MFPPushResponseListener;
	import com.ibm.mobilefirstplatform.clientsdk.android.push.api.MFPPushNotificationListener;
	import com.ibm.mobilefirstplatform.clientsdk.android.push.api.MFPSimplePushNotification;
	```

1. Aggiungi le seguenti dipendenze alla tua applicazione mobile. Le seguenti righe aggiungono l'SDK del client di push Bluemix™ Mobile Services e l'SDK dei servizi Google Play alle tue dipendenze dell'ambito di compilazione.

	```
	dependencies {
	  compile 'com.ibm.mobilefirstplatform.clientsdk.android:push:1.+'
	  compile 'com.google.android.gms:play-services:7.8.0'
	}
	```
1. Nel file **AndroidManifest.xml**, aggiungi le seguenti autorizzazioni. Per visualizzare un manifest di esempio, consulta [Applicazione di esempio Android helloPush](https://github.com/ibm-bluemix-mobile-services/bms-samples-android-hellopush/blob/master/helloPush/app/src/main/AndroidManifest.xml). Per visualizzare un file Gradle di esempio, consulta [Sample Build Gradle file](https://github.com/ibm-bluemix-mobile-services/bms-samples-android-hellopush/blob/master/helloPush/app/build.gradle).

	```
	<uses-permission android:name="android.permission.INTERNET"/>
	<uses-permission android:name="com.ibm.clientsdk.android.app.permission.C2D_MESSAGE" />
	<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
	<uses-permission android:name="android.permission.WAKE_LOCK" />
	<uses-permission android:name="android.permission.GET_ACCOUNTS" />
	<uses-permission android:name="android.permission.USE_CREDENTIALS" />
	<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
	<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
	```

	Puoi leggere ulteriori informazioni sulle [autorizzazioni Android](http://developer.android.com/guide/topics/security/permissions.html) qui.

1. Aggiungi le impostazioni di intento di notifica per l'attività. Questa impostazione avvia l'applicazione
          quando l'utente fa clic sulla notifica ricevuta dall'area di notifica.

	```
	<intent-filter>
		<action android:name="<Your_Android_Package_Name.IBMPushNotification"/>
		<category  android:name="android.intent.category.DEFAULT"/>
	</intent-filter>
	```
	**Nota**: sostituisci *Your_Android_Package_Name* nell'azione sopra indicata con il nome del pacchetto applicazione utilizzato nella tua applicazione.

1. Aggiungi il servizio di intento GCM (Google Cloud Messaging) e i filtri di intento per
          le notifiche di evento RECEIVE.

	```
	service android:name="com.ibm.mobilefirstplatform.clientsdk.android.push.api.MFPPushIntentService" />

	<receiver
	    android:name="com.ibm.mobilefirstplatform.clientsdk.android.push.internal.MFPPushBroadcastReceiver"
	    android:permission="com.google.android.c2dm.permission.SEND">
	    <intent-filter>
	        <action android:name="com.google.android.c2dm.intent.RECEIVE" />

	        <category android:name="com.ibm.mobilefirstplatform.clientsdk.android.app" />
	    </intent-filter>
	    <intent-filter>
	        <action android:name="android.intent.action.BOOT_COMPLETED" />

	        <category android:name="com.ibm.mobilefirstplatform.clientsdk.android.app" />
	    </intent-filter>
	</receiver>
	```

## Inizializzazione di Push SDK per applicazioni Android
{: #android_initialize}

Un posto comune dove inserire il codice di inizializzazione è nel metodo onCreate dell'attività principale nella tua applicazione Android.

Fai clic sul link **Opzioni mobili** nel tuo dashboard dell'applicazione Bluemix per ottenere rotta e applicationGUID dell'applicazione. Utilizza questi valori per la rotta e il GUID dell'applicazione. Modifica il frammento di codice per utilizzare la tua applicazione Bluemix appRoute e i parametri appGUID.

###Inizializza il Core SDK

```
// Inizializza l'SDK for Java (Android) con IBM Bluemix AppGUID e la rotta
BMSClient.getInstance().initialize(getApplicationContext(), "applicationRoute","applicationGUID", bluemixRegion:"Ubicazione in cui è ospitata la tua applicazione");
```

**appRoute**

Specifica la rotta assegnato all'applicazione server creata in Bluemix.

**AppGUID**

Specifica la chiave univoca assegnata all'applicazione creata in Bluemix. Questo valore è
                sensibile al maiuscolo/minuscolo.

**bluemixRegionSuffix**

Specifica l'ubicazione in cui è ospitata l'applicazione. Puoi utilizzare uno dei seguenti tre valori:

- BMSClient.REGION_US_SOUTH
- BMSClient.REGION_UK
- BMSClient.REGION_SYDNEY

###Inizializza il Push SDK client

```
//Inizializza il Push SDK for Java client
MFPPush push = MFPPush.getInstance();
push.initialize(getApplicationContext());
```

## Registrazione di dispositivi Android
{: #android_register}

Utilizza la API `IMFPush.register()` per registrare il dispositivo con un push notification service. Per registrare le periferiche Android, devi prima aggiungere le informazioni di GCM (Google Cloud Messaging) nel dashboard di configurazione del servizio push Bluemix. Per ulteriori informazioni, consulta [Configurazione delle credenziali per GCM (Google Cloud Messaging)](t_push_provider_android.html).

Copia e incolla i seguenti frammenti di codice nella tua applicazione mobile Android.

```
	//Registra dispositivi Android
	push.register(new MFPPushResponseListener<String>() {
	    @Override
	    public void onSuccess(String deviceId) {
	           //gestisce esiti positivi qui
	    }
	    @Override
	    public void onFailure(MFPPushException ex) {
	    //gestisce esiti negativi qui
	    }
	});
```

```
	//Gestisci la notifica quando arriva
	MFPPushNotificationListener notificationListener = new MFPPushNotificationListener() {
	    @Override
	    public void onReceive (final MFPSimplePushNotification message){
	      // Gestisci Push Notification
	    }
	};
```

## Ricezione di notifiche di push su dispositivi Android
{: #android_receive}

Per registrare l'oggetto  notificationListener con push, richiama il metodo **MFPPush.listen()**. Questo metodo viene di norma
                            richiamato dal metodo ** onResume() **dell'attività che
                            sta gestendo le notifiche di push.

1. Per registrare l'oggetto  notificationListener con push, richiama il metodo **listen()**. Questo metodo viene di norma
                            richiamato dal metodo ** onResume() **dell'attività che
                            sta gestendo le notifiche di push.

	```
	@Override
	protected void onResume(){
	   super.onResume();
	   if(push != null) {
	       push.listen(notificationListener);
	   }
	}
```
2. Crea il progetto ed eseguilo sul dispositivo o sull'emulatore. Quando viene richiamato il metodo onSuccess() per il listener di risposte nel metodo register(), ricevi una conferma che il dispositivo ha eseguito correttamente la registrazione presso il push notification service. In questo momento puoi inviare un messaggio come descritto in Invio di notifiche di push di base.
3. Verifica che i tuoi dispositivi abbiano ricevuto la tua notifica. Se l'applicazione è in
            primo piano, la notifica viene gestita da **MFPPushNotificationListener**. Se l'applicazione è in background, viene visualizzato un messaggio nella barra di notifica.

## Invio di notifiche di push di base
{: #send}

Dopo che hai sviluppato le tue applicazioni, puoi inviare delle notifiche di push di base (senza utilizzare tag, badge, payload aggiuntivi o file audio).

Invia notifiche di push di base.

1. In **Choose the Audience**, seleziona uno dei seguenti destinatari: **All Devices** oppure in base alla piattaforma:
**Only iOS devices** o **Only Anroid devices**.

	**Nota**: quando selezioni l'opzione **All Devices**, tutti i dispositivi che hanno sottoscritto le notifiche di push ricevono la tua notifica.

	![Schermata notifiche](images/tag_notification.jpg)

2. In the **Create your Notification**, immetti il tuo messaggio e quindi fai clic su **Send**.
3. Verifica che i tuoi dispositivi abbiano ricevuto la tua notifica.
Il seguente screenshot mostra una casella di avviso che gestisce una notifica push
in primo piano su un dispositivo Android e iOS.

	![Notifica push in primo piano su Android](images/Android_Screenshot.jpg)

	![Notifica push in primo piano su iOS](images/iOS_Screenshot.jpg)

	Il seguente screenshot mostra una notifica push in background per Android.
	![Notifica push in background su Android](images/background.jpg)

## Passi successivi
{: #next_steps_tags}

Dopo che hai correttamente configurato le notifiche di base, puoi configurare le notifiche
        basate sulle tag e le opzioni avanzate.

Aggiungi queste funzioni del Servizio push notifications alla tua applicazione.
Per utilizzare le notifiche basate sulle tag, vedi [Notifiche basate sulle tag](c_tag_basednotifications.html).
Per utilizzare le opzioni di notifica avanzate, vedi [Notifiche di push avanzate](t_advance_notifications.html).


text:
package com.heliosapm.shorthand.store;

import java.io.File;
import java.lang.management.ManagementFactory;

/**
 *
Title: ShorthandChronicleCleaner

 *
Description: Cleans old inactive shorthand chronicle directories

 *
Company: Helios Development Group LLC

 * @author Whitehead (nwhitehead AT heliosdev DOT org)
 *
com.heliosapm.shorthand.store.ShorthandChronicleCleaner

 */

public class ShorthandChronicleCleaner extends Thread {
	/** The chronicle directory to clean */
	private final File chronicleDir;

	/** This JVM's Process ID */
	public static final String PID = ManagementFactory.getRuntimeMXBean().getName().split("@")[0];
	/**
	 * Creates a new ShorthandChronicleCleaner
	 * @param directoryName The chronicle directory to clean
	 */
	public ShorthandChronicleCleaner(String directoryName) {
		super("ShorthandChronicleCleaner");
		setDaemon(true);
		chronicleDir = new File(directoryName);
	}

	/**
	 * {@inheritDoc}
	 * @see java.lang.Thread#run()
	 */
	@Override
	public void run() {
		int filesDeleted = 0, dirsDeleted = 0;
		log("Cleaning Chronicle Dir [" + chronicleDir + "]");
		for(File pDir: chronicleDir.listFiles()) {
			if(pDir.isDirectory()) {
				log("Cleaning Chronicle Dir [%s] PID: [%s]", pDir, pDir.getName());
				if(PID.equals(pDir.getName())) continue;
				File lockFile = new File(pDir.getAbsoluteFile() + File.separator + "shorthand.lock");
				if(lockFile.exists()) {
					if(!lockFile.delete()) {
						log("Lock File [" + lockFile + "] is locked. Must be active");
						continue;
					}
				}
				filesDeleted++;
				for(File pFile: pDir.listFiles()) {
					pFile.delete();
					filesDeleted++;
				}
				if(!pDir.delete()) {
					log("Failed to delete Chronicle Dir [" + pDir + "]");
				} else {
					log("Cleaned Chronicle Dir [" + pDir + "]");
					dirsDeleted++;
				}
			}
		}
		log("Cleaned [%s] files and [%s] directories", filesDeleted, dirsDeleted);
	}

	/**
	 * Simple out formatted logger
	 * @param fmt The format of the message
	 * @param args The message arguments
	 */
	public static void log(String fmt, Object...args) {
		System.out.println(String.format(fmt, args));
	}

}


text:
package org.motechproject.uitest;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.SystemUtils;
import org.apache.commons.vfs2.AllFileSelector;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.VFS;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.rules.TestRule;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
import org.motechproject.uitest.exception.UITestFrameworkException;
import org.motechproject.uitest.page.GenericPage;
import org.motechproject.uitest.page.LoginPage;
import org.motechproject.uitest.page.MotechPage;
import org.motechproject.uitest.page.Page;
import org.motechproject.uitest.page.TestProperties;
import org.motechproject.uitest.startup.StartupHelper;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeDriverService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.TimeUnit;

import static org.junit.Assert.assertEquals;
/**
 * Superclass for all UI Tests. Contains lots of handy "utilities"
 * needed to setup and tear down tests as well as handy methods
 * needed during tests, such as:
 *  - initialize Selenium WebDriver
 *  - @see {@link #currentPage()}
 *  - @see {@link #assertPage(Page)}
 */
public class TestBase {

    private static final TestProperties TEST_PROPERTIES = TestProperties.instance();

    private static WebDriver driver;

    private final Logger logger = LoggerFactory.getLogger(getClass());

    private LoginPage loginPage;

    @BeforeClass
    public static void startWebDriver() throws InterruptedException, IOException {
        driver = setupChromeDriver();
        driver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS);
        new StartupHelper().startUp();
    }

    @AfterClass
    public static void stopWebDriver() {
        if (driver != null) {
            driver.quit();
        }
    }

    @Before
    public void initLoginPage() {
        loginPage = new LoginPage(getDriver());
    }

    public MotechPage login() {
        loginPage.goToPage();
        assertPage(loginPage);
        return loginPage.loginAsAdmin();
    }

    public LoginPage logout() throws InterruptedException {
        return new MotechPage(driver).logOut();
    }

    public void goToHomePage() {
        goToPage("/");
    }

    public void goToPage(String path) {
        driver.get(getServerUrl() + getContextPath() + path);
    }

    // This takes a screen (well, browser) snapshot whenever there's a failure
    // and stores it in a "screenshots" directory.
    @Rule
    public TestRule testWatcher = new TestWatcher() { // NO CHECKSTYLE rules must be public

        @Override
        public void failed(Throwable t, Description test) {
            takeScreenshot(test.getDisplayName().replaceAll("[()]", ""));
        }
    };

    static WebDriver setupChromeDriver() {
        URL chromedriverExecutable = null;
        ClassLoader classLoader = TestBase.class.getClassLoader();

        String chromedriverExecutableFilename = null;
        String chromedriverExecutablePath;

        if (SystemUtils.IS_OS_MAC_OSX) {
            chromedriverExecutableFilename = "chromedriver";
            chromedriverExecutable = classLoader.getResource("chromedriver/mac/chromedriver");
        } else if (SystemUtils.IS_OS_LINUX) {
            chromedriverExecutableFilename = "chromedriver";
            chromedriverExecutable = classLoader.getResource("chromedriver/linux/chromedriver");
        } else if (SystemUtils.IS_OS_WINDOWS) {
            chromedriverExecutableFilename = "chromedriver.exe";
            chromedriverExecutable = classLoader.getResource("chromedriver/windows/chromedriver.exe");
        }

        if (chromedriverExecutable == null) {
            throw new UITestFrameworkException("Cannot find chromedriver executable");
        } else {
            chromedriverExecutablePath = chromedriverExecutable.getPath();
            // This ugly bit checks to see if the chromedriver file is inside a jar, and if so
            // uses VFS to extract it to a temp directory.
            if (chromedriverExecutablePath.contains(".jar!")) {
                FileObject chromedriverVfs;
                try {
                    chromedriverVfs = VFS.getManager().resolveFile(chromedriverExecutable.toExternalForm());
                    File chromedriverFs = new File(FileUtils.getTempDirectory(), chromedriverExecutableFilename);
                    FileObject chromedriverUnzipped = VFS.getManager().toFileObject(chromedriverFs);
                    chromedriverUnzipped.delete();
                    chromedriverUnzipped.copyFrom(chromedriverVfs, new AllFileSelector());
                    chromedriverExecutablePath = chromedriverFs.getPath();
                    if (!SystemUtils.IS_OS_WINDOWS) {
                        chromedriverFs.setExecutable(true);
                    }
                } catch (FileSystemException e) {
                    throw new UITestFrameworkException("Unable to start the UI Test Framework", e);
                }
            }
        }
        System.setProperty(ChromeDriverService.CHROME_DRIVER_EXE_PROPERTY, chromedriverExecutablePath);
        String chromedriverFilesDir = "target/chromedriverlogs";
        try {
            FileUtils.forceMkdir(new File(chromedriverFilesDir));
        } catch (IOException e) {
            throw new UITestFrameworkException("Unable to start the UI Test Framework", e);
        }
        System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY, chromedriverFilesDir + "/chromedriver-"
                + testClassName.name + ".log");
        driver = new ChromeDriver();
        return driver;
    }

    /**
     * Return a Page that represents the current page, so that all the convenient methods in Page
     * can be used.
     *
     * @return a Page
     */
    public static Page currentPage() {
        return new GenericPage(driver);
    }

    /**
     * Assert we're on the expected page.
     *
     * @param expected page
     */
    public static void assertPage(Page expected) {
        assertEquals(getContextPath() + expected.expectedUrlPath(), currentPage().urlPath());
    }

    public void takeScreenshot(String filename) {
        logger.debug("Saving screenshot: {}", filename);
        File tempFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
        try {
            FileUtils.copyFile(tempFile, new File("target/screenshots/" + filename + ".png"));
            logger.debug("Saved screenshot: {}", filename);
        } catch (IOException e) {
            throw new UITestFrameworkException("Unable to take screenshot", e);
        }
    }

    protected Logger getLogger() {
        return logger;
    }

    protected static WebDriver getDriver() {
        return driver;
    }

    protected static TestProperties getTestProperties() {
        return TEST_PROPERTIES;
    }

    protected static String getServerUrl() {
        return TEST_PROPERTIES.getServerUrl();
    }

    protected static String getContextPath() {
        return TEST_PROPERTIES.getContextPath();
    }

    // This junit cleverness picks up the name of the test class, to be used in the chromedriver log file name.
    @ClassRule
    public static TestClassName testClassName = new TestClassName(); // NO CHECKSTYLE rules must be public

    static class TestClassName implements TestRule {

        private String name;

        @Override
        public Statement apply(Statement statement, Description description) {
            name = description.getTestClass().getSimpleName();
            return statement;
        }
    }
}


text:
package com.hazelcast.collection.impl.queue.operations;

import com.hazelcast.collection.impl.queue.QueueContainer;
import com.hazelcast.collection.impl.queue.QueueDataSerializerHook;
import com.hazelcast.monitor.impl.LocalQueueStatsImpl;
import com.hazelcast.spi.ReadonlyOperation;

/**
 * Notify size of the queue.
 */
public class SizeOperation extends QueueOperation implements ReadonlyOperation {

    public SizeOperation() {
    }

    public SizeOperation(String name) {
        super(name);
    }

    @Override
    public void run() {
        QueueContainer queueContainer = getContainer();
        response = queueContainer.size();
    }

    @Override
    public void afterRun() throws Exception {
        LocalQueueStatsImpl stats = getQueueService().getLocalQueueStatsImpl(name);
        stats.incrementOtherOperations();
    }

    @Override
    public int getId() {
        return QueueDataSerializerHook.SIZE;
    }
}


text:
const chalk = require('chalk');

const buildMessage =
  prefix =>
    message => (!prefix
      ? message
      : `${prefix}: ${message}`);

const writeOut =
  message =>
    color =>
      console.log(color(message)); // eslint-disable-line

const log =
  prefix => ({
    cyan: message => writeOut(buildMessage(prefix)(message))(chalk.cyan),
    red: message => writeOut(buildMessage(prefix)(message))(chalk.red),
    green: message => writeOut(buildMessage(prefix)(message))(chalk.green),
    dim: message => writeOut(buildMessage(prefix)(message))(chalk.dim),
    yellow: message => writeOut(buildMessage(prefix)(message))(chalk.yellow),
    blue: message => writeOut(buildMessage(prefix)(message))(chalk.blue),
    reset: log,
  });

module.exports = log;


text:
package org.apache.ojb.broker.accesslayer;

import java.lang.reflect.Constructor;
import java.sql.SQLException;
import java.util.Enumeration;
import java.util.NoSuchElementException;

import org.apache.ojb.broker.Identity;
import org.apache.ojb.broker.PersistenceBroker;
import org.apache.ojb.broker.PersistenceBrokerException;
import org.apache.ojb.broker.PersistenceBrokerSQLException;
import org.apache.ojb.broker.metadata.ClassDescriptor;
import org.apache.ojb.broker.metadata.FieldDescriptor;
import org.apache.ojb.broker.query.Query;
import org.apache.ojb.broker.util.ConstructorHelper;
import org.apache.ojb.broker.util.logging.LoggerFactory;

/**
 * this class can be used to create enumerations of PrimaryKey objects.
 * This is interesting for EJB finder methods
 * in BMP entity beans which must return such enumerations.
 * @author Thomas Mahler
 * @version $Id: PkEnumeration.java,v 1.1 2007-08-24 22:17:30 ewestfal Exp $
 */
public class PkEnumeration implements Enumeration
{
	static final long serialVersionUID = -834955711995869884L;
    protected boolean hasCalledCheck = false;
    protected boolean hasNext = false;

    protected PersistenceBroker broker;

    /**
     * The underlying jdbc resultset produced by select statement
     */
    protected ResultSetAndStatement resultSetAndStatment;

    /**
     * descriptor for the class of which items are to be found
     */
    protected ClassDescriptor classDescriptor;

    /**
     * the Constructor that is needed to build the PrimaryKey Objects
     */
    protected Constructor constructor;

    /**
     * PkEnumeration constructor.
     * @param query the SELECT statement gerating the underlying resultset
     * @param cld classDescriptor of the target entity class (say Article)
     * @param primaryKeyClass the entity classes PrimaryKey class (say ArticleKey).
     * this key-class MUST have a constructor with one argument of type org.apache.ojb.broker.Identity !
     */
    public PkEnumeration(Query query, ClassDescriptor cld, Class primaryKeyClass, PersistenceBroker broker)
    {
        this.resultSetAndStatment = broker.serviceJdbcAccess().executeQuery(query, cld);
        this.classDescriptor = cld;
        this.broker = broker;
        // get a contructor object that can be used to build instances of class primaryKeyClass
        try
        {
            Class[] argArray = {Identity.class};
            this.constructor = primaryKeyClass.getConstructor(argArray);
        }
        catch (NoSuchMethodException e)
        {
            LoggerFactory.getDefaultLogger().error(primaryKeyClass.getName()
                    + " must implement a Constructor with one argument of type org.apache.ojb.broker.Identity");
            throw new PersistenceBrokerException(e);
        }
        catch (SecurityException e)
        {
            LoggerFactory.getDefaultLogger().error(e);
            throw new PersistenceBrokerException(e);
        }
    }

    /**
     * returns an Identity object representing the current resultset row
     */
    private Identity getIdentityFromResultSet()
    {

        try
        {
            // 1. get an empty instance of the target class
            Constructor con = classDescriptor.getZeroArgumentConstructor();
            Object obj = ConstructorHelper.instantiate(con);

            // 2. fill only primary key values from Resultset
            Object colValue;
            FieldDescriptor fld;
            FieldDescriptor[] pkfields = classDescriptor.getPkFields();
            for (int i = 0; i < pkfields.length; i++)
            {
                fld = pkfields[i];
                colValue = fld.getJdbcType().getObjectFromColumn(resultSetAndStatment.m_rs, fld.getColumnName());
                fld.getPersistentField().set(obj, colValue);
            }
            // 3. return the representing identity object
            return broker.serviceIdentity().buildIdentity(classDescriptor, obj);
        }
        catch (SQLException e)
        {
            throw new PersistenceBrokerSQLException("Error reading object from column", e);
        }
        catch (Exception e)
        {
            throw new PersistenceBrokerException("Error reading Identity from result set", e);
        }
    }

    /**
     * Tests if this enumeration contains more elements.
     * @return  true if and only if this enumeration object
     * contains at least one more element to provide;
     * false otherwise.
     */
    public boolean hasMoreElements()
    {
        try
        {
            if (!hasCalledCheck)
            {
                hasCalledCheck = true;
                hasNext = resultSetAndStatment.m_rs.next();
            }
        }
        catch (SQLException e)
        {
            LoggerFactory.getDefaultLogger().error(e);
            //releaseDbResources();
            hasNext = false;
        }
        finally
        {
            if(!hasNext)
            {
                releaseDbResources();
            }
        }
        return hasNext;
    }

    private void releaseDbResources()
    {
        resultSetAndStatment.close();
        resultSetAndStatment = null;
    }

    /**
     * Returns the next element of this enumeration if this enumeration
     * object has at least one more element to provide.
     * @return     the next element of this enumeration.
     * @exception  NoSuchElementException  if no more elements exist.
     */
    public Object nextElement()
    {
        try
        {
            if (!hasCalledCheck)
            {
                hasMoreElements();
            }
            hasCalledCheck = false;
            if (hasNext)
            {
                Identity oid = getIdentityFromResultSet();
                Identity[] args = {oid};
                return this.constructor.newInstance(args);
            }
            else
                throw new NoSuchElementException();
        }
        catch (Exception ex)
        {
            LoggerFactory.getDefaultLogger().error(ex);
            throw new NoSuchElementException();
        }
    }

	/**
	 * protection just in case someone leaks.
	 */
	protected void finalize()
	{
		if(resultSetAndStatment != null)
        {
            LoggerFactory.getDefaultLogger().error("["+PkEnumeration.class.getName()+"] Found unclosed resources while finalize");
            releaseDbResources();
        }
	}
}


text:
import { ShopifyObject } from "./base";

export interface Address extends ShopifyObject {
    /**
     * The mailing address.
     */
    address1?: string;

    /**
     * An additional field for the mailing address.
     */
    address2?: string;

    /**
     * The city.
     */
    city?: string;

    /**
     * The company.
     */
    company?: string;

    /**
     * The country.
     */
    country?: string;

    /**
     * The two-letter country code corresponding to the country.
     */
    country_code?: string;

    /**
     * The normalized country name.
     */
    country_name?: string;

    /**
     * Indicates whether this address is the default address.
     */
    default?: boolean;

    /**
     * The first name.
     */
    first_name?: string;

    /**
     * The last name.
     */
    last_name?: string;

    /**
     * The name.
     */
    name?: string;

    /**
     * The phone number.
     */
    phone?: string;

    /**
     * The province or state name
     */
    province?: string;

    /**
     * The two-letter province or state code.
     */
    province_code?: string;

    /**
     * The ZIP or postal code.
     */
    zip?: string;
}


text:
<?php

namespace ZF\Doctrine\Audit;

use Zend\Mvc\MvcEvent;
use Zend\ModuleManager\Feature\ConfigProviderInterface;
use Zend\ModuleManager\Feature\ConsoleUsageProviderInterface;
use Zend\Console\Adapter\AdapterInterface as Console;
use Zend\ServiceManager\ServiceManager;
use Doctrine\ORM\Mapping\Driver\XmlDriver;
use Doctrine\ORM\Events;
use Doctrine\DBAL\Events as DBALEvents;

class Module implements
    ConfigProviderInterface,
    ConsoleUsageProviderInterface
{
    public function getConsoleUsage(Console $console)
    {
        return array(
            'audit:trigger-tool:create' => 'Create trigger SQL for target database',
            'audit:trigger-tool:drop' => 'Drop trigger SQL for target database',
            'audit:epoch:import' => 'Create epoch stored procedures SQL for target database',
        );
    }

    public function getAutoloaderConfig()
    {
        return array(
            'Zend\Loader\StandardAutoloader' => array(
                'namespaces' => array(
                    __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
                ),
            ),
        );
    }

    public function getConfig()
    {
        return include __DIR__ . '/config/module.config.php';
    }

    public function onBootstrap(MvcEvent $e)
    {
        $serviceManager = $e->getParam('application')->getServiceManager();

        $config = $serviceManager->get('config')['zf-doctrine-audit'];

        $serviceManager->get('ZF\Doctrine\Audit\Loader\EntityAutoloader')->register();
        $serviceManager->get('ZF\Doctrine\Audit\Loader\JoinEntityAutoloader')->register();

        $mergedDriver = $serviceManager->get('ZF\Doctrine\Audit\Mapping\Driver\MergedDriver');
        $mergedDriver->addDriver($serviceManager->get('ZF\Doctrine\Audit\Mapping\Driver\EntityDriver'));
        $mergedDriver->addDriver($serviceManager->get('ZF\Doctrine\Audit\Mapping\Driver\JoinEntityDriver'));
        $mergedDriver->register();

        $postConnectListener = $serviceManager->get(EventListener\PostConnect::class);
        $postFlushListener = $serviceManager->get(EventListener\PostFlush::class);

        $objectManager = $serviceManager->get($config['target_object_manager']);
        $auditObjectManager = $serviceManager->get($config['audit_object_manager']);

        // Driver for zf-doctrine-audit entites
        $xmlDriver = new XmlDriver(__DIR__ . '/config/orm');
        $auditObjectManager
            ->getConfiguration()
            ->getMetadataDriverImpl()
            ->addDriver($xmlDriver, 'ZF\Doctrine\Audit\Entity')
            ;

        $objectManager->getEventManager()
            ->addEventListener([DBALEvents::postConnect], $postConnectListener);

        $objectManager->getEventManager()
            ->addEventListener([Events::postFlush], $postFlushListener);
    }
}


text:
package org.springframework.cloud.zookeeper.discovery.dependency;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import org.springframework.context.annotation.Conditional;

/**
 * Annotation to turn off a feature if Zookeeper dependencies have NOT been passed.
 *
 * @author Marcin Grzejszczak
 * @since 1.0.0
 */
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Conditional(DependenciesNotPassedCondition.class)
public @interface ConditionalOnDependenciesNotPassed {

}


text:
import React from 'react'
import { connect } from 'react-redux'
import Instance from './Instance'
import _ from 'lodash'

export default connect(mapStateToProps)(({
  round,
  adjudicatorScores,
  rooms
}) => {
  const filterRooms = roomToMatch => roomToMatch.round === round._id
  const roomsThisRound = rooms.filter(filterRooms)

  let teamsThisRound = roomsThisRound.map(room => [room.gov, room.opp])
  teamsThisRound = _.flatten(teamsThisRound)

  let adjudicatorScoresThisRound = adjudicatorScores.filter(filterRooms)

  return (
    <div>
      {teamsThisRound.map(team =>
        <Instance
          key={team}
          teamId={team}
          adjudicatorScoresThisRound={adjudicatorScoresThisRound}
          roomsThisRound={roomsThisRound}
        />
      )}
    </div>
  )
})

function mapStateToProps (state, ownProps) {
  return {
    rooms: Object.values(state.rooms.data),
    adjudicatorScores: Object.values(state.adjudicatorScores.data)
  }
}


text:
<RelativeLayout
    android:orientation="vertical"
    android:background="@color/colorBackground"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.project.quiz.fragments.FragmentExportAsCsv">
    <com.project.quiz.customviews.TextViewRegularFont
        android:layout_marginTop="50dp"
        android:id="@+id/success_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="20dp"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        android:gravity="center"
        android:text=""
        android:textSize="@dimen/font_size_xxlarge"
        android:textColor="@color/colorPrimaryDark" />
<com.project.quiz.customviews.TextViewBoldFont
    android:layout_below="@+id/success_text"
    android:layout_margin="16dp"
    android:layout_marginBottom="20dp"
    android:layout_width="match_parent"
    android:gravity="center"
    android:id="@+id/filename_header"
    android:textColor="@color/colorTextDark"
    android:text="Export files to Excel"
    android:textSize="@dimen/font_size_large"
    android:layout_height="wrap_content" />
    <android.support.design.widget.TextInputLayout
        android:layout_margin="16dp"
        android:layout_below="@+id/filename_header"
        android:id="@+id/filename_layout"
        android:layout_width="match_parent"
        android:textColorHint="@color/colorPrimary"
        android:layout_height="wrap_content" >
        <com.project.quiz.customviews.EditTextRegularFont
            android:hint="Enter filename to save"
            android:textColor="@color/colorText"
            android:id="@+id/filename"
            android:layout_width="match_parent"
            android:inputType="textCapSentences"
            android:layout_height="wrap_content" />
        </android.support.design.widget.TextInputLayout>

    <com.project.quiz.customviews.TextViewRegularFont
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        android:layout_marginTop="100dp"
        android:layout_marginBottom="50dp"
        android:id="@+id/button_export"
        android:layout_below="@+id/filename_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:background="@drawable/button_yes_drawable"
        android:paddingBottom="@dimen/padding_custom_10dp"
        android:paddingTop="@dimen/padding_custom_10dp"
        android:text="Export"
        android:textColor="@color/colorBackground"
        android:textSize="@dimen/font_size_xlarge" />

    <com.project.quiz.customviews.TextViewRegularFont
        android:layout_margin="16dp"
        android:layout_alignParentBottom="true"
        android:id="@+id/button_delete"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:background="@color/black"
        android:paddingBottom="@dimen/padding_custom_10dp"
        android:paddingTop="@dimen/padding_custom_10dp"
        android:text="Delete the Excel file"
        android:textColor="@color/colorText"
        android:textSize="@dimen/font_size_xlarge" />

</RelativeLayout>


text:
<!doctype html>

		<title>Zabuun - Learn Egyptian Arabic for English speakers</title>
		<meta name="description" content="">
		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/head.php';?>

		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/ie8.php';?>
		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/header.php';?>

			<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/side.php';?>

Essays > Tonya Harding and Nancy Kerrigan

						Expand All | Collapse All

Tonya Harding and Nancy Kerrigan

Harding remained in the American limelight for several years following the incident. Her ex-husband released a wedding sex video of Harding and himself. Some of those images were published by Penthouse Magazine. She competed in a Fox TV network broadcast of Celebrity Boxing in 2002. She went on to try a professional boxing career the following year, but with little success. Kerrigan, on the other hand, fell out of the American culture scene, never to be heard of again.

		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/footer.php';?>
		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/scripts.php';?>


text:
<template name="afInputText_materialize">
  <input type="text" value="{{this.value}}" {{this.atts}}/>
</template>


text:
using System;

namespace Silphid.Requests
{
    public abstract class TypedRequestHandler<TRequest> : ITypedRequestHandler where TRequest : class, IRequest
    {
        public Type SupportedRequestType => typeof(TRequest);

        public bool Handle(IRequest request)
        {
            var req = request as TRequest;
            if (req != null)
                return Handle(req);

            return false;
        }

        protected abstract bool Handle(TRequest request);
    }
}


text:
class Tournaments::InvitesController < ApplicationController
  before_action :authenticate_user!
  before_action :find_invite_for_tournament, :only => [:show, :update]
  before_action :find_tournament, :only => [:new, :create]

  layout 'tournament_title', :only => [:new, :create]

  def show
  end

  def update
    if InviteAcceptor.new(@invite, current_user).accept
      redirect_to tournament_path(@tournament)
    else
      render :show
    end
  end

  def new
    @invite = @tournament.invites.build
  end

  def create
    @invite = @tournament.invites.build(params.require(:invite).permit(:email))
    @invite.owner = current_user
    if @invite.save
      Notifications.tournament_invitation(@invite).deliver_now
      redirect_to tournament_path(@tournament),
        :notice => t('tournaments.invites.create.success', :email => @invite.email)
    else
      render :new
    end
  end

  private

  def find_invite_for_tournament
    @tournament = Tournament.friendly.find(params[:tournament_id])
    @invite = @tournament.invites.available.find_by_code!(params[:id])
  end

  def find_tournament
    @tournament = Tournament.participant(current_user).friendly.find(params[:tournament_id])
  end
end


text:
package uk.ac.man.entitytagger.generate;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.sql.PreparedStatement;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.logging.Logger;
import java.util.regex.Pattern;

import martin.common.Tuple;
import martin.common.compthreads.ArrayBasedMaster;
import martin.common.compthreads.IteratorBasedMaster;
import martin.common.compthreads.Problem;
import uk.ac.man.entitytagger.generate.DictionaryEntry;
import dk.brics.automaton.*;

/**
 * Class providing functions used to generate automatons for efficient regular expression matching
 * @author Martin
 *
 */
class GenerateAutomatons {
	/**
	 * Class used to join several automatons together and minimize the result (put into a class to enable concurrent computations)
	 * @author Martin
	 *
	 */
	private class ProcessProblem implements Problem<Automaton>{
		private ArrayList<Automaton> automatons;
		private boolean minimize;

		public ProcessProblem(ArrayList<Automaton> automatons, boolean minimize){
			this.automatons = automatons;
			this.minimize = minimize;
		}

		public Automaton compute() {
			Automaton res;

			if (automatons.size() > 1){
				res = BasicOperations.union(automatons);
				res.setDeterministic(false);
			} else {
				res = automatons.get(0);
			}

			res.determinize();

			if (minimize)
				res.minimize();

			return res;
		}

	}
	private class ToAutomatonProblem implements Problem<Automaton>{
		private DictionaryEntry entry;
		private boolean lowercase;
		public ToAutomatonProblem(DictionaryEntry entry, boolean lowercase){
			this.entry = entry;
			this.lowercase = lowercase;
		}

		public Automaton compute() {
			//System.out.println("(" + entry.getRegexp() + ")" + AutomatonMatcher.delimiter + species);
			String sr = "(" + entry.getRegexp() + ")";

			if (lowercase)
				sr = sr.toLowerCase();

			if (sr.contains(""+CustomRunAutomaton.delimiter))
				throw new IllegalStateException("The regular expression " + sr + " contains the CustomRunAutomaton.delimiter character. You need to change character.");

			RegExp r = null;
			try{
				r = new RegExp(sr + CustomRunAutomaton.delimiter + entry.getId());
			} catch (Exception e){
				System.err.println("Detected exception when creating regular expression: '" + sr + CustomRunAutomaton.delimiter + entry.getId() + "'");
				System.err.println(e);
				e.printStackTrace();
				System.exit(-1);
			}

			Automaton a = r.toAutomaton();

			String shortest = a.getShortestExample(true);

			if (shortest == null || shortest.equals(CustomRunAutomaton.delimiter + entry.getId())){
				System.err.println("Warning: detected erroneous regexp for id " + entry.getId() + ", returning null automaton (regexp: '" + sr + "'");
				return null;
			}

			a.setDeterministic(false);
			a.determinize();
			return a;
		}
	}
	private class ToAutomatonProblemIterator implements Iterator<Problem<Automaton>>{
		private ArrayList<DictionaryEntry> dictionaryEntries;
		int currentItem = 0;
		private boolean lowercase;

		public ToAutomatonProblemIterator(ArrayList<DictionaryEntry> dictionaryEntries, boolean lowercase){
			this.dictionaryEntries = dictionaryEntries;
			this.lowercase = lowercase;
		}

		public boolean hasNext() {
			return currentItem < dictionaryEntries.size();
		}

		public ToAutomatonProblem next() {
			return new ToAutomatonProblem(dictionaryEntries.get(currentItem++),lowercase);
		}

		/**
		 * not implemented
		 */
		public void remove() {
			throw new IllegalStateException("not implemented");
		}
	}

	/**
	 * Function which will take a list of automatons and join them together in groups of size multiJoin (e.g. input 12 automatons and multiJoin=3 would give output of 4 automatons)
	 * @param automatons the list of automatons to be joined together
	 * @param multiJoin the number of automatons that should be joined at a time
	 * @param minimize whether to perform automaton minimization afterwards (will produce smaller automatons requiring less memory, but requires more time to perform)
	 * @param showNumStates whether to print some statistics at the end
	 * @param numThreads the number of concurrent joins to perform (note that multiple threads will increase memory requirements)
	 * @param logger
	 * @return a list of joined automatons of size (automatons.size() / multiJoin).
	 */
	ArrayList<Automaton> process(ArrayList<Automaton> automatons, int multiJoin, boolean minimize, boolean showNumStates, int numThreads, Logger logger){
		ArrayList<Automaton> res = new ArrayList<Automaton>();

		int numRuns = automatons.size() / multiJoin;

		int numStartStates=0,numEndStates=0;

		if (numRuns * multiJoin < automatons.size())
			numRuns++;

		Problem<Automaton> problems[] = new ProcessProblem[numRuns];

		for (int i = 0; i < numRuns; i++){
			ArrayList<Automaton> temp = new ArrayList<Automaton>();

			for (int j = 0; j < multiJoin; j++){
				int index = i * multiJoin + j;
				if (index < automatons.size()){
					temp.add(automatons.get(index));
					if (showNumStates)
						numStartStates += automatons.get(index).getNumberOfStates();
				}
			}

			problems[i] = new ProcessProblem(temp,minimize);
		}

		ArrayBasedMaster<Automaton> master = new ArrayBasedMaster<Automaton>(problems, numThreads);

		logger.info("%t: Processing automatons... ");

		new Thread(master).start();

		Object[] solutions = master.getSolutions();

		for (int i = 0; i < solutions.length; i++){
			Automaton a = (Automaton) solutions[i];

			numEndStates += a.getNumberOfStates();
			res.add(a);
		}

		logger.info("done. " + automatons.size() + " automatons (" + numStartStates + " states) -> " + res.size() + " (" + numEndStates + " states)\n");

		return res;
	}

	static CustomRunAutomaton[] loadRArray(File file, Logger logger){
		CustomRunAutomaton[] r = null;
		try {
			ObjectInputStream inStream = new ObjectInputStream(new BufferedInputStream(new FileInputStream(file)));

			int size = inStream.readInt();

			logger.info("%t: Loading runautomatons...");

			r = new CustomRunAutomaton[size];

			for (int i = 0; i < r.length; i++)
				r[i] = (CustomRunAutomaton) inStream.readObject();

			logger.info(" done, loaded " + size + " automatons from file " + file.getAbsolutePath() + ".\n");

			inStream.close();
		} catch (Exception e){
			System.err.println(e);
			e.printStackTrace();
			System.exit(-1);
		}
		return r;
	}

	static void storeRArray(ArrayList<Automaton> list, boolean ignoreCase, boolean tableize, File file, Logger logger){
		CustomRunAutomaton[] r = new CustomRunAutomaton[list.size()];

		logger.info("%t: Converting automatons to runautomatons (tableize = " + tableize + ")...");
		for (int i = 0; i < list.size(); i++)
			r[i] = new CustomRunAutomaton(list.get(i),tableize);
		logger.info(" done.\n");

		try {
			logger.info("%t: Storing runautomatons...");
			ObjectOutputStream outStream = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(file)));

			outStream.writeInt(list.size());
			outStream.writeBoolean(ignoreCase);

			for (int i = 0; i < r.length; i++)
				outStream.writeObject(r[i]);

			outStream.close();

			logger.info(" done. Stored " + r.length + " runautomatons to file " + file.getAbsolutePath() + "\n");
		} catch (Exception e){
			System.err.println(e);
			e.printStackTrace();
			System.exit(-1);
		}
	}

	/**
	 * converts a list of dictionary entries to their corresponding automatons
	 * @param dictionaryEntries  the list of dictionary entries
	 * @param numThreads the number of concurrent threads to use for conversion
	 * @param report null if the function should not output progress, will otherwise print progress after every report:th conversion)
	 * @param b
	 * @param logger
	 * @return the list of automatons representing the list of dictionary entries
	 */
	ArrayList<Automaton> toAutomatons(ArrayList<DictionaryEntry> dictionaryEntries, int numThreads, Integer report, boolean ignoreCase, Logger logger){
		logger.info("%t: Generating automatons, ignoreCase = " + ignoreCase + "...\n");

		Iterator<Problem<Automaton>> problems = new ToAutomatonProblemIterator(dictionaryEntries,ignoreCase);
		IteratorBasedMaster<Automaton> master = new IteratorBasedMaster<Automaton>(problems, numThreads);
		new Thread(master).start();

		int i = 0;

		ArrayList<Automaton> res = new ArrayList<Automaton>();

		while (master.hasNext()){
			Automaton a = master.next();

			if (a != null)
				res.add(a);

			if (report != null && ++i % report == 0)
				logger.info(i + " / " + dictionaryEntries.size() + "\n");
		}

		logger.info("%t: Automatons complete.\n");

		return res;
	}

	static Tuple<ArrayList<Automaton>, Boolean> loadArray(File file) {
		ArrayList<Automaton> l = new ArrayList<Automaton>();
		boolean ignoreCase = false;
		try {
			ObjectInputStream inStream = new ObjectInputStream(new BufferedInputStream(new FileInputStream(file)));

			int size = inStream.readInt();
			ignoreCase = inStream.readBoolean();

			for (int i = 0; i < size; i++)
				l.add((Automaton)inStream.readObject());

			inStream.close();
		} catch (Exception e){
			System.err.println(e);
			e.printStackTrace();
			System.exit(-1);
		}
		return new Tuple<ArrayList<Automaton>, Boolean>(l, ignoreCase);
	}

	static void storeArray(File file, ArrayList<Automaton> l, boolean ignoreCase) {
		try {
			ObjectOutputStream outStream = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(file)));

			outStream.writeInt(l.size());
			outStream.writeBoolean(ignoreCase);

			for (int i = 0; i < l.size(); i++){
				outStream.writeObject(l.get(i));
			}

			outStream.close();

		} catch (Exception e){
			System.err.println(e);
			e.printStackTrace();
			System.exit(-1);
		}
	}

	public static void storeVariants(File file, PreparedStatement pstmt, List<Automaton> automatons,
			Logger logger, int report) {
		try{
			BufferedWriter outStream = file != null ? new BufferedWriter(new FileWriter(file)) : null;

			Pattern splitter = Pattern.compile(""+CustomRunAutomaton.delimiter);
			int c = 0;
			logger.info("%t: Starting automaton conversion.\n");
			for (Automaton a : automatons){
				Set<String> variants = a.getFiniteStrings();

				if (variants == null)
					throw new IllegalStateException("Non-finite automaton detected - this cannot be converted");

				if (variants.size() == 0)
					System.err.println("0");

				for (String v : variants){
					String[] parts = splitter.split(v);

					if (parts.length != 2)
						throw new IllegalStateException("parts.length == " + parts.length);

					if (outStream != null)
						outStream.write(parts[1] + "\t" + parts[0] + "\n");
					if (pstmt != null){
						pstmt.setString(1, parts[1]);
						pstmt.setString(2, parts[0]);
						pstmt.setNull(3, java.sql.Types.NULL);
						pstmt.addBatch();
					}
				}

				if (pstmt != null)
					pstmt.executeBatch();

				if (report != -1 && ++c % report == 0)
					logger.info("%t: Converted " + c + " automatons to variants.\n");
			}

			if (outStream != null)
				outStream.close();

			logger.info("%t: Completed.\n");
		} catch (Exception e){
			System.err.println(e);
			e.printStackTrace();
			System.exit(-1);
		}
	}
}


text:
//
//  AirViewAppDelegate_iPhone.m
//  AirView
//
//  Created by Clément Vasseur on 12/18/10.
//  Copyright 2010 Clément Vasseur. All rights reserved.
//

#import "AirViewAppDelegate_iPhone.h"

@implementation AirViewAppDelegate_iPhone

#pragma mark -
#pragma mark Application lifecycle

/**
 Superclass implementation saves changes in the application's managed object context before the application terminates.
 */
- (void)applicationWillTerminate:(UIApplication *)application {
	[super applicationWillTerminate:application];
}

#pragma mark -
#pragma mark Memory management

- (void)dealloc {
	[super dealloc];
}

@end


text:
/**
 * Created by usucuha on 2/19/14.
 */

function doValidation() {
    var EncounterTable = Parse.Object.extend('EncounterTable');
    var query = new Parse.Query(EncounterTable);
    query.find({
        success: function(results) {
            for (var i = 0; i < results.length; i++) {
                var table = results[i];
                getDungeonEncounterTable(table.get('name'), undefined, function(table, callback) {
                    for (var j = 0; j < table._items.length; j++) {
                        checkForMonster(table.getName(), table._items[j]['name']);
                    }
                });
            }
        }
    });
}

function checkForMonster(tableName, monsterName) {
    var innerQuery = new Parse.Query("monsters");
    innerQuery.equalTo('name', monsterName);
    innerQuery.first({
        success: function(result) {
            if (result == undefined) {
                console.log(monsterName + ' not found in ' + tableName);
            } else {
//                console.log('found ' + result.get('name'));
            }
        },
        error: function(error) {
            console.log("Error: " + error.code + " " + error.message);
        }
    })
}


text:
layout: default
---

{{ page.title }}

      {% if page.author %}

 By {{ page.author }}

      {%  endif %}

    {{ content }}


text:
// $Id: ZlibOutputStream.java 105 2007-08-07 07:45:45Z pornin $

package org.bolet.jgz;

import java.io.InputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 *
This class implements a stream which compresses data into the
 * zlib format (RFC 1950).

 *
 *
The compression level can be specified, as a symbolic value
 * identical to what the Deflater class expects. The
 * default compression level is MEDIUM.

 *
 * @version   $Revision: 105 $
 * @author    Thomas Pornin
 */

public class ZlibOutputStream extends OutputStream {

	private OutputStream out;
	private Deflater deflater;
	private byte[] oneByte;
	private Adler32 adler;
	private int level;
	private boolean hasDictionary;
	private int dictID;
	private boolean headerWritten;

	/**
	 * Create the stream with the provided transport stream. The
	 * default compression level (MEDIUM) is used.
	 *
	 * @param out   the transport stream
	 * @throws IOException  on I/O error with the transport stream
	 */
	public ZlibOutputStream(OutputStream out)
		throws IOException
	{
		this(out, Deflater.MEDIUM);
	}

	/**
	 * Create the stream with the provided transport stream. The
	 * provided compression level is used.
	 *
	 * @param out     the transport stream
	 * @param level   the compression level
	 * @throws IOException  on I/O error with the transport stream
	 */
	public ZlibOutputStream(OutputStream out, int level)
		throws IOException
	{
		this.out = out;
		this.level = level;
		deflater = new Deflater(level);
		deflater.setOut(out);
		oneByte = new byte[1];
		adler = new Adler32();
	}

	/**
	 * Process a dictionary: the stream contents are used as
	 * dictionary.
	 *
	 * @param dict   the dictionary stream
	 * @throws IOException  on I/O error with dict
	 */
	public void processDictionary(InputStream dict)
		throws IOException
	{
		byte[] buf = new byte[4096];
		Adler32 da = new Adler32();
		for (;;) {
			int rlen = dict.read(buf);
			if (rlen < 0)
				break;
			deflater.processDictionary(buf, 0, rlen);
			da.update(buf, 0, rlen);
		}
		hasDictionary = true;
		dictID = da.getSum();
	}

	/**
	 * Process a dictionary: the buffer contents are used as
	 * dictionary.
	 *
	 * @param dict   the dictionary
	 */
	public void processDictionary(byte[] dict)
	{
		processDictionary(dict, 0, dict.length);
	}

	/**
	 * Process a dictionary: the buffer contents are used as
	 * dictionary.
	 *
	 * @param dict   the dictionary
	 * @param off    the dictionary offset
	 * @param len    the dictionary length
	 */
	public void processDictionary(byte[] dict, int off, int len)
	{
		deflater.processDictionary(dict, off, len);
		hasDictionary = true;
		Adler32 da = new Adler32();
		da.update(dict, off, len);
		dictID = da.getSum();
	}

	/**
	 * Write out a 32-bit integer on the stream (big-endian).
	 *
	 * @param v   the value
	 * @throws IOException  on I/O error with the transport stream
	 */
	private void writes4(int v)
		throws IOException
	{
		out.write(v >>> 24);
		out.write(v >>> 16);
		out.write(v >>> 8);
		out.write(v);
	}

	/**
	 * Write out the header, if needed.
	 *
	 * @throws IOException  on I/O error with the transport stream
	 */
	private void writeHeader()
		throws IOException
	{
		if (headerWritten)
			return;

		/*
		 * Compression method = 8 (DEFLATE).
		 * Compression info = 7 (window length = 2^15).
		 */
		int cmf = 8 + (7 << 4);

		/*
		 * Flags.
		 */
		int flags;
		switch (level) {
		case Deflater.HUFF:
			flags = 0;
			break;
		case Deflater.SPEED:
			flags = 1;
			break;
		case Deflater.MEDIUM:
			flags = 2;
			break;
		case Deflater.COMPACT:
			flags = 3;
			break;
		default:
			flags = 2;
			break;
		}
		flags <<= 6;
		if (hasDictionary)
			flags |= (1 << 5);
		int rem = ((cmf << 8) | flags) % 31;
		if (rem > 0)
			flags += (31 - rem);

		out.write(cmf);
		out.write(flags);
		if (hasDictionary)
			writes4(dictID);
		headerWritten = true;
	}

	/**
	 * Close this stream; the transport stream is also closed.
	 *
	 * @throws IOException  on I/O error with the transport stream
	 */
	public void close()
		throws IOException
	{
		terminate();
		out.close();
	}

	/**
	 * Close the compression stream but do not
	 * close the transport stream. All bytes which constitute the
	 * zlib file are written on the transport stream
	 * (but the transport stream itself is not flushed).
	 *
	 * @throws IOException  on I/O error with the transport stream
	 */
	public void terminate()
		throws IOException
	{
		writeHeader();
		deflater.terminate();
		writes4(adler.getSum());
	}

	/**
	 * Flush this stream; the transport stream is also flushed. At
	 * the DEFLATE level, a "sync flush" is performed, which ensures
	 * that output bytes written so far on the transport stream are
	 * sufficient to recover all the input bytes currently processed.
	 *
	 * @throws IOException  on I/O error with the transport stream
	 */
	public void flush()
		throws IOException
	{
		flushSync(true);
	}

	/**
	 * Flush this stream; the transport stream is also flushed. At
	 * the DEFLATE level, a "sync flush" is performed, with the
	 * provided value for withData.
	 *
	 * @param withData   false to omit the 00 00 FF FF bytes
	 * @throws IOException  on I/O error with the transport stream
	 */
	public void flushSync(boolean withData)
		throws IOException
	{
		writeHeader();
		deflater.flushSync(withData);
		deflater.getOut().flush();
	}

	/**
	 * Flush this stream; the transport stream is also flushed. At
	 * the DEFLATE level, a "full flush" is performed, with the
	 * provided value for withData.
	 *
	 * @param withData   false to omit the 00 00 FF FF bytes
	 * @throws IOException  on I/O error with the transport stream
	 */
	public void flushFull(boolean withData)
		throws IOException
	{
		writeHeader();
		deflater.flushFull(withData);
		deflater.getOut().flush();
	}

	/**
	 * Flush this stream; the transport stream is also flushed. At
	 * the DEFLATE level, a "partial flush" is performed.
	 *
	 * @throws IOException  on I/O error with the transport stream
	 */
	public void flushPartial()
		throws IOException
	{
		writeHeader();
		deflater.flushPartial();
		deflater.getOut().flush();
	}

	/** @see OutputStream */
	public void write(int b)
		throws IOException
	{
		oneByte[0] = (byte)b;
		write(oneByte, 0, 1);
	}

	/** @see OutputStream */
	public void write(byte[] buf)
		throws IOException
	{
		write(buf, 0, buf.length);
	}

	/** @see OutputStream */
	public void write(byte[] buf, int off, int len)
		throws IOException
	{
		writeHeader();
		deflater.process(buf, off, len);
		adler.update(buf, off, len);
	}
}


text:
<?php

namespace System;

/**
 * An exception for an invalid argument.
 *
 * @package System
 * @author Marcel Joachim Kloubert <marcel.kloubert@gmx.net>
 */
class ArgumentException extends Exception {
    /**
     * @var string
     */
    private $_paramName;

    /**
     * Initializes a new instance of that class.
     *
     * @param string $paramName The name of the underlying parameter.
     * @param string $message The message.
     * @param int $code The code.
     * @param \Exception $innerException The inner exception.
     */
    public function __construct($paramName = null,
                                $message = null, \Exception $innerException = null, int $code = 0) {

        $this->_paramName = ClrString::valueToString($paramName, false);

        parent::__construct($message, $innerException, $code);
    }

    /**
     * Gets the name of the underlying parameter.
     *
     * @return string The name of the underlying parameter.
     */
    public final function paramName() {
        return $this->_paramName;
    }
}


text:
<?php

require_once __DIR__.'/../vendor/autoload.php';

\PHPUnit_Extensions_Selenium2TestCase::shareSession(true);