text:
Enables quick directory aliases and navigation. Allows for easy and consistent navigation between disparate directories.

## Table of Contents
**[Installation](#installation)**

**[Usage](#usage)**

**[Autocomplete](#autocomplete)**

**[Supported Environments](#supported-environments)**

**[Implementation Details](#implementation-details)**

**[License](#license)**

## Installation

1. Download the [script](https://github.com/mcwoodle/shell-directory-management/blob/master/quick-directory-aliases.sh)
1. Source the script into your current shell (add this to your shell startup script to always have the command available)
1. Done

#### Quick setup commands

> Note: Before running the following, change `RC_FILE` to match your preferred shell's rc file, or any other file that you source when a new shell/terminal is created.

```bash
RC_FILE=~/.bashrc
SCRIPT_DIRECTORY=~/scripts

mkdir -p $SCRIPT_DIRECTORY
wget -O $SCRIPT_DIRECTORY/quick-directory-aliases.sh https://raw.githubusercontent.com/mcwoodle/shell-directory-management/master/quick-directory-aliases.sh
printf "\n. $SCRIPT_DIRECTORY/quick-directory-aliases.sh\n" >> $RC_FILE
. $RC_FILE
```

> The default name for the command is "d". Edit the `quick-directory-aliases.sh` script and change the function name `d()` to a name of your choosing.

## Usage

#### Add an alias
```bash
% cd /any/really/long/or/short/directory/path/thats/hardoreasy/to/remember
% d + shortAliasName
```
> Note: changes take effect immediately across terminals/shells.

#### Navigate to an alias
```bash
% d shortAliasName

% pwd
/any/really/long/or/short/directory/path/thats/hardoreasy/to/remember
```

#### Remove an alias
```bash
% d - shortAliasName
```

#### See all aliases
```bash
% d
workspace = /home/mcwoodle/workspaces/someWorkspaceDirectory
bin = /usr/bin
nhl = /home/mcwoodle/go/leafs/go
```

#### Autocomplete

Autocomplete is currently only supported using bash and zsh (or any script supporting `complete\compgen` or `compctl` built-ins).

Installation is automatic and works like any other bash/zsh tab based autocomplete.

#### Using with ssh to have your list of aliases available anywhere (not yet implemented)

If you're like me and work with a lot of remote servers, you could use something along the lines of:
```bash
ssh -t <user>@<hostname> "someScriptOrCommands_ToLoadMapFileAndSourceScript; zsh"
```
to push the ~/.dmap file along with the above script in order to get all of your aliases available remotely no matter which host you sign in to.

I have yet to implement this solution yet, but it's on my todo list.  If you get to it first, please let me know your approach.  Thanks!

## Supported Environments

This script uses standard sh and will work with any POSIX compliant shell. It's been tested with sh, bash, ksh, zsh, dash and been used on macOS, RHEL5, Ubuntu, and Bash on Ubuntu on Windows.

> C shell, tcsh/csh, are not POSIX compliant and therefore not supported.

> ksh on Bash On Ubuntu On Windows, along with being a mouthful, does not work due to a "cannot create pipe [Operation not permitted]" error when piping output to sed.

> Autocomplete only works on bash and zsh.

## Implementation Details
* The script is sourced into your current working shell, allowing it to issue change directory commands within your shell.
* A function will be defined named 'd' in the current shell's context. If there is an alias with this name it will be removed.
* It creates and uses a `~/.dmap` file to store a map of aliases to directories.
* This map file can easily be edited manually (e.g. bulk renaming).

## License
Licensed under the Apache License, Version 2.0.


text:
package testdata

import (
	"context"
	"net/http"

	"github.com/Azure/azure-sdk-for-go/version"
	"github.com/Azure/go-autorest/autorest"
	"github.com/Azure/go-autorest/autorest/azure"
)

// content lifted from redis

// summary of changes
//
// type alias
// changed type DayOfWeek name to Day
// changed type KeyType type to int
//
// const
// removed Everyday
//
// func
// added param to DoNothing
// removed param from DoNothingWithParam
// changed return type on List
// added param to List and ListPreparer
// removed name param on Delete and DeletePreparer
//
// interface
// added params to methods on SomeInterface
//
// struct
// removed Tags field from CreateParameters
// changed field types SubnetID and RedisConfiguration in CreateProperties
// made BaseClient field in Client type explicit
// made NextLink in ListResult byval
//

const (
	DefaultBaseURI = "https://management.azure.com"
)

type Day string

const (
	Friday    Day = "Friday"
	Monday    Day = "Monday"
	Saturday  Day = "Saturday"
	Sunday    Day = "Sunday"
	Thursday  Day = "Thursday"
	Tuesday   Day = "Tuesday"
	Wednesday Day = "Wednesday"
	Weekend   Day = "Weekend"
)

type KeyType int

const (
	Primary   KeyType = 1
	Secondary KeyType = 2
)

type BaseClient struct {
	autorest.Client
	BaseURI        string
	SubscriptionID string
}

type Client struct {
	BC BaseClient
}

func DoNothing(s string) {
}

func DoNothingWithParam() {
}

func New(subscriptionID string) BaseClient {
	return NewWithBaseURI(DefaultBaseURI, subscriptionID)
}

func NewWithBaseURI(baseURI string, subscriptionID string) BaseClient {
	return BaseClient{
		Client:         autorest.NewClientWithUserAgent(UserAgent()),
		BaseURI:        baseURI,
		SubscriptionID: subscriptionID,
	}
}

func UserAgent() string {
	return "Azure-SDK-For-Go/" + version.Number + " redis/2017-10-01"
}

type CreateParameters struct {
	*CreateProperties `json:"properties,omitempty"`
	Zones             *[]string `json:"zones,omitempty"`
	Location          *string   `json:"location,omitempty"`
}

func (cp CreateParameters) MarshalJSON() ([]byte, error) {
	return nil, nil
}

func (cp *CreateParameters) UnmarshalJSON(body []byte) error {
	return nil
}

type CreateProperties struct {
	SubnetID           *int               `json:"subnetId,omitempty"`
	StaticIP           *string            `json:"staticIP,omitempty"`
	RedisConfiguration interface{}        `json:"redisConfiguration"`
	EnableNonSslPort   *bool              `json:"enableNonSslPort,omitempty"`
	TenantSettings     map[string]*string `json:"tenantSettings"`
	ShardCount         *int32             `json:"shardCount,omitempty"`
}

type DeleteFuture struct {
	azure.Future
	req *http.Request
}

func (future DeleteFuture) Result(client Client) (ar autorest.Response, err error) {
	return
}

type ListResult struct {
	autorest.Response `json:"-"`
	Value             *[]ResourceType `json:"value,omitempty"`
	NextLink          string          `json:"nextLink,omitempty"`
}

func (lr ListResult) IsEmpty() bool {
	return lr.Value == nil || len(*lr.Value) == 0
}

type ListResultPage struct {
	fn func(ListResult) (ListResult, error)
	lr ListResult
}

func (page *ListResultPage) Next() error {
	return nil
}

func (page ListResultPage) NotDone() bool {
	return !page.lr.IsEmpty()
}

func (page ListResultPage) Response() ListResult {
	return page.lr
}

func (page ListResultPage) Values() []ResourceType {
	return *page.lr.Value
}

type ResourceType struct {
	autorest.Response `json:"-"`
	Zones             *[]string          `json:"zones,omitempty"`
	Tags              map[string]*string `json:"tags"`
	Location          *string            `json:"location,omitempty"`
	ID                *string            `json:"id,omitempty"`
	Name              *string            `json:"name,omitempty"`
	Type              *string            `json:"type,omitempty"`
}

func (client Client) Delete(ctx context.Context, resourceGroupName string) (result DeleteFuture, err error) {
	return
}

func (client Client) DeletePreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) {
	const APIVersion = "2017-10-01"
	return nil, nil
}

func (client Client) DeleteSender(req *http.Request) (future DeleteFuture, err error) {
	return
}

func (client Client) DeleteResponder(resp *http.Response) (result autorest.Response, err error) {
	return
}

func (client Client) List(ctx context.Context, s string) (result ListResult, err error) {
	return
}

func (client Client) ListPreparer(ctx context.Context, s string) (*http.Request, error) {
	const APIVersion = "2017-10-01"
	return nil, nil
}

func (client Client) ListSender(req *http.Request) (*http.Response, error) {
	return nil, nil
}

func (client Client) ListResponder(resp *http.Response) (result ListResult, err error) {
	return
}

func (client Client) listNextResults(lastResults ListResult) (result ListResult, err error) {
	return
}

type SomeInterface interface {
	One(string)
	Two(bool, int)
}

type AnotherInterface interface {
	One()
}

redpajama_set_name: RedPajamaGithub


text:
package org.sagebionetworks.web.test.helper;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.util.LinkedList;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.sagebionetworks.web.test.helper.examples.ExamplePresenter;
import org.sagebionetworks.web.test.helper.examples.ExampleService;
import org.sagebionetworks.web.test.helper.examples.ExampleServiceAsync;
import org.sagebionetworks.web.test.helper.examples.ExampleServiceStub;
import org.sagebionetworks.web.test.helper.examples.SampleDTO;

/**
 * Test the various types of method that the AsyncServiceRecorder is expected to handle.
 *
 * @author jmhill
 *
 */

@SuppressWarnings({"rawtypes", "unused"})
public class AsyncServiceRecorderTest {

	ExampleService serviceStub = null;
	AsyncServiceRecorder<ExampleService, ExampleServiceAsync> recorder = null;
	ExampleServiceAsync asychProxy = null;
	ExamplePresenter presenter = null;

	/**
	 * Create all new objects before each test.
	 */
	@Before
	public void setUp() {
		serviceStub = new ExampleServiceStub();
		// Create our recorder
		recorder = new AsyncServiceRecorder<ExampleService, ExampleServiceAsync>(serviceStub, ExampleServiceAsync.class);
		// Create the asynchronous proxy
		asychProxy = recorder.createAsyncProxyToRecord();
		// Create our test presenter
		presenter = new ExamplePresenter(asychProxy);
	}

	@Test
	public void testGetAsyncCallbackTypeFromSynchReturnType() {
		// Test all eight primitive types

		// int
		Class inType = int.class;
		Class expectedOut = Integer.class;
		Class actualOut = AsyncServiceRecorder.getAsyncCallbackTypeFromSynchReturnType(inType);
		assertEquals(expectedOut, actualOut);
		// long
		inType = long.class;
		expectedOut = Long.class;
		actualOut = AsyncServiceRecorder.getAsyncCallbackTypeFromSynchReturnType(inType);
		assertEquals(expectedOut, actualOut);
		// void
		inType = void.class;
		expectedOut = Void.class;
		actualOut = AsyncServiceRecorder.getAsyncCallbackTypeFromSynchReturnType(inType);
		assertEquals(expectedOut, actualOut);
		// byte
		inType = byte.class;
		expectedOut = Byte.class;
		actualOut = AsyncServiceRecorder.getAsyncCallbackTypeFromSynchReturnType(inType);
		assertEquals(expectedOut, actualOut);
		// char
		inType = char.class;
		expectedOut = Character.class;
		actualOut = AsyncServiceRecorder.getAsyncCallbackTypeFromSynchReturnType(inType);
		assertEquals(expectedOut, actualOut);
		// double
		inType = double.class;
		expectedOut = Double.class;
		actualOut = AsyncServiceRecorder.getAsyncCallbackTypeFromSynchReturnType(inType);
		assertEquals(expectedOut, actualOut);
		// float
		inType = float.class;
		expectedOut = Float.class;
		actualOut = AsyncServiceRecorder.getAsyncCallbackTypeFromSynchReturnType(inType);
		assertEquals(expectedOut, actualOut);
		// boolean
		inType = boolean.class;
		expectedOut = Boolean.class;
		actualOut = AsyncServiceRecorder.getAsyncCallbackTypeFromSynchReturnType(inType);
		assertEquals(expectedOut, actualOut);

		// Now a few non-primitives
		// Object
		inType = Object.class;
		expectedOut = Object.class;
		actualOut = AsyncServiceRecorder.getAsyncCallbackTypeFromSynchReturnType(inType);
		assertEquals(expectedOut, actualOut);
		// Exception
		inType = Exception.class;
		expectedOut = Exception.class;
		actualOut = AsyncServiceRecorder.getAsyncCallbackTypeFromSynchReturnType(inType);
		assertEquals(expectedOut, actualOut);

	}

	/**
	 * Test a method with no arguments.
	 *
	 * @throws Exception
	 */
	@Test
	public void testNoArgs() throws Exception {
		// Add some test data to the service stub before we start
		int idOne = serviceStub.createSample("one", "description for one");
		int idTwo = serviceStub.createSample("two", "description for two");

		// before we start the recoured should have zero calls
		assertEquals(0, recorder.getRecoredCallCount());
		// Now tell the presenter to call the noAgrs method which
		// which should get the list of two entries.
		presenter.doNoArgs();
		// At this point the presenter should not have any data
		// because the asych calls should have been recored but not called yet.
		assertNull(presenter.getNoArgFailure());
		assertNull(presenter.getNoArgSuccess());
		// the recorder should have captured one call
		assertEquals(1, recorder.getRecoredCallCount());
		// Now play a success
		recorder.playOnSuccess(0);
		// Now the presenter should have data
		List<SampleDTO> results = presenter.getNoArgSuccess();
		assertNotNull(results);
		// There should be two samples in the list
		assertEquals(2, results.size());
		// Spot check a sample
		SampleDTO two = results.get(1);
		assertNotNull(two);
		assertEquals(idTwo, two.getId());
	}

	@Test
	public void testWithArgs() throws Exception {
		// Add some test data to the service stub before we start
		int id1 = serviceStub.createSample("A", "description for A");
		int id2 = serviceStub.createSample("B", "description for B");
		int id3 = serviceStub.createSample("C", "description for C");

		// Create the parameters
		List<Integer> idList = new LinkedList<Integer>();
		idList.add(id1);
		idList.add(id3);

		// Now make the call
		presenter.doWithArgs(idList);
		// At this point the presenter should not have any data
		// because the asych calls should have been recored but not called yet.
		assertNull(presenter.getWithArgFailure());
		assertNull(presenter.getWithArgSuccess());
		// the recorder should have captured one call
		assertEquals(1, recorder.getRecoredCallCount());
		// Now play a success
		recorder.playOnSuccess(0);
		// Now the presenter should have data
		List<SampleDTO> results = presenter.getWithArgSuccess();
		assertNotNull(results);
		// There should be two samples in the list
		assertEquals(2, results.size());
		// Spot check a sample
		SampleDTO two = results.get(1);
		assertNotNull(two);
		assertEquals(id3, two.getId());
	}

	@Test
	public void testNullReturn() throws Exception {
		// We do not need any data for this test.
		// Now make the call
		presenter.doNullReturn();
		// This time the presenter starts will non-null data
		// and the play should set it to null.
		assertNotNull(presenter.getNullReturnSuccess());
		// the recorder should have captured one call
		assertEquals(1, recorder.getRecoredCallCount());
		// Now play a success
		recorder.playOnSuccess(0);
		// Now the presenter should have data
		List<SampleDTO> results = presenter.getNullReturnSuccess();
		assertNull(results);
	}

	@Test
	public void testVoidReturn() throws Exception {
		// We do not need any data for this test.
		// Now make the call
		presenter.doVoidReturn(12);
		assertFalse(presenter.isVoidReturnSuccess());
		// the recorder should have captured one call
		assertEquals(1, recorder.getRecoredCallCount());
		// Now play a success
		recorder.playOnSuccess(0);
		//
		assertTrue(presenter.isVoidReturnSuccess());
	}

	@Test
	public void testCreate() throws Exception {
		presenter.doCreateSample("createName", "createDescription");
		assertNull(presenter.getCreateSucces());
		// Play should create the sample
		recorder.playOnSuccess(0);
		// The stub should have this sample
		List<SampleDTO> list = serviceStub.noArgs();
		assertNotNull(list);
		assertEquals(1, list.size());
		SampleDTO created = list.get(0);
		assertNotNull(created);
		// Now compare it with the Id the presenter was handed
		assertNotNull(presenter.getCreateSucces());
		assertEquals(created.getId(), presenter.getCreateSucces().intValue());

	}

}


text:
package init

import (
	"fmt"
	"os"
	"path"
	"strings"

	"github.com/micro/micro/v3/cmd"
	"github.com/urfave/cli/v2"
)

var (
	// The import path we use for imports
	Import = "github.com/micro/micro/profile"
	// Vesion of micro
	Version = "v3"
)

func Run(ctx *cli.Context) error {
	var imports []string

	for _, val := range ctx.StringSlice("profile") {
		for _, profile := range strings.Split(val, ",") {
			p := strings.TrimSpace(profile)
			if len(p) == 0 {
				continue
			}
			path := path.Join(Import, p, Version)
			imports = append(imports, fmt.Sprintf("\t_ \"%s\"\n", path))
		}
	}

	if len(ctx.String("package")) > 0 {
		imports = append(imports, fmt.Sprintf("\t_ \"%s\"\n", ctx.String("package")))
	}

	if len(imports) == 0 {
		return nil
	}

	f := os.Stdout

	if v := ctx.String("output"); v != "stdout" {
		var err error
		f, err = os.Create(v)
		if err != nil {
			return err
		}
	}

	fmt.Fprint(f, "package main\n\n")
	fmt.Fprint(f, "import (\n")

	// write the imports
	for _, i := range imports {
		fmt.Fprint(f, i)
	}

	fmt.Fprint(f, ")\n")
	return nil
}

func init() {
	cmd.Register(&cli.Command{
		Name:        "init",
		Usage:       "Generate a profile for micro plugins",
		Description: `'micro init' generates a profile.go file defining plugins and imports`,
		Action:      Run,
		Flags: []cli.Flag{
			&cli.StringFlag{
				Name:  "package",
				Usage: "The package to load, e.g. github.com/m3o/platform/profile/ci",
			},
			&cli.StringSliceFlag{
				Name:  "profile",
				Usage: "A comma separated list of imports to load",
				Value: cli.NewStringSlice(),
			},
			&cli.StringFlag{
				Name:  "output",
				Usage: "Where to output the file, by default stdout",
				Value: "stdout",
			},
		},
	})
}


text:
'use strict';

async function main(
  projectId = 'my-project',
  locationId = 'us-east1',
  namespaceId = 'my-namespace',
  serviceId = 'my-service'
) {
  // [START servicedirectory_delete_service]
  //
  // TODO(developer): Uncomment these variables before running the sample.
  //
  // const projectId = 'my-project';
  // const locationId = 'us-central1';
  // const namespaceId = 'my-namespace';
  // const serviceId = 'my-service';

  // Imports the Google Cloud client library
  const {
    RegistrationServiceClient,
  } = require('@google-cloud/service-directory');

  // Creates a client
  const registrationServiceClient = new RegistrationServiceClient();

  // Build the service name
  const serviceName = registrationServiceClient.servicePath(
    projectId,
    locationId,
    namespaceId,
    serviceId
  );

  async function deleteService() {
    await registrationServiceClient.deleteService({
      name: serviceName,
    });

    console.log(`Deleted service: ${serviceName}`);
  }

  deleteService();
  // [END servicedirectory_delete_service]
}

const args = process.argv.slice(2);
main(...args).catch(console.error);


text:
package org.firstinspires.ftc.robotcontroller.external.samples;

import com.qualcomm.robotcore.eventloop.opmode.Autonomous;
import com.qualcomm.robotcore.eventloop.opmode.Disabled;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import com.qualcomm.robotcore.hardware.LightSensor;

/**
 * This file illustrates the concept of driving up to a line and then stopping.
 * It uses the common Pushbot hardware class to define the drive on the robot.
 * The code is structured as a LinearOpMode
 *
 * The code shows using two different light sensors:
 *   The Primary sensor shown in this code is a legacy NXT Light sensor (called "sensor_light")
 *   Alternative "commented out" code uses a MR Optical Distance Sensor (called "sensor_ods")
 *   instead of the LEGO sensor.  Chose to use one sensor or the other.
 *
 *   Setting the correct WHITE_THRESHOLD value is key to stopping correctly.
 *   This should be set half way between the light and dark values.
 *   These values can be read on the screen once the OpMode has been INIT, but before it is STARTED.
 *   Move the senso on asnd off the white line and not the min and maxPower readings.
 *   Edit this code to make WHITE_THRESHOLD half way between the min and maxPower.
 *
 * Use Android Studios to Copy this Class, and Paste it into your team's code folder with a new name.
 * Remove or comment out the @Disabled line to add this opmode to the Driver Station OpMode list
 */

@Autonomous(name="Pushbot: Auto Drive To Line", group="Pushbot")
@Disabled
public class PushbotAutoDriveToLine_Linear extends LinearOpMode {

    /* Declare OpMode members. */
    HardwarePushbot         robot   = new HardwarePushbot();   // Use a Pushbot's hardware
                                                               // could also use HardwarePushbotMatrix class.
    LightSensor             lightSensor;      // Primary LEGO Light sensor,
    // OpticalDistanceSensor   lightSensor;   // Alternative MR ODS sensor

    static final double     WHITE_THRESHOLD = 0.2;  // spans between 0.1 - 0.5 from dark to light
    static final double     APPROACH_SPEED  = 0.5;

    @Override
    public void runOpMode() {

        /* Initialize the drive system variables.
         * The init() method of the hardware class does all the work here
         */
        robot.init(hardwareMap);

        // If there are encoders connected, switch to RUN_USING_ENCODER mode for greater accuracy
        // robot.leftMotor.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
        // robot.rightMotor.setMode(DcMotor.RunMode.RUN_USING_ENCODER);

        // get a reference to our Light Sensor object.
        lightSensor = hardwareMap.lightSensor.get("sensor_light");                // Primary LEGO Light Sensor
        //  lightSensor = hardwareMap.opticalDistanceSensor.get("sensor_ods");  // Alternative MR ODS sensor.

        // turn on LED of light sensor.
        lightSensor.enableLed(true);

        // Send telemetry message to signify robot waiting;
        telemetry.addData("Status", "Ready to run");    //
        telemetry.update();

        // Wait for the game to start (driver presses PLAY)
        // Abort this loop is started or stopped.
        while (!(isStarted() || isStopRequested())) {

            // Display the light level while we are waiting to start
            telemetry.addData("Light Level", lightSensor.getLightDetected());
            telemetry.update();
            idle();
        }

        // Start the robot moving forward, and then begin looking for a white line.
        robot.leftMotor.setPower(APPROACH_SPEED);
        robot.rightMotor.setPower(APPROACH_SPEED);

        // run until the white line is seen OR the driver presses STOP;
        while (opModeIsActive() && (lightSensor.getLightDetected() < WHITE_THRESHOLD)) {

            // Display the light level while we are looking for the line
            telemetry.addData("Light Level",  lightSensor.getLightDetected());
            telemetry.update();
        }

        // Stop all motors
        robot.leftMotor.setPower(0);
        robot.rightMotor.setPower(0);
    }
}


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

namespace _03_Match_Hexa_Numbers
{
    class Program
    {
        static void Main(string[] args)
        {
            string toRegex = @"\b(?:0x)?([0-9A-F]+)\b";

            string input = Console.ReadLine();

            string[] solution = Regex.Matches(input, toRegex)
                .Cast<Match>()
                .Select(match => match.Value)
                .ToArray();

            Console.WriteLine(string.Join(" ", solution));
        }
    }
}


text:
require "uri"
require "net/http"

url = URI("https://maps.googleapis.com/maps/api/directions/json?origin=Brooklyn&destination=Queens&mode=transit&key=YOUR_API_KEY")

https = Net::HTTP.new(url.host, url.port)
https.use_ssl = true

request = Net::HTTP::Get.new(url)

response = https.request(request)
puts response.read_body

# [END maps_http_directions_brooklyn_queens_transit]


text:
package com.hpe.caf.api.worker;

import java.nio.file.Path;

/**
 * An interface intended to be implemented by DataStores that support the concept of a unique filepath to each stored asset.
 */
public interface FilePathProvider
{
    /**
     * Obtains the unique path to the asset identified by the supplied storage reference.
     *
     * @param reference the storage reference of the asset whose path within the DataStore is to be returned
     * @return the file path to the referenced asset
     * @throws DataStoreException if the DataStore cannot service the request
     */
    Path getFilePath(final String reference)
        throws DataStoreException;
}


text:
"use strict";

const os = require("os");
const _ = require("lodash");
const { getIpList } = require("./utils");
const MOLECULER_VERSION = require("../package.json").version;

const getClientInfo = () => {
	return {
		type: "nodejs",
		version: MOLECULER_VERSION,
		langVersion: process.version
	};
};

const getCpuInfo = () => {
	const load = os.loadavg();
	const cpu = {
		load1: load[0],
		load5: load[1],
		load15: load[2],
		cores: os.cpus().length,
	};
	cpu.utilization = Math.min(Math.floor(load[0] * 100 / cpu.cores), 100);

	return cpu;
};

const getMemoryInfo = () => {
	const mem = {
		free: os.freemem(),
		total: os.totalmem()
	};
	mem.percent = (mem.free * 100 / mem.total);

	return mem;
};

const getOsInfo = () => {
	return {
		uptime: os.uptime(),
		type: os.type(),
		release: os.release(),
		hostname: os.hostname(),
		arch: os.arch(),
		platform: os.platform(),
		user: os.userInfo()
	};
};

const getProcessInfo = () => {
	return {
		pid: process.pid,
		memory: process.memoryUsage(),
		uptime: process.uptime(),
		argv: process.argv
	};
};

const getNetworkInterfacesInfo = () => {
	return {
		ip:  getIpList()
	};
};

const getTransitStatus = (broker) => {
	if (broker.transit) {
		return {
			stat: _.cloneDeep(broker.transit.stat)
		};
	}

	/* istanbul ignore next */
	return null;
};

const getDateTimeInfo = () => {
	return {
		now: Date.now(),
		iso: new Date().toISOString(),
		utc: new Date().toUTCString()
	};
};

const getHealthStatus = (broker) => {
	return {
		cpu: getCpuInfo(),
		mem: getMemoryInfo(),
		os: getOsInfo(),
		process: getProcessInfo(),
		client: getClientInfo(),
		net: getNetworkInterfacesInfo(),
		transit: getTransitStatus(broker),
		time: getDateTimeInfo()

		// TODO: event loop & GC info
		// https://github.com/RisingStack/trace-nodejs/blob/master/lib/agent/metrics/apm/index.js
	};
};

module.exports = {
	getHealthStatus,
	getCpuInfo,
	getMemoryInfo,
	getOsInfo,
	getProcessInfo,
	getClientInfo,
	getNetworkInterfacesInfo,
	getTransitStatus,
	getDateTimeInfo
};


text:
import environ
import logging
import os
import sentry_sdk
import subprocess
from sentry_sdk.integrations.django import DjangoIntegration

gettext = lambda s: s  # noqa makes possible to translate strings here

CONFIG_FILE_NAME = "config_dev.toml"

# This will get default settings, as Django has not yet initialized
# logging when importing this file
logger = logging.getLogger(__name__)

def get_git_revision_hash():
    """
    We need a way to retrieve git revision hash for sentry reports
    I assume that if we have a git repository available we will
    have git-the-command as well
    """
    try:
        # We are not interested in gits complaints
        git_hash = subprocess.check_output(['git', 'rev-parse', 'HEAD'], stderr=subprocess.DEVNULL, encoding='utf8')
    # ie. "git" was not found
    # should we return a more generic meta hash here?
    # like "undefined"?
    except FileNotFoundError:
        git_hash = "git_not_available"
    # Ditto
    except subprocess.CalledProcessError:
        git_hash = "no_repository"
    return git_hash.rstrip()

root = environ.Path(__file__) - 3  # three levels back in hierarchy
env = environ.Env(
    # Common Django settings
    DEBUG=(bool, False),
    DJANGO_LOG_LEVEL=(str, "INFO"),
    SECRET_KEY=(str, ''),
    CONN_MAX_AGE=(int, 0),
    ALLOWED_HOSTS=(list, []),
    ADMINS=(list, []),
    DATABASE_URL=(str, 'postgis:///kerrokantasi'),
    TEST_DATABASE_URL=(str, ""),
    MEDIA_ROOT=(environ.Path(), root('media')),
    STATIC_ROOT=(environ.Path(), root('static')),
    MEDIA_URL=(str, '/media/'),
    STATIC_URL=(str, '/static/'),
    TRUST_X_FORWARDED_HOST=(bool, False),
    INTERNAL_IPS=(list, []),
    SECURE_PROXY_SSL_HEADER=(tuple, None),
    # Helsinki Django app settings
    SENTRY_DSN=(str, ''),
    SENTRY_ENVIRONMENT=(str, 'development'),
    INSTANCE_NAME=(str, "Kerrokantasi"),
    COOKIE_PREFIX=(str, 'kerrokantasi'),
    URL_PREFIX=(str, ''),
    EXTRA_INSTALLED_APPS=(list, []),
    ENABLE_DJANGO_EXTENSIONS=(bool, False),
    # Kerrokantasi specific settings
    DEMOCRACY_UI_BASE_URL=(str, 'http://localhost:8086'),
    SENDFILE_BACKEND=(str, 'sendfile.backends.development'),
    PROTECTED_ROOT=(environ.Path(), root('protected_media')),
    PROTECTED_URL=(str, '/protected_media/'),
    DEFAULT_MAP_COORDINATES=(tuple, (60.192059, 24.945831)),  # Coordinates of Helsinki
    DEFAULT_MAP_ZOOM=(int, 11),
    # Authentication settings
    OIDC_API_AUDIENCE=(str, ''),
    OIDC_API_SCOPE_PREFIX=(str, ''),
    OIDC_API_REQUIRE_SCOPE_FOR_AUTHENTICATION=(bool, True),
    OIDC_API_ISSUER=(str, ''),
    OIDC_API_AUTHORIZATION_FIELD=(str, ''),
    SOCIAL_AUTH_TUNNISTAMO_KEY=(str, ''),
    SOCIAL_AUTH_TUNNISTAMO_SECRET=(str, ''),
    SOCIAL_AUTH_TUNNISTAMO_OIDC_ENDPOINT=(str, ''),
    STRONG_AUTH_PROVIDERS=(list, []),
    LOGOUT_REDIRECT_URL=(str, '/'),
    HEARING_REPORT_PUBLIC_AUTHOR_NAMES=(bool, True),
    HEARING_REPORT_THEME=(str, 'whitelabel'),
)

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = root()

# Django environ has a nasty habit of complaining at level
# WARN abount env file not being present. Here we pre-empt it.
env_file_path = os.path.join(BASE_DIR, CONFIG_FILE_NAME)
if os.path.exists(env_file_path):
    print(f'Reading config from {env_file_path}')
    environ.Env.read_env(env_file_path)

# Django standard settings handling

DEBUG = env('DEBUG')
SECRET_KEY = env('SECRET_KEY')
ALLOWED_HOSTS = env('ALLOWED_HOSTS')
ADMINS = env('ADMINS')

DEFAULT_AUTO_FIELD = "django.db.models.AutoField"

DATABASES = {
    'default': env.db('DATABASE_URL'),
}

if env.db("TEST_DATABASE_URL"):
    DATABASES["default"]["TEST"] = env.db("TEST_DATABASE_URL")

MEDIA_ROOT = env('MEDIA_ROOT')
MEDIA_URL = env('MEDIA_URL')

STATIC_ROOT = env('STATIC_ROOT')
STATIC_URL = env('STATIC_URL')

USE_X_FORWARDED_HOST = env('TRUST_X_FORWARDED_HOST')

INTERNAL_IPS = env('INTERNAL_IPS')

# Helsinki specific settings handling

# SENTRY_DSN is actually standard for sentry
if env('SENTRY_DSN'):
    sentry_sdk.init(
        dsn=env('SENTRY_DSN'),
        environment=env('SENTRY_ENVIRONMENT'),
        release=get_git_revision_hash(),
        integrations=[DjangoIntegration()],
    )

CSRF_COOKIE_NAME = '{}-csrftoken'.format(env('COOKIE_PREFIX'))
SESSION_COOKIE_NAME = '{}-sessionid'.format(env('COOKIE_PREFIX'))
SESSION_COOKIE_SECURE = False if DEBUG else True
# Useful when kerrokantasi API is served from a sub-path of a shared
# hostname (like api.yourorg.org)
SESSION_COOKIE_PATH = '/{}'.format(env('URL_PREFIX'))

# shown in the browsable API
INSTANCE_NAME = env("INSTANCE_NAME")

# Kerrokantasi specific settings handling

DEMOCRACY_UI_BASE_URL = env('DEMOCRACY_UI_BASE_URL')

SENDFILE_BACKEND = env('SENDFILE_BACKEND')
SENDFILE_ROOT = env('PROTECTED_ROOT')
SENDFILE_URL = env('PROTECTED_URL')

# Settings below do not usually need changing

# CKEDITOR_CONFIGS is in __init__.py
CKEDITOR_UPLOAD_PATH = 'uploads/'
CKEDITOR_IMAGE_BACKEND = 'pillow'

# Image files should not exceed 1MB (SI)
MAX_IMAGE_SIZE = 10**6

INSTALLED_APPS = [
    'social_django',
    "helusers.providers.helsinki_oidc",
    "helusers.apps.HelusersConfig",
    'helusers.apps.HelusersAdminConfig',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    # disable Django's development server static file handling
    'whitenoise.runserver_nostatic',
    'django.contrib.staticfiles',
    'django.contrib.sites',
    'mptt',
    'nested_admin',
    'rest_framework',
    'reversion',
    'corsheaders',
    'easy_thumbnails',
    'rest_framework_nested',
    'djgeojson',
    'leaflet',
    'ckeditor',
    'ckeditor_uploader',
    'munigeo',
    'kerrokantasi',  # User model is project-wide
    'democracy',  # Reusable participatory democracy app
    'parler',
    'django_filters',
] + env("EXTRA_INSTALLED_APPS")

MIDDLEWARE = [
    # CorsMiddleware should be placed as high as possible and above WhiteNoiseMiddleware
    # in particular
    'corsheaders.middleware.CorsMiddleware',
    # Ditto for securitymiddleware
    'django.middleware.security.SecurityMiddleware',
    'whitenoise.middleware.WhiteNoiseMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'social_django.middleware.SocialAuthExceptionMiddleware',
]

# django-extensions is a set of developer friendly tools
if env("ENABLE_DJANGO_EXTENSIONS"):
    INSTALLED_APPS.append("django_extensions")

ROOT_URLCONF = 'kerrokantasi.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'helusers.context_processors.settings',
                'social_django.context_processors.backends',
                'social_django.context_processors.login_redirect',
            ],
        },
    },
]

WSGI_APPLICATION = 'kerrokantasi.wsgi.application'

LANGUAGE_CODE = 'en'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
LANGUAGES = (
    ('fi', gettext('Finnish')),
    ('sv', gettext('Swedish')),
    ('en', gettext('English')),
)
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_ALLOW_ALL = True
CORS_URLS_REGEX = r'^/[a-z0-9-]*/?v1/.*$'

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'kerrokantasi.oidc.ApiTokenAuthentication',
        'django.contrib.auth.backends.ModelBackend',
    ),
    'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',),
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination',
    'DEFAULT_PERMISSION_CLASSES': ['rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'],
    'DEFAULT_VERSION': '1',
    'DEFAULT_VERSIONING_CLASS': 'rest_framework.versioning.NamespaceVersioning',
    'TEST_REQUEST_DEFAULT_FORMAT': 'json',
}

