text:
"""Utilities for combining namedtuples."""

__copyright__ = "Copyright (C) 2016-2017, DV Klopfenstein, H Tang. All rights reserved."
__author__ = "DV Klopfenstein"

import collections as cx

def get_dict_w_id2nts(ids, id2nts, flds, dflt_null=""):
    """Return a new dict of namedtuples by combining "dicts" of namedtuples or objects."""
    assert len(ids) == len(set(ids)), "NOT ALL IDs ARE UNIQUE: {IDs}".format(IDs=ids)
    assert len(flds) == len(set(flds)), "DUPLICATE FIELDS: {IDs}".format(IDs=cx.Counter(flds).most_common())
    usr_id_nt = []
    # 1. Instantiate namedtuple object
    ntobj = cx.namedtuple("Nt", " ".join(flds))
    # 2. Fill dict with namedtuple objects for desired ids
    for item_id in ids:
        # 2a. Combine various namedtuples into a single namedtuple
        nts = [id2nt.get(item_id) for id2nt in id2nts]
        vals = _combine_nt_vals(nts, flds, dflt_null)
        usr_id_nt.append((item_id, ntobj._make(vals)))
    return cx.OrderedDict(usr_id_nt)

def get_list_w_id2nts(ids, id2nts, flds, dflt_null=""):
    """Return a new list of namedtuples by combining "dicts" of namedtuples or objects."""
    combined_nt_list = []
    # 1. Instantiate namedtuple object
    ntobj = cx.namedtuple("Nt", " ".join(flds))
    # 2. Fill dict with namedtuple objects for desired ids
    for item_id in ids:
        # 2a. Combine various namedtuples into a single namedtuple
        nts = [id2nt.get(item_id) for id2nt in id2nts]
        vals = _combine_nt_vals(nts, flds, dflt_null)
        combined_nt_list.append(ntobj._make(vals))
    return combined_nt_list

def combine_nt_lists(lists, flds, dflt_null=""):
    """Return a new list of namedtuples by zipping "lists" of namedtuples or objects."""
    combined_nt_list = []
    # Check that all lists are the same length
    lens = [len(lst) for lst in lists]
    assert len(set(lens)) == 1, \
        "LIST LENGTHS MUST BE EQUAL: {Ls}".format(Ls=" ".join(str(l) for l in lens))
    # 1. Instantiate namedtuple object
    ntobj = cx.namedtuple("Nt", " ".join(flds))
    # 2. Loop through zipped list
    for lst0_lstn in zip(*lists):
        # 2a. Combine various namedtuples into a single namedtuple
        combined_nt_list.append(ntobj._make(_combine_nt_vals(lst0_lstn, flds, dflt_null)))
    return combined_nt_list

def wr_py_nts(fout_py, nts, docstring=None, varname="nts"):
    """Save namedtuples into a Python module."""
    import sys
    import datetime
    if nts:
        with open(fout_py, 'w') as prt:
            first_nt = nts[0]
            nt_name = type(first_nt).__name__
            if docstring is not None:
                prt.write('"""{DOCSTRING}"""\n\n'.format(DOCSTRING=docstring))
            prt.write("# Created: {DATE}\n".format(DATE=str(datetime.date.today())))
            prt.write("import collections as cx\n\n")
            prt.write("nt_fields = [\n")
            for fld in first_nt._fields:
                prt.write('    "{F}",\n'.format(F=fld))
            prt.write("]\n\n")
            prt.write('{NtName} = cx.namedtuple("{NtName}", " ".join(nt_fields))\n\n'.format(
                NtName=nt_name))
            prt.write("# {N:,} items\n".format(N=len(nts)))
            prt.write("{VARNAME} = [\n".format(VARNAME=varname))
            for ntup in nts:
                prt.write("    {NT},\n".format(NT=ntup))
            prt.write("]\n")
            sys.stdout.write("  WROTE: {PY}\n".format(PY=fout_py))

def get_unique_fields(fld_lists):
    """Get unique namedtuple fields, despite potential duplicates in lists of fields."""
    flds = []
    fld_set = set([f for flst in fld_lists for f in flst])
    fld_seen = set()
    # Add unique fields to list of fields in order that they appear
    for fld_list in fld_lists:
        for fld in fld_list:
            # Add fields if the field has not yet been seen
            if fld not in fld_seen:
                flds.append(fld)
                fld_seen.add(fld)
    assert len(flds) == len(fld_set)
    return flds

# -- Internal methods ----------------------------------------------------------------
def _combine_nt_vals(lst0_lstn, flds, dflt_null):
    """Given a list of lists of nts, return a single namedtuple."""
    vals = []
    for fld in flds:
        fld_seen = False
        # Set field value using the **first** value seen in list of nt lists(lst0_lstn)
        for nt_curr in lst0_lstn:
            if hasattr(nt_curr, fld):
                vals.append(getattr(nt_curr, fld))
                fld_seen = True
                break
        # Set default value if GO ID or nt value is not present
        if fld_seen is False:
            vals.append(dflt_null)
    return vals

# Copyright (C) 2016-2017, DV Klopfenstein, H Tang. All rights reserved.


text: This file only keeps the folder `external-resources` from being removed.

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace League\Uri\Modifiers;

use League\Uri\Interfaces\Uri;
use League\Uri\Types\TranscoderTrait;
use Psr\Http\Message\UriInterface;

/**
 * A class to Decode URI parts unreserved characters
 *
 * @package League.uri
 * @author  Ignace Nyamagana Butera <nyamsprod@gmail.com>
 * @since   4.2.0
 */
class DecodeUnreservedCharacters extends AbstractUriModifier
{
    use TranscoderTrait;

    /**
     * Return a Uri object modified according to the modifier
     *
     * @param Uri|UriInterface $uri
     *
     * @return Uri|UriInterface
     */
    public function __invoke($uri)
    {
        $this->assertUriObject($uri);

        foreach (['Path', 'Query', 'Fragment'] as $part) {
            $uri = $this->decodeUriPart($uri, $part);
        }

        return $uri;
    }

    /**
     * Decode an URI part
     *
     * @param Uri|UriInterface $uri
     * @param string           $property
     *
     * @return Uri|UriInterface
     */
    protected function decodeUriPart($uri, $property)
    {
        $decoder = function (array $matches) {
            return rawurldecode($matches[0]);
        };

        $value = preg_replace_callback(
            ',%('.self::$unreservedCharsEncoded.'),i',
            $decoder,
            call_user_func([$uri, 'get'.$property])
        );

        return call_user_func([$uri, 'with'.$property], $value);
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
    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>org.baeldung</groupId>
    <artifactId>spring-cloud-stream</artifactId>
    <name>spring-cloud-stream</name>
    <packaging>pom</packaging>

    <parent>
        <groupId>com.baeldung.spring.cloud</groupId>
        <artifactId>spring-cloud</artifactId>
        <version>1.0.0-SNAPSHOT</version>
    </parent>

    <modules>
        <module>spring-cloud-stream-rabbit</module>
    </modules>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-stream-rabbit</artifactId>
                <version>${spring-cloud-stream.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-stream</artifactId>
                <version>${spring-cloud-stream.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-stream-test-support</artifactId>
                <version>${spring-cloud-stream.version}</version>
                <scope>test</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

</project>


text:
package example

class Inhabitants extends Iterable[Username] {
  private var currentUsers: Seq[Username] = Nil

  def add(user: Username): Boolean = {
    if (currentUsers.contains(user)) false
    else {
      currentUsers = currentUsers :+ user
      true
    }
  }

  def remove(user: Username): Boolean = {
    if (currentUsers.contains(user)) {
      currentUsers = currentUsers.filterNot(_ == user)
      true
    } else false
  }

  override def iterator: Iterator[Username] = currentUsers.iterator
}


text:
#import "HL7PatientSummary.h"
#import "HL7Enums_Private.h"
@class HL7Name;
@class HL7Telecom;
@class HL7PatientRole;
@class HL7Code;

@interface HL7PatientSummary ()
@property (nullable, nonatomic, strong) NSArray<HL7Name *> *names;
@property (nullable, nonatomic, strong) HL7Name *name;
@property (nullable, nonatomic, strong) NSDate *dob;
@property (nullable, nonatomic, strong) NSArray<HL7Telecom *> *telecoms;
@property (nullable, nonatomic, strong) NSNumber *age;
@property (assign) HL7AdministrativeGenderCode genderCode;
@property (assign) HL7MaritalStatusCode maritalStatusCode;
@property (nullable, nonatomic, strong) HL7Code *ethnicGroupCode;
@property (nullable, nonatomic, strong) HL7Code *raceCode;
@property (nullable, nonatomic, strong) HL7Code *religiousAffiliationCode;
@property (nullable, nonatomic, strong) NSArray<HL7GuardianSummary *> *guardians;
@property (nullable, nonatomic, copy)  NSString *preferredLanguage;
- (instancetype _Nonnull)initWithPatientRole:(HL7PatientRole *_Nonnull)patientRole;
@end


text:
<?php

return array(
	'priority'       => 40,
	'capability'     => CAPATIBILITY_EDIT_THEME_OPTIONS,
	'theme_supports' => '',
	'title'          => simpletheme_translate('Special Pages'),
	'description'    => simpletheme_translate('404, Search...'),
);


text:
#ifndef FLOW_H_
#define FLOW_H_

#include <stdint.h>

/**
 * @brief Computes pixel flow from image1 to image2
 *
 * Searches the corresponding position in the new image (image2) of max. 64 pixels from the old image (image1)
 * and calculates the average offset of all.
 *
 * @param image1 previous image buffer
 * @param image2 current image buffer (new)
 * @param x_rate gyro x rate
 * @param y_rate gyro y rate
 * @param z_rate gyro z rate
 * @param pixel_flow_x Computed optical flow in x direction in pixels.
 * @param pixel_flow_y Computed optical flow in y direction in pixels.
 *
 * @return quality of flow calculation
 */
uint8_t compute_flow(uint8_t *image1, uint8_t *image2, float x_rate, float y_rate, float z_rate,
		float *pixel_flow_x, float *pixel_flow_y);

#endif /* FLOW_H_ */


text:
all: # nothing to build

install:
	mkdir -p ${DESTDIR}/etc/apt/sources.list.d
	mkdir -p ${DESTDIR}/etc/apt/trusted.gpg.d
	cp packaging/debian/cernvm.list ${DESTDIR}/etc/apt/sources.list.d/cernvm.list
	cp packaging/debian/cernvm.gpg ${DESTDIR}/etc/apt/trusted.gpg.d/cernvm.gpg


text:
package org.polaris.framework.report.excel.builder;

import java.util.*;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.polaris.framework.report.excel.items.TagTable;
import org.polaris.framework.report.excel.items.TagTr;
import org.springframework.stereotype.Service;

import jxl.write.WritableSheet;

@Service
public class TableBuilder
{
	Log log = LogFactory.getLog(getClass().getName());

	@Resource
	private TrBuilder trBuilder;

	/**
	 * 返回所生成的行数
	 */
	public int build(WritableSheet sheet, Object data, TagTable tagTable, int row)
	{
		int leftMargin = tagTable.getLeftmargin();
		int[] rowArray = null;// 定义一个行数组,初始化为空
		int currentCol = leftMargin;// 设置当前列
		int currentRow = row;// 设置当前行
		Iterator<Object> it = tagTable.getRowList().iterator();
		int count = 0;
		while (it.hasNext())
		{
			Object obj = it.next();
			if (obj instanceof TagTr)
			{
				TagTr tr = (TagTr) obj;
				// 处理这个tr
				TrParam result = trBuilder.build(sheet, data, currentRow, currentCol, tr, rowArray);
				if (result.getArray() != null)
				{
					rowArray = result.getArray();
				}
				for (int i = 0; i < rowArray.length; i++)
				{
					rowArray[i] -= result.getDr();
				}
				currentRow += result.getDr();
				count += result.getDr();
			}
			else
			{
				log.warn("UnKnown tag: " + obj.getClass());
			}
		}
		return count;
	}
}


text:
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null && pwd )"

# Source library
source $DIR/../../utils/helper.sh
source $DIR/../../utils/ccloud_library.sh

ccloud::validate_version_cli $CLI_MIN_VERSION || exit 1
ccloud::validate_logged_in_cli || exit 1
check_jq || exit 1

if [ -z "$1" ]; then
  echo "ERROR: Must supply argument that is the client configuration file created from './ccloud_stack_create.sh'. (Is it in stack-configs/ folder?) "
  exit 1
else
  CONFIG_FILE=$1
fi

PRESERVE_ENVIRONMENT="${PRESERVE_ENVIRONMENT:-false}"
if [[ $PRESERVE_ENVIRONMENT == "false" ]]; then
  read -p "This script will destroy all the resources (including the Confluent Cloud environment) in $CONFIG_FILE.  Do you want to proceed? [y/n] " -n 1 -r
else
  read -p "This script will destroy all the resources (except the Confluent Cloud environment) in $CONFIG_FILE.  Do you want to proceed? [y/n] " -n 1 -r
fi
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]
then
  exit 1
fi

ccloud::validate_ccloud_config $CONFIG_FILE || exit 1
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null && pwd )"
ccloud::generate_configs $CONFIG_FILE > /dev/null
source delta_configs/env.delta
SERVICE_ACCOUNT_ID=$(ccloud::get_service_account $CLOUD_KEY) || exit 1

echo
ccloud::destroy_ccloud_stack $SERVICE_ACCOUNT_ID

echo
echo "Tip: 'confluent' CLI currently has no environment set"


text:
package org.apache.fineract.portfolio.meeting.attendance.service;

import java.util.List;

import org.apache.fineract.infrastructure.core.data.EnumOptionData;

public interface AttendanceDropdownReadPlatformService {

