text:
<?php

declare(strict_types=1);

namespace ApiPlatform\Core\Tests\Fixtures\TestBundle\Document;

use ApiPlatform\Core\Annotation\ApiProperty;
use ApiPlatform\Core\Annotation\ApiResource;
use ApiPlatform\Core\Tests\Fixtures\TestBundle\Filter\ArrayItemsFilter;
use ApiPlatform\Core\Tests\Fixtures\TestBundle\Filter\BoundsFilter;
use ApiPlatform\Core\Tests\Fixtures\TestBundle\Filter\EnumFilter;
use ApiPlatform\Core\Tests\Fixtures\TestBundle\Filter\LengthFilter;
use ApiPlatform\Core\Tests\Fixtures\TestBundle\Filter\MultipleOfFilter;
use ApiPlatform\Core\Tests\Fixtures\TestBundle\Filter\PatternFilter;
use ApiPlatform\Core\Tests\Fixtures\TestBundle\Filter\RequiredAllowEmptyFilter;
use ApiPlatform\Core\Tests\Fixtures\TestBundle\Filter\RequiredFilter;
use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;

/**
 * Filter Validator entity.
 *
 * @author Julien Deniau <julien.deniau@gmail.com>
 * @author Alan Poulain <contact@alanpoulain.eu>
 *
 * @ApiResource(attributes={
 *     "filters"={
 *         ArrayItemsFilter::class,
 *         BoundsFilter::class,
 *         EnumFilter::class,
 *         LengthFilter::class,
 *         MultipleOfFilter::class,
 *         PatternFilter::class,
 *         RequiredFilter::class,
 *         RequiredAllowEmptyFilter::class
 *     }
 * })
 * @ODM\Document
 */
class FilterValidator
{
    /**
     * @var int The id
     *
     * @ODM\Id(strategy="INCREMENT", type="integer")
     */
    private $id;

    /**
     * @var string A name
     *
     * @ODM\Field
     * @ApiProperty(iri="http://schema.org/name")
     */
    private $name;

    public function getId()
    {
        return $this->id;
    }

    public function setName($name)
    {
        $this->name = $name;
    }

    public function getName()
    {
        return $this->name;
    }
}


text:
require_relative '../../spec_helper'
require_relative 'fixtures/classes'

describe "Numeric#real" do
  before :each do
    @numbers = [
      20,             # Integer
      398.72,         # Float
      Rational(3, 4), # Rational
      bignum_value,   # Bignum
      infinity_value,
      nan_value
    ].map{ |n| [n, -n] }.flatten
  end

  it "returns self" do
    @numbers.each do |number|
      if number.to_f.nan?
        number.real.nan?.should be_true
      else
        number.real.should == number
      end
    end
  end

  it "raises an ArgumentError if given any arguments" do
    @numbers.each do |number|
      -> { number.real(number) }.should raise_error(ArgumentError)
    end
  end
end

describe "Numeric#real?" do
  it "returns true" do
    NumericSpecs::Subclass.new.should.real?
  end
end

redpajama_set_name: RedPajamaGithub


text:
import os
import imp
from distutils.core import setup

PKG_DIR = 'pathtools'
version = imp.load_source('version',
                          os.path.join(PKG_DIR, 'version.py'))

def read_file(filename):
    """
    Reads the contents of a given file relative to the directory
    containing this file and returns it.

    :param filename:
        The file to open and read contents from.
    """
    return open(os.path.join(os.path.dirname(__file__), filename)).read()

setup(name='pathtools',
      version=version.VERSION_STRING,
      description='File system general utilities',
      long_description=read_file('README'),
      author="Yesudeep Mangalapilly",
      author_email="yesudeep@gmail.com",
      license="MIT License",
      url="http://github.com/gorakhargosh/pathtools",
      classifiers=[
          'Development Status :: 3 - Alpha',
          'Intended Audience :: Developers',
          'License :: OSI Approved :: MIT License',
          'Natural Language :: English',
          'Operating System :: OS Independent',
          'Programming Language :: Python',
          'Programming Language :: Python :: 2',
          'Topic :: Software Development :: Libraries',
          'Topic :: System :: Filesystems',
          'Topic :: Utilities',
          ],
      packages=['pathtools']
      )


text:
//
//  MICViewController.h
//  MadeInChina
//
//  Created by mac on 13-9-9.
//  Copyright (c) 2013年 mac. All rights reserved.
//

/*!
 @header
 @abstract MICViewController
 */

#import <UIKit/UIKit.h>
#import "UIViewController+MadeInChina.h"

///完成操作
typedef void (^MICCompletionBlock)(void);

/*!
 @class
 @abstract MICViewController父类.(废弃)
 @discussion 不建议继承.
 */
@interface MICViewController : UIViewController

@end


text:
namespace inet {

EXECUTE_ON_STARTUP(
        cEnum * e = cEnum::find("inet::ChooseDestAddrMode");
        if (!e)
            enums.getInstance()->add(e = new cEnum("inet::ChooseDestAddrMode"));
        e->insert(UDPBasicBurst::ONCE, "once");
        e->insert(UDPBasicBurst::PER_BURST, "perBurst");
        e->insert(UDPBasicBurst::PER_SEND, "perSend");
        );

Define_Module(UDPBasicBurst);

int UDPBasicBurst::counter;

simsignal_t UDPBasicBurst::sentPkSignal = registerSignal("sentPk");
simsignal_t UDPBasicBurst::rcvdPkSignal = registerSignal("rcvdPk");
simsignal_t UDPBasicBurst::outOfOrderPkSignal = registerSignal("outOfOrderPk");
simsignal_t UDPBasicBurst::dropPkSignal = registerSignal("dropPk");

UDPBasicBurst::~UDPBasicBurst()
{
    cancelAndDelete(timerNext);
}

void UDPBasicBurst::initialize(int stage)
{
    ApplicationBase::initialize(stage);

    if (stage == INITSTAGE_LOCAL) {
        counter = 0;
        numSent = 0;
        numReceived = 0;
        numDeleted = 0;
        numDuplicated = 0;

        delayLimit = par("delayLimit");
        startTime = par("startTime");
        stopTime = par("stopTime");
        if (stopTime >= SIMTIME_ZERO && stopTime <= startTime)
            throw cRuntimeError("Invalid startTime/stopTime parameters");

        messageLengthPar = &par("messageLength");
        burstDurationPar = &par("burstDuration");
        sleepDurationPar = &par("sleepDuration");
        sendIntervalPar = &par("sendInterval");
        nextSleep = startTime;
        nextBurst = startTime;
        nextPkt = startTime;

        destAddrRNG = par("destAddrRNG");
        const char *addrModeStr = par("chooseDestAddrMode").stringValue();
        int addrMode = cEnum::get("inet::ChooseDestAddrMode")->lookup(addrModeStr);
        if (addrMode == -1)
            throw cRuntimeError("Invalid chooseDestAddrMode: '%s'", addrModeStr);
        chooseDestAddrMode = (ChooseDestAddrMode)addrMode;

        WATCH(numSent);
        WATCH(numReceived);
        WATCH(numDeleted);
        WATCH(numDuplicated);

        localPort = par("localPort");
        destPort = par("destPort");

        timerNext = new cMessage("UDPBasicBurstTimer");
    }
}

L3Address UDPBasicBurst::chooseDestAddr()
{
    if (destAddresses.size() == 1)
        return destAddresses[0];

    int k = getRNG(destAddrRNG)->intRand(destAddresses.size());
    return destAddresses[k];
}

cPacket *UDPBasicBurst::createPacket()
{
    char msgName[32];
    sprintf(msgName, "UDPBasicAppData-%d", counter++);
    long msgByteLength = messageLengthPar->longValue();
    ApplicationPacket *payload = new ApplicationPacket(msgName);
    payload->setByteLength(msgByteLength);
    payload->setSequenceNumber(numSent);
    payload->addPar("sourceId") = getId();
    payload->addPar("msgId") = numSent;

    return payload;
}

void UDPBasicBurst::processStart()
{
    socket.setOutputGate(gate("udpOut"));
    socket.bind(localPort);

    const char *destAddrs = par("destAddresses");
    cStringTokenizer tokenizer(destAddrs);
    const char *token;
    bool excludeLocalDestAddresses = par("excludeLocalDestAddresses").boolValue();

    IInterfaceTable *ift = getModuleFromPar<IInterfaceTable>(par("interfaceTableModule"), this);

    while ((token = tokenizer.nextToken()) != nullptr) {
        if (strstr(token, "Broadcast") != nullptr)
            destAddresses.push_back(IPv4Address::ALLONES_ADDRESS);
        else {
            L3Address addr = L3AddressResolver().resolve(token);
            if (excludeLocalDestAddresses && ift && ift->isLocalAddress(addr))
                continue;
            destAddresses.push_back(addr);
        }
    }

    nextSleep = simTime();
    nextBurst = simTime();
    nextPkt = simTime();
    activeBurst = false;

    isSource = !destAddresses.empty();

    if (isSource) {
        if (chooseDestAddrMode == ONCE)
            destAddr = chooseDestAddr();

        activeBurst = true;
    }
    timerNext->setKind(SEND);
    processSend();
}

void UDPBasicBurst::processSend()
{
    if (stopTime < SIMTIME_ZERO || simTime() < stopTime) {
        // send and reschedule next sending
        if (isSource) // if the node is a sink, don't generate messages
            generateBurst();
    }
}

void UDPBasicBurst::processStop()
{
    socket.close();
}

void UDPBasicBurst::handleMessageWhenUp(cMessage *msg)
{
    if (msg->isSelfMessage()) {
        switch (msg->getKind()) {
            case START:
                processStart();
                break;

            case SEND:
                processSend();
                break;

            case STOP:
                processStop();
                break;

            default:
                throw cRuntimeError("Invalid kind %d in self message", (int)msg->getKind());
        }
    }
    else if (msg->getKind() == UDP_I_DATA) {
        // process incoming packet
        processPacket(PK(msg));
    }
    else if (msg->getKind() == UDP_I_ERROR) {
        EV_WARN << "Ignoring UDP error report\n";
        delete msg;
    }
    else {
        throw cRuntimeError("Unrecognized message (%s)%s", msg->getClassName(), msg->getName());
    }

    if (hasGUI()) {
        char buf[40];
        sprintf(buf, "rcvd: %d pks\nsent: %d pks", numReceived, numSent);
        getDisplayString().setTagArg("t", 0, buf);
    }
}

void UDPBasicBurst::processPacket(cPacket *pk)
{
    if (pk->getKind() == UDP_I_ERROR) {
        EV_WARN << "UDP error received\n";
        delete pk;
        return;
    }

    if (pk->hasPar("sourceId") && pk->hasPar("msgId")) {
        // duplicate control
        int moduleId = (int)pk->par("sourceId");
        int msgId = (int)pk->par("msgId");
        auto it = sourceSequence.find(moduleId);
        if (it != sourceSequence.end()) {
            if (it->second >= msgId) {
                EV_DEBUG << "Out of order packet: " << UDPSocket::getReceivedPacketInfo(pk) << endl;
                emit(outOfOrderPkSignal, pk);
                delete pk;
                numDuplicated++;
                return;
            }
            else
                it->second = msgId;
        }
        else
            sourceSequence[moduleId] = msgId;
    }

    if (delayLimit > 0) {
        if (simTime() - pk->getTimestamp() > delayLimit) {
            EV_DEBUG << "Old packet: " << UDPSocket::getReceivedPacketInfo(pk) << endl;
            emit(dropPkSignal, pk);
            delete pk;
            numDeleted++;
            return;
        }
    }

    EV_INFO << "Received packet: " << UDPSocket::getReceivedPacketInfo(pk) << endl;
    emit(rcvdPkSignal, pk);
    numReceived++;
    delete pk;
}

void UDPBasicBurst::generateBurst()
{
    simtime_t now = simTime();

    if (nextPkt < now)
        nextPkt = now;

    double sendInterval = sendIntervalPar->doubleValue();
    if (sendInterval <= 0.0)
        throw cRuntimeError("The sendInterval parameter must be bigger than 0");
    nextPkt += sendInterval;

    if (activeBurst && nextBurst <= now) {    // new burst
        double burstDuration = burstDurationPar->doubleValue();
        if (burstDuration < 0.0)
            throw cRuntimeError("The burstDuration parameter mustn't be smaller than 0");
        double sleepDuration = sleepDurationPar->doubleValue();

        if (burstDuration == 0.0)
            activeBurst = false;
        else {
            if (sleepDuration < 0.0)
                throw cRuntimeError("The sleepDuration parameter mustn't be smaller than 0");
            nextSleep = now + burstDuration;
            nextBurst = nextSleep + sleepDuration;
        }

        if (chooseDestAddrMode == PER_BURST)
            destAddr = chooseDestAddr();
    }

    if (chooseDestAddrMode == PER_SEND)
        destAddr = chooseDestAddr();

    cPacket *payload = createPacket();
    payload->setTimestamp();
    emit(sentPkSignal, payload);
    socket.sendTo(payload, destAddr, destPort);
    numSent++;

    // Next timer
    if (activeBurst && nextPkt >= nextSleep)
        nextPkt = nextBurst;

    if (stopTime >= SIMTIME_ZERO && nextPkt >= stopTime) {
        timerNext->setKind(STOP);
        nextPkt = stopTime;
    }
    scheduleAt(nextPkt, timerNext);
}

void UDPBasicBurst::finish()
{
    recordScalar("Total sent", numSent);
    recordScalar("Total received", numReceived);
    recordScalar("Total deleted", numDeleted);
    ApplicationBase::finish();
}

bool UDPBasicBurst::handleNodeStart(IDoneCallback *doneCallback)
{
    simtime_t start = std::max(startTime, simTime());

    if ((stopTime < SIMTIME_ZERO) || (start < stopTime) || (start == stopTime && startTime == stopTime)) {
        timerNext->setKind(START);
        scheduleAt(start, timerNext);
    }

    return true;
}

bool UDPBasicBurst::handleNodeShutdown(IDoneCallback *doneCallback)
{
    if (timerNext)
        cancelEvent(timerNext);
    activeBurst = false;
    //TODO if(socket.isOpened()) socket.close();
    return true;
}

void UDPBasicBurst::handleNodeCrash()
{
    if (timerNext)
        cancelEvent(timerNext);
    activeBurst = false;
}

} // namespace inet