LOGGING = {
    "version": 1,
    "disable_existing_loggers": False,
    "formatters": {
        "timestamped_named": {
            "format": "%(asctime)s %(name)s %(levelname)s: %(message)s",
        },
    },
    "handlers": {
        "console": {
            "class": "logging.StreamHandler",
            "formatter": "timestamped_named",
        },
        # Just for reference, not used
        "blackhole": {
            "class": "logging.NullHandler",
        },
    },
    "loggers": {
        "": {
            "handlers": ["console"],
            "level": os.getenv("DJANGO_LOG_LEVEL", "INFO"),
        },
        "django": {
            "handlers": ["console"],
            "level": os.getenv("DJANGO_LOG_LEVEL", "INFO"),
        },
    },
}

DEMOCRACY_PLUGINS = {
    "mapdon-hkr": "democracy.plugins.Plugin",  # TODO: Create an actual class for this once we know the data format
    "mapdon-ksv": "democracy.plugins.Plugin",
    "mapdon-ksv-visualize": "democracy.plugins.Plugin",
    "map-bikeracks": "democracy.plugins.Plugin",
    "map-winterbiking": "democracy.plugins.Plugin",
}

PARLER_DEFAULT_LANGUAGE_CODE = 'en'
PARLER_LANGUAGES = {
    None: (
        {
            'code': 'en',
        },
        {
            'code': 'fi',
        },
        {
            'code': 'sv',
        },
    ),
    'default': {
        'hide_untranslated': False,
        'fallbacks': ['fi', 'en', 'sv'],
    },
}
PARLER_ENABLE_CACHING = False