    List<EnumOptionData> retrieveAttendanceTypeOptions();
}


text:
require 'carte/server'
require 'pry'
include Carte::Server::Models

namespace :carte do
  desc 'analyze data'
  task :analyze do
    title, content = {max: 0, min: 0}, {max: 0, min: 0}
    count = Hash.new(0)
    Card.all.each do |card|
      title[:max] = [card.title.length, title[:max]].max
      title[:min] = [card.title.length, title[:min]].min
      content[:max] = [card.content.length, content[:max]].max
      content[:min] = [card.content.length, content[:min]].min
      if card.content == ''
        puts "#{card.title} : content is empty"
      end
      count[card.title] += 1
    end
    puts "title: #{title}, content: #{content}"
    count.each do |title, count|
      puts "duplicate: #{title}: #{count} items" if count != 1
    end
  end

  desc 'import pdic one line format data'
  task :import do
    entries = []
    file = File.open(ENV['FILE'])
    lines = file.read.split("\n")
    lines.each_slice(2) do |title, content|
      Card.create!(title: title, content: content)
    end
  end

  desc 'export data as pdic one line format'
  task :export do
    Card.all.each do |card|
      puts card.title
      puts card.content
    end
  end

  desc 'reset database'
  task :reset do
    Card.delete_all
  end

  desc 'create indexes'
  task :create_indexes do
    Card.create_indexes
  end

  desc 'update random point'
  task :update_random do
    Card.all.each do |card|
      card.random_point = [Random.rand, 0]
      card.save!
    end
  end

  desc 'start console'
  task :console do
    binding.pry
  end
end


text:
/*
 * Copyright (c) 2008-2012, Stephen Colebourne & Michael Nascimento Santos
 *
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *  * Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *
 *  * Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 *  * Neither the name of JSR-310 nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package tck.java.time.temporal.serial;

import static java.time.temporal.ChronoUnit.CENTURIES;
import static java.time.temporal.ChronoUnit.DAYS;
import static java.time.temporal.ChronoUnit.DECADES;
import static java.time.temporal.ChronoUnit.ERAS;
import static java.time.temporal.ChronoUnit.FOREVER;
import static java.time.temporal.ChronoUnit.HALF_DAYS;
import static java.time.temporal.ChronoUnit.HOURS;
import static java.time.temporal.ChronoUnit.MICROS;
import static java.time.temporal.ChronoUnit.MILLENNIA;
import static java.time.temporal.ChronoUnit.MILLIS;
import static java.time.temporal.ChronoUnit.MINUTES;
import static java.time.temporal.ChronoUnit.MONTHS;
import static java.time.temporal.ChronoUnit.NANOS;
import static java.time.temporal.ChronoUnit.SECONDS;
import static java.time.temporal.ChronoUnit.WEEKS;
import static java.time.temporal.ChronoUnit.YEARS;

import java.io.IOException;
import java.time.temporal.ChronoUnit;

import com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import com.tngtech.java.junit.dataprovider.UseDataProvider;
import org.junit.runner.RunWith;
import org.junit.Test;

import tck.java.time.AbstractTCKTest;

/**
 * Test.
 */

@RunWith(DataProviderRunner.class)
public class TCKChronoUnitSerialization extends AbstractTCKTest {

    //-----------------------------------------------------------------------
    // ChronoUnits
    //-----------------------------------------------------------------------
    @DataProvider
    public static Object[][] data_chronoUnit() {
        return new Object[][] {
                {FOREVER},
                {ERAS},
                {MILLENNIA},
                {CENTURIES},
                {DECADES},
                {YEARS},
                {MONTHS},
                {WEEKS},
                {DAYS},

                {HALF_DAYS},
                {HOURS},
                {MINUTES},
                {SECONDS},
                {MICROS},
                {MILLIS},
                {NANOS},

        };
    }