text:
package messengers.actions;

import static jalse.attributes.Attributes.STRING_TYPE;
import static jalse.attributes.Attributes.newTypeOf;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;

import jalse.actions.Action;
import jalse.actions.ActionContext;
import jalse.attributes.AttributeContainer;
import jalse.attributes.DefaultAttributeContainer;
import jalse.entities.Entity;
import jalse.entities.EntityContainer;
import messengers.entities.Messenger;

public class SendMessage implements Action<Entity> {

    private static final List<String> WORDS = Arrays.asList("Hello", "friend", "I", "am", "talking", "to", "you");

    private static String createText() {
	final StringBuilder text = new StringBuilder();
	final Random r = ThreadLocalRandom.current();

	for (int i = 0; i < 5; i++) {
	    text.append(WORDS.get(r.nextInt(WORDS.size()))).append(' ');
	}

	return text.replace(text.length() - 1, text.length(), ".").toString();
    }

    private final UUID to;

    public SendMessage(final UUID to) {
	// Recipient
	this.to = Objects.requireNonNull(to);
    }

    @Override
    public void perform(final ActionContext<Entity> context) {
	// Actor this action was for
	final Entity actor = context.getActor();

	// Creates random 'sentence'
	final String text = createText();
	System.out.println(String.format("%s -> %s: %s", actor.getID(), to, text));

	// Get parent JALSE
	final EntityContainer container = actor.getContainer();
	// Get recipient messenger
	final Messenger recipient = container.getEntityAsType(to, Messenger.class);

	// Create message contents
	final AttributeContainer contents = new DefaultAttributeContainer();
	contents.setAttribute("text", STRING_TYPE, text);
	contents.setAttribute("from", newTypeOf(UUID.class), actor.getID());

	// Create the message and trigger response
	recipient.newMessage(contents);
    }
}


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

namespace PCU.Librerias.EntidadesNegocio
{
    public class bePersonaGrid
    {
        public int PersonaId { get; set; }
        public string NombreRazonSocial { get; set; }
        public string ApellidoPaterno { get; set; }
        public string ApellidoMaterno { get; set; }
        public string TipoDocumento { get; set; }
        public string NumeroDocumento { get; set; }
        public bool IndicadorCliente { get; set; }
        public string EstadoPersona { get; set; }
    }
}