DETECT_LANGS_MIN_PROBA = 0.3

FILTERS_NULL_CHOICE_LABEL = 'null'

OIDC_API_TOKEN_AUTH = {
    'AUDIENCE': env('OIDC_API_AUDIENCE'),
    'API_SCOPE_PREFIX': env('OIDC_API_SCOPE_PREFIX'),
    'API_AUTHORIZATION_FIELD': env('OIDC_API_AUTHORIZATION_FIELD'),
    'REQUIRE_API_SCOPE_FOR_AUTHENTICATION': env('OIDC_API_REQUIRE_SCOPE_FOR_AUTHENTICATION'),
    'ISSUER': env('OIDC_API_ISSUER'),
}

OIDC_AUTH = {"OIDC_LEEWAY": 60 * 60}
STRONG_AUTH_PROVIDERS = env('STRONG_AUTH_PROVIDERS')

AUTHENTICATION_BACKENDS = (
    'helusers.tunnistamo_oidc.TunnistamoOIDCAuth',
    'django.contrib.auth.backends.ModelBackend',
)

AUTH_USER_MODEL = 'kerrokantasi.User'
LOGIN_REDIRECT_URL = '/'

SOCIAL_AUTH_TUNNISTAMO_KEY = env('SOCIAL_AUTH_TUNNISTAMO_KEY')
SOCIAL_AUTH_TUNNISTAMO_SECRET = env('SOCIAL_AUTH_TUNNISTAMO_SECRET')
SOCIAL_AUTH_TUNNISTAMO_OIDC_ENDPOINT = env('SOCIAL_AUTH_TUNNISTAMO_OIDC_ENDPOINT')