    @Test
    @UseDataProvider("data_chronoUnit")
    public void test_unitType(ChronoUnit unit) throws IOException, ClassNotFoundException {
        assertSerializableSame(unit);
    }

}


text:
bool leopard_cam_ext::set_exposure(uint32_t exposureVal)
{
	return false;
}

uint32_t leopard_cam_ext::get_exposure()
{
	return uint32_t();
}

bool leopard_cam_ext::set_gain(uint32_t gain)
{
	return false;
}

long leopard_cam_ext::get_gain()
{
	return 0;
}

bool leopard_cam_ext::set_trigger(bool isEnabled)
{
	return false;
}

int leopard_cam_ext::set_trigger_delay_time_zero()
{
	return 0;
}


text:
package com.seleritycorp.common.base.http.common;

import com.seleritycorp.common.base.http.server.Negotiator;

/**
 * Interface for checking if objects meets another objects specifications.
 *
 * @param <T> class of specification objects.
 *
 * @see Negotiator
 */
public interface Negotiable<T> {
  /**
   * Checks if this objects meets the given specification.
   *
   * @param specification The specification to check against.
   * @return True, if this object meets the specification. False otherwise.
   */
  public boolean meets(T specification);
}


text:
FROM nginx

MAINTAINER Robert Stern <lexandro2000@gmail.com>

COPY . /usr/share/nginx/html


text:
set -e

cd $(dirname $0)

if [[ $# -ne 1 ]]; then
  echo 'Usage: buildrelease.sh version'
  echo 'e.g. buildrelease.sh 2.0.0'
  echo 'or buildrelease.sh 2.0.0-rc1'
  echo 'It is expected that a git tag will already exist'
  exit 1
fi

# Make sure the packages end up with suitable embedded paths
export ContinuousIntegrationBuild=true

declare -r VERSION=$1
declare -r OUTPUT=artifacts

rm -rf releasebuild
git clone https://github.com/nodatime/nodatime.git releasebuild -c core.autocrlf=input
cd releasebuild
git checkout "$VERSION"

# Check that the version requested matches the one in the code
declare -r ACTUAL_VERSION=$(grep \<Version\> Directory.Build.props | sed 's/<[^>]*>//g' | sed 's/ //g')

if [[ $VERSION != $ACTUAL_VERSION ]]
then
  echo "Tagged version: $VERSION. Version in Directory.Build.props: $ACTUAL_VERSION"
  echo "Aborting"
  exit 1
fi

export Configuration=Release

dotnet build src/NodaTime.sln

# Even run the slow tests before a release...
dotnet test src/NodaTime.Test

mkdir $OUTPUT

dotnet pack --no-build src/NodaTime
dotnet pack --no-build src/NodaTime.Testing
cp src/NodaTime/bin/Release/*.nupkg $OUTPUT
cp src/NodaTime.Testing/bin/Release/*.nupkg $OUTPUT
git archive $VERSION -o $OUTPUT/NodaTime-$VERSION-src.zip --prefix=NodaTime-$VERSION-src/

mkdir NodaTime-$VERSION
cp AUTHORS.txt NodaTime-$VERSION
cp LICENSE.txt NodaTime-$VERSION
cp NOTICE.txt NodaTime-$VERSION
cp 'NodaTime Release Public Key.snk' NodaTime-$VERSION
cp build/zip-readme.txt NodaTime-$VERSION/readme.txt
mkdir NodaTime-$VERSION/Portable

# Doc files
cp src/NodaTime/bin/Release/netstandard2.0/NodaTime.xml NodaTime-$VERSION
cp src/NodaTime.Testing/bin/Release/netstandard2.0/NodaTime.Testing.xml NodaTime-$VERSION

# Assemblies
cp src/NodaTime/bin/Release/netstandard2.0/NodaTime.dll NodaTime-$VERSION
cp src/NodaTime.Testing/bin/Release/netstandard2.0/NodaTime.Testing.dll NodaTime-$VERSION

# PDBs
cp src/NodaTime/bin/Release/netstandard2.0/NodaTime.pdb NodaTime-$VERSION
cp src/NodaTime.Testing/bin/Release/netstandard2.0/NodaTime.Testing.pdb NodaTime-$VERSION

declare -r BUILD_DATE=$(git show -s --format=%cI)

# see https://wiki.debian.org/ReproducibleBuilds/TimestampsInZip.
find NodaTime-$VERSION -print0 | \
  xargs -0r touch --no-dereference --date="${BUILD_DATE}"
# Assumption: -X on Windows zip is equivalent to --no-extra
TZ=UTC zip -r -9 -X --latest-time $OUTPUT/NodaTime-$VERSION.zip NodaTime-$VERSION


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

namespace Wox.Core.Exception
{
    /// <summary>
    /// Represent exceptions that wox can't handle and MUST close running Wox.
    /// </summary>
    public class WoxCritialException : WoxException
    {
        public WoxCritialException(string msg) : base(msg)
        {
        }
    }
}


text:
/**
 * @author Michael Guerrero / http://realitymeltdown.com
 */

THREE.BlendCharacter = function ( customMaterial ) {

	this.animations = {};
	this.weightSchedule = [];
	this.warpSchedule = [];

	this.load = function( url, onLoad ) {

		var scope = this;
		var ext = url.substring( url.lastIndexOf('.'), url.length );

		if ( ext === '.js') {

			var loader = new THREE.JSONLoader();
			loader.load( url, function( geometry, materials ) {

				var material = scope.createMaterial( materials[ 0 ] );

				THREE.SkinnedMesh.call( scope, geometry, material );

				scope.createAnimations( geometry );
				scope.createDebug();

				// Loading is complete, fire the callback
				if ( onLoad !== undefined ) onLoad();

			} );

		} else if ( ext === '.dae' ) {

			var loader = THREE.ColladaLoader();
			loader.load( url, function( geometry, materials ) {

				var mesh = null;

				geometry.scene.traverse( function( node ) {

					 if ( node instanceof THREE.SkinnedMesh ) {

						 mesh = node;

					 }

				});

				var material = scope.createMaterial( mesh.material );

				THREE.SkinnedMesh.call( scope, mesh.geometry, mesh.material );

				scope.createAnimations( mesh.geometry );
				scope.createDebug();

				// Loading is complete, fire the callback
				if ( onLoad !== undefined ) onLoad();

			} );
		}

	};

	this.createMaterial = function( originalMaterial ) {

		if ( customMaterial ) {

				var material = customMaterial;

				// Map must be set in order for the shader compile in support for our texture
				material.map = originalMaterial.map;
				material.uniforms.map.value = originalMaterial.map;

			} else {

				var material = originalMaterial;
				material.skinning = true;

			}

			return material;

	}

	this.createAnimations = function( geometry ) {

		if ( geometry.animations ) {

			for ( var i = 0; i < geometry.animations.length; ++i ) {

				THREE.AnimationHandler.add( geometry.animations[ i ] );

				var animName = geometry.animations[ i ].name;
				this.animations[ animName ] = new THREE.Animation( this, animName );

			}

		} else if ( geometry.animation ) {

			THREE.AnimationHandler.add( geometry.animation );

			var animName = geometry.animation.name;
			this.animations[ animName ] = new THREE.Animation( this, animName );
		}

	}

	this.createDebug = function() {

		this.geometry.computeBoundingSphere();
		var size = this.geometry.boundingSphere.radius * 0.01;

		this.skeletonHelper = new THREE.SkeletonHelper( this, size );
		this.skeletonHelper.material.linewidth = 2;
		this.add( this.skeletonHelper );

		this.showSkeleton( true );

	}

	this.update = function( dt ) {

		for ( var i = this.weightSchedule.length - 1; i >= 0; --i ) {

			var data = this.weightSchedule[ i ];
			data.timeElapsed += dt;

			// If the transition is complete, remove it from the schedule

			if ( data.timeElapsed > data.duration ) {

				data.anim.weight = data.endWeight;
				this.weightSchedule.splice( i, 1 );

				// If we've faded out completely, stop the animation

				if ( data.anim.weight == 0 ) {

					data.anim.stop( 0 );

				}

			} else {

				// interpolate the weight for the current time

				data.anim.weight = data.startWeight + (data.endWeight - data.startWeight) * data.timeElapsed / data.duration;

			}

		}

		this.updateWarps( dt );
		this.skeletonHelper.update();

	};

	this.updateWarps = function( dt ) {

		// Warping modifies the time scale over time to make 2 animations of different
		// lengths match. This is useful for smoothing out transitions that get out of
		// phase such as between a walk and run cycle

		for ( var i = this.warpSchedule.length - 1; i >= 0; --i ) {

			var data = this.warpSchedule[ i ];
			data.timeElapsed += dt;

			if ( data.timeElapsed > data.duration ) {

				data.to.weight = 1;
				data.to.timeScale = 1;
				data.from.weight = 0;
				data.from.timeScale = 1;
				data.from.stop( 0 );

				this.warpSchedule.splice( i, 1 );

			} else {

				var alpha = data.timeElapsed / data.duration;

				var fromLength = data.from.data.length;
				var toLength = data.to.data.length;

				var fromToRatio = fromLength / toLength;
				var toFromRatio = toLength / fromLength;

				// scale from each time proportionally to the other animation

				data.from.timeScale = ( 1 - alpha ) + fromToRatio * alpha;
				data.to.timeScale = alpha + toFromRatio * ( 1 - alpha );

				data.from.weight = 1 - alpha;
				data.to.weight = alpha;

			}

		}

	}

	this.play = function(animName, weight) {

		this.animations[ animName ].timeScale = 1.0;
		this.animations[ animName ].play( 0, weight );

	};

	this.crossfade = function( fromAnimName, toAnimName, duration ) {

		var fromAnim = this.animations[ fromAnimName ];
		var toAnim = this.animations[ toAnimName ];

		fromAnim.play( 0, 1 );
		toAnim.play( 0, 0 );

		this.weightSchedule.push( {

			anim: fromAnim,
			startWeight: 1,
			endWeight: 0,
			timeElapsed: 0,
			duration: duration

		} );

		this.weightSchedule.push( {

			anim: toAnim,
			startWeight: 0,
			endWeight: 1,
			timeElapsed: 0,
			duration: duration

		} );

	};

	this.warp = function( fromAnimName, toAnimName, duration ) {

		var fromAnim = this.animations[ fromAnimName ];
		var toAnim = this.animations[ toAnimName ];

		fromAnim.play( 0, 1 );
		toAnim.play( 0, 0 );

		this.warpSchedule.push( {

			from: fromAnim,
			to: toAnim,
			timeElapsed: 0,
			duration: duration

		} );

	};

	this.applyWeight = function(animName, weight) {

		this.animations[ animName ].weight = weight;

	};

	this.pauseAll = function() {

		for ( var a in this.animations ) {

			if ( this.animations[ a ].isPlaying ) {

				this.animations[ a ].pause();

			}

		}

	};

	this.unPauseAll = function() {

		for ( var a in this.animations ) {

			if ( this.animations[ a ].isPaused ) {

				this.animations[ a ].pause();

			}

		}

	};

	this.stopAll = function() {

		for ( a in this.animations ) {

			if ( this.animations[ a ].isPlaying ) {
				this.animations[ a ].stop(0);
			}

			this.animations[ a ].weight = 0;

		}

		this.weightSchedule.length = 0;
		this.warpSchedule.length = 0;

	}

	this.showSkeleton = function( shouldShow ) {

		this.skeletonHelper.visible = shouldShow;

	}

	this.showModel = function( boolean ) {

		this.visible = boolean;

	}

};

THREE.BlendCharacter.prototype = Object.create( THREE.SkinnedMesh.prototype );

THREE.BlendCharacter.prototype.getForward = function() {

	var forward = new THREE.Vector3();

	return function() {

		// pull the character's forward basis vector out of the matrix
		forward.set(
			-this.matrix.elements[ 8 ],
			-this.matrix.elements[ 9 ],
			-this.matrix.elements[ 10 ]
		);

		return forward;
	}
}


text:
PP-HGNet series model training Benchmark evaluation process can be referred to [PaddleClas-TIPC](https://github.com/paddlepaddle/paddleclas/blob/release%2F2.5/test_tipc/docs/benchmark_train.md).

## 2. Inference Benchmark

### 2.1 Environment

* The following tests are based on the NVIDIA® Tesla® V100,and the TensorRT engine is turned on;
* The precision type is FP32;

### 2.2 Dataset

The PP-HGNet series models were evaluated using the ImageNet1k validation dataset.

### 2.3 Metrics

| Model | Latency(ms) |
|:--: |:--: |
| PPHGNet_tiny      | 1.77 |
| PPHGNet_tiny_ssld  | 1.77 |
| PPHGNet_small     | 2.52  |
| PPHGNet_small_ssld | 2.52  |
| PPHGNet_base_ssld | 5.97   |

## 3. Instructions

For more information please refer to[PaddleClas-PPHGNet](https://github.com/PaddlePaddle/PaddleClas/blob/release%2F2.5/docs/en/models/PP-HGNet_en.md).


text:
require 'backports/tools/make_block_optional'

Backports.make_block_optional Array, :delete_if, :test_on => [42]


text:
package org.statefulj.persistence.mongo.demo;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = DemoBootStrap.class)
public class DemoApplicationTests {

	@Test
	public void contextLoads() {
	}

}


text:
"""Can be used to point environment variable to hermetic Go toolset.

Usage (on linux and mac):
$ eval `./env.py`
$ go version

Or it can be used to wrap a command:

$ ./env.py go version
"""

assert __name__ == '__main__'

import imp
import os
import subprocess
import sys

# Do not want to mess with sys.path, load the module directly.
bootstrap = imp.load_source(
    'bootstrap', os.path.join(os.path.dirname(__file__), 'bootstrap.py'))

# Do not bring in vendor paths when running goop itself. Goop gets confused.
running_goop = len(sys.argv) > 1 and sys.argv[1] == 'goop'

old = os.environ.copy()
new = bootstrap.prepare_go_environ(skip_goop_update=running_goop)

if len(sys.argv) == 1:
  for key, value in sorted(new.iteritems()):
    if old.get(key) != value:
      print 'export %s="%s"' % (key, value)
else:
  exe = sys.argv[1]
  if exe == 'python':
    exe = sys.executable
  else:
    # Help Windows to find the executable in new PATH, do it only when
    # executable is referenced by name (and not by path).
    if os.sep not in exe:
      exe = bootstrap.find_executable(exe, [bootstrap.WORKSPACE])
  sys.exit(subprocess.call([exe] + sys.argv[2:], env=new))


text:
<?php
error_reporting(E_ALL | E_STRICT);

if (defined('E_DEPRECATED'))
{
  error_reporting(error_reporting() | E_DEPRECATED);
}

define('HAMCREST_TEST_BASE', realpath(dirname(__FILE__)));
define('HAMCREST_BASE', realpath(dirname(dirname(__FILE__))));

set_include_path(implode(PATH_SEPARATOR, array(
  HAMCREST_TEST_BASE,
  HAMCREST_BASE . '/hamcrest',
  get_include_path()
)));

require_once 'Hamcrest.php';


text:
package com.cloud.agent.manager.authn;

import com.cloud.legacymodel.communication.command.startup.StartupCommand;
import com.cloud.utils.component.Adapter;

public interface AgentAuthorizer extends Adapter {
    boolean authorizeAgent(StartupCommand[] cmd);
}


text:
<?php if (!defined('PRETZEL_EXCEPTION_SERVER')) exit('No Pretzel No (Server) Exception');

class Pretzel_Exception_Server_SpCursorMismatch extends Pretzel_Exception_Server
{
}


text:
module PostmanMta
  module Archive
    class Conversation < PostmanMta::Conversation
      def index(params = {})
        get('/archive/conversations', body: params)
      end

      def find(conversation_id)
        get("/archive/conversations/#{conversation_id}")
      end

      def move(params = {})
        patch('/archive/conversations/move', body: params)
      end
    end
  end
end


text:
// ======================================================================
/*!
 * \brief Patterns
 *
 *  container
 */
// ======================================================================

#pragma once

#include <json/json.h>

namespace CTPP
{
class CDT;
}

namespace SmartMet
{
namespace Plugin
{
namespace Dali
{
class Config;
class State;

class Patterns
{
 private:
  using PatternMap = std::map<std::string, std::string>;
  PatternMap patterns;

 public:
  void init(const Json::Value& theJson, const State& theState);
};

}  // namespace Dali
}  // namespace Plugin
}  // namespace SmartMet


text:
USING_NS_CC;

using namespace cocostudio::timeline;

Scene* HelloWorld::createScene()
{
    // 'scene' is an autorelease object
    auto scene = Scene::create();

    // 'layer' is an autorelease object
    auto layer = HelloWorld::create();

    // add layer as a child to scene
    scene->addChild(layer);

    // return the scene
    return scene;
}

// on "init" you need to initialize your instance
bool HelloWorld::init()
{
    //////////////////////////////
    // 1. super init first
    if ( !Layer::init() )
    {
        return false;
    }

	auto* background = LayerColor::create(ccc4(255,255,255,255));
	addChild(background);
	bomb = Sprite::create("bomb.png");
	bomb->setPosition(480, 320);
	addChild(bomb);
	scheduleOnce(schedule_selector(HelloWorld::bang), 5.0f);

    return true;
}
void HelloWorld::bang(float dt)
{
	auto* m_frameCache = SpriteFrameCache::getInstance();
	m_frameCache->addSpriteFramesWithFile("bang.plist", "bang.png");
	Vector<SpriteFrame*> frameArray;
	for (int i = 1; i < 11; i++)
	{
		auto* frame = m_frameCache->getSpriteFrameByName(String::createWithFormat("bang%d.png", i)->getCString());
		frameArray.pushBack(frame);
	}
	Animation* animation = Animation::createWithSpriteFrames(frameArray);
	animation->setLoops(1);
	animation->setDelayPerUnit(0.1f);
	auto* action = Animate::create(animation);
	bomb->runAction(action);
}


text:
The <internet connection firewall> inspectors provide access to the settings of the Internet Connection Firewall introduced in Windows XP. The Internet Connection Firewall helps to protect a computer that is directly connected to the Internet, or a home network, from network attacks.

# enabled of <internet connection firewall> : boolean

Returns `True` if the local computer has the Windows XP built-in firewall enabled.

# port mapping of <internet connection firewall> : port mapping

Creates a port mapping object for the built-in firewall.


text:
(function (global, factory) {
    typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
    typeof define === 'function' && define.amd ? define(['exports'], factory) :
    (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global["chrisweb-utilities"] = {}));
})(this, (function (exports) { 'use strict';

    /**
     * returns the timestamp for any date or for now(), also works with browsers that dont support es5 Date.now
     * @param dateString
     */
    var getTimestamp = function (dateString) {
        if (dateString === void 0) { dateString = ''; }
        var timestamp;
        if (dateString === '') {
            timestamp = new Date().getTime();
        }
        else {
            var date = new Date(dateString);
            timestamp = date.getTime();
        }
        return timestamp;
    };

    /**
     * does the script run on the server
     */
    var isServer = function () {
        if (typeof (global) === 'object') {
            return true;
        }
        else {
            return false;
        }
    };
    /**
     * does the script run in a client
     */
    var isClient = function () {
        return !isServer();
    };

    /**
     * decode uri
     * @param inputString
     */
    var decodeUri = function (inputString) {
        var plusRegularExpression = /\+/g;
        // replace addition symbol with a space
        return decodeURIComponent(inputString.replace(plusRegularExpression, ' '));
    };
    /**
     * encode uri
     * @param inputString
     */
    var encodeUri = function (inputString) {
        var findRegularExpression = /[!'()~]|%20|%00/g;
        var replaceList = {
            '!': '%21',
            // tslint:disable-next-line
            "'": '%27',
            '(': '%28',
            ')': '%29',
            '~': '%7E',
            '%20': '+',
            '%00': '+'
        };
        return encodeURIComponent(inputString).replace(findRegularExpression, function (match) { return replaceList[match]; });
    };

    /**
     * get url parameters
     * @param query
     */
    var getUrlParameters = function (query) {
        if (query === void 0) { query = ''; }
        var urlParameters = {};
        if (query !== '' && typeof query === 'string') {
            var questionmarkIndex = query.indexOf('?');
            // if -1 there is no questionmark, skip, all is fine
            // else just keep what comes after the questionmark
            if (questionmarkIndex !== -1) {
                query = query.slice(questionmarkIndex + 1);
            }
            var pairs = query.split('&');
            var i = void 0;
            for (i = 0; i < pairs.length; i++) {
                var pair = pairs[i];
                var equalIndex = pair.indexOf('=');
                var parameterKey = '';
                var parameterValue = '';
                if (equalIndex > -1) {
                    parameterKey = pair.slice(0, equalIndex);
                    parameterValue = pair.slice(equalIndex + 1);
                }
                else {
                    parameterKey = pair;
                }
                urlParameters[decodeUri(parameterKey)] = decodeUri(parameterValue);
            }
        }
        return urlParameters;
    };
    /**
     * URL utility to get a parameter by name from an URL
     * @param name
     * @param url
     */
    var getUrlParameterByName = function (name, url) {
        if (!url) {
            url = window.location.href;
        }
        name = name.replace(/[[]]/g, '\\$&');
        var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)');
        var results = regex.exec(url);
        if (!results) {
            return null;
        }
        if (!results[2]) {
            return '';
        }
        return decodeUri(results[2]);
    };
    /**
     * URL utility to replace a given parameter
     * @param url
     * @param paramName
     * @param paramValue
     */
    var replaceUrlParameter = function (url, paramName, paramValue) {
        var pattern = new RegExp('\\b(' + paramName + '=).*?(&|$)');
        if (url.search(pattern) >= 0) {
            return url.replace(pattern, '$1' + paramValue + '$2');
        }
        return url + (url.indexOf('?') > 0 ? '&' : '?') + paramName + '=' + paramValue;
    };

    /*! *****************************************************************************
    Copyright (c) Microsoft Corporation.

    Permission to use, copy, modify, and/or distribute this software for any
    purpose with or without fee is hereby granted.

    THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
    REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
    AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
    INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
    LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
    OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
    PERFORMANCE OF THIS SOFTWARE.
    ***************************************************************************** */

    function __values(o) {
        var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
        if (m) return m.call(o);
        if (o && typeof o.length === "number") return {
            next: function () {
                if (o && i >= o.length) o = void 0;
                return { value: o && o[i++], done: !o };
            }
        };
        throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
    }

    var _this = undefined;
    /**
     * finds "removeMe" and removes it from the array
     * @param array
     * @param removeMe
     */
    var removeString = function (myArray, removeMe) {
        var index = myArray.indexOf(removeMe);
        if (index > -1) {
            myArray.splice(index, 1);
        }
        return myArray;
    };
    /**
     * is array with polyfill for older browsers
     * @param input
     */
    var isArray = function (input) {
        // MDN is array documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray
        if (!Array.isArray) {
            return Object.prototype.toString.call(input) === '[object Array]';
        }
        else {
            return Array.isArray(input);
        }
    };
    /**
     * finds "toFind" in an array, starting at an optional index
     * @param inputArray
     * @param toFind
     * @param fromIndex
     */
    var includes = function (inputArray, toFind, fromIndex) {
        // MDN includes documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes
        if (!Array.prototype.includes) {
            // https://tc39.github.io/ecma262/#sec-array.prototype.includes
            if (_this == null) {
                throw new TypeError('"this" is null or not defined');
            }
            // 1. Let O be ? ToObject(this value)
            var o = Object(_this);
            // 2. Let len be ? ToLength(? Get(O, "length"))
            var len = o.length >>> 0;
            // 3. If len is 0, return false
            if (len === 0) {
                return false;
            }
            // 4. Let n be ? ToInteger(fromIndex)
            //    (If fromIndex is undefined, this step produces the value 0.)
            var n = fromIndex | 0;
            // 5. If n ≥ 0, then
            //  a. Let k be n.
            // 6. Else n < 0,
            //  a. Let k be len + n.
            //  b. If k < 0, let k be 0.
            var k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
            // 7. Repeat, while k < len
            while (k < len) {
                // a. Let elementK be the result of ? Get(O, ! ToString(k))
                // b. If SameValueZero(valueToFind, elementK) is true, return true
                if (sameValueZero(o[k], toFind)) {
                    return true;
                }
                // c. Increase k by 1
                k++;
            }
            // 8. Return false
            return false;
        }
        else {
            var n = fromIndex | 0;
            return inputArray.includes(toFind, n);
        }
    };
    var sameValueZero = function (x, y) {
        return x === y || (typeof x === 'number' && typeof y === 'number' && isNaN(x) && isNaN(y));
    };
    /**
     *
     * @param inputArray
     * @param predicate
     * @param args
     */
    // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
    var find = function (inputArray, predicate, args) {
        // MDN find documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
        if (!Array.prototype.find) {
            // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
            // 1. Let O be ? ToObject(this value)
            if (_this == null) {
                throw new TypeError('"this" is null or not defined');
            }
            var o = Object(_this);
            // 2. Let len be ? ToLength(? Get(O, "length"))
            var len = o.length >>> 0;
            // 3. If IsCallable(predicate) is false, throw a TypeError exception
            if (typeof predicate !== 'function') {
                throw new TypeError('predicate must be a function');
            }
            // 4. If thisArg was supplied, let T be thisArg; else let T be undefined
            var thisArg = args[1];
            // 5. Let k be 0.
            var k = 0;
            // 6. Repeat, while k < len
            while (k < len) {
                // a. Let Pk be ! ToString(k)
                // b. Let kValue be ? Get(O, Pk)
                // c. Let testResult be ToBoolean(? Call(predicate, T, « kValue, k, O »))
                // d. If testResult is true, return kValue
                var kValue = o[k];
                if (predicate.call(thisArg, kValue, k, o)) {
                    return kValue;
                }
                // e. Increase k by 1
                k++;
            }
            // 7. Return undefined
            return undefined;
        }
        else {
            // eslint-disable-next-line
            return inputArray.find(predicate, args);
        }
    };
    /**
     * array flat polyfill, if depth is unknow set it to "Infinity"
     * @param inputArray
     * @param depth
     */
    var flat = function (inputArray, depth) {
        // MDN flat documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat
        if (depth === void 0) { depth = Infinity; }
        if (!Array.prototype.flat) {
            return flatten(inputArray, Math.floor(depth) || 1);
        }
        else {
            return inputArray.flat(depth);
        }
    };
    /**
     * flattens a multidimensional array
     * @param inputArray
     * @param depth
     */
    var flatten = function (inputArray, depth) {
        var e_1, _a;
        if (depth === void 0) { depth = Infinity; }
        var flattend = [];
        try {
            for (var inputArray_1 = __values(inputArray), inputArray_1_1 = inputArray_1.next(); !inputArray_1_1.done; inputArray_1_1 = inputArray_1.next()) {
                var el = inputArray_1_1.value;
                if (isArray(el) && depth > 0) {
                    flatten(el, depth - 1);
                }
                else {
                    flattend.push(el);
                }
            }
        }
        catch (e_1_1) { e_1 = { error: e_1_1 }; }
        finally {
            try {
                if (inputArray_1_1 && !inputArray_1_1.done && (_a = inputArray_1.return)) _a.call(inputArray_1);
            }
            finally { if (e_1) throw e_1.error; }
        }
        return flattend;
    };

    /**
     * filters a string
     * removes everything that is a not an alpha or numeric character, plus
     * the characters if any that got specified as second argument
     * @param inputString
     * @param specialCharacters
     */
    var filterAlphaNumericPlus = function (inputString, specialCharacters) {
        if (typeof (inputString) === 'string' && inputString.length > 0) {
            var outputString = void 0;
            if (specialCharacters !== undefined) {
                var regex = RegExp('[^a-z0-9' + specialCharacters + ']', 'gi');
                outputString = inputString.replace(regex, '');
            }
            else {
                outputString = inputString.replace(/[^a-z0-9]/gi, '');
            }
            return outputString;
        }
        return false;
    };
    /**
     * filters a string
     * removes everything that is a not a  numeric character, plus
     * the characters if any that got specified as second argument
     * @param inputString
     * @param specialCharacters
     */
    var filterNumericPlus = function (inputString, specialCharacters) {
        if (typeof (inputString) === 'string' && inputString.length > 0) {
            var outputString = void 0;
            if (specialCharacters !== undefined) {
                var regex = RegExp('[^0-9' + specialCharacters + ']', 'gi');
                outputString = inputString.replace(regex, '');
            }
            else {
                outputString = inputString.replace(/[^0-9]/gi, '');
            }
            return outputString;
        }
        return false;
    };
    /**
     * capitalise first letter of a string
     * @param inputString
     */
    var capitaliseFirstLetter = function (inputString) {
        return inputString.charAt(0).toUpperCase() + inputString.slice(1);
    };
    /**
     * does a string contain another string
     * @param inputString
     * @param contains
     */
    var stringContains = function (inputString, contains) {
        if (typeof inputString !== 'string') {
            throw 'input is not a string';
        }
        if (inputString.indexOf(contains) > -1) {
            return true;
        }
        else {
            return false;
        }
    };
    /**
     * get the index of a substring in a string with optional nth time it occurs
     * @param inputString
     * @param substring
     * @param nthTime
     */
    var getSubstringIndex = function (inputString, substring, nthTime) {
        var times = 0;
        var index = null;
        if (nthTime === 0) {
            nthTime = 1;
        }
        while (times < nthTime && index !== -1) {
            index = inputString.indexOf(substring, index + 1);
            times++;
        }
        return index;
    };
    /**
     * replace the placeholder(s) with some value
     * @param input
     * @param replacements
     */
    var replacePlaceholders = function (input, replacements) {
        var output = input;
        if (typeof input === 'string' && typeof replacements === 'object') {
            output = input.replace(/\b\w+?\b/g, function replacePlaceHolder(placeholder) {
                return Object.prototype.hasOwnProperty.call(replacements, placeholder) ? replacements[placeholder] : placeholder;
            });
        }
        return output;
    };
    /**
     * remove all spaces from a string
     * @param input
     */
    var removeAllSpaces = function (input) {
        return input.replace(/\s/g, '');
    };

    /**
     * returns a universally unique identifier
     */
    var generateUUID = function () {
        // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript
        // http://www.ietf.org/rfc/rfc4122.txt
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        var s = [];
        var hexDigits = '0123456789abcdef';
        var i;
        for (i = 0; i < 36; i++) {
            s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
        }
        s[14] = 4; // bits 12-15 of the time_hi_and_version field to 0010
        s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
        s[8] = s[13] = s[18] = s[23] = '-';
        var uuid = s.join('');
        return uuid;
    };

    /**
     * extracts html elements (and their content) from strings
     * @param text
     * @param removeTextBetweenTags
     */
    var removeElements = function (text, removeTextBetweenTags) {
        if (removeTextBetweenTags === false) {
            // replace single tags
            text = text.replace(/<[^>]*>?/g, '');
        }
        else {
            // replace all tags and whats inside
            text = text.replace(/<[^>]*>[^>]*<\/[^>]*>?/g, '');
            // replace single tags
            text = text.replace(/<[^>]*>?/g, '');
        }
        return text;
    };

    /**
     * html log
     * create a div an insert the messages in div
     * can be usefull on mobile if no other console is available
     * @param logObjects
     * @param logObjectsLength
     * @param logFontColor
     * @param logBackgroundColor
     */
    var htmlLog = function (logObjects, logObjectsLength, logFontColor, logBackgroundColor) {
        // TODO: fix: seems that if logging starts before "domload" some
        // messages get lost
        if (document.getElementById('log') === null) {
            var logDiv = document.createElement('div');
            logDiv.id = 'log';
            logDiv.style.cssText = 'position: absolute; overflow: scroll; left: 0; bottom: 0; padding: 0; margin: 0; border: 0; z-index: 999999; width: 100%; height: 20%; background-color: #fff;';
            document.body.appendChild(logDiv);
        }
        var i;
        for (i = 0; i < logObjectsLength; i++) {
            var logSpan = document.createElement('span');
            logSpan.style.cssText = 'color: #' + logFontColor + '; background-color: #' + logBackgroundColor + ';';
            var logObject = logObjects[i];
            var spanContent = document.createTextNode(logObject);
            logSpan.appendChild(spanContent);
            document.getElementById('log').appendChild(logSpan);
            var brElement = document.createElement('br');
            document.getElementById('log').appendChild(brElement);
        }
    };

    /**
     * nodejs logging to file
     * @param logObjects
     * @param logObjectsLength
     * @param logFontColor
     */
    var fileLog = function (logObjects, logObjectsLength, logFontColor) {
        console.log(logObjects);
        console.log(logObjectsLength);
        console.log(logFontColor);
        throw new Error('sorry this feature is broken');
    };

    var defaultLogFontColor = 'default';
    var defaultLogBackgroundColor = 'default';
    /**
     * log messages
     * @param args
     */
    var log = function () {
        var args = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            args[_i] = arguments[_i];
        }
        // is console defined, some older IEs don't have a console
        if (typeof (console) === 'undefined') {
            throw new Error('This browser does not support console');
        }
        // extract options and get objects to log
        // read: https://github.com/Microsoft/TypeScript/issues/1609
        var logArguments = handleLogArguments(args);
        var logObjects = logArguments.objects;
        var logFontColor = logArguments.fontColor;
        var logBackgroundColor = logArguments.backgroundColor;
        var logObjectsLength = logObjects.length;
        // nodejs or browser mode
        if (typeof (window) === 'undefined') {
            {
                // get background and fontColor codes
                var color = getServerColors(logFontColor, logBackgroundColor);
                // log each object
                for (var i = 0; i < logObjectsLength; i++) {
                    if (typeof (logObjects[i]) === 'string') {
                        console.log(color.background + color.font + logObjects[i] + color.reset);
                    }
                    else {
                        console.log(logObjects[i]);
                    }
                }
            }
            // log to file if logSpecial is enabled or if the fontColor is red
            // if (logSpecial === true || logFontColor === 'red') {
            if (logFontColor === 'red') {
                fileLog(logObjects, logObjectsLength, logFontColor);
            }
        }
        else {
            // get background and fontColor codes
            var color = getClientColors(logFontColor, logBackgroundColor);
            {
                // log each object
                for (var i = 0; i < logObjectsLength; i++) {
                    if (typeof (logObjects[i]) === 'string') {
                        console.log('%c' + logObjects[i], 'background: #' + color.background + '; color: #' + color.font);
                    }
                    else {
                        console.log(logObjects[i]);
                    }
                }
            }
            // log to html if logSpecial is enabled
            //if (logSpecial === true) {
            var stringLogObjects_1 = [];
            logObjects.forEach(function (logObject) {
                stringLogObjects_1.push(logObject.toString());
            });
            htmlLog(stringLogObjects_1, logObjectsLength, color.font, color.background);
            //}
        }
    };
    /**
     * get the client side (browser) colors
     * @param logFontColor
     * @param logBackgroundColor
     */
    var getClientColors = function (logFontColor, logBackgroundColor) {
        var colors = {
            red: 'FF0000',
            green: '00FF00',
            yellow: 'FFFF00',
            blue: '0000FF',
            magenta: 'FF00FF',
            cyan: '00FFFF',
            white: 'FFFFFF',
            black: '000000'
        };
        var fontColor;
        var backgroundColor;
        // font color
        if (typeof (logFontColor) === 'undefined'
            || logFontColor === 'default') {
            fontColor = colors['black'];
        }
        else {
            if (typeof (colors[logFontColor]) !== 'undefined') {
                fontColor = colors[logFontColor];
            }
            else {
                throw 'unknown fontColor in utilities console log';
            }
        }
        // background color
        if (typeof (logBackgroundColor) === 'undefined'
            || logBackgroundColor === 'default') {
            backgroundColor = colors['white'];
        }
        else {
            if (typeof (colors[logBackgroundColor]) !== 'undefined') {
                backgroundColor = colors[logBackgroundColor];
            }
            else {
                throw 'unknown fontColor in utilities console log';
            }
        }
        return { font: fontColor, background: backgroundColor };
    };
    /**
     * get the colors for the backend (server) console
     * @param logFontColor
     * @param logBackgroundColor
     */
    var getServerColors = function (logFontColor, logBackgroundColor) {
        var backgroundColors = {
            black: '\u001b[40m',
            red: '\u001b[41m',
            green: '\u001b[42m',
            yellow: '\u001b[43m',
            blue: '\u001b[44m',
            magenta: '\u001b[45m',
            cyan: '\u001b[46m',
            white: '\u001b[47m'
        };
        var foregroundColors = {
            black: '\u001b[30m',
            red: '\u001b[31m',
            green: '\u001b[32m',
            yellow: '\u001b[33m',
            blue: '\u001b[34m',
            magenta: '\u001b[35m',
            cyan: '\u001b[36m',
            white: '\u001b[37m'
        };
        var fontColor;
        var backgroundColor;
        // font color
        if (typeof (logFontColor) === 'undefined'
            || logFontColor === 'default') {
            fontColor = foregroundColors['white'];
        }
        else {
            if (typeof (foregroundColors[logFontColor]) !== 'undefined') {
                fontColor = foregroundColors[logFontColor];
            }
            else {
                throw 'unknown font color in utilities console log';
            }
        }
        // background color
        if (typeof (logBackgroundColor) === 'undefined'
            || logBackgroundColor === 'default') {
            backgroundColor = backgroundColors['black'];
        }
        else {
            if (typeof (backgroundColors[logBackgroundColor]) !== 'undefined') {
                backgroundColor = backgroundColors[logBackgroundColor];
            }
            else {
                throw 'unknown background color in utilities console log';
            }
        }
        return { font: fontColor, background: backgroundColor, reset: '\u001b[0m' };
    };
    /**
     * handle log arguments
     * extract the color infos from the arguments to log
     * @param logArguments
     */
    var handleLogArguments = function (logArguments) {
        var logObjects = [];
        var logFontColor = defaultLogFontColor;
        var logBackgroundColor = defaultLogBackgroundColor;
        var argumentsLength = logArguments.length;
        var i;
        for (i = 0; i < argumentsLength; i++) {
            var argument = logArguments[i];
            if (typeof argument === 'string') {
                if (argument.substr(0, 10) === 'fontColor:') {
                    logFontColor = argument.substr(10, argument.length).trim();
                }
                else if (argument.substr(0, 16) === 'backgroundColor:') {
                    logBackgroundColor = argument.substr(16, argument.length).trim();
                }
                else {
                    logObjects.push(argument);
                }
            }
            else {
                logObjects.push(argument);
            }
        }
        return { objects: logObjects, fontColor: logFontColor, backgroundColor: logBackgroundColor };
    };

    /**
     * pauses your script for a given time, returns a promise that you can use to do so
     * @param ms
     */
    var sleep = function (ms) {
        return new Promise(function (resolve) { return setTimeout(resolve, ms); });
    };

    /**
     * returns a random integer that lies between min (included) and max (included)
     * @param min
     * @param max
     */
    var randomInteger = function (min, max, prng) {
        if (min === void 0) { min = 0; }
        if (max === void 0) { max = Infinity; }
        // support for custom PRNGs, like https://www.npmjs.com/package/seedrandom
        if (prng) {
            prng.floor(prng.random() * (max - min + 1) + min);
        }
        else {
            return Math.floor(Math.random() * (max - min + 1) + min);
        }
    };
    var choice = function (sequence, prng) {
        if (sequence === void 0) { sequence = []; }
        // support for custom PRNGs, like https://www.npmjs.com/package/seedrandom
        if (prng) {
            return sequence[prng.floor(prng.random() * sequence.length)];
        }
        else {
            return sequence[Math.floor(Math.random() * sequence.length)];
        }
    };

    var version = '1.4.0';

    exports.capitaliseFirstLetter = capitaliseFirstLetter;
    exports.choice = choice;
    exports.decodeUri = decodeUri;
    exports.encodeUri = encodeUri;
    exports.filterAlphaNumericPlus = filterAlphaNumericPlus;
    exports.filterNumericPlus = filterNumericPlus;
    exports.find = find;
    exports.flat = flat;
    exports.generateUUID = generateUUID;
    exports.getSubstringIndex = getSubstringIndex;
    exports.getTimestamp = getTimestamp;
    exports.getUrlParameterByName = getUrlParameterByName;
    exports.getUrlParameters = getUrlParameters;
    exports.includes = includes;
    exports.isArray = isArray;
    exports.isClient = isClient;
    exports.isServer = isServer;
    exports.log = log;
    exports.randomInteger = randomInteger;
    exports.removeAllSpaces = removeAllSpaces;
    exports.removeElements = removeElements;
    exports.removeString = removeString;
    exports.replacePlaceholders = replacePlaceholders;
    exports.replaceUrlParameter = replaceUrlParameter;
    exports.sleep = sleep;
    exports.stringContains = stringContains;
    exports.version = version;

    Object.defineProperty(exports, '__esModule', { value: true });

}));
//# sourceMappingURL=index.js.map


text:
// bsn GoldParser .NET Engine
// --------------------------
//
// Copyright 2009, 2010 by Arsène von Wyss - avw@gmx.ch
//
// Development has been supported by Sirius Technologies AG, Basel
//
// Source:
//
// https://bsn-goldparser.googlecode.com/hg/
//
// License:
//
// The library is distributed under the GNU Lesser General Public License:
// http://www.gnu.org/licenses/lgpl.html
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//
namespace bsn.GoldParser.Grammar {
	/// <summary>
	/// Record type byte in the binary grammar file.
	/// </summary>
	internal enum CgtRecordType {
		Parameters = (int)'P', // 80
		Property = (int)'p', // 112
		Groups = (int)'g', // 103
		TableCounts = (int)'T', // 84
		TableCountsEnhanced = (int)'t', // 116
		Initial = (int)'I', // 73
		Symbols = (int)'S', // 83
		Charsets = (int)'C', // 67
		PackedCharsets = (int)'c', // 99
		Rules = (int)'R', // 82
		DfaStates = (int)'D', // 68
		LRStates = (int)'L', // 76
		Comment = (int)'!' // 33
	}
}


text:
#include <aws/snowball/model/SnowballCapacity.h>
#include <aws/core/utils/HashingUtils.h>
#include <aws/core/Globals.h>
#include <aws/core/utils/EnumParseOverflowContainer.h>

using namespace Aws::Utils;

namespace Aws
{
  namespace Snowball
  {
    namespace Model
    {
      namespace SnowballCapacityMapper
      {

        static const int T50_HASH = HashingUtils::HashString("T50");
        static const int T80_HASH = HashingUtils::HashString("T80");
        static const int T100_HASH = HashingUtils::HashString("T100");
        static const int T42_HASH = HashingUtils::HashString("T42");
        static const int T98_HASH = HashingUtils::HashString("T98");
        static const int T8_HASH = HashingUtils::HashString("T8");
        static const int T14_HASH = HashingUtils::HashString("T14");
        static const int NoPreference_HASH = HashingUtils::HashString("NoPreference");

        SnowballCapacity GetSnowballCapacityForName(const Aws::String& name)
        {
          int hashCode = HashingUtils::HashString(name.c_str());
          if (hashCode == T50_HASH)
          {
            return SnowballCapacity::T50;
          }
          else if (hashCode == T80_HASH)
          {
            return SnowballCapacity::T80;
          }
          else if (hashCode == T100_HASH)
          {
            return SnowballCapacity::T100;
          }
          else if (hashCode == T42_HASH)
          {
            return SnowballCapacity::T42;
          }
          else if (hashCode == T98_HASH)
          {
            return SnowballCapacity::T98;
          }
          else if (hashCode == T8_HASH)
          {
            return SnowballCapacity::T8;
          }
          else if (hashCode == T14_HASH)
          {
            return SnowballCapacity::T14;
          }
          else if (hashCode == NoPreference_HASH)
          {
            return SnowballCapacity::NoPreference;
          }
          EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
          if(overflowContainer)
          {
            overflowContainer->StoreOverflow(hashCode, name);
            return static_cast<SnowballCapacity>(hashCode);
          }

          return SnowballCapacity::NOT_SET;
        }

        Aws::String GetNameForSnowballCapacity(SnowballCapacity enumValue)
        {
          switch(enumValue)
          {
          case SnowballCapacity::T50:
            return "T50";
          case SnowballCapacity::T80:
            return "T80";
          case SnowballCapacity::T100:
            return "T100";
          case SnowballCapacity::T42:
            return "T42";
          case SnowballCapacity::T98:
            return "T98";
          case SnowballCapacity::T8:
            return "T8";
          case SnowballCapacity::T14:
            return "T14";
          case SnowballCapacity::NoPreference:
            return "NoPreference";
          default:
            EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
            if(overflowContainer)
            {
              return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue));
            }

            return {};
          }
        }

      } // namespace SnowballCapacityMapper
    } // namespace Model
  } // namespace Snowball
} // namespace Aws