text:
name: Orange trees at Los Angeles State Historic Park
address_1: 1245 North Spring Street
address_2:
city: Los Angeles
state: CA
zip: 90012
latitude: 34.067136
longitude: -118.232630
category: Orchard
website: http://lashp.com/2017/05/12/fallen-fruit-a-monument-to-sharing/
phone:
title: Orange trees at Los Angeles State Historic Park, Food Oasis Los Angeles
uri: /locations/orange-trees-at-los-angeles-state-historic-park/
---
This is a group of orange trees, planted as part of the [Endless Orchard](http://endlessorchard.com) project by [Fallen Fruit](http://fallenfruit.org).

From the website…

> "The oranges are for everyone to share."


text:
using System;
using System.Reflection;
using NUnit.Common;
using NUnitLite;

namespace Mono.Posix.Test
{
    class Program
    {
        static int Main(string[] args)
        {
            return new AutoRun(typeof(Program).GetTypeInfo().Assembly)
                .Execute(args, new ExtendedTextWrapper(Console.Out), Console.In);
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project>
  <import file="build_transtype-html2.xml"/>
</project>


text:
namespace PinnedDownClient
{
	namespace Systems
	{
		namespace Screens
		{
			enum ScreenName
			{
				Login,
				Game
			};
		}
	}
}


text:
require 'faraday'
require 'faraday_middleware'

module HttpEventstore
  module Api
    class ErrorsHandler < Faraday::Response::Middleware

      def on_complete(env)
        code = env[:status]
        case code
          when (400..499)
            raise ClientError.new(code)
          when (500..599)
            raise ServerError.new(code)
        end
      end
    end
  end
end


text:
Module Name: Office365Connect
Module Guid: 80168612-0c36-42bd-9f69-e6a4eeda33d1
Download Help Link: https://github.com/PhilipHaglund/Office365Connect/tree/master/docs
Help Version: 1.0.0
Locale: en-US
---

# Office365Connect Module
## Description
Office365Connect is a module to connect to all Office 365 services that offer a way in with PowerShell.

## Office365Connect Cmdlets
### [Connect-Office365](Connect-Office365.md)
Connect to one or more Office 365 services using Powershell.

### [Disconnect-Office365](Disconnect-Office365.md)
Disconnect from one or more Office 365 services using Powershell.


text:
import { ActivatedRouteSnapshot } from '@angular/router';
import { OrganizationManagementResolve } from 'app/admin/organization-management/organization-management-resolve.service';
import { OrganizationManagementService } from 'app/admin/organization-management/organization-management.service';
import { Organization } from 'app/entities/organization.model';
import { of } from 'rxjs';

describe('OrganizationManagementResolve', () => {
    let organizationManagementService: OrganizationManagementService;
    let organizationManagementResolve: OrganizationManagementResolve;

    beforeEach(() => {
        organizationManagementService = { getOrganizationById: jest.fn() } as any as OrganizationManagementService;
        organizationManagementResolve = new OrganizationManagementResolve(organizationManagementService);
    });

    it('should search for organization by id', () => {
        const toReturn = new Organization();
        const spy = jest.spyOn(organizationManagementService, 'getOrganizationById').mockReturnValue(of(toReturn));

        let result = undefined;
        // @ts-ignore
        organizationManagementResolve.resolve({ params: { id: 1 } } as any as ActivatedRouteSnapshot).subscribe((org) => (result = org));
        expect(result).toBe(toReturn);
        expect(spy).toHaveBeenCalledTimes(1);
        expect(spy).toHaveBeenCalledWith(1);
    });

    it('should return new organization if no id is given', () => {
        const toReturn = new Organization();
        const spy = jest.spyOn(organizationManagementService, 'getOrganizationById').mockReturnValue(of(toReturn));

        const result = organizationManagementResolve.resolve({ params: { id: undefined } } as any as ActivatedRouteSnapshot);
        expect(result).not.toBe(toReturn);
        expect(result).toBeInstanceOf(Organization);
        expect(spy).not.toHaveBeenCalled();
    });
});


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="Hello">Hello World, Click Me!</string>
    <string name="ApplicationName">WhatTheMovie</string>
  <string-array name="planets_array">
    <item>Mercury</item>
    <item>Venus</item>
    <item>Earth</item>
    <item>Mars</item>
    <item>Jupiter</item>
    <item>Saturn</item>
    <item>Uranus</item>
    <item>Neptune</item>
  </string-array>
  <string name="drawer_open">Open navigation drawer</string>
  <string name="drawer_close">Close navigation drawer</string>
  <string name="action_websearch">Web search</string>
  <string name="app_not_available">Sorry, there\'s no web browser available</string>
</resources>


text:
<?php $iainPageTitle = 'Angular Testing'; $docDepth = 1;?>
<?php include '../partials/head.php'; ?>

Testing overview

Each test is contained in a Test block:

describe('Unit: MainController', function() {
  // Our tests will go here
})

Within the block we need to give the test a few things:

The module, beforeEach(module('myApp'));, which contains the controller we're looking for

A manually instantiated controller and scope object

var ctrl, scope;
  // inject the $controller and $rootScope services
  // in the beforeEach block
  beforeEach(inject(function($controller, $rootScope) {
    // Create a new scope that's a child of the $rootScope
    scope = $rootScope.$new();
    // Create the controller
    ctrl = $controller('MainController', {
      $scope: scope
    });
  }));

A test!

it('describe what the function you are testing should do',
    function() {
      expect(something).toBeUndefined(); //or whatever!
      scope.doTheFunction();
      expect(something).toEqual("perfection"); //or whatever!
  });

Thanks to ng-newsletter for a more in depth tutorial on testing Angular with Karma!

In more detail: Jasmine

Every test suite begins with describe() taking a descriptive string and a function containing the tests.

Every test is wrapped with it() which again takes a descriptive string and a funciton which is the test.

BDD style would have the strings of describe()
	followed by it() form a full sentence, for example:

describe("A spec using beforeEach and afterEach", function() {
	...
	it("is just a function, so it can contain any code", function() {
		...
	});

	it("can have more than one expectation", function() {
		...
	});
}

Tests are made up of expect(input) followed by a matcher function which informs Jasmine what the input should be. Any failing expectation fails the whole test.

matcher functions:The full list for each version of Jasmine are, as you might expect, included in the Docs.  But here are some anyway:

expect(a).toBe(b) compares with ===

.not.toBe(null);

.toEqual(12); simple literals and variables

.toMatch(/bar/); regular expressions

.not.toMatch("bars");

.toBeDefined(); checks against 'undefined'

.not.toBeDefined();

.not.toBeUndefined();

.toBeUndefined();

.toBeNull();

.not.toBeNull();

.toBeTruthy(); for boolean casting

.toContain("bar"); finds an item in an array

.not.toContain("quux");

.toBeLessThan(pi);

.not.toBeLessThan(e);

.toBeGreaterThan(e);

.not.toBeGreaterThan(pi);

.toThrow(); to test if a function throws an exception

.not.toThrow();

Setup and Teardown: a few handy functions to prepare the context (variables defined on the describe scope),

beforeEach(function(){ ... };)

afterEach

beforeAll

afterAll

this is an empty object on the describe scope, it is set to empty for each block of tests,
	we can use it to share objects between it's, this.value = "sharedThing";

Nested Describe are possible! And work with beforeEach and whatnot

Disabling suites so as to skip them: xdescribe and xit

Pending functions will show up as pending if:

xit

pending(); is called within it()

it('doesn't have a function')

Spies: checking up on calls, their arguments, return values, exceptions thrown...

In these examples,

obj = {
	functionName: function(value) {
		bar = value;
	}
}

spyOn(obj, 'functionName') allows us to spy on the function

expect(obj.functionName).toHaveBeenCalled() true if obj.functionName was called

expect(obj.method).toHaveBeenCalledWith('foo', 'bar') can be called at seperate times with each arg

obj.method.callCount number of times it was called

obj.method.mostRecentCall.args args to the most recent call

obj.method.reset() resets calles made to the spy

spyOn(obj, 'functionName').and.callThrough(); The spy method also calls through the real method? not sure what this is

spyOn(obj, 'functionName').and.returnValue(745); every call the functionName will return 745

spyOn(obj, "functionName").and.callFake(function() {
      return 1001;
    });

    like returnValue but allows us to write a function in place

spyOn(obj, 'functionName').and.throwError("errorName");

obj.method.and.stub(); //not sure

Calls to functions that we ae spying on are tracked by the calls property, it's an array:

.calls.any() returns true if the function has been called at least once

.calls.count() what it says on the tin!

.calls.argsFor(index) index number of the call you're interested in, returns the args it was passed

.calls.allArgs() all the args sent to your function ever (in this suite)

.calls.all() //not too sure

.calls.first() returns the first call and it's details

.calls.reset() resets the tracking!

jasmine.any matches the class, eg expect(foo).toHaveBeenCalledWith(jasmine.any(Number), jasmine.any(Function));

jasmine.objectContaining({ bar: "baz" }) returns true if the object containes this pair

Manipulating time:

To set up we must have jasmine.clock().install;, usually in beforeEach(), followed by jasmine.clock().uninstall();
in afterEach().  Good example from the docs:

it("causes a timeout to be called synchronously", function() {
	setTimeout(function() {
		timerCallback();
	}, 100);

	expect(timerCallback).not.toHaveBeenCalled();

	jasmine.clock().tick(101);

	expect(timerCallback).toHaveBeenCalled();
});

Mock the date:

var baseTime = new Date(2013, 9, 23);
jasmine.clock().mockDate(baseTime);

It does asyncronous! but I don't understand the docs at the moment

<?php $footerAddress = (ltrim($homePath,'"')) . 'partials/footer.php'; ?>
<?php include $footerAddress; ?>


text:
import {assert} from '@open-wc/testing';
import '../test/common-test-setup';
import {getUserDashboard} from './dashboard-util';

suite('gr-navigation tests', () => {
  suite('_getUserDashboard', () => {
    const sections = [
      {name: 'section 1', query: 'query 1'},
      {name: 'section 2', query: 'query 2 for ${user}'},
      {name: 'section 3', query: 'self only query', selfOnly: true},
      {name: 'section 4', query: 'query 4', suffixForDashboard: 'suffix'},
    ];

    test('dashboard for self', () => {
      const dashboard = getUserDashboard('self', sections, 'title');
      assert.deepEqual(dashboard, {
        title: 'title',
        sections: [
          {name: 'section 1', query: 'query 1'},
          {name: 'section 2', query: 'query 2 for self'},
          {
            name: 'section 3',
            query: 'self only query',
            selfOnly: true,
          },
          {
            name: 'section 4',
            query: 'query 4',
            suffixForDashboard: 'suffix',
          },
        ],
      });
    });

    test('dashboard for other user', () => {
      const dashboard = getUserDashboard('user', sections, 'title');
      assert.deepEqual(dashboard, {
        title: 'title',
        sections: [
          {name: 'section 1', query: 'query 1'},
          {name: 'section 2', query: 'query 2 for user'},
          {
            name: 'section 4',
            query: 'query 4',
            suffixForDashboard: 'suffix',
          },
        ],
      });
    });
  });
});


text:
<?php

    require get_template_directory() . '/inc/theme-options.php';

    if (($portfolio_number) && ($portfolio_style != 'shuffle')) {$max = $portfolio_number;} else {$max = -1;};
    $args = array( 'post_type'=>'portfolio', 'orderby' => $portfolio_order,'order' => 'ASC', 'numberposts' => $max );
    $portfolio = get_posts( $args );
    $total_portfolio = count($portfolio);
?>

<section id="portfolio"<?php if ( $atts['bg'] ) { ?> style="background:<?php echo $atts['bg'] ?>"<?php } ?>>
    <?php if (is_front_page()) { ?>
<?php } ?>
        <?php if ($portfolio_style == 'shuffle'){ ?>

<?php _e( 'All', 'startup-reloaded' ) ?>

                <?php
                    $args = array( 'hide_empty' => 0 );
                    $myterms = get_terms( 'portfolio-category', $args );
                    if ( ! empty( $myterms ) && ! is_wp_error( $myterms ) ){
                        foreach ( $myterms as $myterms ) {
                            echo '
slug . '">' . $myterms->name . '
';
                        }
                    }
                ?>

        <?php } ?>

        <?php if ($portfolio_style == 'shuffle'){ ?>

                <?php foreach ($portfolio as $key=> $portfolio_item) {
                    $thumbnail = wp_get_attachment_image( get_post_meta( $portfolio_item->ID, '_startup_cpt_portfolio_thumbnail_id', 1 ), 'col-3-full' );
                    $main_pic = wp_get_attachment_image( get_post_meta( $portfolio_item->ID, '_startup_cpt_portfolio_main_pic_id', 1 ), 'col-3-full' );
                    $detail_thumbnail = wp_get_attachment_image( get_post_meta( $portfolio_item->ID, '_startup_cpt_portfolio_main_pic_id', 1 ), 'col-8-full' );
                    $detail_pic = wp_get_attachment_image( get_post_meta( $portfolio_item->ID, '_startup_cpt_portfolio_main_pic_id', 1 ), 'col-8-full' );
                    $gallery  = get_post_meta( $portfolio_item->ID, '_startup_cpt_portfolio_gallery', true );
                    $short = get_post_meta( $portfolio_item->ID, '_startup_cpt_portfolio_short', true );
                    $description  = get_post_meta( $portfolio_item->ID, '_startup_cpt_portfolio_description', true );
                    $categories = get_the_terms( $portfolio_item->ID, 'portfolio-category' );
                    $client  = get_post_meta( $portfolio_item->ID, '_startup_cpt_portfolio_client', true );
                    $date  = get_post_meta( $portfolio_item->ID, '_startup_cpt_portfolio_date', true );
                    $url  = get_post_meta( $portfolio_item->ID, '_startup_cpt_portfolio_url', true );
                ?>
                    <div class="item col-xs-12 col-sm-6 col-md-4 col-lg-3" data-groups='[<?php if ( $categories ) { foreach( $categories as $category ) { print '"' . $category->slug . '",'; unset($category); } } ?>"all"]'>

                                <?php if ( $thumbnail ) { $image = $thumbnail; }
                                elseif ( $main_pic ) { $image = $main_pic; }
                                else { $image = __( 'Image missing!', 'startup-reloaded' ); } ?>
                                <?php echo $image ?>

<?php echo $portfolio_item->post_title ?>

                                    <?php if ( $short ) { echo '
' . esc_html( $short ) . '
'; } ?>

                                    <a href="#" data-toggle="modal" data-target="#myModal-<?php echo $portfolio_item->ID ?>" class="btn btn-custom btn-lg btn-block" role="button"><?php _e( 'More information', 'startup-reloaded' ) ?>

                    <div class="modal fade simple" id="myModal-<?php echo $portfolio_item->ID ?>" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">

                                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

<?php echo $portfolio_item->post_title ?>

                                            <?php if ( $gallery ) { ?>
                                                <div id="carousel-popup-<?php echo $portfolio_item->ID ?>" class="carousel slide" data-ride="carousel">

                                                        <?php $x = 1;
                                                        foreach ( $gallery as $attachment_id => $img_portfolio_main_url ) { ?>
                                                            <div class="item <?php echo ( $x==1 ) ? 'active' : '' ?>">
                                                                <?php $image = wp_get_attachment_image($attachment_id, 'col-3-crop'); ?>
                                                                <a href="#carousel-popup-<?php echo $portfolio_item->ID ?>" role="button" data-slide="next"><?php echo $image ?>

                                                        <?php $x++;
                                                        } ?>

                                                        <div class="carousel-arrow left hvr-<?php echo $slider_arrows_hover ?> hidden-xs">
                                                            <a class="left carousel-control" href="#carousel-popup-<?php echo $portfolio_item->ID ?>" role="button" data-slide="prev">

                                                        <div class="carousel-arrow right hvr-<?php echo $slider_arrows_hover ?> hidden-xs">
                                                           <a class="right carousel-control" href="#carousel-popup-<?php echo $portfolio_item->ID ?>" role="button" data-slide="next">

                                                <?php } elseif ( $detail_pic ) { $image = $detail_pic; }
                                                    elseif ( $detail_thumbnail ) { $image = $detail_thumbnail; }
                                                    else { $image = __( 'Image missing!', 'startup-reloaded' ); } ?>
                                            <?php echo $image ?>

                                            <?php if ( $description ) {
                                                    if( $auto_format_off == 1 ){
                                                        echo '
' . $description . '
';
                                                    } else {
                                                        echo '
' . wpautop( $description ) . '
';
                                                    }
                                                } ?>

                                            <?php if ($client || $date){ ?>

                                                    <?php if($client) { ?><?php _e( 'Client', 'startup-reloaded' ) ?>: <?php echo $client ?><?php } ?> <?php if($date) { ?><?php _e( 'Date', 'startup-reloaded' ) ?>: <?php echo gmdate("m/Y", $date) ?><?php } ?>

                                            <?php } ?>
                                            <?php if($url) { ?><a href="<?php echo $url ?>" class="btn btn-custom" target="_blank"><?php _e( 'Visit', 'startup-reloaded' ) ?><?php }?>

                <?php } // endforeach ?>

        <?php } else { ?>

                <?php foreach ($portfolio as $key=> $portfolio_item) {
                    $thumbnail = wp_get_attachment_image( get_post_meta( $portfolio_item->ID, '_startup_cpt_portfolio_thumbnail_id', 1 ), 'col-3-square' );
                    $main_pic = wp_get_attachment_image( get_post_meta( $portfolio_item->ID, '_startup_cpt_portfolio_main_pic_id', 1 ), 'col-3-square' );
                    $detail_thumbnail = wp_get_attachment_image( get_post_meta( $portfolio_item->ID, '_startup_cpt_portfolio_main_pic_id', 1 ), 'col-8-full' );
                    $detail_pic = wp_get_attachment_image( get_post_meta( $portfolio_item->ID, '_startup_cpt_portfolio_main_pic_id', 1 ), 'col-8-full' );
                    $gallery  = get_post_meta( $portfolio_item->ID, '_startup_cpt_portfolio_gallery', true );
                    $description  = get_post_meta( $portfolio_item->ID, '_startup_cpt_portfolio_description', true );
                    $client  = get_post_meta( $portfolio_item->ID, '_startup_cpt_portfolio_client', true );
                    $date  = get_post_meta( $portfolio_item->ID, '_startup_cpt_portfolio_date', true );
                    $url  = get_post_meta( $portfolio_item->ID, '_startup_cpt_portfolio_url', true );
                ?>

                                <?php if ( $thumbnail ) { $image = $thumbnail; }
                                elseif ( $main_pic ) { $image = $main_pic; }
                                else { $image = __( 'Image missing!', 'startup-reloaded' ); } ?>
                                <?php echo $image ?>

                                    <a href="#" data-toggle="modal" data-target="#myModal-<?php echo $portfolio_item->ID ?>">

                    <div class="modal fade simple" id="myModal-<?php echo $portfolio_item->ID ?>" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">

                                        <button type="button" class="close" data-dismiss="modal" aria-label="Close"></button>

<?php echo $portfolio_item->post_title ?>

                                            <?php if ( $detail_pic ) { $image = $detail_pic; }
                                                    elseif ( $detail_thumbnail ) { $image = $detail_thumbnail; }
                                                    else { $image = __( 'Image missing!', 'startup-reloaded' ); } ?>
                                            <?php echo $image ;?>

                                            <?php if ( $description ) {
                                                    if( $auto_format_off == 1 ){
                                                        echo '
' . $description . '
';
                                                    } else {
                                                        echo '
' . wpautop( $description ) . '
';
                                                    }
                                                } ?>

                                            <?php if ($client || $date){ ?>

                                                    <?php if($client) { ?><?php _e( 'Client', 'startup-reloaded' ) ?>: <?php echo $client ?><?php } ?> <?php if($date) { ?><?php _e( 'Date', 'startup-reloaded' ) ?>: <?php echo gmdate("m/Y", $date) ?><?php } ?>

                                            <?php } ?>
                                            <?php if($url) { ?><a href="<?php echo $url ?>" class="btn btn-custom" target="_blank"><?php _e( 'Visit', 'startup-reloaded' ) ?><?php }?>

                <?php } // endforeach ?>

        <?php } ?>
    <?php if (is_front_page()) { ?>
<?php } ?>


text:
FactoryBot.define do
  factory :partner do
    name { Faker::Name.name }
    logo do
      Rack::Test::UploadedFile.new(
        Rails.root.join('spec/support/brands/logos/TGDF.png'),
        'image/jpeg'
      )
    end
    type { create(:partner_type) }
  end
end


text:
import unittest

import numpy
import six

import chainer
from chainer import cuda
from chainer import functions
from chainer import gradient_check
from chainer import testing
from chainer.testing import attr
from chainer.testing import condition

@testing.parameterize(*testing.product_dict(
    [
        # we assume insize as (2, 1)
        # standard output size which is estimated with get_deconv_outsize
        # function
        {'cover_all': False, 'outsize': (4, 2)},
        {'cover_all': True, 'outsize': (3, 1)},
        {'cover_all': False, 'outsize': None, 'expected_outsize': (4, 2)},
        {'cover_all': True, 'outsize': None, 'expected_outsize': (3, 1)},
        # another sizes which can be outsize of insize (2, 1)
        {'cover_all': False, 'outsize': (5, 2)},
        {'cover_all': True, 'outsize': (4, 2)},
    ],
    [
        {'dtype': numpy.float16},
        {'dtype': numpy.float32},
        {'dtype': numpy.float64},
    ],
))
class TestUnpooling2D(unittest.TestCase):

    def setUp(self):
        self.N = 2
        self.n_channels = 3
        inh, inw = 2, 1
        self.x = numpy.arange(
            self.N * self.n_channels * inh * inw,
            dtype=self.dtype).reshape(self.N, self.n_channels, inh, inw)
        numpy.random.shuffle(self.x)
        self.x = 2 * self.x / self.x.size - 1

        self.ksize = 2
        outh, outw = self.outsize or self.expected_outsize
        self.gy = numpy.random.uniform(
            -1, 1, (self.N, self.n_channels, outh, outw)).astype(self.dtype)
        self.check_backward_options = {}
        if self.dtype == numpy.float16:
            self.check_backward_options = {'atol': 0.05, 'rtol': 0.05}

    def check_forward(self, x_data):
        x = chainer.Variable(x_data)
        y = functions.unpooling_2d(x, self.ksize, outsize=self.outsize,
                                   cover_all=self.cover_all)
        self.assertEqual(y.data.dtype, self.dtype)
        y_data = cuda.to_cpu(y.data)

        self.assertEqual(self.gy.shape, y_data.shape)
        for i in six.moves.range(self.N):
            for c in six.moves.range(self.n_channels):
                outsize = self.outsize or self.expected_outsize
                assert y_data.shape[2:] == outsize
                if outsize == (5, 2):
                    expect = numpy.zeros(outsize, dtype=self.dtype)
                    expect[:2, :] = self.x[i, c, 0, 0]
                    expect[2:4, :] = self.x[i, c, 1, 0]
                elif outsize == (4, 2):
                    expect = numpy.array([
                        [self.x[i, c, 0, 0], self.x[i, c, 0, 0]],
                        [self.x[i, c, 0, 0], self.x[i, c, 0, 0]],
                        [self.x[i, c, 1, 0], self.x[i, c, 1, 0]],
                        [self.x[i, c, 1, 0], self.x[i, c, 1, 0]],
                    ])
                elif outsize == (3, 1):
                    expect = numpy.array([
                        [self.x[i, c, 0, 0]],
                        [self.x[i, c, 0, 0]],
                        [self.x[i, c, 1, 0]],
                    ])
                else:
                    raise ValueError('Unsupported outsize: {}'.format(outsize))
                gradient_check.assert_allclose(expect, y_data[i, c])

    @condition.retry(3)
    def test_forward_cpu(self):
        self.check_forward(self.x)

    @attr.gpu
    @condition.retry(3)
    def test_forward_gpu(self):
        self.check_forward(cuda.to_gpu(self.x))

    def check_backward(self, x_data, y_grad):
        gradient_check.check_backward(
            functions.Unpooling2D(self.ksize, outsize=self.outsize,
                                  cover_all=self.cover_all),
            x_data, y_grad, **self.check_backward_options)

    @condition.retry(3)
    def test_backward_cpu(self):
        self.check_backward(self.x, self.gy)

    @attr.gpu
    @condition.retry(3)
    def test_backward_gpu(self):
        self.check_backward(cuda.to_gpu(self.x), cuda.to_gpu(self.gy))

testing.run_module(__name__, __file__)


text:
from __future__ import absolute_import, unicode_literals

from eb_sqs import settings
from eb_sqs.worker.worker_factory import WorkerFactory
from eb_sqs.worker.worker_task import WorkerTask

def _get_kwarg_val(kwargs, key, default):
    # type: (dict, str, Any) -> Any
    return kwargs.pop(key, default) if kwargs else default

def func_delay_decorator(func, queue_name, max_retries_count, use_pickle):
    # type: (Any, str, int, bool) -> (tuple, dict)
    def wrapper(*args, **kwargs):
        # type: (tuple, dict) -> Any
        queue = _get_kwarg_val(kwargs, 'queue_name', queue_name if queue_name else settings.DEFAULT_QUEUE)
        max_retries = _get_kwarg_val(kwargs, 'max_retries', max_retries_count if max_retries_count else settings.DEFAULT_MAX_RETRIES)
        pickle = _get_kwarg_val(kwargs, 'use_pickle', use_pickle if use_pickle else settings.USE_PICKLE)

        execute_inline = _get_kwarg_val(kwargs, 'execute_inline', False) or settings.EXECUTE_INLINE
        delay = _get_kwarg_val(kwargs, 'delay',  settings.DEFAULT_DELAY)
        group_id = _get_kwarg_val(kwargs, 'group_id', None)

        worker = WorkerFactory.default().create()
        return worker.delay(group_id, queue, func, args, kwargs, max_retries, pickle, delay, execute_inline)

    return wrapper

def func_retry_decorator(worker_task):
    # type: (WorkerTask) -> (tuple, dict)
    def wrapper(*args, **kwargs):
        # type: (tuple, dict) -> Any
        execute_inline = _get_kwarg_val(kwargs, 'execute_inline', False) or settings.EXECUTE_INLINE
        delay = _get_kwarg_val(kwargs, 'delay', settings.DEFAULT_DELAY)
        count_retries = _get_kwarg_val(kwargs, 'count_retries', settings.DEFAULT_COUNT_RETRIES)

        worker = WorkerFactory.default().create()
        return worker.retry(worker_task, delay, execute_inline, count_retries)
    return wrapper

class task(object):
    def __init__(self, queue_name=None, max_retries=None, use_pickle=None):
        # type: (str, int, bool) -> None
        self.queue_name = queue_name
        self.max_retries = max_retries
        self.use_pickle = use_pickle

    def __call__(self, *args, **kwargs):
        # type: (tuple, dict) -> Any
        func = args[0]
        func.retry_num = 0
        func.delay = func_delay_decorator(func, self.queue_name, self.max_retries, self.use_pickle)
        return func


text:
Sometimes you know you will need to make a bunch of requests and you don't want to wait for one to finish to start the next. When using parallel requests there is the potential to finish many requests all at the same time taking only as long as the single longest request. To use parallel requests you will need to set Flexirest to use a Faraday adapter that supports parallel requests [(such as Typhoeus)](https://github.com/lostisland/faraday/wiki/Parallel-requests).

```ruby
# Set adapter to Typhoeus to use parallel requests
Flexirest::Base.adapter = :typhoeus
```

Now you just need to get ahold of the connection that is going to make the requests by specifying the same host that the models will be using. When inside the `in_parallel` block call request methods as usual and access the results after the `in_parallel` block ends.

```ruby
Flexirest::ConnectionManager.in_parallel('https://www.example.com') do
    @person = Person.find(1234)
    @employers = Employer.all

    puts @person #=> nil
    puts @employers #=> nil
end # The requests are all fired in parallel during this end statement

puts @person.name #=> "John"
puts @employers.size #=> 7
```

-----

[< Body types](body-types.md) | [Faking calls >](faking-calls.md)


text:
shellVarParser
==============

![Build Status](https://travis-ci.org/createbang/shellVarParser.png)

Parse shell constant variables into a Javascript object.

Convert the contents of a shell constant variables file to a JavaScript object literal.

.env file
```sh
ENV_VAR1=foobar
ENV_VAR2=bazbang
```

js file
```js
var shellVarParser = require('shellVarParser');

var fileContents = fs.readFileSync(__dirname + '/.env', 'utf8');
var envVars = shellVarParser.parse(fileContents)

// returns {ENV_VAR1: "foobar", ENV_VAR2: "bazbang"}
```

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Added some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request

## Running tests

```bash
npm install
npm test
```


text:
import os

import tweepy

def get_api(access_token, access_token_secret):
    auth = tweepy.OAuthHandler(os.environ['TWITTER_CONSUMER_KEY'], os.environ['TWITTER_CONSUMER_SECRET'])
    auth.set_access_token(access_token, access_token_secret)
    return tweepy.API(auth)

def _get_tokens(user):
    social = user.social_auth.get(provider='twitter')
    return {'access_token': social.access_token['oauth_token'],
            'access_token_secret': social.access_token['oauth_token_secret']}

class TwitterMiddleware(object):

    def process_request(self, request):
        if hasattr(request, 'user') and hasattr(request.user, 'social_auth'):
            tokens = _get_tokens(request.user)
            request.twitter_api = get_api(tokens['access_token'], tokens['access_token_secret'])
            request.user.twitter_id = int(request.user.social_auth.get(provider='twitter').uid)


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

import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.JavaDelegate;

public class TestJoinDelegate implements JavaDelegate {

  @Override
  public void execute(DelegateExecution execution) {
    // dummy task
  }

}


text:
package br.com.transmetais.type;

public enum TipoEstoqueMovimentacaoEnum {
	E("Entrada"), S("Saída");
	private String descricao;
	TipoEstoqueMovimentacaoEnum tipo;
	private TipoEstoqueMovimentacaoEnum(String descricao) {
		this.setDescricao(descricao);
	}

	public String getDescricao() {
		return descricao;
	}
	public void setDescricao(String descricao) {
		this.descricao = descricao;
	}

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


text:
var express = require('express')
var logger = require('morgan')
var cookieParser = require('cookie-parser')
var bodyParser = require('body-parser')
var path = require('path');
//var jwt = require('jsonwebtoken')

global.music_files = path.join(__dirname, 'music_files')

// var monogoLab = 'mongodb://admin:admin@ds013330.mlab.com:13330/react_nodejs'
var MongoClient = require('mongodb').MongoClient
var co = require('co')
console.log(process.env.MONGOLAB_URI)
co(function*() {
  global.db = yield MongoClient.connect(process.env.MONGOLAB_URI /* || monogoLab */)
  global.colSongs = global.db.collection('songs')
  console.log('Connected correctly to server')
})

// routes
// var users   = require('./routes/users');
var songs = require('./routes/songs')
// var fileUpdater = require('./routes/fileUpdater');

var app = express()

app.engine('html', require('ejs').renderFile)
app.set('view engine', 'html')

// uncomment after placing your favicon in /public
// app.use(favicon(  'public', 'favicon.ico')));
app.use(function (req, res, next) {
  res.header('Access-Control-Allow-Origin', '*')
  res.header('Access-Control-Request-Headers', '*')
  res.header('Access-Control-Allow-Methods', 'GET, POST, DELETE, OPTIONS')
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization')
  res.header('Access-Control-Allow-Credentials', 'true')
  next()
})

var staticPath = global.music_files

app.use(logger('dev'))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))
app.use(cookieParser())
/*
// middleware that checks if JWT token exists and verifies it if it does exist.
// In all the future routes, this helps to know if the request is authenticated or not.
app.use(function (req, res, next) {
  // check header or url parameters or post parameters for token
  var token = req.body.token || req.query.token || req.headers['x-access-token']

  // decode token
  if (token) {
    jwt.verify(token, process.env.JWT_SECRET, function (err, user) {
      if (err) {
        return res.status(401).json({ success: false, message: 'Failed to authenticate token.' })
      } else {
        req.user = user
        next()
      }
    })
  } else {
    next()
  }
})
*/

app.use('/api/', songs)
// app.use('/api/', fileUpdater);

// app.use('/api/', users);
app.use(express.static(staticPath))
app.use('/', express.static(staticPath))
app.use('/songs/*', express.static(staticPath))

// app.use('/new/*', express.static(staticPath));
// app.use('/validateEmail/*', express.static(staticPath));

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  var err = new Error('Not Found!!')
  err.status = 404
  next(err)
})

// app.use(function(err, req, res, next) {
//   console.error(err.stack);
//   console.log(1)
//   res.status(500).send('Uh oh! Something broke!');
// });

// error handlers
// no stacktraces leaked to user
app.use(function (err, req, res, next) {
  console.dir(err)
  res.status(err.status || 500)
  if (err.status === 500) {
    console.error(err.stack)
    res.json({ error: 'Internal Server Error' })
  }  else if (err.status === 404) {
    res.render('error')    // render error page
  } else {
    res.json({ error: err.message })
  }
})

module.exports = app


text:
import java.util.Scanner;

/**
 * Demonstration of simple functions to
 * calculate the area of simpel geometric shapes.
 * This version is interactive, using Scanner class
 * to take user input.

 *
 * Created for merit badge college.

 * Released to the public under the MIT license.
 *
 * @author Rich Lynch
 * @version 10.
 */
public class AreaCalc_withInput {
	/* This is the main function of the program, all executable programs have a main */
	public static void main(String[] args) {
		double radius;
		double area;
		Scanner scannerDouble = new Scanner(System.in);

		/*
			Use the Scanner object to get user input from the keyboard.
			In this case we are looking for a double
		*/
		System.out.print("Enter radius: ");
		if(scannerDouble.hasNextDouble()){
			radius = scannerDouble.nextDouble();
			area = calculateCircleArea(radius);

			/* We only want a radius that is positive */
			if(area != 0)
				System.out.println("Area of circle with radius of " + radius + " is " + area);
			else
				System.out.println("Invalid radius");
		}
		else{
			System.out.println("Invalid input, please try again.");
			return;
		}

		/* It is up to the student to expand this to support rectangles */

	}
	/**
	 * Calculate the area of a circle.
	 * @param radius The radius of the circle.
	 * @return The area of the circle if radius is greater than zero, otherwise returns zero.
	 */
	public static double calculateCircleArea(double radius){
		if(radius <= 0){

			return 0;
		}
		else{
			double area = radius * radius * Math.PI;
			return area;
		}

	}

}


text:
/* Timur Aydin (taydin@snet.net) */

#include "test.h"

#include <sys/timeb.h>

pthread_cond_t cnd;
pthread_mutex_t mtx;

int main()
{
   int rc;

   struct timespec abstime = { 0, 0 };
   PTW32_STRUCT_TIMEB currSysTime;
   const DWORD NANOSEC_PER_MILLISEC = 1000000;

   assert(pthread_cond_init(&cnd, 0) == 0);
   assert(pthread_mutex_init(&mtx, 0) == 0);

   /* get current system time */
   PTW32_FTIME(&currSysTime);

   abstime.tv_sec = (long)currSysTime.time;
   abstime.tv_nsec = NANOSEC_PER_MILLISEC * currSysTime.millitm;
   abstime.tv_sec += 1;

   /* Here pthread_cond_timedwait should time out after one second. */

   assert(pthread_mutex_lock(&mtx) == 0);

   assert((rc = pthread_cond_timedwait(&cnd, &mtx, &abstime)) == ETIMEDOUT);

   assert(pthread_mutex_unlock(&mtx) == 0);

   /* Here, the condition variable is signaled, but there are no
      threads waiting on it. The signal should be lost and
      the next pthread_cond_timedwait should time out too. */

//   assert(pthread_mutex_lock(&mtx) == 0);

   assert((rc = pthread_cond_signal(&cnd)) == 0);

//   assert(pthread_mutex_unlock(&mtx) == 0);

   assert(pthread_mutex_lock(&mtx) == 0);

   abstime.tv_sec = (long)currSysTime.time;
   abstime.tv_nsec = NANOSEC_PER_MILLISEC * currSysTime.millitm;
   abstime.tv_sec += 1;

   assert((rc = pthread_cond_timedwait(&cnd, &mtx, &abstime)) == ETIMEDOUT);

   assert(pthread_mutex_unlock(&mtx) == 0);

   return 0;
}


text:
import GithubCreationState from '../github/GithubCreationState';

const GHECreationState = GithubCreationState.extend({
    PENDING_LOADING_SERVERS: 'PENDING_LOADING_SERVERS',
    STEP_CHOOSE_SERVER: 'STEP_CHOOSE_SERVER',
});

export default GHECreationState;


text:
Chat logger feature
====================

This feature stores logs of Pokemon Showdown chat rooms, storing them in `./logs/` path. Logs have the same format as received from Pokemon Showdown server.

**Configuration** (in `config.js`):
 - `rooms` - Array of rooms to log
 - `ignore` - What kind of messages should be ignored? For example tournaments updates and query responses
 - `logIntroMessages` - Log roomintros, intro-logs, initial messages?
 - `ageOfLogs` - Max age of logs before being removed (in days)

```js
/*
* Chat Logger
*/

exports.chatLogger = {
	rooms: [],
	ignore: {'tournament': ['update', 'updateEnd'], 'formats': true, 'challstr': true, 'updateuser': true, 'queryresponse': true},
	logIntroMessages: true,
	ageOfLogs: 7 //in days (max age of logs, 0 to keep logs infinitely)
};
```

**Logs Server**: Simple html servers for an easy access to chat logs.
 - `port` - Server listening port
 - `rooms` - Add chatrooms whose logs can be requested, set private attribute if you want that only a few users can access room logs.
 - `users` - Add users credential in order to accessing private logs (useful for staff)

```js
exports.logServer = {
	port: 5400,
	bindaddress: null,
	users: {
		'admin': {
			name: 'Administrator',
			pass: 'password',
			access: {'room1': 1, 'room2': 1}
		}
	},
	rooms: {
		'room1': {private: true},
		'room2': {private: true}
	}
};
```


text:
{% extends '_base.html' %}
{% import "bootstrap/wtf.html" as wtf %}

{% block content %}

Languages

        {% if language %}
        Added: {{ language.add_date }}, Modified: {{ language.mod_date }}, Process: {{ language.process_code }}, Status: {{ language.process_status }}
        {%endif%}

        {% if locale_code %}
        <form class="form-inline" role="form" method="post" action="{{ url_for('lexicon.language') }}">
            <button class="btn btn-primary" type="submit">Add language</button>
        </form>
        {%endif%}

{% if not locale_code %}
  <form class="form" role="form" method="post" action="{{ url_for('lexicon.language') }}">
{%else%}
  <form class="form" role="form" method="post" action="{{ url_for('lexicon.mod_language') }}">
{%endif%}

    {{ form.csrf_token }}
    {{ form.hidden_tag() }}
    {{ wtf.form_errors(form, hiddens="only") }}

        {{ wtf.form_field(form.locale_code) }}
        {{ wtf.form_field(form.description) }}
        {{ wtf.form_field(form.description_en) }}
        {{ wtf.form_field(form.submit, class="btn btn-success") }}

Locale	Description	Action

          {% for language in languages %}

            {{ language.locale_code }}	{{ language.description }}	 Delete | Modify

          {% endfor %}

  </form>

{% endblock content %}


text:
package org.knowm.xchange.independentreserve.service;

import org.knowm.xchange.Exchange;
import org.knowm.xchange.service.BaseExchangeService;
import org.knowm.xchange.service.BaseService;

/**
 * Author: Kamil Zbikowski Date: 4/9/15
 */
public class IndependentReserveBaseService extends BaseExchangeService implements BaseService {

  /**
   * Constructor
   *
   * @param exchange
   */
  protected IndependentReserveBaseService(Exchange exchange) {
    super(exchange);
  }
}


text:
namespace Raven {
    class OpenGLRenderer : public Renderer {
//    protected:
//        GLFWwindow* window;
    public:
//        GLFWwindow *getWindow() const;
//        void setWindow(GLFWwindow *window);
        void setup() override;
        void render() override;
    };
}

#endif //RAVEN_OPENGLRENDER_H


text:
namespace MassTransit.Tests.SagaStateMachineTests.Automatonymous
{
    using System;
    using NUnit.Framework;
    using SagaStateMachine;

    [TestFixture]
    public class When_a_state_is_declared
    {
        [Test]
        public void It_should_capture_the_name_of_final()
        {
            Assert.AreEqual("Final", _machine.Final.Name);
        }

        [Test]
        public void It_should_capture_the_name_of_initial()
        {
            Assert.AreEqual("Initial", _machine.Initial.Name);
        }

        [Test]
        public void It_should_capture_the_name_of_running()
        {
            Assert.AreEqual("Running", _machine.Running.Name);
        }

        [Test]
        public void Should_be_an_instance_of_the_proper_type()
        {
            Assert.IsInstanceOf<StateMachineState<Instance>>(_machine.Initial);
        }

        class Instance :
SagaStateMachineInstance
        {
            public Guid CorrelationId { get; set; }
            public State CurrentState { get; set; }
        }

        TestStateMachine _machine;

        [OneTimeSetUp]
        public void A_state_is_declared()
        {
            _machine = new TestStateMachine();
        }

        class TestStateMachine :
            MassTransitStateMachine<Instance>
        {
            public TestStateMachine()
            {
                InstanceState(x => x.CurrentState);
            }

            public State Running { get; private set; }
        }
    }

    [TestFixture]
    public class When_a_state_is_stored_another_way
    {
        [Test]
        public void It_should_get_the_name_right()
        {
            Assert.AreEqual("Running", _instance.CurrentState);
        }

        TestStateMachine _machine;
        Instance _instance;

        [OneTimeSetUp]
        public void A_state_is_declared()
        {
            _machine = new TestStateMachine();
            _instance = new Instance();

            _machine.RaiseEvent(_instance, x => x.Started).Wait();
        }

        /// <summary>
        /// For this instance, the state is actually stored as a string. Therefore,
        /// it is important that the StateMachine property is initialized when the
        /// instance is hydrated, as it is used to get the State for the name of
        /// the current state. This makes it easier to save the instance using
        /// an ORM that doesn't support user types (cough, EF, cough).
        /// </summary>
        class Instance :
SagaStateMachineInstance
        {
            public Guid CorrelationId { get; set; }
            /// <summary>
            /// The CurrentState is exposed as a string for the ORM
            /// </summary>
            public string CurrentState { get; private set; }
        }

        class TestStateMachine :
            MassTransitStateMachine<Instance>
        {
            public TestStateMachine()
            {
                InstanceState(x => x.CurrentState);

                Initially(
                    When(Started)
                        .TransitionTo(Running));
            }

            public Event Started { get; private set; }
            public State Running { get; private set; }
        }
    }

    [TestFixture]
    public class When_storing_state_as_an_int
    {
        [Test]
        public void It_should_get_the_name_right()
        {
            Assert.AreEqual(_machine.Running, _machine.GetState(_instance).Result);
        }

        TestStateMachine _machine;
        Instance _instance;

        [OneTimeSetUp]
        public void A_state_is_declared()
        {
            _machine = new TestStateMachine();
            _instance = new Instance();

            _machine.RaiseEvent(_instance, x => x.Started).Wait();
        }

        /// <summary>
        /// For this instance, the state is actually stored as a string. Therefore,
        /// it is important that the StateMachine property is initialized when the
        /// instance is hydrated, as it is used to get the State for the name of
        /// the current state. This makes it easier to save the instance using
        /// an ORM that doesn't support user types (cough, EF, cough).
        /// </summary>
        class Instance :
SagaStateMachineInstance
        {
            public Guid CorrelationId { get; set; }
            /// <summary>
            /// The CurrentState is exposed as a string for the ORM
            /// </summary>
            public int CurrentState { get; private set; }
        }

        class TestStateMachine :
            MassTransitStateMachine<Instance>
        {
            public TestStateMachine()
            {
                InstanceState(x => x.CurrentState, Running);

                Initially(
                    When(Started)
                        .TransitionTo(Running));
            }

            public Event Started { get; private set; }
            public State Running { get; private set; }
        }
    }
}


text:
@interface CPTColor : NSObject<NSCopying, NSCoding, NSSecureCoding>

@property (nonatomic, readonly, nonnull) CGColorRef cgColor;
@property (nonatomic, readonly, getter = isOpaque) BOOL opaque;

/// @name Factory Methods
/// @{
+(nonnull instancetype)clearColor;
+(nonnull instancetype)whiteColor;
+(nonnull instancetype)lightGrayColor;
+(nonnull instancetype)grayColor;
+(nonnull instancetype)darkGrayColor;
+(nonnull instancetype)blackColor;
+(nonnull instancetype)redColor;
+(nonnull instancetype)greenColor;
+(nonnull instancetype)blueColor;
+(nonnull instancetype)cyanColor;
+(nonnull instancetype)yellowColor;
+(nonnull instancetype)magentaColor;
+(nonnull instancetype)orangeColor;
+(nonnull instancetype)purpleColor;
+(nonnull instancetype)brownColor;

+(nonnull instancetype)colorWithCGColor:(nonnull CGColorRef)newCGColor;
+(nonnull instancetype)colorWithComponentRed:(CGFloat)red green:(CGFloat)green blue:(CGFloat)blue alpha:(CGFloat)alpha;
+(nonnull instancetype)colorWithGenericGray:(CGFloat)gray;
/// @}

/// @name Initialization
/// @{
-(nonnull instancetype)initWithCGColor:(nonnull CGColorRef)cgColor NS_DESIGNATED_INITIALIZER;
-(nonnull instancetype)initWithComponentRed:(CGFloat)red green:(CGFloat)green blue:(CGFloat)blue alpha:(CGFloat)alpha;
-(nullable instancetype)initWithCoder:(nonnull NSCoder *)decoder NS_DESIGNATED_INITIALIZER;

-(nonnull instancetype)colorWithAlphaComponent:(CGFloat)alpha;
/// @}

@end


text:
#ifndef CMFT_CLCONTEXT_H_HEADER_GUARD
#define CMFT_CLCONTEXT_H_HEADER_GUARD

#include <stdint.h>

#include <bx/cl.h>

#define CMFT_CL_VENDOR_INTEL             (0x1)
#define CMFT_CL_VENDOR_AMD               (0x2)
#define CMFT_CL_VENDOR_NVIDIA            (0x4)
#define CMFT_CL_VENDOR_OTHER             (0x8)
#define CMFT_CL_VENDOR_ANY_GPU           (CMFT_CL_VENDOR_AMD|CMFT_CL_VENDOR_NVIDIA)
#define CMFT_CL_VENDOR_ANY_CPU           (CMFT_CL_VENDOR_AMD|CMFT_CL_VENDOR_INTEL)

#define CMFT_CL_DEVICE_TYPE_DEFAULT      CL_DEVICE_TYPE_DEFAULT
#define CMFT_CL_DEVICE_TYPE_CPU          CL_DEVICE_TYPE_CPU
#define CMFT_CL_DEVICE_TYPE_GPU          CL_DEVICE_TYPE_GPU
#define CMFT_CL_DEVICE_TYPE_ACCELERATOR  CL_DEVICE_TYPE_ACCELERATOR
#define CMFT_CL_DEVICE_TYPE_ALL          CL_DEVICE_TYPE_ALL

namespace cmft
{
    struct ClContext
    {
        ClContext()
            : m_device(NULL)
            , m_context(NULL)
            , m_commandQueue(NULL)
        {
            m_deviceVendor[0] = '\0';
            m_deviceName[0] = '\0';
        }

        bool init(uint8_t _vendor                     = CMFT_CL_VENDOR_ANY_GPU
                , cl_device_type _preferredDeviceType = CMFT_CL_DEVICE_TYPE_GPU
                , cl_uint _preferredDeviceIdx         = 0
                , char* _vendorStrPart                = NULL
                );

        void destroy();

        cl_device_id m_device;
        cl_context m_context;
        cl_command_queue m_commandQueue;
        cl_device_type m_deviceType;
        char m_deviceVendor[128];
        char m_deviceName[128];
    };

    ///
    void clPrintDevices();

} // namespace cmft

#endif //CMFT_CLCONTEXT_H_HEADER_GUARD

/* vim: set sw=4 ts=4 expandtab: */


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.github.s1ck</groupId>
    <artifactId>gdl</artifactId>
    <version>0.3.9-SNAPSHOT</version>

    <name>GDL - Graph Definition Language</name>
    <description>ANTLR Grammar for the definition of extended property graphs.</description>
    <url>http://github.com/s1ck/gdl.git</url>

    <licenses>
        <license>
            <name>Apache License, Version 2.0</name>
            <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
            <distribution>repo</distribution>
        </license>
    </licenses>

    <developers>
        <developer>
            <name>Martin Junghanns</name>
            <email>m.junghanns@mailbox.org</email>
            <id>s1ck</id>
        </developer>
    </developers>

    <scm>
        <url>http://github.com/s1ck/gdl.git</url>
        <connection>scm:git:git@github.com:s1ck/gdl.git</connection>
        <developerConnection>scm:git:s1ck@github.com/s1ck/gdl.git</developerConnection>
    </scm>

    <distributionManagement>
        <snapshotRepository>
            <id>release_artifacts</id>
            <url>https://oss.sonatype.org/content/repositories/snapshots</url>
        </snapshotRepository>
        <repository>
            <id>release_artifacts</id>
            <url>https://oss.sonatype.org/service/local/staging/deploy/maven2/</url>
        </repository>
    </distributionManagement>

    <properties>
        <project.build.targetJdk>11</project.build.targetJdk>

        <dep.antlr.version>4.9.1</dep.antlr.version>
        <dep.junit.version>4.13.1</dep.junit.version>

        <plugin.maven-compiler.version>3.8.0</plugin.maven-compiler.version>
        <plugin.maven-release.version>2.5.3</plugin.maven-release.version>
        <plugin.maven-source.version>3.2.1</plugin.maven-source.version>
        <plugin.maven-javadoc.version>3.2.0</plugin.maven-javadoc.version>
        <plugin.maven-gpg.version>1.6</plugin.maven-gpg.version>
        <plugin.maven-nexus-staging.version>1.6.8</plugin.maven-nexus-staging.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.antlr</groupId>
            <artifactId>antlr4-runtime</artifactId>
            <version>${dep.antlr.version}</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${dep.junit.version}</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>${plugin.maven-compiler.version}</version>
                <configuration>
                    <source>${project.build.targetJdk}</source>
                    <target>${project.build.targetJdk}</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.antlr</groupId>
                <artifactId>antlr4-maven-plugin</artifactId>
                <version>${dep.antlr.version}</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>antlr4</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-release-plugin</artifactId>
                <version>${plugin.maven-release.version}</version>
                <configuration>
                    <autoVersionSubmodules>true</autoVersionSubmodules>
                    <pushChanges>false</pushChanges>
                    <tagNameFormat>${project.version}</tagNameFormat>
                </configuration>
            </plugin>
            <!-- deployment plugins -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-source-plugin</artifactId>
                <version>${plugin.maven-source.version}</version>
                <executions>
                    <execution>
                        <id>attach-sources</id>
                        <phase>deploy</phase>
                        <goals>
                            <goal>jar-no-fork</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-javadoc-plugin</artifactId>
                <version>${plugin.maven-javadoc.version}</version>
                <configuration>
                    <additionalparam>-Xdoclint:none</additionalparam>
                </configuration>
                <executions>
                    <execution>
                        <id>attach-javadocs</id>
                        <phase>deploy</phase>
                        <goals>
                            <goal>jar</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-gpg-plugin</artifactId>
                <version>${plugin.maven-gpg.version}</version>
                <configuration>
                    <gpgArguments>
                        <arg>--pinentry-mode</arg>
                        <arg>loopback</arg>
                    </gpgArguments>
                </configuration>
                <executions>
                    <execution>
                        <id>sign_artifacts</id>
                        <phase>deploy</phase>
                        <goals>
                            <goal>sign</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.sonatype.plugins</groupId>
                <artifactId>nexus-staging-maven-plugin</artifactId>
                <version>${plugin.maven-nexus-staging.version}</version>
                <extensions>true</extensions>
                <configuration>
                    <serverId>release_artifacts</serverId>
                    <nexusUrl>https://oss.sonatype.org/</nexusUrl>
                    <autoReleaseAfterClose>true</autoReleaseAfterClose>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>


text:
<?php
namespace TYPO3\Flow\Mvc\Controller\Exception;

/**
 * An Inactive Package Exception
 *
 */
class InactivePackageException extends \TYPO3\Flow\Mvc\Controller\Exception
{
}


text:
package com.hendrix.zorn.managers;

import com.hendrix.zorn.workers.IWorker;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * a further implementation of {@link AbstractWorkerManager}, that handles
 * the {@code getRunningWorkers(), getFailedWorkers(), getFinishedWorkers()}
 *
 * @author Tomer Shalev
 */
@SuppressWarnings("UnusedDeclaration")
abstract public class BaseAbstractWorkerManager extends AbstractWorkerManager {
    /**
     * the list that holds currently running processes
     */
    private ArrayList<IWorker> _runningWorkers = null;
    /**
     * a map that holds finished processes
     */
    private Map<String, IWorker> _finishedWorkers = null;
    /**
     * a map that holds failed processes
     */
    private ArrayList<IWorker> _failedWorkers = null;

    /**
     * a mutable flag indicating if finished processes are stored and can later be retrieved with the api
     */
    private boolean _storeFinishedWorkers =	true;

    /**
     * {@inheritDoc}
     *
     */
    public BaseAbstractWorkerManager(String id) {
        super(id);

        if(_storeFinishedWorkers)
            _finishedWorkers    =	new HashMap<>();

        _runningWorkers         =   new ArrayList<>();
        _failedWorkers          =   new ArrayList<>();
    }

    /**
     * {@inheritDoc}
     *
     */
    public BaseAbstractWorkerManager() {
        this(null);
    }

    /**
     * dispose the object
     */
    @Override
    public void dispose() {
        super.dispose();

        _finishedWorkers = null;
        _failedWorkers   = null;
        _runningWorkers  = null;
    }

    /**
     * Get the failed workers
     *
     * @return A vector of {@code IWorker} elements
     */
    @Override
    public Collection<IWorker> getFailedWorkers() {
        return _failedWorkers;
    }

    /**
     * signals completion, or more specifically
     * when status went from {@code WORKING} into {@code IDLE}.
     */
    @Override
    public void notifyComplete() {
        if(_listener != null)
            _listener.onComplete(this);
    }
    /**
     * signals progress to listener
     *
     * @param worker the process that made progress
     */
    @Override
    public void notifyProgress(IWorker worker) {
        if(_listener != null)
            _listener.onProgress(worker.getId());
    }
    /**
     * signals Error
     *
     * @param res the error description
     */
    @Override
    public void notifyError(WorkerManagerErrorInfo res) {
        if(_listener != null)
            _listener.onError(res);
    }

    /**
     * get a finished process by it's id
     *
     * @param id {@code id} of the process.
     * @return the process
     */
    @Override
    public IWorker getFinishedWorker(String id) {
        return _finishedWorkers.get(id);
    }

    /**
     * get finished workers
     *
     * @return A map of {@code IWorker} elements
     */
    @Override
    public Map<String, IWorker> getFinishedWorkers() {
        return _finishedWorkers;
    }

    /**
     * a mutable flag indicating if finished processes are stored and can later be retrieved with the api.
     *
     * @param flag {@code true/false}
     */
    public void storeFinishedWorkers(boolean flag) {
        _storeFinishedWorkers = flag;
    }

    /**
     * @return the number of overall workers = pending + running + failed
     *
     */

    @Override
    public int numWorkers() {
        return getRunningWorkers().size() + getFailedWorkers().size() + sizePendingWorkers();
    }

    /**
     * would ou like to store finished workers
     *
     * @return {@code true/false}
     */
    @Override
    protected boolean storeFinishedWorkers() {
        return _storeFinishedWorkers;
    }

    /**
     * get currently running workers
     *
     * @return a {@link Collection} of {@link IWorker}
     */
    @Override
    protected Collection<IWorker> getRunningWorkers() {
        return _runningWorkers;
    }

}


text:
package sistema_de_diagnostico;

import com.nilo.plaf.nimrod.NimRODLookAndFeel;
import com.nilo.plaf.nimrod.NimRODProgressBarUI;
import com.nilo.plaf.nimrod.NimRODTheme;
import java.awt.Color;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.plaf.ProgressBarUI;

public class Entradita extends javax.swing.JFrame implements Runnable {

    public void run() {
        try {
            initComponents();
            setIconImage(new ImageIcon(getClass().getResource("/imagenes/linux.png")).getImage());
            setVisible(true);
            for (int i = 0; i <= 100; i += 5) {
                if (i == 5) {
                    lblTextito.setText("Cargando Modulos...");
                } else if (i == 50) {
                    lblTextito.setText("Cargando Librerias...");
                } else if (i == 90) {
                    lblTextito.setText("Iniciando el programa...");
                }
                jpbEntrada.setBackground(Color.BLACK);
                jpbEntrada.setForeground(jpbEntrada.getForeground());
                jpbEntrada.setUI((ProgressBarUI) NimRODProgressBarUI.createUI(null));
                jpbEntrada.setValue(i);
                Thread.sleep(100);
            }
        } catch (InterruptedException ex) {
            Logger.getLogger(Entradita.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception e) {
        }
        new Pantalla_Principal().setVisible(true);
        this.setVisible(false);

    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jpbEntrada = new javax.swing.JProgressBar();
        lblTextito = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("MICCASIB 1.0");
        setUndecorated(true);

        jPanel1.setName("jPanel1"); // NOI18N
        jPanel1 = new Panelcito("Azulll.jpg");
        jPanel1.setLayout(null);

        jpbEntrada.setName("jpbEntrada"); // NOI18N
        jPanel1.add(jpbEntrada);
        jpbEntrada.setBounds(60, 150, 305, 10);

        lblTextito.setForeground(new java.awt.Color(0, 51, 51));
        lblTextito.setName("lblTextito"); // NOI18N
        jPanel1.add(lblTextito);
        lblTextito.setBounds(60, 160, 179, 14);

        jLabel3.setForeground(new java.awt.Color(0, 51, 51));
        jLabel3.setText("® Copyright (C) 2010-2011");
        jLabel3.setName("jLabel3"); // NOI18N
        jPanel1.add(jLabel3);
        jLabel3.setBounds(112, 267, 305, 14);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 417, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 302, Short.MAX_VALUE)
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-417)/2, (screenSize.height-302)/2, 417, 302);
    }// </editor-fold>//GEN-END:initComponents

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                Entradita e = new Entradita();
                Thread t = new Thread(e);
                t.setDaemon(true);
                t.start();
                NimRODTheme nt = new NimRODTheme();
                //Pone en rojo los colores
//                nt.setPrimary1(new Color(184, 00, 00));
//                nt.setPrimary2(new Color(194, 00, 00));
//                nt.setPrimary3(new Color(204, 00, 00));
//                nt.setSecondary1(new Color(220, 220, 220));
//                nt.setSecondary2(new Color(230, 230, 230));
//                nt.setSecondary3(new Color(240, 240, 240));

                //Pone en azul los colores
                nt.setPrimary1(new Color(00, 133, 235));
                nt.setPrimary2(new Color(00, 143, 245));
                nt.setPrimary3(new Color(00, 153, 255));
                nt.setSecondary1(new Color(220, 220, 220));
                nt.setSecondary2(new Color(230, 230, 230));
                nt.setSecondary3(new Color(240, 240, 240));
                nt.setWhite(new Color(250, 250, 250));
                nt.setBlack(new Color(0, 0, 0));
                nt.setOpacity(0);
                nt.setMenuOpacity(0);
                nt.setFrameOpacity(0);
                NimRODLookAndFeel nlf = new NimRODLookAndFeel();
                nlf.setCurrentTheme(nt);

                try {
                    UIManager.setLookAndFeel(nlf);
                } catch (UnsupportedLookAndFeelException ex) {
                    Logger.getLogger(Entradita.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JProgressBar jpbEntrada;
    private javax.swing.JLabel lblTextito;
    // End of variables declaration//GEN-END:variables

}


text:
using Chloe.Server.Models;

namespace Chloe.Server.Dtos
{
    public class FrameworkDto: TechnologyDto
    {
        public FrameworkDto(Framework entity)
        {
            this.Id = entity.Id;
            this.Abstract = entity.Abstract;
            this.Name = entity.Name;
            this.Rating = entity.Rating;
            this.Description = entity.Description;
            this.TechnologyType = TechnologyType.Framework;
        }
    }
}


text:
class RecordMailer < ActionMailer::Base
  helper LibraryHoldingsHelper

  # Email a record to a user
  def email_record(documents, details, url_gen_params)
    #raise ArgumentError.new("RecordMailer#email_record only works with documents with a #to_marc") unless document.respond_to?(:to_marc)

    subject = I18n.t('blacklight.email.text.subject', :count => documents.length, :title => (documents.first.to_semantic_values[:title] rescue 'N/A') )

    @documents      = documents
    @message        = details[:message]
    @url_gen_params = url_gen_params

    mail(:to => details[:to],  :subject => subject, :from => 'libref@linnbenton.edu')
  end

  # Text a record to a user
  def sms_record(documents, details, url_gen_params)
    @documents      = documents
    @url_gen_params = url_gen_params
    mail(:to => details[:to], :subject => "LBCC Library item", :from => 'libref@linnbenton.edu')
  end

end


text:
import datetime as dt
from collections import defaultdict
import logging
import os
import csv
from chatbot.utils import norm

logger = logging.getLogger('hr.chatbot.server.response_cache')

class ResponseCache(object):

    def __init__(self):
        self.record = []
        self.cursor = 0
        self.index = defaultdict(list)
        self.last_question = None
        self.last_answer = None
        self.that_question = None
        self.last_time = None

    def clean(self):
        del self.record[:]
        del self.index
        self.record = []
        self.cursor = 0
        self.index = defaultdict(list)
        self.last_question = None
        self.last_answer = None
        self.that_question = None
        self.last_time = None

    def check(self, question, answer):
        # each additional character over the 10 characters, adds 30 seconds
        # delay before that AIML string is allowed to repeat.
        same_answers = [r for r in self.record if norm(r['Answer']) == norm(answer)]
        time_elapsed = (dt.datetime.utcnow() - same_answers[-1]['Datetime']
                        ).seconds if same_answers else 0
        if max(0, len(norm(answer)) - 10) * 30 <= time_elapsed:
            logger.debug("Allow repeat answer {}".format(answer))
            logger.debug("Answer length {}, time elapsed {}".format(
                len(norm(answer)), time_elapsed))
            return True

        if norm(answer) == norm(self.last_answer):
            logger.debug("Last answer repeat")
            return False
        if not self.is_unique(answer):
            logger.debug("Non unique answer")
            return False
        if self.contain(question, answer):
            logger.debug("Repeat answer")
            return False
        return True

    def add(self, record):
        question = record['Question']
        answer = record['Answer']
        self.record.append(record)
        self.index[norm(question)].append(len(self.record) - 1)
        self.last_question = question
        self.last_answer = answer
        self.last_time = record.get('Datetime')

    def update(self, idx, **kwargs):
        if idx < 0:
            idx = len(self.record) + idx
        if idx >= 0 and idx < len(self.record):
            for k, v in kwargs.iteritems():
                self.record[idx][k] = v
            if 'Feedback' in kwargs:
                answer = kwargs.pop('Feedback')
                self.record[idx]['Answer'] = answer
                self.record[idx]['Label'] = kwargs.pop('Label', '')
                self.last_answer = answer
                logger.warn("Updated feedback at %s", idx)
            return True
        return False

    def rate(self, rate, idx):
        if idx < 0:
            idx = len(self.record) + idx
        if idx < len(self.record):
            self.record[idx]['Rate'] = rate
            return True
        return False

    def contain(self, question, answer):
        question = norm(question)
        answer = norm(answer)
        records = self._get_records(question)
        answers = [norm(r['Answer']) for r in records]
        return answer in answers

    def is_unique(self, answer):
        answers = [norm(r['Answer']) for r in self.record]
        return not norm(answer) in answers

    def _get_records(self, question):
        records = [self.record[i] for i in self.index[norm(question)]]
        return records

    def dump(self, fname):
        if not self.record:
            logger.warn("Nothing to dump")
            return False
        if self.record and self.cursor >= len(self.record):
            logger.warn("Nothing to dump")
            return False
        dirname = os.path.dirname(fname)
        if not os.path.isdir(dirname):
            os.makedirs(dirname)
        header = self.record[0].keys()
        with open(fname, 'a') as f:
            writer = csv.DictWriter(f, header, extrasaction='ignore')
            if self.cursor == 0:
                writer.writeheader()
            writer.writerows(self.record[self.cursor:])
            self.cursor = len(self.record)
            logger.warn("Dumpped chat history to {}".format(fname))
            return True
        return False

if __name__ == '__main__':
    cache = ResponseCache()
    cache.add('a', 'hi', dt.datetime(2016, 4, 22, 12, 0, 0),
              Answeredby='bot', User='user')
    cache.add('a', 'Hi there', dt.datetime(2016, 4, 22, 12, 30, 0))
    cache.add('a', 'how are you', dt.datetime(2016, 4, 22, 12, 30, 0))
    cache.add('a', 'hi there', dt.datetime(2016, 4, 22, 12, 30, 0))
    cache.add('a', 'how are you', dt.datetime(2016, 4, 22, 12, 32, 0))
    cache.add('a', 'how are you', dt.datetime(2016, 4, 22, 12, 32, 0))
    print cache.is_unique('Hi')
    print cache.is_unique('hello')
    cache.dump('./tmp')
    cache.dump('./tmp')


text:
export {CartService} from './cart.service';
export {CartItem} from './cart-item.model';


text:
#pragma once

#include "std/utility.hpp"

namespace routing
{

/// \brief The RoutingSettings struct is intended to collect all the settings of
/// following along the route.
/// For example, route matching properties, rerouting properties and so on.
struct RoutingSettings
{
  /// \brief if m_matchRoute is equal to true the bearing follows the
  /// route direction if the current position is matched to the route.
  /// If m_matchRoute is equal to false GPS bearing is used while
  /// the current position is matched to the route.
  bool    m_matchRoute;
  /// \brief if m_soundDirection is equal to true an end user gets sound notification
  /// before directions.
  bool    m_soundDirection;

  /// \brief m_matchingThresholdM is half width of the passage around the route
  /// for route matching in meters. That means if a real current position is closer than
  /// m_matchingThresholdM to the route than the current position is moved to
  /// the closest point to the route.
  double  m_matchingThresholdM;

  /// \brief m_keepPedestrianInfo flag for keeping in memory additional information for pedestrian
  /// routing.
  bool m_keepPedestrianInfo;

  /// \brief if m_showTurnAfterNext is equal to true end users see a notification
  /// about the turn after the next in some cases.
  bool m_showTurnAfterNext;
};

inline RoutingSettings GetPedestrianRoutingSettings()
{
  return RoutingSettings({ false /* m_matchRoute */, false /* m_soundDirection */,
                           20. /* m_matchingThresholdM */, true /* m_keepPedestrianInfo */,
                           false /* m_showTurnAfterNext */});
}

inline RoutingSettings GetCarRoutingSettings()
{
  return RoutingSettings({ true /* m_matchRoute */, true /* m_soundDirection */,
                           50. /* m_matchingThresholdM */, false /* m_keepPedestrianInfo */,
                           true /* m_showTurnAfterNext */});
}
}  // namespace routing


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>
  Class: MudServer::DefaultController

    — Documentation by YARD 0.8.7.6

</title>

  <link rel="stylesheet" href="../css/style.css" type="text/css" charset="utf-8" />

  <link rel="stylesheet" href="../css/common.css" type="text/css" charset="utf-8" />

    Index (D) »
    ArcherSysOS » MudServer
     »
    DefaultController

(no frames)

      Class List

      Method List

      File List

Class: MudServer::DefaultController

Inherits:

      Object

Object

MudServer::DefaultController

        show all

Defined in:

AerodiaServer.rb

      Instance Method Summary
      (collapse)

      - (Object) allowed_methods

      - (Object) on_start

      - (Object) say

User input after a command is provided via `params`.

      - (Object) secret

Transfer people to a different menu / area using `transfer_to`.

      - (Object) study

      - (Object) time

Instance Method Details

    - (<tt>Object</tt>) allowed_methods

31
32
33
34

# File 'AerodiaServer.rb', line 31

def allowed_methods
  super + ['time', 'secret', 'say','study'] # Quit is available by default via `super`
                                    # No need to implement it yourself.
end

    - (<tt>Object</tt>) on_start

22
23
24
25
26
27
28
29
30

# File 'AerodiaServer.rb', line 22

def on_start
  # Send messages via send_text.
  send_text "Welcome! Here's a list of available commands"
  send_text "TIME  : See the current time."
  send_text "SAY   : Talk."
  send_text "SECRET: Go somewhere super secret."
  send_text "QUIT  : Disconnect from the server."

end

    - (<tt>Object</tt>) say

User input after a command is provided via `params`.

36
37
38

# File 'AerodiaServer.rb', line 36

def say
 send_text "You just said: #{params}"
end

    - (<tt>Object</tt>) secret

Transfer people to a different menu / area using `transfer_to`

44
45
46

# File 'AerodiaServer.rb', line 44

def secret
  transfer_to PokerRoom # Define the PokerRoom as a controller.
end

    - (<tt>Object</tt>) study

47
48
49

# File 'AerodiaServer.rb', line 47

def study
   transfer_to StudyHall
end

    - (<tt>Object</tt>) time

40
41
42

# File 'AerodiaServer.rb', line 40

def time
  send_text "The time is now #{Time.now}"
end

  Generated on Thu Apr 16 23:48:13 2015 by
  yard
  0.8.7.6 (ruby-2.2.1).