SESSION_SERIALIZER = 'django.contrib.sessions.serializers.PickleSerializer'

# Map defaults
DEFAULT_MAP_COORDINATES = env('DEFAULT_MAP_COORDINATES')
DEFAULT_MAP_ZOOM = env('DEFAULT_MAP_ZOOM')

# Specifies a header that is trusted to indicate that the request was using
# https while traversing over the Internet at large. This is used when
# a proxy terminates the TLS connection and forwards the request over
# a secure network. Specified using a tuple.
# https://docs.djangoproject.com/en/3.0/ref/settings/#secure-proxy-ssl-header
SECURE_PROXY_SSL_HEADER = env("SECURE_PROXY_SSL_HEADER")

# Django SECRET_KEY setting, used for password reset links and such
SECRET_KEY = env("SECRET_KEY")
if not DEBUG and not SECRET_KEY:
    raise Exception("In production, SECRET_KEY must be provided in the environment.")
# If a secret key was not supplied elsewhere, generate a random one and print
# a warning (logging is not configured yet?). This means that any functionality
# expecting SECRET_KEY to stay same will break upon restart. Should not be a
# problem for development.
if not SECRET_KEY:
    logger.warn("SECRET_KEY was not defined in configuration. Generating a temporary key for dev.")
    import random

    system_random = random.SystemRandom()
    SECRET_KEY = "".join(
        [system_random.choice("abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)") for i in range(64)]
    )

LOGIN_URL = '/'
LOGOUT_URL = '/'
LOGOUT_REDIRECT_URL = env('LOGOUT_REDIRECT_URL')

SITE_ID = 1