text:
COMPONENT=BaseStationC

# radio options.  channel settings will be overridden by the driver
 CFLAGS += -DCC2420_DEF_RFPOWER=3

# this is necessary, otherwise we will allocate a heap by including
# the lowpan target
CFLAGS += -DNO_IP_MALLOC

# this aligns the 802.15.4 payload on the data field of a message_t.
# very convenient for forwarding, and means we don't have to do a
# memmove.  This doesn't mean that motes running blip also need this--
# they can use IFRAMES or IEEE154FRAMES
CFLAGS += -DIEEE154FRAMES_ENABLED

# if you're worried about your interface mote crashing, enable this to
# turn on a hardware watchdog that will reset it if it does.  CFLAGS
# += -DBLIP_WATCHDOG
#
# debugging
#
#CFLAGS += "-DCC2420_DEF_RFPOWER=7"

# filter packets based on a specified topology
# PFLAGS += -I../UDPEcho/NodeConnectivity -DSW_TOPOLOGY

# part of the test harness
# CFLAGS += -DDBG_TRACK_FLOWS

# for simulation
# CFLAGS += -DBASESTATION_ID=100

# defs for snooping-- handy for debugging LPL, etc.
# CFLAGS += -DCC2420_NO_UNIQUE
# CFLAGS += -DCC2420_DEF_CHANNEL=15
# CFLAGS += -DCC2420_NO_ACKNOWLEDGEMENTS
# CFLAGS += -DCC2420_NO_ADDRESS_RECOGNITION