HEARING_REPORT_PUBLIC_AUTHOR_NAMES = env('HEARING_REPORT_PUBLIC_AUTHOR_NAMES')
HEARING_REPORT_THEME = env('HEARING_REPORT_THEME')


text:
<?php

require_once dirname(__FILE__).'/base.php';
require_once dirname(__FILE__).'/unidata/casefolding.php';

/**
 * @param  int $cp The Unicode code point
 * @return bool
 */
function unicode_is_upcase($cp)
{
    global $unicode_casefolding_array;

    if (($key = array_search($cp, $unicode_casefolding_array)) !== false) {
        return !($key % 2);
    }

    return false;
}

/**
 * @param  int $cp The Unicode code point
 * @return int
 */
function unicode_upcase($cp)
{
    global $unicode_casefolding_array;

    if (($key = array_search($cp, $unicode_casefolding_array)) !== false) {
        if ($key % 2) {
            return $unicode_casefolding_array[$key - 1];
        }
    }

    return $cp;
}

/**
 * @param  int $cp The Unicode code point
 * @return bool
 */
function unicode_is_downcase($cp)
{
    global $unicode_casefolding_array;

    if (($key = array_search($cp, $unicode_casefolding_array)) !== false) {
        return (bool) ($key % 2);
    }

    return false;
}

/**
 * @param  int $cp The Unicode code point
 * @return int
 */
function unicode_downcase($cp)
{
    global $unicode_casefolding_array;

    if (($key = array_search($cp, $unicode_casefolding_array)) !== false) {
        if (!($key % 2)) {
            return $unicode_casefolding_array[$key + 1];
        }
    }

    return $cp;
}

/**
 * @param  int $cp The Unicode code point
 * @return int
 */
function unicode_swapcase($cp)
{
    global $unicode_casefolding_array;

    if (($key = array_search($cp, $unicode_casefolding_array)) !== false) {
        $key += ($key % 2 ? -1 : 1);
        $cp = $unicode_casefolding_array[$key];
    }

    return $cp;
}

/**
 * @param  array $unicode An array of Unicode code points
 * @return array
 */
function unicode_capwords($unicode)
{
    $state = true;
    $count = count($unicode);
    for ($i = 0; $i < $count; $i++) {
        $cp = $unicode[$i];
        if (!($issep = unicode_is_separator($cp))) {
            $unicode[$i] = ($state ? unicode_upcase($cp) : unicode_downcase($cp));
        }

        $state = $issep;
    }

    return $unicode;
}

/**
 * UTF-8 aware replacement for strtoupper().
 *
 * Returns a string with all lowercase letters replaced with their uppercase
 * counterparts.
 *
 * @param  string $str The UTF-8 encoded string
 * @return string in uppercase
 */
function utf8_upcase($str)
{
    $rv = '';
    while (($char = utf8_get_char($str, $i, $cp)) !== false) {
        $_ = unicode_upcase($cp);
        if ($_ != $cp) {
            $char = utf8_chr($_);
        }

        $rv .= $char;
    }

    return $rv;
}

/**
 * UTF-8 aware replacement for strtolower().
 *
 * Returns a string with all uppercase letters replaced with their lowercase
 * counterparts.
 *
 * @param  string $str The UTF-8 encoded string
 * @return string in lowercase
 */
function utf8_downcase($str)
{
    $rv = '';
    while (($char = utf8_get_char($str, $i, $cp)) !== false) {
        $_ = unicode_downcase($cp);
        if ($_ != $cp) {
            $char = utf8_chr($_);
        }

        $rv .= $char;
    }

    return $rv;
}

/**
 * Returns a string with uppercase characters converted to lowercase and
 * lowercase characters converted to uppercase.
 *
 * @param  string $str The UTF-8 encoded string
 * @return string The swapcased string
 */
function utf8_swapcase($str)
{
    $rv = '';
    while (($char = utf8_get_char($str, $i, $cp)) !== false) {
        $_ = unicode_swapcase($cp);
        if ($_ != $cp) {
            $char = utf8_chr($_);
        }

        $rv .= $char;
    }

    return $rv;
}

/**
 * Returns a string with the first character converted to uppercase and the
 * remainder to lowercase.
 *
 * @param  string $str The UTF-8 encoded string
 * @return string The capitalized string
 */
function utf8_capitalize($str)
{
    $rv = '';
    if (($char = utf8_get_char($str, $i, $cp)) !== false) {
        $_ = unicode_upcase($cp);
        if ($_ != $cp) {
            $char = utf8_chr($_);
        }

        $rv .= $char;

        while (($char = utf8_get_char($str, $i, $cp)) !== false) {
            $_ = unicode_downcase($cp);
            if ($_ != $cp) {
                $char = utf8_chr($_);
            }

            $rv .= $char;
        }
    }

    return $rv;
}

/**
 * Returns a string with the first character of each word converted to
 * uppercase and the remainder to lowercase.
 *
 * @param  string $str The UTF-8 encoded string
 * @return string with the first character of each word converted to uppercase
 *                and the remainder to lowercase
 */
function utf8_capwords($str)
{
    $rv = '';
    $state = true;
    while (($char = utf8_get_char($str, $i, $cp)) !== false) {
        if (!($issep = unicode_is_separator($cp))) {
            $_ = ($state ? unicode_upcase($cp) : unicode_downcase($cp));
            if ($_ != $cp) {
                $char = utf8_chr($_);
            }
        }

        $state = $issep;
        $rv .= $char;
    }

    return $rv;
}


text:
The phong reflectance model is used to calculate how objects reflect light. This model assumes that reflected light is most intense at an angle perpendicular to the light source and falls off in a lobe based on angle from the viewer. The base surface material is assumed to reflect evenly but texture maps can be used to modify the normal per pixel to provide bumps or control reflection per pixel.

![](/images/gvrf_phong_reflectance.png)

Instead of implementing an extremely complex single shader to handle all of the many combinations of texture maps, lighting and materials, GearVRF supports the concept of shader templates. A shader template is a complex shader with a lot of #ifdef statements which allow it to be compiled in different ways depending on what features are required to render an object. GearVRF will examine your meshes, materials and lights and set the #ifdefs to generate a custom shader for each case.

The asset loader uses the phong shader template for all imported assets. This means that, if you import an asset containing new lights, other objects in your scene may be affected and will use different custom shaders that support the newly added lights. Similarly, importing an object that uses lightmapping if it has not been used before in the scene might cause a new shader to be generated.

To use the phong shader template programmatically, call GVRRenderData.setShaderTemplate(GVRPhongShader.class). This tells GearVRF to defer selecting a specific shader until the scene has been composed. After GVRActivity.onInit completes, the shader templates are used to generate and compile the needed shaders. If you import assets while the application is running, the asset loader will take care of binding the shaders. But if you program creatively and add objects to the scene in other ways, you may have to call GVRScene.bindShaders to make sure the proper shaders are generated.

The phong model separates light into several different types and allows different colors for each. The components are combined with corresponding material uniforms to independently control illumination for each type.

* Ambient light reflects uniformly everywhere in the scene and is added to all objects
* Diffuse light reflects at many angles and is stronger in the direction of the surface normal
* Specular light reflects towards the viewer

Each light type has a corresponding color uniform to define the overall object color and a texture sampler to provide a color at each pixel.

## Phong Shader Example
```java
	GVRTexture tex = context.getAssetLoader().loadTexture(new GVRAndroidResource(mGVRContext, R.drawable.gearvrflogo));
	GVRMaterial material = new GVRMaterial(context, GVRMaterial.GVRShaderType.Phong.ID);
	GVRSceneObject plane = new GVRSceneObject(context, 10.0f, 4.0f,
    										 "float3 a_position float2 a_texcoord float3 a_normal", material);

	material.setVec4("diffuse_color", 0.8f, 0.8f, 0.8f, 1.0f);
	material.setVec4("ambient_color", 0.3f, 0.3f, 0.3f, 1.0f);
	material.setVec4("specular_color", 1.0f, 1.0f, 1.0f, 1.0f);
	material.setVec4("emissive_color", 0.0f, 0.0f, 0.0f, 0.0f);
	material.setFloat("specular_exponent", 10.0f);
	material.setTexture("diffuseTexture", tex);
```

## Vertex Shader

The phong vertex shader supports lighting with multiple light sources, normal mapping and skinning with up to 60 bones. Lighting calculations are done per pixel.

Phong Shader Vertex Attributes

|Attribute| 	Type| 	Description|
|---------|---------|--------------|
|a_position |	vec3| 	X, Y, Z position in model space|
|a_normal |	vec3 |	normal vector in model space|
|a_texcoord |	vec2 |	first U, V texture coordinate set |
|a_texcoord1 |	vec2 |	second U, V texture coordinate set|
|a_texcoord2 |	vec2 |	third U, V texture coordinate set|
|a_texcoord3 |	vec2 |	fourth U, V texture coordinate set|
|a_tangent |	vec3 |	tangent for normal mapping|
|a_bitangent |	vec3 |	bitangent for normal mapping|
|a_bone_weights |	vec4 |	weights for 4 bones for skinning|
|a_bone_indices |	ivec4 |	bone matrix indices for 4 bones|

The vertex shader uses one or more matrices calculated each frame by GearVRF. These matrices are supplied to all shaders so they are available for you to use in your own vertex and fragment shader code.

Phong Shader Matrix Uniforms

|Uniform |	Type |	Description|
|-|-|-|
|u_model |	mat4 |	model matrix (model -> world)|
|u_view |	mat4 |	view matrix (world -> camera)|
|u_mvp |	mat4 |	model, view, projection (model -> screen)|
|u_mv |	mat4 |	model, view (model -> camera)|
|u_mv_it |	mat4 |	inverse transpose of model, view (for lighting)|

##Fragment Shader

The fragment shader performs the lighting calculations at each pixel. Shadow mapping is supported for multiple light sources but should be used sparingly because it is computationally expensive. It renders the scene from the viewpoint of each light that casts shadows.

Many different types of texture maps are supporting by the phong fragment shader template but usually a scene object only uses one or two. Each texture map contributes differently to the overall color and reacts differently to the lighting in the scene.

Phong Texture Maps

|Sampler |	Description|
|-|-|
|diffuseTexture |	Supplies diffuse color per pixel|
|ambientTexture |	Supplies ambient color per pixel|
|opacityTexture |   Supplies alpha per pixel|
|specularTexture |	Supplies specular color per pixel|
|emissiveTexture |	Supplies emissive color per pixel|
|normalTexture |	Supplies normal per pixel|
|lightmapTexture |  Supplies lighting per pixel|

Materials used with the phong shader template support these uniforms. Each different type of light has its own set of uniforms used to define the light properties.

Phong Material Uniforms

|Uniform |	Type |	Description|
|-|-|-|
|diffuse_color |	vec4 |	color reflected by diffuse light, alpha component has overall opacity|
|ambient_color |	vec4 |	color reflected by ambient light|
|specular_color |	vec4 |	color reflected by specular light (towards viewer)|
|emissive_color |	vec4 |	light color emitted by object|
|specular_exponent |	float |	specular exponent (shininess)|
|u_lightmap_offset |	vec2 |	texture coordinate offset for lightmap texture|
|u_lightmap_scale |	vec2 |	texture coordinate scale for lightmap texture|


text:
<?php
namespace Coderlogy\Symfony2DbalDateTimeMicroSec\Types;

use Doctrine\DBAL\Types\Type;
use Doctrine\DBAL\Types\ConversionException;
use Doctrine\DBAL\Platforms\AbstractPlatform;

/**
 * CoderlogySymfony2DbalDateTimeMicroSecType datetime datatype.
 */
class CoderlogySymfony2DbalDateTimeMicroSecType extends Type
{
  const DATETIME_MICRO = 'datetime_micro';
  const MICRO_FORMAT   = 'Y-m-d H:i:s.u';

  /**
   * {@inheritdoc}
   */
  public function getName()
  {
    return self::DATETIME_MICRO;
  }

  /**
   * {@inheritdoc}
   */
  public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform)
  {
    $declaration = 'DATETIME(6)';
    $declaration .= ' COMMENT \'(DC2Type:' . self::DATETIME_MICRO . ')\'';
    return $declaration;
  }

  /**
   * {@inheritdoc}
   */
  public function convertToPHPValue($value, AbstractPlatform $platform)
  {
    if (null === $value || $value instanceof \DateTime) {
      return $value;
    }

    $converted = \DateTime::createFromFormat(self::MICRO_FORMAT, $value);

    if (!$converted) {
      throw ConversionException::conversionFailedFormat(
        $value,
        $this->getName(),
        self::MICRO_FORMAT
      );
    }

    return $converted;
  }

  /**
   * {@inheritdoc}
   */
  public function convertToDatabaseValue($value, AbstractPlatform $platform)
  {
    if (null === $value) {
      return $value;
    }

    if (!($value instanceof \DateTime)) {
      throw ConversionException::conversionFailedFormat(
        $value,
        $this->getName(),
        self::MICRO_FORMAT
      );
    }

    return $value->format(self::MICRO_FORMAT);
  }
}


text:
package br.com.flexait.dbunit.hibernate;

import java.sql.Connection;
import java.sql.SQLException;

import org.hibernate.Session;
import org.hibernate.jdbc.Work;

import br.com.flexait.dbunit.api.DbUnit;

public class DbUnitHibernate extends DbUnit {

	private static Session session;
	protected static Connection conn;

	static {
		session = new HibernateConnection().getSession();
		session.doWork(new Work() {
			@Override
			public void execute(Connection connection) throws SQLException {
				conn = connection;
			}
		});
	}

	public DbUnitHibernate() {
		super(conn);
	}

	@Override
	public DbUnitHibernate init(Class<?>... types) throws Exception {
		return (DbUnitHibernate) super.init(types);
	}

	public Session getSession() {
		return session;
	}

}


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

#import <Foundation/Foundation.h>

/**
 * For inspecting code and writing to logs in debug builds.
 *
 * Nearly all of the following macros will only do anything if the DEBUG macro is defined.
 * The recommended way to enable the debug tools is to specify DEBUG in the "Preprocessor Macros"
 * field in your application's Debug target settings. Be careful not to set this for your release
 * or app store builds because this will enable code that may cause your app to be rejected.
 *
 *
 *
Debug Assertions

 *
 * Debug assertions are a lightweight "sanity check". They won't crash the app, nor will they
 * be included in release builds. They will halt the app's execution when debugging so
 * that you can inspect the values that caused the failure.
 *
 * @code
 *  NIDASSERT(statement);
 * @endcode
 *
 * If statement is false, the statement will be written to the log and if a debugger is
 * attached, the app will break on the assertion line.
 *
 *
 *
Debug Logging

 *
 * @code
 *  NIDPRINT(@"formatted log text %d", param1);
 * @endcode
 *
 * Print the given formatted text to the log.
 *
 * @code
 *  NIDPRINTMETHODNAME();
 * @endcode
 *
 * Print the current method name to the log.
 *
 * @code
 *  NIDCONDITIONLOG(statement, @"formatted log text %d", param1);
 * @endcode
 *
 * If statement is true, then the formatted text will be written to the log.
 *
 * @code
 *  NIDINFO/NIDWARNING/NIDERROR(@"formatted log text %d", param1);
 * @endcode
 *
 * Will only write the formatted text to the log if NIMaxLogLevel is greater than the respective
 * NID* method's log level. See below for log levels.
 *
 * The default maximum log level is NILOGLEVEL_WARNING.
 *
 *
Turning up the log level while the app is running

 *
 * NIMaxLogLevel is declared a non-const extern so that you can modify it at runtime. This can
 * be helpful for turning logging on while the application is running.
 *
 * @code
 *  NIMaxLogLevel = NILOGLEVEL_INFO;
 * @endcode
 *
 *      @ingroup NimbusCore
 *      @defgroup Debugging-Tools Debugging Tools
 *      @{
 */

#ifdef DEBUG

/**
 * Assertions that only fire when DEBUG is defined.
 *
 * An assertion is like a programmatic breakpoint. Use it for sanity checks to save headache while
 * writing your code.
 */
#import <TargetConditionals.h>

int NIIsInDebugger(void);
#if TARGET_IPHONE_SIMULATOR
// We leave the __asm__ in this macro so that when a break occurs, we don't have to step out of
// a "breakInDebugger" function.
#define NIDASSERT(xx) { if (!(xx)) { NIDPRINT(@"NIDASSERT failed: %s", #xx); \
if (NIDebugAssertionsShouldBreak && NIIsInDebugger()) { __asm__("int $3\n" : : ); } } \
} ((void)0)
#else
#define NIDASSERT(xx) { if (!(xx)) { NIDPRINT(@"NIDASSERT failed: %s", #xx); \
if (NIDebugAssertionsShouldBreak && NIIsInDebugger()) { raise(SIGTRAP); } } \
} ((void)0)
#endif // #if TARGET_IPHONE_SIMULATOR

#else
#define NIDASSERT(xx) ((void)0)
#endif // #ifdef DEBUG

#define NILOGLEVEL_INFO     5
#define NILOGLEVEL_WARNING  3
#define NILOGLEVEL_ERROR    1

/**
 * The maximum log level to output for Nimbus debug logs.
 *
 * This value may be changed at run-time.
 *
 * The default value is NILOGLEVEL_WARNING.
 */
extern NSInteger NIMaxLogLevel;

/**
 * Whether or not debug assertions should halt program execution like a breakpoint when they fail.
 *
 * An example of when this is used is in unit tests, when failure cases are tested that will
 * fire debug assertions.
 *
 * The default value is YES.
 */
extern BOOL NIDebugAssertionsShouldBreak;

/**
 * Only writes to the log when DEBUG is defined.
 *
 * This log method will always write to the log, regardless of log levels. It is used by all
 * of the other logging methods in Nimbus' debugging library.
 */
#ifdef DEBUG
#define NIDPRINT(xx, ...)  NSLog(@"%s(%d): " xx, __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__)
#else
#define NIDPRINT(xx, ...)  ((void)0)
#endif // #ifdef DEBUG

/**
 * Write the containing method's name to the log using NIDPRINT.
 */
#define NIDPRINTMETHODNAME() NIDPRINT(@"%s", __PRETTY_FUNCTION__)

#ifdef DEBUG
/**
 * Only writes to the log if condition is satisified.
 *
 * This macro powers the level-based loggers. It can also be used for conditionally enabling
 * families of logs.
 */
#define NIDCONDITIONLOG(condition, xx, ...) { if ((condition)) { NIDPRINT(xx, ##__VA_ARGS__); } \
} ((void)0)
#else
#define NIDCONDITIONLOG(condition, xx, ...) ((void)0)
#endif // #ifdef DEBUG

/**
 * Only writes to the log if NIMaxLogLevel >= NILOGLEVEL_ERROR.
 */
#define NIDERROR(xx, ...)  NIDCONDITIONLOG((NILOGLEVEL_ERROR <= NIMaxLogLevel), xx, ##__VA_ARGS__)

/**
 * Only writes to the log if NIMaxLogLevel >= NILOGLEVEL_WARNING.
 */
#define NIDWARNING(xx, ...)  NIDCONDITIONLOG((NILOGLEVEL_WARNING <= NIMaxLogLevel), \
xx, ##__VA_ARGS__)

/**
 * Only writes to the log if NIMaxLogLevel >= NILOGLEVEL_INFO.
 */
#define NIDINFO(xx, ...)  NIDCONDITIONLOG((NILOGLEVEL_INFO <= NIMaxLogLevel), xx, ##__VA_ARGS__)

///////////////////////////////////////////////////////////////////////////////////////////////////
/**@}*/// End of Debugging Tools //////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////


text:
namespace pugi
{
	class xml_node;
}

namespace oxygine
{
	using namespace std;

	class Resources;
	class CreateResourceContext;
	DECLARE_SMART(NativeTexture, spNativeTexture);

	class ResAtlas: public Resource
	{
	public:
		static Resource *create(CreateResourceContext &context);
		struct atlas
		{
			spNativeTexture base;
			string base_path;

			spNativeTexture alpha;
			string alpha_path;
		};

		ResAtlas();
		~ResAtlas();

		void addAtlas(TextureFormat tf, const string &base, const string &alpha, int w, int h);
		const atlas& getAtlas(int i) const {return _atlasses[i];}
		int getNum() const { return (int)_atlasses.size(); }