include $(MAKERULES)


text:
/*
Nihonium Engine
This file is licensed under the terms of the MIT License.
See LICENCE.txt for the full licence.
*/

#include <glad/glad.h>

#include "filesystem.h"
#include "luautils.h"

#ifndef NH_SHADER_H
#define NH_SHADER_H

namespace shader {

struct Shader {

  GLuint program;

  Shader() {}
  Shader(const char* vertex_filename, const char* fragment_filename);

};

void init(lua_State* state);

extern Shader current_shader;

}

#endif


text:
![logo](/images/value-link-logo.png)

# Painless React forms, validation, and state management

NestedLink is `useState` React Hook on steroids providing an elegant callback-free solution for complex forms with input validation and making the React state a perfect state container. It's lightweight (6.5K minified) and designed to be used with both JS and TypeScript.

The `Link` is the object representing the writable reference to the member of the component's state encapsulating the value, function to update the value, and the validation error. `Link` class has a set of methods to perform useful transformations, such as `$link.props` generating the pair of standard `{ value, onChange }` props.

`NestedLink` dramatically improves your React project's modularity and code readability.

```javascript
import { useLink } from 'valuelink'
import { MyInput } from './controls.jsx'

const coolState = { some : { name : '' } };
const MyCoolComponent = () => {
    // Digging through the object to get a link to the `coolState.some.name`
    const $name = useLink( coolState ).at( 'some' ).at( 'name' )

    // applying the validation rules
    $name.check( x => x.length > 0, 'Name is required' ),
         .check( x => x.length > 2, 'Name is too short' );
         .check( x => x.length < 20, 'Name is too long' );

    return (
        <MyInput $value={$name} />
    )
}

// controls.jsx
import * as React from 'react'

// Custom form field with validation taking the link to the `value`
const MyInput = ({ $value }) => (
    <div>
        <input {...$value.props} className={ $value.error ? 'error' : '' } />
        <span>{ $value.error || '' }</span>
    </div>
)
```