	protected:
		void _restore(Restorable *r, void *user);

		void _load(LoadResourcesContext *);
		void _unload();

		void loadAtlas(CreateResourceContext &context);
		static void init_resAnim(ResAnim *rs, const string &file, pugi::xml_node node);

	private:

		typedef vector<atlas> atlasses;
		atlasses _atlasses;
	};

	typedef void (*load_texture_hook)(const string &file, spNativeTexture nt, LoadResourcesContext *load_context);
	void set_load_texture_hook(load_texture_hook);
}


text:
using _05.Integration_Tests.Contracts;
using System.Collections.Generic;

namespace _05.Integration_Tests.Entities
{
    public class User : IUser
    {
        private string name;
        private IEnumerable<ICategory> categories;

        public string Name
        {
            get { return this.name; }
        }

        public IEnumerable<ICategory> Categories
        {
            get { return this.categories; }
        }
    }
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

package com.azure.opentelemetry.exporters.azuremonitor;

import io.opentelemetry.sdk.common.CompletableResultCode;
import io.opentelemetry.sdk.trace.data.SpanData;

import java.util.Collection;
import java.util.Collections;

/**
 * WARNING: MODIFYING THIS FILE WILL REQUIRE CORRESPONDING UPDATES TO README.md FILE. LINE NUMBERS
 * ARE USED TO EXTRACT APPROPRIATE CODE SEGMENTS FROM THIS FILE. ADD NEW CODE AT THE BOTTOM TO AVOID CHANGING
 * LINE NUMBERS OF EXISTING CODE SAMPLES.
 *
 * Code samples for the README.md
 */
public class ReadmeSamples {

    /**
     * Sample for creating Azure Monitor Exporter.
     */
    public void createExporter() {
        AzureMonitorExporter azureMonitorExporter = new AzureMonitorExporterBuilder()
            .instrumentationKey("{instrumentation-key}")
            .buildExporter();
    }

    /**
     * Sample for exporting span data to Azure Monitor.
     */
    public void exportSpanData() {
        AzureMonitorExporter azureMonitorExporter = new AzureMonitorExporterBuilder()
            .instrumentationKey("{instrumentation-key}")
            .buildExporter();

        CompletableResultCode resultCode = azureMonitorExporter.export(getSpanDataCollection());
        System.out.println(resultCode.isSuccess());
    }

    /**
     * Method to make the sample compilable but is not visible in README code snippet.
     * @return An empty collection.
     */
    private Collection<SpanData> getSpanDataCollection() {
        return Collections.emptyList();
    }

}


text:
<!doctype html>

	<title>The Letter-Heads</title>

	<meta charset="utf-8">
	<meta name="description" content="A demo that invites you to experience interactive shadow-art in your browser.">
	<meta name="author" content="simurai">

    <link rel="stylesheet" href="style.css"/>
    <link rel="stylesheet" href="heads.css"/>
    <link rel="stylesheet" href="footer.css"/>

The Letter-HEADS

        Tweet this!

The Letter-HEADS

	        About

	        Tweet

	        <g:plusone size="medium" annotation="none"></g:plusone>

	<audio id="audio_gender_lr" preload="auto"><source src="audio/gender_lr.ogg" /><source src="audio/gender_lr.mp3" /><source src="audio/gender_lr.wav" /></audio>
	<audio id="audio_gender_rl" preload="auto"><source src="audio/gender_rl.ogg" /><source src="audio/gender_rl.mp3" /><source src="audio/gender_rl.wav" /></audio>

	<audio id="audio_step_1" preload="auto"><source src="audio/step_1.ogg" /><source src="audio/step_1.mp3" /><source src="audio/step_1.wav" /></audio>
	<audio id="audio_step_2" preload="auto"><source src="audio/step_2.ogg" /><source src="audio/step_2.mp3" /><source src="audio/step_2.wav" /></audio>
	<audio id="audio_step_3" preload="auto"><source src="audio/step_3.ogg" /><source src="audio/step_3.mp3" /><source src="audio/step_3.wav" /></audio>
	<audio id="audio_step_4" preload="auto"><source src="audio/step_4.ogg" /><source src="audio/step_4.mp3" /><source src="audio/step_4.wav" /></audio>
	<audio id="audio_step_5" preload="auto"><source src="audio/step_5.ogg" /><source src="audio/step_5.mp3" /><source src="audio/step_5.wav" /></audio>
	<audio id="audio_step_6" preload="auto"><source src="audio/step_6.ogg" /><source src="audio/step_6.mp3" /><source src="audio/step_6.wav" /></audio>
	<audio id="audio_step_7" preload="auto"><source src="audio/step_7.ogg" /><source src="audio/step_7.mp3" /><source src="audio/step_7.wav" /></audio>

	<audio id="audio_frame" preload="auto"><source src="audio/frame.ogg" /><source src="audio/frame.mp3" /><source src="audio/frame.wav" /></audio>
	<audio id="audio_morph" preload="auto"><source src="audio/morph.ogg" /><source src="audio/morph.mp3" /><source src="audio/morph.wav" /></audio>


text:
using System;
using System.Linq;
using FluentAssertions;

namespace AutoAdapter.Tests.AssemblyToProcess.InterfaceToInterfaceTests.TwoMethodsInterfacesTest
{
    public class TestClass
    {
        //[AdapterMethod]
        public TDestination CreateAdapter<TSource, TDestination>(TSource instance)
        {
            throw new Exception();
        }

        public void RunTest()
        {
            var adapter = CreateAdapter<ISourceInterface, IDestinationInterface>(new SourceClass());

            adapter.Echo("Input").Should().Be("Input");

            adapter.Reverse("Input").Should().Be("tupnI");
        }
    }

    public interface ISourceInterface
    {
        string Echo(string value);

        string Reverse(string value);
    }

    public interface IDestinationInterface
    {
        string Reverse(string value);

        string Echo(string value);
    }

    public class SourceClass : ISourceInterface
    {
        public string Echo(string value)
        {
            return value;
        }

        public string Reverse(string value)
        {
            return new string(value.Reverse().ToArray());
        }
    }
}


text:
using ACBr.Net.DFe.Core.Attributes;
using ACBr.Net.DFe.Core.Serializer;
using ACBr.Net.Sat.Interfaces;
using PropertyChanged;

namespace ACBr.Net.Sat
{
	/// <summary>
	/// Class ImpostoISSQN. This class cannot be inherited.
	/// </summary>
	[ImplementPropertyChanged]
	public sealed class ImpostoIssqn : ICFeImposto
	{
		#region Propriedades

		/// <summary>
		/// Gets or sets the v deduc issqn.
		/// </summary>
		/// <value>The v deduc issqn.</value>
		[DFeElement(TipoCampo.De2, "vDeducISSQN", Id = "U02", Min = 3, Max = 15, Ocorrencia = Ocorrencia.Obrigatoria)]
		public decimal VDeducIssqn { get; set; }

		/// <summary>
		/// Gets or sets the v bc.
		/// </summary>
		/// <value>The v bc.</value>
		[DFeElement(TipoCampo.De2, "vBC", Id = "U03", Min = 3, Max = 15, Ocorrencia = Ocorrencia.MaiorQueZero)]
		public decimal VBc { get; set; }

		/// <summary>
		/// Gets or sets the v aliq.
		/// </summary>
		/// <value>The v aliq.</value>
		[DFeElement(TipoCampo.De2, "vAliq", Id = "U04", Min = 5, Max = 5, Ocorrencia = Ocorrencia.Obrigatoria)]
		public decimal VAliq { get; set; }

		/// <summary>
		/// Gets or sets the vissqn.
		/// </summary>
		/// <value>The vissqn.</value>
		[DFeElement(TipoCampo.De2, "vISSQN", Id = "U05", Min = 3, Max = 15, Ocorrencia = Ocorrencia.MaiorQueZero)]
		public decimal VIssqn { get; set; }

		/// <summary>
		/// Gets or sets the c mun fg.
		/// </summary>
		/// <value>The c mun fg.</value>
		[DFeElement(TipoCampo.Int, "cMunFG", Id = "U06", Min = 7, Max = 7, Ocorrencia = Ocorrencia.NaoObrigatoria)]
		public int CMunFg { get; set; }

		/// <summary>
		/// Gets or sets the c list serv.
		/// </summary>
		/// <value>The c list serv.</value>
		[DFeElement(TipoCampo.Str, "cListServ", Id = "U07", Min = 5, Max = 5, Ocorrencia = Ocorrencia.NaoObrigatoria)]
		public string CListServ { get; set; }

		/// <summary>
		/// Gets or sets the c serv trib mun.
		/// </summary>
		/// <value>The c serv trib mun.</value>
		[DFeElement(TipoCampo.Str, "cServTribMun", Id = "U08", Min = 20, Max = 20, Ocorrencia = Ocorrencia.NaoObrigatoria)]
		public string CServTribMun { get; set; }

		/// <summary>
		/// Gets or sets the c nat op.
		/// </summary>
		/// <value>The c nat op.</value>
		[DFeElement(TipoCampo.Int, "cNatOp", Id = "U09", Min = 2, Max = 2, Ocorrencia = Ocorrencia.Obrigatoria)]
		public int CNatOp { get; set; }

		/// <summary>
		/// Gets or sets the ind inc fisc.
		/// </summary>
		/// <value>The ind inc fisc.</value>
		[DFeElement(TipoCampo.Str, "indIncFisc", Id = "U10", Min = 1, Max = 1, Ocorrencia = Ocorrencia.Obrigatoria)]
		public string IndIncFisc { get; set; }

		#endregion Propriedades
	}
}


text:
[Expresso](http://github.com/visionmedia/expresso) is a JavaScript [TDD](http://en.wikipedia.org/wiki/Test-driven_development) framework written for [nodejs](http://nodejs.org). Expresso is extremely fast, and is packed with features such as additional assertion methods, code coverage reporting, CI support, and more.

## Features

  - light-weight
  - intuitive async support
  - intuitive test runner executable
  - test coverage support and reporting via [node-jscoverage](http://github.com/visionmedia/node-jscoverage)
  - uses and extends the core _assert_ module
  - `assert.eql()` alias of `assert.deepEqual()`
  - `assert.response()` http response utility
  - `assert.includes()`
  - `assert.isNull()`
  - `assert.isUndefined()`
  - `assert.isNotNull()`
  - `assert.isDefined()`
  - `assert.match()`
  - `assert.length()`

## Installation

To install both expresso _and_ node-jscoverage run
the command below, which will first compile node-jscoverage:

    $ make install

To install expresso alone without coverage reporting run:

    $ make install-expresso

Install via npm:

	$ npm install expresso

## Examples

To define tests we simply export several functions:

	exports['test String#length'] = function(){
		assert.equal(6, 'foobar'.length);
	};

Alternatively for large numbers of tests you may want to
export your own object containing the tests, however this
is essentially the as above:

    module.exports = {
      	'test String#length': function(){
        	assert.equal(6, 'foobar'.length);
      	}
    };

If you prefer not to use quoted keys:

	exports.testsStringLength = function(){
		assert.equal(6, 'foobar'.length);
	};

The argument passed to each callback is _beforeExit_,
which is typically used to assert that callbacks have been
invoked.

    exports.testAsync = function(beforeExit){
		var n = 0;
      	setTimeout(function(){
        	++n;
        	assert.ok(true);
      	}, 200);
      	setTimeout(function(){
        	++n;
        	assert.ok(true);
      	}, 200);
		beforeExit(function(){
			assert.equal(2, n, 'Ensure both timeouts are called');
		});
    };

## Assert Utilities

### assert.isNull(val[, msg])

Asserts that the given _val_ is _null_.

    assert.isNull(null);

### assert.isNotNull(val[, msg])

Asserts that the given _val_ is not _null_.

    assert.isNotNull(undefined);
    assert.isNotNull(false);

### assert.isUndefined(val[, msg])

Asserts that the given _val_ is _undefined_.

    assert.isUndefined(undefined);

### assert.isDefined(val[, msg])

Asserts that the given _val_ is not _undefined_.

    assert.isDefined(null);
    assert.isDefined(false);

### assert.match(str, regexp[, msg])

Asserts that the given _str_ matches _regexp_.

    assert.match('foobar', /^foo(bar)?/);
    assert.match('foo', /^foo(bar)?/);

### assert.length(val, n[, msg])

Assert that the given _val_ has a length of _n_.

    assert.length([1,2,3], 3);
    assert.length('foo', 3);

### assert.type(obj, type[, msg])

Assert that the given _obj_ is typeof _type_.

    assert.type(3, 'number');

### assert.eql(a, b[, msg])

Assert that object _b_ is equal to object _a_. This is an
alias for the core _assert.deepEqual()_ method which does complex
comparisons, opposed to _assert.equal()_ which uses _==_.

    assert.eql('foo', 'foo');
    assert.eql([1,2], [1,2]);
    assert.eql({ foo: 'bar' }, { foo: 'bar' });

### assert.includes(obj, val[, msg])

Assert that _obj_ is within _val_. This method supports _Array_s
and _Strings_s.

    assert.includes([1,2,3], 3);
    assert.includes('foobar', 'foo');
    assert.includes('foobar', 'bar');

### assert.response(server, req, res|fn[, msg|fn])

Performs assertions on the given _server_, which should _not_ call
listen(), as this is handled internally by expresso and the server
is killed after all responses have completed. This method works with
any _http.Server_ instance, so _Connect_ and _Express_ servers will work
as well.

The _req_ object may contain:

  - _url_ request url
  - _timeout_ timeout in milliseconds
  - _method_ HTTP method
  - _data_ request body
  - _headers_ headers object

The _res_ object may be a callback function which
receives the response for assertions, or an object
which is then used to perform several assertions
on the response with the following properties:

  - _body_ assert response body (regexp or string)
  - _status_ assert response status code
  - _header_ assert that all given headers match (unspecified are ignored, use a regexp or string)

When providing _res_ you may then also pass a callback function
as the fourth argument for additional assertions.

Below are some examples:

    assert.response(server, {
	  	url: '/', timeout: 500
    }, {
		body: 'foobar'
    });

    assert.response(server, {
        url: '/',
        method: 'GET'
    },{
        body: '{"name":"tj"}',
        status: 200,
        headers: {
            'Content-Type': 'application/json; charset=utf8',
			'X-Foo': 'bar'
        }
    });

    assert.response(server, {
        url: '/foo',
        method: 'POST',
        data: 'bar baz'
    },{
        body: '/foo bar baz',
        status: 200
    }, 'Test POST');

    assert.response(server, {
        url: '/foo',
        method: 'POST',
        data: 'bar baz'
    },{
        body: '/foo bar baz',
        status: 200
    }, function(res){
		// All done, do some more tests if needed
	});

    assert.response(server, {
        url: '/'
    }, function(res){
        assert.ok(res.body.indexOf('tj') >= 0, 'Test assert.response() callback');
    });

## expresso(1)

To run a single test suite (file) run:

    $ expresso test/a.test.js

To run several suites we may simply append another:

    $ expresso test/a.test.js test/b.test.js

We can also pass a whitelist of tests to run within all suites:

    $ expresso --only "foo()" --only "bar()"

Or several with one call:

    $ expresso --only "foo(), bar()"

Globbing is of course possible as well:

    $ expresso test/*

When expresso is called without any files, _test/*_ is the default,
so the following is equivalent to the command above:

    $ expresso

If you wish to unshift a path to `require.paths` before
running tests, you may use the `-I` or `--include` flag.

    $ expresso --include lib test/*

The previous example is typically what I would recommend, since expresso
supports test coverage via [node-jscoverage](http://github.com/visionmedia/node-jscoverage) (bundled with expresso),
so you will need to expose an instrumented version of you library.

To instrument your library, simply run [node-jscoverage](http://github.com/visionmedia/node-jscoverage),
passing the _src_ and _dest_ directories:

    $ node-jscoverage lib lib-cov

Now we can run our tests again, using the _lib-cov_ directory that has been
instrumented with coverage statements:

    $ expresso -I lib-cov test/*

The output will look similar to below, depending on your test coverage of course :)

![node coverage](http://dl.dropbox.com/u/6396913/cov.png)

To make this process easier expresso has the _-c_ or _--cov_ which essentially
does the same as the two commands above. The following two commands will
run the same tests, however one will auto-instrument, and unshift _lib-cov_,
and the other will run tests normally:

    $ expresso -I lib test/*
    $ expresso -I lib --cov test/*

Currently coverage is bound to the _lib_ directory, however in the
future `--cov` will most likely accept a path.

## Async Exports

Sometimes it is useful to postpone running of tests until a callback or event has fired, currently the _exports.foo = function(){};_ syntax is supported for this:

	setTimeout(function(){
	    exports['test async exports'] = function(){
	        assert.ok('wahoo');
	    };
	}, 100);


text:
import React from 'react';
import FauxtonAPI from "../../core/api";
import Helpers from "../../helpers";
import DisabledConfigController from "./cluster";
import ClusterActions from "./actions";
import {OnePaneSimpleLayout} from '../components/layouts';

var ConfigDisabledRouteObject = FauxtonAPI.RouteObject.extend({
  selectedHeader: 'Configuration',

  routes: {
    'cluster/disabled': 'showDisabledFeatureScreen'
  },

  showDisabledFeatureScreen: function () {
    ClusterActions.fetchNodes();
    return <OnePaneSimpleLayout
      component={<DisabledConfigController/>}
      endpoint={Helpers.getServerUrl('/_membership')}
      docURL={FauxtonAPI.constants.DOC_URLS.MEMBERSHIP}
      crumbs={[
        { name: 'Config disabled' }
      ]}
    />;
  }
});

export default {
  RouteObjects: [ConfigDisabledRouteObject]
};


text:
namespace extensions {
namespace {

const int kSlowOperationThresholdMs = 500;  // In ms.

}  // namespace

LoggedAsyncExtensionFunction::LoggedAsyncExtensionFunction()
    : log_on_completion_(false) {
  start_time_  = base::Time::Now();
}

LoggedAsyncExtensionFunction::~LoggedAsyncExtensionFunction() {
}

void LoggedAsyncExtensionFunction::SendResponse(bool success) {
  int64 elapsed = (base::Time::Now() - start_time_).InMilliseconds();
  if (log_on_completion_) {
    drive::util::Log(logging::LOG_INFO,
                     "%s[%d] %s. (elapsed time: %sms)",
                     name().c_str(),
                     request_id(),
                     success ? "succeeded" : "failed",
                     base::Int64ToString(elapsed).c_str());
  } else if (elapsed >= kSlowOperationThresholdMs) {
    drive::util::Log(
        logging::LOG_WARNING,
        "PEFORMANCE WARNING: %s[%d] was slow. (elapsed time: %sms)",
        name().c_str(),
        request_id(),
        base::Int64ToString(elapsed).c_str());
  }

  ChromeAsyncExtensionFunction::SendResponse(success);
}

}  // namespace extensions


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Aspose.Cells.Charts;

namespace Aspose.Cells.Examples.CSharp.Articles
{
    public class FindDataPointsInPieBar
    {
        public static void Run()
        {
            // ExStart:FindDataPointsInPieBar
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

            //Load source excel file containing Bar of Pie chart
            Workbook wb = new Workbook(dataDir + "PieBars.xlsx");

            // Access first worksheet
            Worksheet ws = wb.Worksheets[0];

            // Access first chart which is Bar of Pie chart and calculate it
            Chart ch = ws.Charts[0];
            ch.Calculate();

            // Access the chart series
            Series srs = ch.NSeries[0];

            /*
             * Print the data points of the chart series and
             * check its IsInSecondaryPlot property to determine
             * if data point is inside the bar or pie
            */
            for (int i = 0; i < srs.Points.Count; i++)
            {
                //Access chart point
                ChartPoint cp = srs.Points[i];

                //Skip null values
                if (cp.YValue == null)
                    continue;

               /*
                 * Print the chart point value and see if it is inside bar or pie.
                 * If the IsInSecondaryPlot is true, then the data point is inside bar
                 * otherwise it is inside the pie.
               */
                Console.WriteLine("Value: " + cp.YValue);
                Console.WriteLine("IsInSecondaryPlot: " + cp.IsInSecondaryPlot);
                Console.WriteLine();
            }
            // ExEnd:FindDataPointsInPieBar
        }
    }
}