## Features

***IMPORTANT! Version 2.x is not entirely backwards compatible with 1.x, see the release notes at the bottom.***

- Callback-free form controls binding to the component state.
- Complete separation of the validation logic from the markup.
- Easy handling of nested objects and arrays in the component state.
- Complete support for the React Hooks API and functional components.
- Pricise TypeScript typings.

Reference implementation of 'linked' UI controls (optional `linked-controls` npm package):

- Standard tags: `<Input />`, `<TextArea />`, `<Select />`,
- Custom tags: `<Radio />`, `<Checkbox />`, `<NumberInput />`
- Validator functions: `isNumber`, `isEmail`, `isRequred`.

## Tutorials

The rationale behind the design and a high-level overview of how amazing NestedLink is: [React Hooks, form validation, and complex state](https://itnext.io/react-hooks-and-two-way-data-binding-dd4210f0ed94)

The series of 5-minute tutorials (with `React.Component`):

- [The basics of ValueLink design pattern](https://medium.com/@gaperton/managing-state-and-forms-with-react-part-1-12eacb647112#.j7sqgkj88)
- [Form validation with ValueLinks](https://medium.com/@gaperton/react-forms-with-value-links-part-2-validation-9d1ba78f8e49#.nllbm4cr7)
- [Complex state with ValueLinks](https://medium.com/@gaperton/state-and-forms-in-react-part-3-handling-the-complex-state-acf369244d37#.x0fjcxljo)

### [API Reference](/valuelink/API.md)

### [Linked Controls Reference](/linked-controls/README.md)

### [Examples](https://volijs.github.io/NestedLink)([sources](/examples/))

## How to

### Use it in your project

There are no side dependencies except `react` as peer dependency. Installation:

`npm install valuelink --save-dev`

Usage with React Hooks (check out the [React Hooks starting boilerplate](/examples/babel-starter)).

```javascript
import React from 'react'
import { useLink } from 'valuelink'
...
// Instead of const [ name, setName ] = useState('')
const $name = useLink('');
```

Usage with React Component.

```javascript
import React from 'react'
// Instead of React.Component...
import { LinkedComponent } from 'valuelink'
...
// In a render, do
const $name = this.$at('name');
// Or, to link all the state members at once...
const state$ = this.state$();
```

Refer to the [databinding examples](/examples/databinding) and the [manual](/linked-controls/README.md) for the typical data binding scenarios.

### Create your own data bound controls

Use [linked-controls](/linked-controls) project as the starting boilerplate for your components.

### Create the binding to the custom state container

NestedLink is an abstraction of the data binding independent on both the particular control and the state container. The [default binding](/valuelink/src/component.ts) implemented
in the library is for the standard React state. It's fairly easy to create your own.

You need to subclass React.Component and make your own `$at` and `state$` methods.
You can either use `Link.value` inside to create links dynamically, or extend the `Link` as it's done in [/valuelink/src/component.ts](/valuelink/src/component.ts).

### Start hacking

![design](/images/valuelinks.jpg)

It's a very simple library written with TypeScript, there's no any magic inside (except some scary type annotations). If you want to play with the examples, fix the bug, or whatever:

`yarn` - installs the dependencies.

`yarn build` - compiles everything including examples.

## Release Notes
### 2.0

- IMPORTANT: Repository is converted to the monorepository based on yarn worspaces.
- IMPORTANT: `valuelink/tags.jsx` is moved to the dedicated package `linked-controls`.
- Complete support of new React Hooks API.
    - `useLink()` to create the state link.
    - `useIO()` to perform promised IO on mount.
    - `useLocalStorage()` to persist links to the local storage (loaded on mount, saved on unmount).
- $-notation for the link variables.
- New React.Component API (`this.linkAt -> this.$at`, `this.linkAll` -> `this.state$`)
- Group operations `Link.getValues()`, `Link.setValues()`, `Link.getErrors()`

### v1.6

React Hooks support.

- `useLink( initValue )` - create linked state.
- `setLinks({ lnk1, lnk2, ... }, json )` - bulk set link values from an object.
- `linksValues({ lnk1, lnk2, ... })` - extract values object from links.
- `linksErrors({ lnk1, lnk2, ... })` - extract errors object from links.

### v1.5

- `<input {...link.props} />` can be used to bind the link to any of the standard controls expecting `value` and `onChange` props.

---
![usedby](/images/usedby.png)


text:
package bookshop2.buyer.client.orderBooks;

import org.aries.bean.Proxy;
import org.aries.message.Message;
import org.aries.message.MessageInterceptor;
import org.aries.util.ExceptionUtil;

import bookshop2.OrderRequestMessage;

public class OrderBooksInterceptor extends MessageInterceptor<OrderBooks> implements OrderBooks {

	@Override
	public void orderBooks(OrderRequestMessage orderRequestMessage) {
		try {
			log.info("#### [buyer]: orderBooks() sending");
			Message message = createMessage("orderBooks");
			message.addPart("orderRequestMessage", orderRequestMessage);
			message.addPart("correlationId", orderRequestMessage.getCorrelationId());
			message.addPart("transactionId", orderRequestMessage.getTransactionId());
			Proxy<OrderBooks> proxy = getProxy();
			proxy.send(message);

		} catch (Exception e) {
			throw ExceptionUtil.rewrap(e);
		}
	}

}


text:
BIN   = ./node_modules/.bin
PATH := $(BIN):$(PATH)
TESTS = $(shell find ./lib -path '**/tests/*.js')

install:
	@npm $@

lint:
	@eslint-jsx lib/

clean:
	@rm -rf ./node_modules/

test: test-phantomjs

docs::
	@$(MAKE) --no-print-directory -C docs html

publish-docs::
	@$(MAKE) --no-print-directory -C docs publish

ci:
	@NODE_PATH=$(NODE_PATH) mochify --watch -R dot $(TESTS)

test-phantomjs:
	@NODE_PATH=$(NODE_PATH) mochify -R spec $(TESTS)


text:
import os
import ssl

import ldap3

from datadog_checks.base import AgentCheck, ConfigurationError, is_affirmative

class OpenLDAP(AgentCheck):
    METRIC_PREFIX = 'openldap'
    SERVICE_CHECK_CONNECT = '{}.can_connect'.format(METRIC_PREFIX)

    SEARCH_BASE = 'cn=Monitor'
    SEARCH_FILTER = '(objectClass=*)'
    ATTRS = ['*', '+']

    # Some docs here https://www.openldap.org/doc/admin24/monitoringslapd.html#Monitor%20Information
    CONNECTIONS_METRICS_DN = 'cn=connections,cn=monitor'
    OPERATIONS_METRICS_DN = 'cn=operations,cn=monitor'
    STATISTICS_METRICS_DN = 'cn=statistics,cn=monitor'
    THREADS_METRICS_DN = 'cn=threads,cn=monitor'
    TIME_METRICS_DN = 'cn=time,cn=monitor'
    WAITERS_METRICS_DN = 'cn=waiters,cn=monitor'

    def check(self, instance):
        url, username, password, ssl_params, custom_queries, tags = self._get_instance_params(instance)

        server = ldap3.Server(url, tls=self._get_tls_object(ssl_params))
        conn = ldap3.Connection(server, username, password, collect_usage=True)

        # Try binding to the server
        try:
            res = conn.bind()
            if not res:
                raise ldap3.core.exceptions.LDAPBindError("Error binding to server: {}".format(conn.result))
        except ldap3.core.exceptions.LDAPExceptionError as e:
            self.log.exception("Could not connect to server at %s: %s", url, e)
            self.service_check(self.SERVICE_CHECK_CONNECT, self.CRITICAL, tags=tags)
            raise

        self.service_check(self.SERVICE_CHECK_CONNECT, self.OK, tags=tags)
        bind_time = self._get_query_time(conn)
        self.gauge("{}.bind_time".format(self.METRIC_PREFIX), bind_time, tags=tags)

        try:
            # Search Monitor database to get all metrics
            conn.search(self.SEARCH_BASE, self.SEARCH_FILTER, attributes=self.ATTRS)
            self._collect_monitor_metrics(conn, tags)

            # Get additional custom metrics
            self._perform_custom_queries(conn, custom_queries, tags, instance)
        finally:
            conn.unbind()

    def _get_tls_object(self, ssl_params):
        """
        Return a TLS object to establish a secure connection to a server
        """
        if ssl_params is None:
            return None

        if not ssl_params["verify"] and ssl_params["ca_certs"]:
            self.warning(
                "Incorrect configuration: trying to disable server certificate validation, "
                "while also specifying a capath. No validation will be performed. Fix your "
                "configuration to remove this warning"
            )

        validate = ssl.CERT_REQUIRED if ssl_params["verify"] else ssl.CERT_NONE

        if ssl_params["ca_certs"] is None or os.path.isfile(ssl_params["ca_certs"]):
            tls = ldap3.core.tls.Tls(
                local_private_key_file=ssl_params["key"],
                local_certificate_file=ssl_params["cert"],
                ca_certs_file=ssl_params["ca_certs"],
                version=ssl.PROTOCOL_SSLv23,
                validate=validate,
            )
        elif os.path.isdir(ssl_params["ca_certs"]):
            tls = ldap3.core.tls.Tls(
                local_private_key_file=ssl_params["key"],
                local_certificate_file=ssl_params["cert"],
                ca_certs_path=ssl_params["ca_certs"],
                version=ssl.PROTOCOL_SSLv23,
                validate=validate,
            )
        else:
            raise ConfigurationError(
                'Invalid path {} for ssl_ca_certs: no such file or directory'.format(ssl_params['ca_certs'])
            )
        return tls

    @classmethod
    def _get_instance_params(cls, instance):
        """
        Parse instance configuration and perform minimal verification
        """
        url = instance.get("url")
        if url is None:
            raise ConfigurationError("You must specify a url for your instance in `conf.yaml`")
        username = instance.get("username")
        password = instance.get("password")
        ssl_params = None
        if url.startswith("ldaps"):
            ssl_params = {
                "key": instance.get("ssl_key"),
                "cert": instance.get("ssl_cert"),
                "ca_certs": instance.get("ssl_ca_certs"),
                "verify": is_affirmative(instance.get("ssl_verify", True)),
            }
        custom_queries = instance.get("custom_queries", [])
        tags = list(instance.get("tags", []))
        tags.append("url:{}".format(url))

        return url, username, password, ssl_params, custom_queries, tags

    def _collect_monitor_metrics(self, conn, tags):
        """
        Collect metrics from the monitor backend
        """
        for entry in conn.entries:
            # Get metrics from monitor backend
            dn = entry.entry_dn.lower()
            if dn.endswith(self.CONNECTIONS_METRICS_DN):
                self._handle_connections_entry(entry, tags)
            elif dn.endswith(self.OPERATIONS_METRICS_DN):
                self._handle_operations_entry(entry, tags)
            elif dn.endswith(self.STATISTICS_METRICS_DN):
                self._handle_statistics_entry(entry, tags)
            elif dn.endswith(self.THREADS_METRICS_DN):
                self._handle_threads_entry(entry, tags)
            elif dn.endswith(self.TIME_METRICS_DN):
                self._handle_time_entry(entry, tags)
            elif dn.endswith(self.WAITERS_METRICS_DN):
                self._handle_waiters_entry(entry, tags)

    def _perform_custom_queries(self, conn, custom_queries, tags, instance):
        """
        Perform custom queries to collect additional metrics like number of result and duration of the query
        """
        for query in custom_queries:
            name = query.get("name")
            if name is None:
                self.log.error("`name` field is required for custom query")
                continue
            search_base = query.get("search_base")
            if search_base is None:
                self.log.error("`search_base` field is required for custom query #%s", name)
                continue
            search_filter = query.get("search_filter")
            if search_filter is None:
                self.log.error("`search_filter` field is required for custom query #%s", name)
                continue
            attrs = query.get("attributes")
            if "username" in query:
                username = query.get("username")
                password = query.get("password")
                if not username:
                    # username is an empty string, we want anonymous bind
                    username = None
                    password = None
            else:
                # username not specified, we want to reuse the credentials for the monitor backend
                username = instance.get("username")
                password = instance.get("password")

            try:
                # Rebind with different credentials
                auth_method = ldap3.SIMPLE if username else ldap3.ANONYMOUS
                if username is None:
                    conn.user = None
                res = conn.rebind(user=username, password=password, authentication=auth_method)
                if not res:
                    raise ldap3.core.exceptions.LDAPBindError("Error binding to server: {}".format(conn.result))
            except ldap3.core.exceptions.LDAPBindError:
                self.log.exception("Could not rebind to server at %s to perform query %s", instance.get("url"), name)
                continue

            try:
                # Perform the search query
                conn.search(search_base, search_filter, attributes=attrs)
            except ldap3.core.exceptions.LDAPException:
                self.log.exception("Unable to perform search query for %s", name)
                continue

            query_tags = ['query:{}'.format(name)]
            query_tags.extend(tags)
            query_time = self._get_query_time(conn)
            results = len(conn.entries)
            self.gauge("{}.query.duration".format(self.METRIC_PREFIX), query_time, tags=query_tags)
            self.gauge("{}.query.entries".format(self.METRIC_PREFIX), results, tags=query_tags)

    def _handle_connections_entry(self, entry, tags):
        cn = self._extract_common_name(entry.entry_dn)
        if cn in ["max_file_descriptors", "current"]:
            self.gauge("{}.connections.{}".format(self.METRIC_PREFIX, cn), entry["monitorCounter"].value, tags=tags)
        elif cn == "total":
            self.monotonic_count(
                "{}.connections.{}".format(self.METRIC_PREFIX, cn), entry["monitorCounter"].value, tags=tags
            )

    def _handle_operations_entry(self, entry, tags):
        cn = self._extract_common_name(entry.entry_dn)
        initiated = entry["monitorOpInitiated"].value
        completed = entry["monitorOpCompleted"].value
        if cn == "operations":
            # the root of the "cn=operations,cn=monitor" has the total number of initiated and completed operations
            self.monotonic_count("{}.operations.initiated.total".format(self.METRIC_PREFIX), initiated, tags=tags)
            self.monotonic_count("{}.operations.completed.total".format(self.METRIC_PREFIX), completed, tags=tags)
        else:
            self.monotonic_count(
                "{}.operations.initiated".format(self.METRIC_PREFIX), initiated, tags=tags + ["operation:{}".format(cn)]
            )
            self.monotonic_count(
                "{}.operations.completed".format(self.METRIC_PREFIX), completed, tags=tags + ["operation:{}".format(cn)]
            )

    def _handle_statistics_entry(self, entry, tags):
        cn = self._extract_common_name(entry.entry_dn)
        if cn != "statistics":
            self.monotonic_count(
                '{}.statistics.{}'.format(self.METRIC_PREFIX, cn), entry['monitorCounter'].value, tags=tags
            )

    def _handle_threads_entry(self, entry, tags):
        cn = self._extract_common_name(entry.entry_dn)
        try:
            value = entry["monitoredInfo"].value
        except ldap3.core.exceptions.LDAPKeyError:
            return
        if cn in ["max", "max_pending"]:
            self.gauge("{}.threads.{}".format(self.METRIC_PREFIX, cn), value, tags=tags)
        elif cn in ["open", "starting", "active", "pending", "backload"]:
            self.gauge("{}.threads".format(self.METRIC_PREFIX), value, tags=tags + ["status:{}".format(cn)])

    def _handle_time_entry(self, entry, tags):
        cn = self._extract_common_name(entry.entry_dn)
        if cn == "uptime":
            self.gauge("{}.uptime".format(self.METRIC_PREFIX), entry["monitoredInfo"].value, tags=tags)

    def _handle_waiters_entry(self, entry, tags):
        cn = self._extract_common_name(entry.entry_dn)
        if cn != "waiters":
            self.gauge("{}.waiter.{}".format(self.METRIC_PREFIX, cn), entry["monitorCounter"].value, tags=tags)

    @classmethod
    def _extract_common_name(cls, dn):
        """
        extract first common name (cn) from DN that looks like "cn=max file descriptors,cn=connections,cn=monitor"
        """
        dn = dn.lower().replace(" ", "_")
        return dn.split(",")[0].split("=")[1]

    @classmethod
    def _get_query_time(cls, conn):
        return (conn.usage.last_received_time - conn.usage.last_transmitted_time).total_seconds()


text:
"""
The MatchMaker classes should except a Topic or Fanout exchange key and
return keys for direct exchanges, per (approximate) AMQP parlance.
"""

import contextlib

import eventlet
from oslo.config import cfg

from muranorepository.openstack.common.gettextutils import _  # noqa
from muranorepository.openstack.common import log as logging

matchmaker_opts = [
    cfg.IntOpt('matchmaker_heartbeat_freq',
               default=300,
               help='Heartbeat frequency'),
    cfg.IntOpt('matchmaker_heartbeat_ttl',
               default=600,
               help='Heartbeat time-to-live.'),
]

CONF = cfg.CONF
CONF.register_opts(matchmaker_opts)
LOG = logging.getLogger(__name__)
contextmanager = contextlib.contextmanager

class MatchMakerException(Exception):
    """Signified a match could not be found."""
    message = _("Match not found by MatchMaker.")

class Exchange(object):
    """Implements lookups.

    Subclass this to support hashtables, dns, etc.
    """
    def __init__(self):
        pass

    def run(self, key):
        raise NotImplementedError()

class Binding(object):
    """A binding on which to perform a lookup."""
    def __init__(self):
        pass

    def test(self, key):
        raise NotImplementedError()

class MatchMakerBase(object):
    """Match Maker Base Class.

    Build off HeartbeatMatchMakerBase if building a heartbeat-capable
    MatchMaker.
    """
    def __init__(self):
        # Array of tuples. Index [2] toggles negation, [3] is last-if-true
        self.bindings = []

        self.no_heartbeat_msg = _('Matchmaker does not implement '
                                  'registration or heartbeat.')

    def register(self, key, host):
        """Register a host on a backend.

        Heartbeats, if applicable, may keepalive registration.
        """
        pass

    def ack_alive(self, key, host):
        """Acknowledge that a key.host is alive.

        Used internally for updating heartbeats, but may also be used
        publically to acknowledge a system is alive (i.e. rpc message
        successfully sent to host)
        """
        pass

    def is_alive(self, topic, host):
        """Checks if a host is alive."""
        pass

    def expire(self, topic, host):
        """Explicitly expire a host's registration."""
        pass

    def send_heartbeats(self):
        """Send all heartbeats.

        Use start_heartbeat to spawn a heartbeat greenthread,
        which loops this method.
        """
        pass

    def unregister(self, key, host):
        """Unregister a topic."""
        pass

    def start_heartbeat(self):
        """Spawn heartbeat greenthread."""
        pass

    def stop_heartbeat(self):
        """Destroys the heartbeat greenthread."""
        pass

    def add_binding(self, binding, rule, last=True):
        self.bindings.append((binding, rule, False, last))

    #NOTE(ewindisch): kept the following method in case we implement the
    #                 underlying support.
    #def add_negate_binding(self, binding, rule, last=True):
    #    self.bindings.append((binding, rule, True, last))

    def queues(self, key):
        workers = []

        # bit is for negate bindings - if we choose to implement it.
        # last stops processing rules if this matches.
        for (binding, exchange, bit, last) in self.bindings:
            if binding.test(key):
                workers.extend(exchange.run(key))

                # Support last.
                if last:
                    return workers
        return workers

class HeartbeatMatchMakerBase(MatchMakerBase):
    """Base for a heart-beat capable MatchMaker.

    Provides common methods for registering, unregistering, and maintaining
    heartbeats.
    """
    def __init__(self):
        self.hosts = set()
        self._heart = None
        self.host_topic = {}

        super(HeartbeatMatchMakerBase, self).__init__()

    def send_heartbeats(self):
        """Send all heartbeats.

        Use start_heartbeat to spawn a heartbeat greenthread,
        which loops this method.
        """
        for key, host in self.host_topic:
            self.ack_alive(key, host)

    def ack_alive(self, key, host):
        """Acknowledge that a host.topic is alive.

        Used internally for updating heartbeats, but may also be used
        publically to acknowledge a system is alive (i.e. rpc message
        successfully sent to host)
        """
        raise NotImplementedError("Must implement ack_alive")

    def backend_register(self, key, host):
        """Implements registration logic.

        Called by register(self,key,host)
        """
        raise NotImplementedError("Must implement backend_register")

    def backend_unregister(self, key, key_host):
        """Implements de-registration logic.

        Called by unregister(self,key,host)
        """
        raise NotImplementedError("Must implement backend_unregister")

    def register(self, key, host):
        """Register a host on a backend.

        Heartbeats, if applicable, may keepalive registration.
        """
        self.hosts.add(host)
        self.host_topic[(key, host)] = host
        key_host = '.'.join((key, host))

        self.backend_register(key, key_host)

        self.ack_alive(key, host)

    def unregister(self, key, host):
        """Unregister a topic."""
        if (key, host) in self.host_topic:
            del self.host_topic[(key, host)]

        self.hosts.discard(host)
        self.backend_unregister(key, '.'.join((key, host)))

        LOG.info(_("Matchmaker unregistered: %(key)s, %(host)s"),
                 {'key': key, 'host': host})

    def start_heartbeat(self):
        """Implementation of MatchMakerBase.start_heartbeat.

        Launches greenthread looping send_heartbeats(),
        yielding for CONF.matchmaker_heartbeat_freq seconds
        between iterations.
        """
        if not self.hosts:
            raise MatchMakerException(
                _("Register before starting heartbeat."))

        def do_heartbeat():
            while True:
                self.send_heartbeats()
                eventlet.sleep(CONF.matchmaker_heartbeat_freq)

        self._heart = eventlet.spawn(do_heartbeat)

    def stop_heartbeat(self):
        """Destroys the heartbeat greenthread."""
        if self._heart:
            self._heart.kill()

class DirectBinding(Binding):
    """Specifies a host in the key via a '.' character.

    Although dots are used in the key, the behavior here is
    that it maps directly to a host, thus direct.
    """
    def test(self, key):
        return '.' in key

class TopicBinding(Binding):
    """Where a 'bare' key without dots.

    AMQP generally considers topic exchanges to be those *with* dots,
    but we deviate here in terminology as the behavior here matches
    that of a topic exchange (whereas where there are dots, behavior
    matches that of a direct exchange.
    """
    def test(self, key):
        return '.' not in key

class FanoutBinding(Binding):
    """Match on fanout keys, where key starts with 'fanout.' string."""
    def test(self, key):
        return key.startswith('fanout~')

class StubExchange(Exchange):
    """Exchange that does nothing."""
    def run(self, key):
        return [(key, None)]

class LocalhostExchange(Exchange):
    """Exchange where all direct topics are local."""
    def __init__(self, host='localhost'):
        self.host = host
        super(Exchange, self).__init__()

    def run(self, key):
        return [('.'.join((key.split('.')[0], self.host)), self.host)]

class DirectExchange(Exchange):
    """Exchange where all topic keys are split, sending to second half.

    i.e. "compute.host" sends a message to "compute.host" running on "host"
    """
    def __init__(self):
        super(Exchange, self).__init__()

    def run(self, key):
        e = key.split('.', 1)[1]
        return [(key, e)]

class MatchMakerLocalhost(MatchMakerBase):
    """Match Maker where all bare topics resolve to localhost.

    Useful for testing.
    """
    def __init__(self, host='localhost'):
        super(MatchMakerLocalhost, self).__init__()
        self.add_binding(FanoutBinding(), LocalhostExchange(host))
        self.add_binding(DirectBinding(), DirectExchange())
        self.add_binding(TopicBinding(), LocalhostExchange(host))

class MatchMakerStub(MatchMakerBase):
    """Match Maker where topics are untouched.

    Useful for testing, or for AMQP/brokered queues.
    Will not work where knowledge of hosts is known (i.e. zeromq)
    """
    def __init__(self):
        super(MatchMakerStub, self).__init__()

        self.add_binding(FanoutBinding(), StubExchange())
        self.add_binding(DirectBinding(), StubExchange())
        self.add_binding(TopicBinding(), StubExchange())


text:
require 'torch'
require 'nn'

torch.setdefaulttensortype('torch.FloatTensor')

input = torch.Tensor(6,3,128,128)

net = nn.Add(6,3,128,128)
net:evaluate()

output = net:forward(input)

--print(output:size())

torch.save(arg[1], input)
torch.save(arg[2], output)

net:clearState()
torch.save(arg[3], net)