text:
GOPATH_DIR := $(GOPATH)/src/github.com/open-telemetry/opentelemetry-proto
GENDIR := gen
GOPATH_GENDIR := $(GOPATH_DIR)/$(GENDIR)

# Find all .proto files.
PROTO_FILES := $(wildcard opentelemetry/proto/*/*/*.proto opentelemetry/proto/*/*/*/*.proto)

# Function to execute a command. Note the empty line before endef to make sure each command
# gets executed separately instead of concatenated with previous one.
# Accepts command to execute as first parameter.
define exec-command
$(1)

endef

# Generate all implementations
.PHONY: gen-all
gen-all: gen-cpp gen-csharp gen-go gen-java gen-objc gen-openapi gen-php gen-python gen-ruby

OTEL_DOCKER_PROTOBUF ?= otel/build-protobuf:0.4.0
PROTOC := docker run --rm -u ${shell id -u} -v${PWD}:${PWD} -w${PWD} ${OTEL_DOCKER_PROTOBUF} --proto_path=${PWD}
PROTO_INCLUDES := -I/usr/include/github.com/gogo/protobuf

PROTO_GEN_CPP_DIR ?= $(GENDIR)/cpp
PROTO_GEN_CSHARP_DIR ?= $(GENDIR)/csharp
PROTO_GEN_GO_DIR ?= $(GENDIR)/go
PROTO_GEN_JAVA_DIR ?= $(GENDIR)/java
PROTO_GEN_JS_DIR ?= $(GENDIR)/js
PROTO_GEN_OBJC_DIR ?= $(GENDIR)/objc
PROTO_GEN_OPENAPI_DIR ?= $(GENDIR)/openapi
PROTO_GEN_PHP_DIR ?= $(GENDIR)/php
PROTO_GEN_PYTHON_DIR ?= $(GENDIR)/python
PROTO_GEN_RUBY_DIR ?= $(GENDIR)/ruby

# Docker pull image.
.PHONY: docker-pull
docker-pull:
	docker pull $(OTEL_DOCKER_PROTOBUF)

# Generate gRPC/Protobuf implementation for C++.
.PHONY: gen-cpp
gen-cpp:
	rm -rf ./$(PROTO_GEN_CPP_DIR)
	mkdir -p ./$(PROTO_GEN_CPP_DIR)
	$(foreach file,$(PROTO_FILES),$(call exec-command, $(PROTOC) --cpp_out=./$(PROTO_GEN_CPP_DIR) $(file)))
	$(PROTOC) --cpp_out=./$(PROTO_GEN_CPP_DIR) --grpc-cpp_out=./$(PROTO_GEN_CPP_DIR) opentelemetry/proto/collector/trace/v1/trace_service.proto
	$(PROTOC) --cpp_out=./$(PROTO_GEN_CPP_DIR) --grpc-cpp_out=./$(PROTO_GEN_CPP_DIR) opentelemetry/proto/collector/metrics/v1/metrics_service.proto
	$(PROTOC) --cpp_out=./$(PROTO_GEN_CPP_DIR) --grpc-cpp_out=./$(PROTO_GEN_CPP_DIR) opentelemetry/proto/collector/logs/v1/logs_service.proto

# Generate gRPC/Protobuf implementation for C#.
.PHONY: gen-csharp
gen-csharp:
	rm -rf ./$(PROTO_GEN_CSHARP_DIR)
	mkdir -p ./$(PROTO_GEN_CSHARP_DIR)
	$(foreach file,$(PROTO_FILES),$(call exec-command, $(PROTOC) --csharp_out=./$(PROTO_GEN_CSHARP_DIR) $(file)))
	$(PROTOC) --csharp_out=./$(PROTO_GEN_CSHARP_DIR) --grpc-csharp_out=./$(PROTO_GEN_CSHARP_DIR) opentelemetry/proto/collector/trace/v1/trace_service.proto
	$(PROTOC) --csharp_out=./$(PROTO_GEN_CSHARP_DIR) --grpc-csharp_out=./$(PROTO_GEN_CSHARP_DIR) opentelemetry/proto/collector/metrics/v1/metrics_service.proto
	$(PROTOC) --csharp_out=./$(PROTO_GEN_CSHARP_DIR) --grpc-csharp_out=./$(PROTO_GEN_CSHARP_DIR) opentelemetry/proto/collector/logs/v1/logs_service.proto

# Generate gRPC/Protobuf implementation for Go.
.PHONY: gen-go
gen-go:
	rm -rf ./$(PROTO_GEN_GO_DIR)
	mkdir -p ./$(PROTO_GEN_GO_DIR)
	$(foreach file,$(PROTO_FILES),$(call exec-command,$(PROTOC) $(PROTO_INCLUDES) --gogo_out=plugins=grpc:./$(PROTO_GEN_GO_DIR) $(file)))
	$(PROTOC) --grpc-gateway_out=logtostderr=true,grpc_api_configuration=opentelemetry/proto/collector/trace/v1/trace_service_http.yaml:./$(PROTO_GEN_GO_DIR) opentelemetry/proto/collector/trace/v1/trace_service.proto
	$(PROTOC) --grpc-gateway_out=logtostderr=true,grpc_api_configuration=opentelemetry/proto/collector/metrics/v1/metrics_service_http.yaml:./$(PROTO_GEN_GO_DIR) opentelemetry/proto/collector/metrics/v1/metrics_service.proto
	$(PROTOC) --grpc-gateway_out=logtostderr=true,grpc_api_configuration=opentelemetry/proto/collector/logs/v1/logs_service_http.yaml:./$(PROTO_GEN_GO_DIR) opentelemetry/proto/collector/logs/v1/logs_service.proto

# Generate gRPC/Protobuf implementation for Java.
.PHONY: gen-java
gen-java:
	rm -rf ./$(PROTO_GEN_JAVA_DIR)
	mkdir -p ./$(PROTO_GEN_JAVA_DIR)
	$(foreach file,$(PROTO_FILES),$(call exec-command, $(PROTOC) --java_out=./$(PROTO_GEN_JAVA_DIR) $(file)))

# Generate gRPC/Protobuf implementation for JavaScript.
.PHONY: gen-js
gen-js:
	rm -rf ./$(PROTO_GEN_JS_DIR)
	mkdir -p ./$(PROTO_GEN_JS_DIR)
	$(foreach file,$(PROTO_FILES),$(call exec-command, $(PROTOC) --js_out=import_style=commonjs:./$(PROTO_GEN_JS_DIR) $(file)))
	$(PROTOC) --js_out=import_style=commonjs:./$(PROTO_GEN_JS_DIR) --grpc-web_out=import_style=commonjs,mode=grpcweb:./$(PROTO_GEN_JS_DIR) opentelemetry/proto/collector/trace/v1/trace_service.proto
	$(PROTOC) --js_out=import_style=commonjs:./$(PROTO_GEN_JS_DIR) --grpc-web_out=import_style=commonjs,mode=grpcweb:./$(PROTO_GEN_JS_DIR) opentelemetry/proto/collector/metrics/v1/metrics_service.proto
	$(PROTOC) --js_out=import_style=commonjs:./$(PROTO_GEN_JS_DIR) --grpc-web_out=import_style=commonjs,mode=grpcweb:./$(PROTO_GEN_JS_DIR) opentelemetry/proto/collector/logs/v1/logs_service.proto

# Generate gRPC/Protobuf implementation for Objective-C.
.PHONY: gen-objc
gen-objc:
	rm -rf ./$(PROTO_GEN_OBJC_DIR)
	mkdir -p ./$(PROTO_GEN_OBJC_DIR)
	$(foreach file,$(PROTO_FILES),$(call exec-command, $(PROTOC) --objc_out=./$(PROTO_GEN_OBJC_DIR) $(file)))
	$(PROTOC) --objc_out=./$(PROTO_GEN_OBJC_DIR) --grpc-objc_out=./$(PROTO_GEN_OBJC_DIR) opentelemetry/proto/collector/trace/v1/trace_service.proto
	$(PROTOC) --objc_out=./$(PROTO_GEN_OBJC_DIR) --grpc-objc_out=./$(PROTO_GEN_OBJC_DIR) opentelemetry/proto/collector/metrics/v1/metrics_service.proto
	$(PROTOC) --objc_out=./$(PROTO_GEN_OBJC_DIR) --grpc-objc_out=./$(PROTO_GEN_OBJC_DIR) opentelemetry/proto/collector/logs/v1/logs_service.proto

# Generate gRPC/Protobuf for swagger
.PHONY: gen-openapi
gen-openapi:
	mkdir -p $(PROTO_GEN_OPENAPI_DIR)
	$(PROTOC) --swagger_out=logtostderr=true,grpc_api_configuration=opentelemetry/proto/collector/trace/v1/trace_service_http.yaml:$(PROTO_GEN_OPENAPI_DIR) opentelemetry/proto/collector/trace/v1/trace_service.proto
	$(PROTOC) --swagger_out=logtostderr=true,grpc_api_configuration=opentelemetry/proto/collector/metrics/v1/metrics_service_http.yaml:$(PROTO_GEN_OPENAPI_DIR) opentelemetry/proto/collector/metrics/v1/metrics_service.proto
	$(PROTOC) --swagger_out=logtostderr=true,grpc_api_configuration=opentelemetry/proto/collector/logs/v1/logs_service_http.yaml:$(PROTO_GEN_OPENAPI_DIR) opentelemetry/proto/collector/logs/v1/logs_service.proto

# Generate gRPC/Protobuf implementation for PhP.
.PHONY: gen-php
gen-php:
	rm -rf ./$(PROTO_GEN_PHP_DIR)
	mkdir -p ./$(PROTO_GEN_PHP_DIR)
	$(foreach file,$(PROTO_FILES),$(call exec-command, $(PROTOC) --php_out=./$(PROTO_GEN_PHP_DIR) $(file)))
	$(PROTOC) --php_out=./$(PROTO_GEN_PHP_DIR) --grpc-php_out=./$(PROTO_GEN_PHP_DIR) opentelemetry/proto/collector/trace/v1/trace_service.proto
	$(PROTOC) --php_out=./$(PROTO_GEN_PHP_DIR) --grpc-php_out=./$(PROTO_GEN_PHP_DIR) opentelemetry/proto/collector/metrics/v1/metrics_service.proto
	$(PROTOC) --php_out=./$(PROTO_GEN_PHP_DIR) --grpc-php_out=./$(PROTO_GEN_PHP_DIR) opentelemetry/proto/collector/logs/v1/logs_service.proto

# Generate gRPC/Protobuf implementation for Python.
.PHONY: gen-python
gen-python:
	rm -rf ./$(PROTO_GEN_PYTHON_DIR)
	mkdir -p ./$(PROTO_GEN_PYTHON_DIR)
	$(foreach file,$(PROTO_FILES),$(call exec-command, $(PROTOC) --python_out=./$(PROTO_GEN_PYTHON_DIR) $(file)))
	$(PROTOC) --python_out=./$(PROTO_GEN_PYTHON_DIR) --grpc-python_out=./$(PROTO_GEN_PYTHON_DIR) opentelemetry/proto/collector/trace/v1/trace_service.proto
	$(PROTOC) --python_out=./$(PROTO_GEN_PYTHON_DIR) --grpc-python_out=./$(PROTO_GEN_PYTHON_DIR) opentelemetry/proto/collector/metrics/v1/metrics_service.proto
	$(PROTOC) --python_out=./$(PROTO_GEN_PYTHON_DIR) --grpc-python_out=./$(PROTO_GEN_PYTHON_DIR) opentelemetry/proto/collector/logs/v1/logs_service.proto

# Generate gRPC/Protobuf implementation for Ruby.
.PHONY: gen-ruby
gen-ruby:
	rm -rf ./$(PROTO_GEN_RUBY_DIR)
	mkdir -p ./$(PROTO_GEN_RUBY_DIR)
	$(foreach file,$(PROTO_FILES),$(call exec-command, $(PROTOC) --ruby_out=./$(PROTO_GEN_RUBY_DIR) $(file)))
	$(PROTOC) --ruby_out=./$(PROTO_GEN_RUBY_DIR) --grpc-ruby_out=./$(PROTO_GEN_RUBY_DIR) opentelemetry/proto/collector/trace/v1/trace_service.proto
	$(PROTOC) --ruby_out=./$(PROTO_GEN_RUBY_DIR) --grpc-ruby_out=./$(PROTO_GEN_RUBY_DIR) opentelemetry/proto/collector/metrics/v1/metrics_service.proto
	$(PROTOC) --ruby_out=./$(PROTO_GEN_RUBY_DIR) --grpc-ruby_out=./$(PROTO_GEN_RUBY_DIR) opentelemetry/proto/collector/logs/v1/logs_service.proto


text:
function SetVariable([string]$key, [string]$value)
{
    [environment]::SetEnvironmentVariable($key, $value, "User")
    [environment]::SetEnvironmentVariable($key, $value)
}

function AskYesNoQuestion([string]$question, [string]$key)
{
	$answer = Read-Host -Prompt ($question + " Press Y to set this, otherwise we'll skip it")
	if ($answer -eq "Y")
	{
		SetVariable $key "YES"
	}
	else
	{
		SetVariable $key $null
	}

	Write-Host

	return ($answer -eq "Y")
}

function VerifyEnvironmentVariable([string]$friendlyName, [string]$key, [bool]$optional = $false)
{
	if ($optional -eq $true)
	{
		$label = "(optional)"
	}
	else
	{
		$label = "(required)"
	}

	$existing_value = [environment]::GetEnvironmentVariable($key,"User")
	if ($existing_value -eq $null)
	{
		$value = Read-Host -Prompt "Set the $friendlyName to use for the integration tests $label"
		SetVariable $key $value
	}
	else
	{
		Write-Host "$existing_value found as the configured $friendlyName"
		if ($optional -eq $true)
		{
			$clear = Read-Host -Prompt 'Want to remove or change this optional value, press Y'
			if ($clear -eq "Y")
			{
				$reset = Read-Host -Prompt "Press R to remove and Press C to change the value, otherwise we'll move on"
				if ($reset -eq "C")
				{
					$value = Read-Host -Prompt "Change the $friendlyName to use for the integration tests"
       				SetVariable $key $value
				}
				elseif ($reset -eq "R")
				{
					SetVariable $key $null
				}
			}
		}
		else
		{
			$reset = Read-Host -Prompt "Press Y to change this value, otherwise we'll move on "
			if ($reset -eq "Y")
			{
				$value = Read-Host -Prompt "Change the $friendlyName to use for the integration tests"
       			SetVariable $key $value
			}
		}
	}

	Write-Host
}

Write-Host
Write-Warning "BIG FREAKING WARNING!!!!!"
Write-Warning "You should use a test account when running the Octokit integration tests!"
Write-Host
Write-Host

VerifyEnvironmentVariable "test account name" "OCTOKIT_GITHUBUSERNAME"
VerifyEnvironmentVariable "test account password" "OCTOKIT_GITHUBPASSWORD" $true
VerifyEnvironmentVariable "test account OAuth token" "OCTOKIT_OAUTHTOKEN"

if (AskYesNoQuestion "Some tests require a second test account, do you want to set one up?" "OCTOKIT_PRIVATEREPOSITORIES")
{
	VerifyEnvironmentVariable "Second test account name" "OCTOKIT_GITHUBUSERNAME_2"
	VerifyEnvironmentVariable "Second account password" "OCTOKIT_GITHUBPASSWORD_2"
}

AskYesNoQuestion "Do you have private repositories associated with your test account?" "OCTOKIT_PRIVATEREPOSITORIES" | Out-Null

VerifyEnvironmentVariable "organization name" "OCTOKIT_GITHUBORGANIZATION" $true

VerifyEnvironmentVariable "Override GitHub URL" "OCTOKIT_CUSTOMURL" $true

VerifyEnvironmentVariable "application ClientID" "OCTOKIT_CLIENTID" $true
VerifyEnvironmentVariable "application Secret" "OCTOKIT_CLIENTSECRET" $true

if (AskYesNoQuestion "Do you wish to setup GitHubApps integration test settings?" "OCTOKIT_GITHUBAPP_ENABLED")
{
	VerifyEnvironmentVariable "GitHub App ID" "OCTOKIT_GITHUBAPP_ID"
	VerifyEnvironmentVariable "GitHub App SLUG" "OCTOKIT_GITHUBAPP_SLUG"
	VerifyEnvironmentVariable "GitHub App Installation ID" "OCTOKIT_GITHUBAPP_INSTALLATIONID"
	VerifyEnvironmentVariable "GitHub App Pem File" "OCTOKIT_GITHUBAPP_PEMFILE"
}

if (AskYesNoQuestion "Do you wish to enable GitHub Enterprise (GHE) Integration Tests?" "OCTOKIT_GHE_ENABLED")
{
    VerifyEnvironmentVariable "GitHub Enterprise account name" "OCTOKIT_GHE_USERNAME"
    VerifyEnvironmentVariable "GitHub Enterprise account password" "OCTOKIT_GHE_PASSWORD" $true
    VerifyEnvironmentVariable "GitHub Enterprise OAuth token" "OCTOKIT_GHE_OAUTHTOKEN"

    VerifyEnvironmentVariable "GitHub Enterprise organization name" "OCTOKIT_GHE_ORGANIZATION" $true

    VerifyEnvironmentVariable "GitHub Enterprise URL" "OCTOKIT_GHE_URL" $true

    VerifyEnvironmentVariable "GitHub Enterprise application ClientID" "OCTOKIT_GHE_CLIENTID" $true
    VerifyEnvironmentVariable "GitHub Enterprise application Secret" "OCTOKIT_GHE_CLIENTSECRET" $true
}

redpajama_set_name: RedPajamaGithub


text:
/*!
 * \file countmin.c
 *
 * \brief CountMin sketch implementation
 *
 * \implementation
 * The basic CountMin sketch is a set of DEPTH arrays, each with NUMCOUNTERS counters.
 * The idea is that each of those arrays is used as an independent random trial of the
 * same process: for all the values x in a set, each holds counts of h_i(x) mod NUMCOUNTERS for a different random hash function h_i.
 * Estimates of the count of some value x are based on the <i>minimum</i> counter h_i(x) across
 * the DEPTH arrays (hence the name CountMin.)
 *
 * Let's call the process described above "sketching" the x's.  To support range
 * lookups, we repeat the basic CountMin sketching process INT64BITS times as follows.
 * (This is the "dyadic range" trick mentioned in Cormode/Muthu.)
 *
 * Every value x/(2^i) is sketched
 * at a different power-of-2 (dyadic) "range" i.  So we sketch x in range 0, then sketch x/2
 * in range 1, then sketch x/4 in range 2, etc.
 * This allows us to count up ranges (like 14-48) by doing CountMin equality lookups on constituent
 * dyadic ranges ({[14-15] as 7 in range 2, [16-31] as 1 in range 16, [32-47] as 2 in range 16, [48-48] as 48 in range 1}).
 * Dyadic ranges are similarly useful for histogramming, order stats, etc.
 *
 * The results of the estimators below generally have guarantees of the form
 * "the answer is within \epsilon of the true answer with probability 1-\delta."
 */

#include <postgres.h>
#include <utils/fmgroids.h>
#include <utils/array.h>
#include <utils/elog.h>
#include <utils/builtins.h>
#include <utils/lsyscache.h>
#include <utils/numeric.h>
#include <nodes/execnodes.h>
#include <fmgr.h>
#include <catalog/pg_type.h>
#include <ctype.h>
#include "sketch_support.h"
#include "countmin.h"

PG_FUNCTION_INFO_V1(__cmsketch_int8_trans);

/*
 * This is the UDF interface.  It does sanity checks and preps values
 * for the interesting logic in countmin_dyadic_trans_c
 */
Datum __cmsketch_int8_trans(PG_FUNCTION_ARGS)
{
    bytea *     transblob = NULL;
    cmtransval *transval;

    /*
     * This function makes destructive updates to its arguments.
     * Make sure it's being called in an agg context.
     */

    if (!(fcinfo->context &&
          (IsA(fcinfo->context, AggState)
    #ifdef NOTGP
           || IsA(fcinfo->context, WindowAggState)
    #endif
          )))
        elog(ERROR,
             "destructive pass by reference outside agg");

    /* get the provided element, being careful in case it's NULL */
    if (!PG_ARGISNULL(1)) {
        transblob = cmsketch_check_transval(fcinfo, true);
        transval = (cmtransval *)(VARDATA(transblob));

        /* the following line modifies the contents of transval, and hence transblob */
        countmin_dyadic_trans_c(transval, PG_GETARG_DATUM(1));
        PG_RETURN_DATUM(PointerGetDatum(transblob));
    }
    else PG_RETURN_DATUM(PointerGetDatum(PG_GETARG_BYTEA_P(0)));
}

/*!
 * check if the transblob is not initialized, and do so if not
 * \param transblob a cmsketch transval packed in a bytea
 */
bytea *cmsketch_check_transval(PG_FUNCTION_ARGS, bool initargs)
{
    bytea *     transblob = PG_GETARG_BYTEA_P(0);
    cmtransval *transval;

    /*
     * an uninitialized transval should be a datum smaller than sizeof(cmtransval).
     * if this one is small, initialize it now, else return it.
     */
    if (!CM_TRANSVAL_INITIALIZED(transblob)) {
        /* XXX would be nice to pfree the existing transblob, but pfree complains. */
        transblob = cmsketch_init_transval();
        transval = (cmtransval *)VARDATA(transblob);

        if (initargs) {
            int nargs = PG_NARGS();
            int i;
            /* carry along any additional args */
            if (nargs - 2 > MAXARGS)
                elog(
                    ERROR,
                    "no more than %d additional arguments should be passed to __cmsketch_int8_trans",
                    MAXARGS);
            transval->nargs = nargs - 2;
            for (i = 2; i < nargs; i++) {
                if (PG_ARGISNULL(i))
                    elog(ERROR,
                         "NULL parameter %d passed to __cmsketch_int8_trans",
                         i);
                transval->args[i-2] = PG_GETARG_INT64(i);
            }
        }
        else transval->nargs = -1;
    }
    return(transblob);
}

bytea *cmsketch_init_transval()
{
    /* allocate and zero out a transval via palloc0 */
    bytea *     transblob = (bytea *)palloc0(CM_TRANSVAL_SZ);
    SET_VARSIZE(transblob, CM_TRANSVAL_SZ);

    return(transblob);
}

/*!
 * perform multiple sketch insertions, one for each dyadic range (from 0 up to RANGES-1).
 * * \param transval the cmsketch transval
 * * \param inputi the value to be inserted
 */
void countmin_dyadic_trans_c(cmtransval *transval, Datum input)
{
    uint32 j;

    for (j = 0; j < RANGES; j++) {
        countmin_trans_c(transval->sketches[j], input,
                         F_INT8OUT, INT8OID);
        /* now divide by 2 for the next dyadic range */
        input = Int64GetDatum(DatumGetInt64(input) >> 1);
    }
}

/*!
 * Main loop of Cormode and Muthukrishnan's sketching algorithm, for setting counters in
 * sketches at a single "dyadic range". For each call, we want to use DEPTH independent
 * hash functions.  We do this by using a single md5 hash function, and taking
 * successive 16-bit runs of the result as independent hash outputs.
 * \param sketch the current countmin sketch
 * \param dat the datum to be inserted
 * \param outFuncOid Oid of the PostgreSQL function to convert dat to a string
 * \param typOid Oid of the Postgres type for dat
 */
Datum countmin_trans_c(countmin sketch, Datum dat, Oid outFuncOid, Oid typOid)
{
	(void) outFuncOid; /* avoid warning about unused parameter */
    bytea *nhash;

    nhash = sketch_md5_bytea(dat, typOid);

    /*
     * iterate through all sketches, incrementing the counters indicated by the hash
     * we don't care about return value here, so 3rd (initialization) argument is arbitrary.
     */
    (void)hash_counters_iterate(nhash, sketch, 0, &increment_counter);
    return(PointerGetDatum(nhash));
}

/*
 * FINAL functions for various UDAs built on countmin sketches
 */

/*
 * pasted code from utils/encode.c, facilitating __cmsketch_base64_final
 */
static const char _base64[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

static const int8 b64lookup[128] = {
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63,
    52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1,
    -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
    15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1,
    -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
    41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1,
};

static unsigned
b64_encode(const char *src, unsigned len, char *dst)
{
    char       *p,
               *lend = dst + 76;
    const char *s,
               *end = src + len;
    int         pos = 2;
    uint32      buf = 0;

    s = src;
    p = dst;

    while (s < end)
    {
        buf |= (unsigned char) *s << (pos << 3);
        pos--;
        s++;

        /* write it out */
        if (pos < 0)
        {
            *p++ = _base64[(buf >> 18) & 0x3f];
            *p++ = _base64[(buf >> 12) & 0x3f];
            *p++ = _base64[(buf >> 6) & 0x3f];
            *p++ = _base64[buf & 0x3f];

            pos = 2;
            buf = 0;
        }
        if (p >= lend)
        {
            *p++ = '\n';
            lend = p + 76;
        }
    }
    if (pos != 2)
    {
        *p++ = _base64[(buf >> 18) & 0x3f];
        *p++ = _base64[(buf >> 12) & 0x3f];
        *p++ = (pos == 0) ? _base64[(buf >> 6) & 0x3f] : '=';
        *p++ = '=';
    }

    return p - dst;
}

static unsigned
b64_enc_len(unsigned srclen)
{
    /* 3 bytes will be converted to 4, linefeed after 76 chars */
    return (srclen + 2) * 4 / 3 + srclen / (76 * 3 / 4);
}
// done pasted code

/*!
 * return the array of sketch counters as a int8
 */
PG_FUNCTION_INFO_V1(__cmsketch_base64_final);
Datum __cmsketch_base64_final(PG_FUNCTION_ARGS)
{
    bytea *     blob = PG_GETARG_BYTEA_P(0);
    cmtransval *sketch = NULL;
    int         len = RANGES*sizeof(countmin) + VARHDRSZ;
    bytea *out = NULL;

    if (VARSIZE(blob) > VARHDRSZ && !CM_TRANSVAL_INITIALIZED(blob)) {
        elog(ERROR, "invalid transition state for cmsketch");
    }

    out = palloc0(len);
    if (VARSIZE(blob) > VARHDRSZ) {
        sketch = (cmtransval *)VARDATA(blob);
        memcpy((uint8 *)VARDATA(out), sketch->sketches, len - VARHDRSZ);
    }
    SET_VARSIZE(out, len);

    // pasted code from utils/builtins.h:binary_encode()
    bytea *data = out;
    text       *result;
    int         datalen,
                resultlen,
                res;
    datalen = VARSIZE(data) - VARHDRSZ;
    resultlen = b64_enc_len(datalen);
    result = palloc(VARHDRSZ + resultlen);
    res = b64_encode(VARDATA(data), datalen, VARDATA(result));
    /* Make this FATAL 'cause we've trodden on memory ... */
    if (res > resultlen)
        elog(FATAL, "overflow - encode estimate too small");
    SET_VARSIZE(result, VARHDRSZ + res);

    PG_RETURN_TEXT_P(result);
}

/*!
 * Greenplum "prefunc" to combine sketches from multiple machines
 */
PG_FUNCTION_INFO_V1(__cmsketch_merge);
Datum __cmsketch_merge(PG_FUNCTION_ARGS)
{
    bytea *     counterblob1 = PG_GETARG_BYTEA_P(0);
    bytea *     counterblob2 = PG_GETARG_BYTEA_P(1);
    cmtransval *transval2 = (cmtransval *)VARDATA(counterblob2);
    cmtransval *newtrans;
    countmin *  sketches2 = NULL;
    bytea *     newblob;
    countmin *  newsketches;
    uint32      i, j, k;
    int         sz;

    /* make sure they're initialized! */
    if (!CM_TRANSVAL_INITIALIZED(counterblob1)
        && !CM_TRANSVAL_INITIALIZED(counterblob2))
        /* if both are empty can return one of them */
        PG_RETURN_DATUM(PointerGetDatum(counterblob1));
    else if (!CM_TRANSVAL_INITIALIZED(counterblob1)) {
        counterblob1 = cmsketch_init_transval();
    }
    else if (!CM_TRANSVAL_INITIALIZED(counterblob2)) {
        counterblob2 = cmsketch_init_transval();
        transval2 = (cmtransval *)VARDATA(counterblob2);
    }

    sketches2 = transval2 ->sketches;

    sz = VARSIZE(counterblob1);
    /* allocate a new transval as a copy of counterblob1 */
    newblob = (bytea *)palloc(sz);
    memcpy(newblob, counterblob1, sz);
    newtrans = (cmtransval *)(VARDATA(newblob));
    newsketches = (countmin *)(newtrans)->sketches;

    /* add in values from counterblob2 */
    for (i = 0; i < RANGES; i++)
        for (j = 0; j < DEPTH; j++)
            for (k = 0; k < NUMCOUNTERS; k++)
                newsketches[i][j][k] += sketches2[i][j][k];

    if (newtrans->nargs == -1) {
        /* transfer in the args from the other input */
        newtrans->nargs = transval2->nargs;
        for (i = 0; (int)i < transval2->nargs; i++)
            newtrans->args[i] = transval2->args[i];
    }

    PG_RETURN_DATUM(PointerGetDatum(newblob));
}

/*
 *******  Below are scalar methods to manipulate completed sketches.  ******
 */

/*!
 * get the approximate count of objects with value arg
 * \param sketch a countmin sketch
 * \param arg the Datum we want to find the count of
 * \param funcOid the Postgres function that converts arg to a string
 */
int64 cmsketch_count_c(countmin sketch, Datum arg, Oid funcOid, Oid typOid)
{
    bytea *nhash;

    /* get the md5 hash of the argument. */
    nhash = sketch_md5_bytea(arg, typOid);
    return(cmsketch_count_md5_datum(sketch, nhash, funcOid));
}

int64 cmsketch_count_md5_datum(countmin sketch, bytea *md5_bytea, Oid funcOid)
{
	(void) funcOid; /* avoid warning about unused parameter */
    /* iterate through the sketches, finding the min counter associated with this hash */
    return(hash_counters_iterate(md5_bytea, sketch, INT64_MAX,
                                          &min_counter));
}

#if 0
/****** SUPPORT ROUTINES *******/
PG_FUNCTION_INFO_V1(cmsketch_dump);

/*!
 * dump sketch contents
 */
Datum cmsketch_dump(PG_FUNCTION_ARGS)
{
    bytea *   transblob = (bytea *)PG_GETARG_BYTEA_P(0);
    countmin *sketches;
    char *    newblob = (char *)palloc(10240);
    uint32    i, j, k, c;

    if (VARSIZE(transblob) > VARHDRSZ && !CM_TRANSVAL_INITIALIZED(transblob)) {
        elog(ERROR, "invalid transition state for cmsketch");
    }

    if (VARSIZE(transblob) > VARHDRSZ) {
        sketches = ((cmtransval *)VARDATA(transblob))->sketches;
    }
    else {
        sketches = palloc0(RANGES*sizeof(countmin) + VARHDRSZ);
        SET_VARSIZE(sketches, RANGES*sizeof(countmin) + VARHDRSZ);
    }
    for (i=0, c=0; i < RANGES; i++)
        for (j=0; j < DEPTH; j++)
            for(k=0; k < NUMCOUNTERS; k++) {
                if (sketches[i][j][k] != 0)
                    c += sprintf(&newblob[c], "[(%d,%d,%d):" INT64_FORMAT
                                 "], ", i, j, k, sketches[i][j][k]);
                if (c > 10000) break;
            }
    newblob[c] = '\0';
    if (VARSIZE(transblob) <= VARHDRSZ) {
        pfree(sketches);
    }
    PG_RETURN_NULL();
}
#endif

/*!
 * for each row of the sketch, use the 16 bits starting at 2^i mod NUMCOUNTERS,
 * and invoke the lambda on those 16 bits (which may destructively modify counters).
 * \param hashval the MD5 hashed value that we take 16 bits at a time
 * \param sketch the cmsketch
 * \param initial the initialized return value
 * \param lambdaptr the function to invoke on each 16 bits
 */
int64 hash_counters_iterate(bytea *hashval,
                            countmin sketch, /* width is DEPTH*NUMCOUNTERS */
                            int64 initial,
                            int64 (*lambdaptr)(uint32,
                                               uint32,
                                               countmin,
                                               int64))
{
    uint32         i, col;
    char          *c;
    unsigned short twobytes;
    int64          retval = initial;

    /*
     * XXX WARNING: are there problems with unaligned access here?
     * XXX I was using memmove rather than casting, which was inefficient,
     * XXX but I was hoping memmove would deal with unaligned access in a portable way.
     * XXX However the deref of 2 bytes seems to work OK.
     */
    for (i = 0, c = (char *)VARDATA(hashval);
         i < DEPTH;
         i++, c += 2) {
        twobytes = *(unsigned short *)c;
        col = twobytes % NUMCOUNTERS;
        retval = (*lambdaptr)(i, col, sketch, retval);
    }
    return retval;
}

/*!
 * destructive increment lambda for hash_counters_iterate.
 * transval and return val not of particular interest here.
 * \param i which row to update
 * \param col which column to update
 * \param sketch the sketch
 * \param transval we don't need transval here, but its part of the
 * lambda interface for hash_counters_iterate
 */

int64 increment_counter(uint32 i,
                        uint32 col,
                        countmin sketch,
                        int64 transval)
{
	(void) transval; /* avoid warning about unused parameter */
    int64 oldval = sketch[i][col];
    if (sketch[i][col] == (INT64_MAX))
        elog(ERROR, "maximum count exceeded in sketch");
    sketch[i][col] = oldval + 1;

    /* return the incremented value, though unlikely anyone cares. */
    return oldval+1;
}

/*!
 * running minimum lambda for hash_counters_iterate
 * \param i which row to examine
 * \param col which column to examine
 * \param sketch the sketch
 * \param transval smallest counter so far
 * lambda interface for hash_counters_iterate
 */
int64 min_counter(uint32 i,
                  uint32 col,
                  countmin sketch,
                  int64 transval)
{
    int64 thisval = sketch[i][col];
    return (thisval < transval) ? thisval : transval;
}


text:
package main

import (
	"errors"
	"flag"
	"io"
	"log"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
	"time"

	"9fans.net/go/acme"
	"gopkg.in/fsnotify.v1"
)

var path = flag.String("p", ".", "specify the path to watch")

func main() {
	flag.Parse()

	var (
		win *acme.Win
		err error
	)

	err = func() error {
		win, err = acme.New()
		if err != nil {
			return err
		}

		if wd, err := os.Getwd(); err != nil {
			return err
		} else {
			win.Ctl("dumpdir %s", wd)
		}
		win.Ctl("dump %s", strings.Join(os.Args, " "))

		abs, err := filepath.Abs(*path)
		if err != nil {
			return err
		}
		switch info, err := os.Stat(abs); {
		case err != nil:
			return err
		case info.IsDir():
			abs += "/"
		}

		win.Name(abs + "+watch")
		win.Ctl("clean")
		win.Fprintf("tag", "Get ")

		run := make(chan runRequest)
		go events(win, run)
		go runner(win, run)
		return watcher(abs, run)
	}()
	if err != nil {
		win.Ctl("delete")
		log.Fatal(err.Error())
	}
}

// A runRequests is sent to the runner to request
// that the command be re-run.
type runRequest struct {
	// Time is the times for the request.  This
	// is either the modification time of a
	// changed file, or the time at which a
	// Get event was sent to acme.
	time time.Time

	// Done is a channel upon which the runner
	// should signal its completion.
	done chan<- bool
}

// Watcher watches the directory and sends a
// runRequest when the watched path changes.
func watcher(path string, run chan<- runRequest) error {
	w, err := fsnotify.NewWatcher()
	if err != nil {
		return err
	}

	if err := watchDeep(w, path); err != nil {
		return err
	}

	done := make(chan bool)
	for {
		select {
		case ev := <-w.Events:
			switch ev.Op {
			case fsnotify.Create:
				if err := watchDeep(w, ev.Name); err != nil {
					return err
				}
			case fsnotify.Remove:
				// watcher must not be removed as it is already gone (automagic)
				if strings.HasPrefix(path, ev.Name) {
					return errors.New("Watch point " + path + " deleted")
				}
			}
			tstamp := time.Now()
			if info, err := os.Stat(ev.Name); err == nil {
				tstamp = info.ModTime()
			}
			run <- runRequest{tstamp, done}
			<-done

		case err := <-w.Errors:
			return err
		}
	}
}

// WatchDeep watches a directory and all
// of its subdirectories.  If the path is not
// a directory then watchDeep is a no-op.
func watchDeep(w *fsnotify.Watcher, root string) error {
	if err := w.Add(root); err != nil {
		return err
	}
	return filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
		switch {
		case os.IsNotExist(err):
			return nil
		case err != nil:
			return err
		case !info.IsDir():
			return nil
		case info.Name() == ".git", info.Name() == "Godeps":
			return filepath.SkipDir
		default:
			return w.Add(path)
		}
	})
}

// Runner runs the commond upon
// receiving an up-to-date runRequest.
func runner(win *acme.Win, reqs <-chan runRequest) {
	runCommand(win)
	last := time.Now()

	for req := range reqs {
		if last.Before(req.time) {
			runCommand(win)
			last = time.Now()
		}
		req.done <- true
	}
}

// BodyWriter implements io.Writer, writing
// to the body of an acme window.
type BodyWriter struct {
	*acme.Win
}

func (b BodyWriter) Write(data []byte) (int, error) {
	// Don't write too much at once, or else acme
	// can crash…
	sz := len(data)
	for len(data) > 0 {
		n := 1024
		if len(data) < n {
			n = len(data)
		}
		m, err := b.Win.Write("body", data[:n])
		if err != nil {
			return m, err
		}
		data = data[m:]
	}
	return sz, nil
}

// RunCommand runs the command and sends
// the result to the given acme window.
func runCommand(win *acme.Win) {
	err := func() error {
		args := flag.Args()
		if len(args) == 0 {
			return errors.New("Must supply a command")
		}
		cmdStr := strings.Join(args, " ")

		win.Addr(",")
		win.Write("data", nil)
		win.Ctl("clean")
		win.Fprintf("body", "$ %s\n", cmdStr)

		cmd := exec.Command(args[0], args[1:]...)
		r, w, err := os.Pipe()
		if err != nil {
			return err
		}
		defer r.Close()
		cmd.Stdout = w
		cmd.Stderr = w

		if err := cmd.Start(); err != nil {
			win.Fprintf("body", "%s: %s\n", cmdStr, err)
			return err
		}
		w.Close()
		io.Copy(BodyWriter{win}, r)
		if err := cmd.Wait(); err != nil {
			win.Fprintf("body", "%s: %s\n", cmdStr, err)
		}

		win.Fprintf("body", "%s\n", time.Now())
		win.Fprintf("addr", "#0")
		win.Ctl("dot=addr")
		win.Ctl("show")
		win.Ctl("clean")
		return nil
	}()
	if err != nil {
		win.Ctl("delete")
		log.Fatal(err.Error())
	}
}

// Events handles events coming from the
// acme window.
func events(win *acme.Win, run chan<- runRequest) {
	done := make(chan bool)
	for e := range win.EventChan() {
		switch e.C2 {
		case 'x', 'X': // execute
			if string(e.Text) == "Get" {
				run <- runRequest{time.Now(), done}
				<-done
				continue
			}
			if string(e.Text) == "Del" {
				win.Ctl("delete")
			}
		}
		win.WriteEvent(e)
	}
	os.Exit(0)
}


text:
<?php

namespace Drupal\basic_auth\Authentication\Provider;

use Drupal\Component\Utility\SafeMarkup;
use Drupal\Core\Authentication\AuthenticationProviderInterface;
use Drupal\Core\Authentication\AuthenticationProviderChallengeInterface;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Entity\EntityManagerInterface;
use Drupal\Core\Flood\FloodInterface;
use Drupal\user\UserAuthInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;

/**
 * HTTP Basic authentication provider.
 */
class BasicAuth implements AuthenticationProviderInterface, AuthenticationProviderChallengeInterface {

  /**
   * The config factory.
   *
   * @var \Drupal\Core\Config\ConfigFactoryInterface
   */
  protected $configFactory;

  /**
   * The user auth service.
   *
   * @var \Drupal\user\UserAuthInterface
   */
  protected $userAuth;

  /**
   * The flood service.
   *
   * @var \Drupal\Core\Flood\FloodInterface
   */
  protected $flood;

  /**
   * The entity manager.
   *
   * @var \Drupal\Core\Entity\EntityManagerInterface
   */
  protected $entityManager;

  /**
   * Constructs a HTTP basic authentication provider object.
   *
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The config factory.
   * @param \Drupal\user\UserAuthInterface $user_auth
   *   The user authentication service.
   * @param \Drupal\Core\Flood\FloodInterface $flood
   *   The flood service.
   * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
   *   The entity manager service.
   */
  public function __construct(ConfigFactoryInterface $config_factory, UserAuthInterface $user_auth, FloodInterface $flood, EntityManagerInterface $entity_manager) {
    $this->configFactory = $config_factory;
    $this->userAuth = $user_auth;
    $this->flood = $flood;
    $this->entityManager = $entity_manager;
  }

  /**
   * {@inheritdoc}
   */
  public function applies(Request $request) {
    $username = $request->headers->get('PHP_AUTH_USER');
    $password = $request->headers->get('PHP_AUTH_PW');
    return isset($username) && isset($password);
  }

  /**
   * {@inheritdoc}
   */
  public function authenticate(Request $request) {
    $flood_config = $this->configFactory->get('user.flood');
    $username = $request->headers->get('PHP_AUTH_USER');
    $password = $request->headers->get('PHP_AUTH_PW');
    // Flood protection: this is very similar to the user login form code.
    // @see \Drupal\user\Form\UserLoginForm::validateAuthentication()
    // Do not allow any login from the current user's IP if the limit has been
    // reached. Default is 50 failed attempts allowed in one hour. This is
    // independent of the per-user limit to catch attempts from one IP to log
    // in to many different user accounts.  We have a reasonably high limit
    // since there may be only one apparent IP for all users at an institution.
    if ($this->flood->isAllowed('basic_auth.failed_login_ip', $flood_config->get('ip_limit'), $flood_config->get('ip_window'))) {
      $accounts = $this->entityManager->getStorage('user')->loadByProperties(['name' => $username, 'status' => 1]);
      $account = reset($accounts);
      if ($account) {
        if ($flood_config->get('uid_only')) {
          // Register flood events based on the uid only, so they apply for any
          // IP address. This is the most secure option.
          $identifier = $account->id();
        }
        else {
          // The default identifier is a combination of uid and IP address. This
          // is less secure but more resistant to denial-of-service attacks that
          // could lock out all users with public user names.
          $identifier = $account->id() . '-' . $request->getClientIP();
        }
        // Don't allow login if the limit for this user has been reached.
        // Default is to allow 5 failed attempts every 6 hours.
        if ($this->flood->isAllowed('basic_auth.failed_login_user', $flood_config->get('user_limit'), $flood_config->get('user_window'), $identifier)) {
          $uid = $this->userAuth->authenticate($username, $password);
          if ($uid) {
            $this->flood->clear('basic_auth.failed_login_user', $identifier);
            return $this->entityManager->getStorage('user')->load($uid);
          }
          else {
            // Register a per-user failed login event.
            $this->flood->register('basic_auth.failed_login_user', $flood_config->get('user_window'), $identifier);
          }
        }
      }
    }
    // Always register an IP-based failed login event.
    $this->flood->register('basic_auth.failed_login_ip', $flood_config->get('ip_window'));
    return [];
  }

  /**
   * {@inheritdoc}
   */
  public function challengeException(Request $request, \Exception $previous) {
    $site_name = $this->configFactory->get('system.site')->get('name');
    $challenge = SafeMarkup::format('Basic realm="@realm"', [
      '@realm' => !empty($site_name) ? $site_name : 'Access restricted',
    ]);
    return new UnauthorizedHttpException((string) $challenge, 'No authentication credentials provided.', $previous);
  }

}


text:
using System;
using Xamarin.Forms;

namespace Kamishibai.Xamarin.Forms
{
    public abstract class BehaviorBase<T> : Behavior<T> where T : BindableObject
    {
        private bool _inheritedBindingContedt;

		protected T AssociatedObject { get; private set; }

        protected override void OnAttachedTo(T bindableObject)
        {
            base.OnAttachedTo(bindableObject);

            AssociatedObject = bindableObject;
	        InheritBindingContext(bindableObject);

			bindableObject.BindingContextChanged += OnBindingContextChanged;
        }

        private void OnBindingContextChanged(object sender, EventArgs e)
        {
	        InheritBindingContext(AssociatedObject);
        }

		private void InheritBindingContext(T bindableObject)
	    {
		    if (BindingContext == null || _inheritedBindingContedt)
		    {
			    BindingContext = bindableObject.BindingContext;
			    _inheritedBindingContedt = true;
		    }
		}

		protected override void OnDetachingFrom(T bindableObject)
        {
            BindingContext = null;
            bindableObject.BindingContextChanged -= OnBindingContextChanged;
        }
    }
}


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>MZUI</title>
  <link rel="stylesheet" href="dist/css/mzui.min.css">
  <link rel="stylesheet" href="doc/css/doc.min.css">
  <link rel="shortcut icon" href="doc/favicon.ico" type="image/x-icon">

      MZUI
      基础
      控件
      JS
      示例

MZUI

为移动端设计,基于 Flex 的 UI 框架。

        开始使用
        立即下载

最新版本 v1.0.1   下载源码

FLEX

现代化

基于 Flex 设计,支持移动端全部主流浏览器
支持 Android 微信内置浏览器

着色

状态

形状

容器

边距

变形

阴影

滤镜

灵活

独立的外观选项,适合大部分控件,
满足多样的外观定制需求

Gulp

可定制

所有内容可以按需使用,基于 Gulp 构建自定义版本非常简单

jQuery

MZUI

轻量

JS(mzui.min.js)压缩后在 20KB 左右,
CSS(mzui.min.css)压缩后在 76KB 左右,
启用 GZip 压缩之后会更小(css 16KB, js 8KB),
JS 部分兼容 jQuery 最新版本

        开始使用
        立即下载

最新版本 v1.0.1   下载源码

官方 QQ 群:384135104

          访问论坛

在 Github 上支持我们     更新日志

          ZUI

桌面浏览器前端解决方案推荐

一个基于Bootstrap深度定制开源前端实践方案,
帮助你快速构现代跨屏应用。

          访问 ZUI 网站


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

import com.facebook.presto.metadata.FunctionRegistry;
import com.facebook.presto.metadata.SqlOperator;
import com.facebook.presto.spi.block.Block;
import com.facebook.presto.spi.type.StandardTypes;
import com.facebook.presto.spi.type.Type;
import com.facebook.presto.spi.type.TypeManager;
import com.google.common.collect.ImmutableList;

import java.lang.invoke.MethodHandle;
import java.util.Map;

import static com.facebook.presto.metadata.OperatorType.EQUAL;
import static com.facebook.presto.metadata.OperatorType.NOT_EQUAL;
import static com.facebook.presto.metadata.Signature.comparableTypeParameter;
import static com.facebook.presto.metadata.Signature.internalOperator;
import static com.facebook.presto.spi.type.BooleanType.BOOLEAN;
import static com.facebook.presto.util.Reflection.methodHandle;

public class ArrayNotEqualOperator
        extends SqlOperator
{
    public static final ArrayNotEqualOperator ARRAY_NOT_EQUAL = new ArrayNotEqualOperator();
    private static final MethodHandle METHOD_HANDLE = methodHandle(ArrayNotEqualOperator.class, "notEqual", MethodHandle.class, Type.class, Block.class, Block.class);

    private ArrayNotEqualOperator()
    {
        super(NOT_EQUAL, ImmutableList.of(comparableTypeParameter("T")), StandardTypes.BOOLEAN, ImmutableList.of("array<T>", "array<T>"));
    }

    @Override
    public ScalarFunctionImplementation specialize(Map<String, Type> types, int arity, TypeManager typeManager, FunctionRegistry functionRegistry)
    {
        Type elementType = types.get("T");
        MethodHandle equalsFunction = functionRegistry.getScalarFunctionImplementation(internalOperator(EQUAL, BOOLEAN, ImmutableList.of(elementType, elementType))).getMethodHandle();
        MethodHandle method = METHOD_HANDLE.bindTo(equalsFunction).bindTo(elementType);
        return new ScalarFunctionImplementation(false, ImmutableList.of(false, false), method, isDeterministic());
    }

    public static boolean notEqual(MethodHandle equalsFunction, Type type, Block left, Block right)
    {
        return !ArrayEqualOperator.equals(equalsFunction, type, left, right);
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<DexEntry>
  <General>
    <Name>Mienfoo</Name>
    <SpeciesName>Martial Arts</SpeciesName>
    <GrowthGroup>MediumSlow</GrowthGroup>
    <EggGroup1>Field</EggGroup1>
    <EggGroup2>Human-Like</EggGroup2>
  </General>
</DexEntry>


text:
package gollection

import (
	"reflect"
	"sort"

	"go4.org/reflectutil"
)

func processDistinct(v interface{}, m map[interface{}]bool) bool {
	if _, ok := m[v]; !ok {
		m[v] = true
		return true
	}
	return false
}

func processDistinctBy(fv, v reflect.Value, m map[interface{}]bool) bool {
	id := fv.Call([]reflect.Value{v})[0].Interface()
	if _, ok := m[id]; !ok {
		m[id] = true
		return true
	}
	return false
}

func processFilter(fv, v reflect.Value) bool {
	return fv.Call([]reflect.Value{v})[0].Interface().(bool)
}

func processMapFunc(fv, arg reflect.Value) reflect.Value {
	return fv.Call([]reflect.Value{arg})[0]
}

func processReduceFunc(fv, arg1, arg2 reflect.Value) reflect.Value {
	return fv.Call([]reflect.Value{arg1, arg2})[0]
}

func processSort(fv, ret reflect.Value) {
	less := func(i, j int) bool {
		return fv.Call([]reflect.Value{ret.Index(i), ret.Index(j)})[0].Interface().(bool)
	}

	sort.Sort(&funcs{
		length: ret.Len(),
		less:   less,
		swap:   reflectutil.Swapper(ret.Interface()),
	})
}


text:
/* $Id$ */

package org.apache.fop.fonts;

import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;

/**
 * A test suite for the o.a.f.fonts package.
 */
@RunWith(Suite.class)
@SuiteClasses({
        FontManagerConfiguratorTestCase.class,
        EmbedFontInfoTestCase.class,
        FontEventProcessingTestCase.class,
        FontManagerConfiguratorTestCase.class
})
public class FontsTestSuite {

}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Charlotte.Tools;

namespace Charlotte
{
	public partial class PortNoDlg : Form
	{
		public PortNoDlg()
		{
			InitializeComponent();

			this.MinimumSize = this.Size;

			this.PortNo.Text = "" + Gnd.I.PortNo;
		}

		private void PortNoDlg_Load(object sender, EventArgs e)
		{
			// noop
		}

		private void PortNoDlg_FormClosed(object sender, FormClosedEventArgs e)
		{
			Gnd.I.PortNo = IntTools.ToInt(this.PortNo.Text, 1, 65535, Consts.DEF_PORT_NO);
		}

		private void PortNo_TextChanged(object sender, EventArgs e)
		{
			// noop
		}

		private void PortNo_KeyPress(object sender, KeyPressEventArgs e)
		{
			if (e.KeyChar == (char)13) // enter
			{
				e.Handled = true;
				this.Close();
			}
		}
	}
}


text:
/* $Id: tape.c,v 1.1 2003/08/05 03:27:12 fredette Exp $ */

/* generic/tape.c - generic tape implementation support: */

/*
 * Copyright (c) 2003 Matt Fredette
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. 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.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *      This product includes software developed by Matt Fredette.
 * 4. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
 */

#include <tme/common.h>
_TME_RCSID("$Id: tape.c,v 1.1 2003/08/05 03:27:12 fredette Exp $");

/* includes: */
#include <tme/generic/tape.h>

/* this scores a tape connection: */
int
tme_tape_connection_score(struct tme_connection *conn,
			  unsigned int *_score)
{
  struct tme_tape_connection *conn_tape;
  struct tme_tape_connection *conn_tape_other;

  /* both sides must be tape connections: */
  assert(conn->tme_connection_type == TME_CONNECTION_TAPE);
  assert(conn->tme_connection_other->tme_connection_type == TME_CONNECTION_TAPE);

  /* you cannot connect a tape to a tape, or a tape frontend to a tape
     frontend: */
  conn_tape = (struct tme_tape_connection *) conn;
  conn_tape_other = (struct tme_tape_connection *) conn->tme_connection_other;
  *_score
    = ((conn_tape->tme_tape_connection_read != NULL
	|| conn_tape->tme_tape_connection_write != NULL)
       != (conn_tape_other->tme_tape_connection_read != NULL
	   || conn_tape_other->tme_tape_connection_write != NULL));
  return (TME_OK);
}


text:
@interface ParentTableViewCell : UITableViewCell
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
@property (weak, nonatomic) IBOutlet UIImageView *arrowImageView;

- (void)setOpened:(BOOL)opened animated:(BOOL)animated;

@end


text:
"""
hyper/http20/response
~~~~~~~~~~~~~~~~~~~~~

Contains the HTTP/2 equivalent of the HTTPResponse object defined in
httplib/http.client.
"""
import logging
import zlib

from ..common.decoder import DeflateDecoder
from ..common.headers import HTTPHeaderMap

log = logging.getLogger(__name__)

def strip_headers(headers):
    """
    Strips the headers attached to the instance of any header beginning
    with a colon that ``hyper`` doesn't understand. This method logs at
    warning level about the deleted headers, for discoverability.
    """
    # Convert to list to ensure that we don't mutate the headers while
    # we iterate over them.
    for name in list(headers.keys()):
        if name.startswith(b':'):
            del headers[name]

class HTTP20Response(object):
    """
    An ``HTTP20Response`` wraps the HTTP/2 response from the server. It
    provides access to the response headers and the entity body. The response
    is an iterable object and can be used in a with statement (though due to
    the persistent connections used in HTTP/2 this has no effect, and is done
    soley for compatibility).
    """
    def __init__(self, headers, stream):
        #: The reason phrase returned by the server. This is not used in
        #: HTTP/2, and so is always the empty string.
        self.reason = ''

        status = headers[b':status'][0]
        strip_headers(headers)

        #: The status code returned by the server.
        self.status = int(status)
        self.events = stream.events
        #: The response headers. These are determined upon creation, assigned
        #: once, and never assigned again.
        self.headers = headers

        # The response trailers. These are always intially ``None``.
        self._trailers = None

        # The stream this response is being sent over.
        self._stream = stream

        # We always read in one-data-frame increments from the stream, so we
        # may need to buffer some for incomplete reads.
        self._data_buffer = b''

        # This object is used for decompressing gzipped request bodies. Right
        # now we only support gzip because that's all the RFC mandates of us.
        # Later we'll add support for more encodings.
        # This 16 + MAX_WBITS nonsense is to force gzip. See this
        # Stack Overflow answer for more:
        # http://stackoverflow.com/a/2695466/1401686
        if b'gzip' in self.headers.get(b'content-encoding', []):
            self._decompressobj = zlib.decompressobj(16 + zlib.MAX_WBITS)
        elif b'deflate' in self.headers.get(b'content-encoding', []):
            self._decompressobj = DeflateDecoder()
        else:
            self._decompressobj = None

    @property
    def trailers(self):
        """
        Trailers on the HTTP message, if any.

        .. warning:: Note that this property requires that the stream is
                     totally exhausted. This means that, if you have not
                     completely read from the stream, all stream data will be
                     read into memory.
        """
        if self._trailers is None:
            self._trailers = self._stream.gettrailers() or HTTPHeaderMap()
            strip_headers(self._trailers)

        return self._trailers

    def read(self, amt=None, decode_content=True):
        """
        Reads the response body, or up to the next ``amt`` bytes.

        :param amt: (optional) The amount of data to read. If not provided, all
            the data will be read from the response.
        :param decode_content: (optional) If ``True``, will transparently
            decode the response data.
        :returns: The read data. Note that if ``decode_content`` is set to
            ``True``, the actual amount of data returned may be different to
            the amount requested.
        """
        if amt is not None and amt <= len(self._data_buffer):
            data = self._data_buffer[:amt]
            self._data_buffer = self._data_buffer[amt:]
            response_complete = False
        elif amt is not None:
            read_amt = amt - len(self._data_buffer)
            self._data_buffer += self._stream._read(read_amt)
            data = self._data_buffer[:amt]
            self._data_buffer = self._data_buffer[amt:]
            response_complete = len(data) < amt
        else:
            data = b''.join([self._data_buffer, self._stream._read()])
            response_complete = True

        # We may need to decode the body.
        if decode_content and self._decompressobj and data:
            data = self._decompressobj.decompress(data)

        # If we're at the end of the request, we have some cleaning up to do.
        # Close the stream, and if necessary flush the buffer.
        if response_complete:
            if decode_content and self._decompressobj:
                data += self._decompressobj.flush()

            if self._stream.response_headers:
                self.headers.merge(self._stream.response_headers)

        # We're at the end, close the connection.
        if response_complete:
            self.close()

        return data

    def read_chunked(self, decode_content=True):
        """
        Reads chunked transfer encoded bodies. This method returns a generator:
        each iteration of which yields one data frame *unless* the frames
        contain compressed data and ``decode_content`` is ``True``, in which
        case it yields whatever the decompressor provides for each chunk.

        .. warning:: This may yield the empty string, without that being the
                     end of the body!
        """
        while True:
            data = self._stream._read_one_frame()

            if data is None:
                break

            if decode_content and self._decompressobj:
                data = self._decompressobj.decompress(data)

            yield data

        if decode_content and self._decompressobj:
            yield self._decompressobj.flush()

        self.close()

        return

    def fileno(self):
        """
        Return the ``fileno`` of the underlying socket. This function is
        currently not implemented.
        """
        raise NotImplementedError("Not currently implemented.")

    def close(self):
        """
        Close the response. In effect this closes the backing HTTP/2 stream.

        :returns: Nothing.
        """
        self._stream.close()

    # The following methods implement the context manager protocol.
    def __enter__(self):
        return self

    def __exit__(self, *args):
        self.close()
        return False  # Never swallow exceptions.

class HTTP20Push(object):
    """
    Represents a request-response pair sent by the server through the server
    push mechanism.
    """
    def __init__(self, request_headers, stream):
        #: The scheme of the simulated request
        self.scheme = request_headers[b':scheme'][0]
        #: The method of the simulated request (must be safe and cacheable,
        #: e.g. GET)
        self.method = request_headers[b':method'][0]
        #: The authority of the simulated request (usually host:port)
        self.authority = request_headers[b':authority'][0]
        #: The path of the simulated request
        self.path = request_headers[b':path'][0]

        strip_headers(request_headers)

        #: The headers the server attached to the simulated request.
        self.request_headers = request_headers

        self._stream = stream

    def get_response(self):
        """
        Get the pushed response provided by the server.

        :returns: A :class:`HTTP20Response <hyper.HTTP20Response>` object
            representing the pushed response.
        """
        return HTTP20Response(self._stream.getheaders(), self._stream)

    def cancel(self):
        """
        Cancel the pushed response and close the stream.

        :returns: Nothing.
        """
        self._stream.close(8)  # CANCEL


text:
#ifndef _ALTOVA_INCLUDED_AIMXML_ALTOVA__ALTOVA_CcaptionType
#define _ALTOVA_INCLUDED_AIMXML_ALTOVA__ALTOVA_CcaptionType

namespace AIMXML
{

class CcaptionType : public TypeBase
{
public:
	AIMXML_EXPORT CcaptionType(xercesc::DOMNode* const& init);
	AIMXML_EXPORT CcaptionType(CcaptionType const& init);
	void operator=(CcaptionType const& other) { m_node = other.m_node; }
	static altova::meta::ComplexType StaticInfo() { return altova::meta::ComplexType(types + _altova_ti_altova_CcaptionType); }
	AIMXML_EXPORT void operator=(const string_type& value);
	AIMXML_EXPORT operator string_type();

	MemberAttribute<string_type,_altova_mi_altova_CcaptionType_altova_ID, 0, 0> ID;	// ID CID

	MemberAttribute<string_type,_altova_mi_altova_CcaptionType_altova_language, 0, 0> language;	// language CNMTOKEN

	MemberAttribute<string_type,_altova_mi_altova_CcaptionType_altova_styleCode, 0, 0> styleCode;	// styleCode CNMTOKENS
	MemberElement<ClinkHtmlType, _altova_mi_altova_CcaptionType_altova_linkHtml> linkHtml;
	struct linkHtml { typedef Iterator<ClinkHtmlType> iterator; };
	MemberElement<xs::CstringType, _altova_mi_altova_CcaptionType_altova_sub> sub;
	struct sub { typedef Iterator<xs::CstringType> iterator; };
	MemberElement<xs::CstringType, _altova_mi_altova_CcaptionType_altova_sup> sup;
	struct sup { typedef Iterator<xs::CstringType> iterator; };
	MemberElement<CfootnoteType, _altova_mi_altova_CcaptionType_altova_footnote> footnote;
	struct footnote { typedef Iterator<CfootnoteType> iterator; };
	MemberElement<CfootnoteRefType, _altova_mi_altova_CcaptionType_altova_footnoteRef> footnoteRef;
	struct footnoteRef { typedef Iterator<CfootnoteRefType> iterator; };
	AIMXML_EXPORT void SetXsiType();
};

}	// namespace AIMXML

#endif // _ALTOVA_INCLUDED_AIMXML_ALTOVA__ALTOVA_CcaptionType


text:
Il faut utiliser les terrains en périphérie d'une ville pour nourrir celle-ci.

Pendant des années, les grandes **villes dépendaient complètement du pétrole** pour se nourrir. Seulement deux ou trois pourcents de la nourriture était produite localement !

En plus, les **agriculteurs sont partis à la retraite** sans trouver de remplaçant.

Maintenant, comme je vous l'ai dit, **chacun produit une partie de sa nourriture**. Soit en famille en faisant un potager dans son jardin ou dans un jardin partagé, soit en petit collectif. C'est une solution qu'on a trouvé pour améliorer notre résilience alimentaire, l'adaptabilité de notre système alimentaire : on produit localement, sans se soucier des pénuries de pétrole ou d'importation. C'est aussi une manière de partager du matériel, comme des moulins et des pressoirs. *(Voir également [les Jardins de la victoire](https://fr.wikipedia.org/wiki/Jardin_de_la_victoire) mentionnés dans* Comment tout peut s'effondrer*).*

Pour ce qu'on ne peut pas faire soi-même, on va au **marché, chez des artisans ou dans son magasin collectif**.

Si on ne veut pas passer trop de temps en cuisine et bien manger quand même, il y a la **cantine communautaire**, dont je vous ai également parlé. L'idée est de cuisiner pour beaucoup de monde, à tour de rôle. Ça demande une demie journée tous les mois et on peut venir manger quand on veut pour quelques euros ! *[NFS I]*

*Liens avec Loisirs*

??


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

    <artifactId>liquid-sledgehammer-command-line</artifactId>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-assembly-plugin</artifactId>
                <configuration>
                    <archive>
                        <manifest>
                            <mainClass>com.coltsoftware.liquidsledgehammer.CommandsMain</mainClass>
                        </manifest>
                    </archive>
                    <descriptorRefs>
                        <descriptorRef>jar-with-dependencies</descriptorRef>
                    </descriptorRefs>
                </configuration>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>single</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.4</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>com.coltsoftware</groupId>
            <artifactId>liquid-sledgehammer-core</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>

        <dependency>
            <groupId>com.coltsoftware</groupId>
            <artifactId>liquid-sledgehammer-json</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>

        <dependency>
            <groupId>com.coltsoftware</groupId>
            <artifactId>liquid-sledgehammer-command-line-lib</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>

    </dependencies>

</project>


text:
product_type = Spree::ProductType.find_by_name('car')
Spree::TravelCalculator.where(name: 'Spree::CalculatorCar').first_or_create(product_type: product_type)


text:
#include "bot_types.h"

bool     BotSetupNav( const botClass_t *botClass, qhandle_t *navHandle );
void         BotShutdownNav();

void         BotDisableArea( const vec3_t origin, const vec3_t mins, const vec3_t maxs );
void         BotEnableArea( const vec3_t origin, const vec3_t mins, const vec3_t maxs );
void         BotSetNavMesh( int botClientNum, qhandle_t nav );
bool     BotFindRouteExt( int botClientNum, const botRouteTarget_t *target, bool allowPartial );
void         BotUpdateCorridor( int botClientNum, const botRouteTarget_t *target, botNavCmd_t *cmd );
void         BotFindRandomPoint( int botClientNum, vec3_t point );
bool     BotFindRandomPointInRadius( int botClientNum, const vec3_t origin, vec3_t point, float radius );
bool     BotNavTrace( int botClientNum, botTrace_t *trace, const vec3_t start, const vec3_t end );
void         BotAddObstacle( const vec3_t mins, const vec3_t maxs, qhandle_t *obstacleHandle );
void         BotRemoveObstacle( qhandle_t obstacleHandle );
void         BotUpdateObstacles();


text:
class Folio::Console::Transportable::DropdownCell < Folio::ConsoleCell
  def links
    if model.try(:id)
      [
        { title: t(".in"), url: controller.folio.in_console_transport_path(model.class, model.id) },
        { title: t(".out"), url: controller.folio.out_console_transport_path(model.class, model.id) },
      ]
    else
      [
        { title: t(".in_new"), url: controller.folio.in_console_transport_path },
      ]
    end
  end

  def title
    content_tag(:span, "more_vert", class: "mi f-c-transportable-dropdown__ico")
  end
end


text:
<Alloy>
	<Window class="container">
		<Toolbar id="toolbar" platform="ios">
	        <Items>
	            <Button id="menuBtn" title="Menu" />
	            <FlexSpace/>
	            <Label id="titleLabel" text="Home" />
	            <FlexSpace/>
	        </Items>
	    </Toolbar>
	    <View layout="composite">
			<Require type="widget" src="com.drawermenu.widget" id="drawermenu"/>
		</View>
	</Window>
</Alloy>


text:
using System;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using UnityEngine;

namespace Software10101.Serialization.Json {
    public static class FileHelper {
        private static readonly HashAlgorithm HashAlgorithm = MD5.Create();

        public static void SaveAsync(JsonDictionary data, string fileName, Action callback = null, bool includeHash = true) {
            ThreadPool.QueueUserWorkItem(stateInfo => {
                try {
                    byte[] payload = GenericJson.Serialize(data).GetBytes(Encoding.UTF8);

                    using (FileStream fileStream = File.Open(fileName, FileMode.Create, FileAccess.Write)) {
                        if (includeHash) {
                            byte[] hash = HashAlgorithm.ComputeHash(payload);
                            byte[] hashStringBytes = hash.ToHexStringBytes();

                            fileStream.Write(hashStringBytes, 0, hashStringBytes.Length);
                            fileStream.WriteByte(10);
                        }

                        fileStream.Write(payload, 0, payload.Length);
                    }

                    callback?.Invoke();
                } catch (Exception e) {
                    Debug.LogException(e);
                }
            });
        }

        public static void LoadAsync(string fileName, Action<JsonDictionary, bool> callback = null, bool requireHash = true) {
            ThreadPool.QueueUserWorkItem(stateInfo => {
                try {
                    int hashLength = HashAlgorithm.HashSize / 8 * 2; // 8 bits per byte but each byte is represented by 2 characters

                    byte[] hashStringBytes = new byte[hashLength];
                    int separatorByte;
                    byte[] buffer = new byte[8192];
                    StringBuilder stringBuilder = new StringBuilder();

                    using (FileStream fileStream = File.Open(fileName, FileMode.Open, FileAccess.Read)) {
                        int readByteCount;

                        int totalHashBytesRead = 0;
                        while ((readByteCount = fileStream.Read(hashStringBytes, totalHashBytesRead, hashLength - totalHashBytesRead)) > 0) {
                            totalHashBytesRead += readByteCount;

                            if (totalHashBytesRead == hashLength) {
                                break;
                            }

                            if (totalHashBytesRead > hashLength) {
                                throw new Exception("Something went terribly wrong while reading the file header.");
                            }
                        }

                        if (totalHashBytesRead != hashLength) {
                            if (requireHash) {
                                throw new Exception("Could not read file hash. (file too short)");
                            }

                            stringBuilder.Append(Encoding.UTF8.GetString(hashStringBytes,0, totalHashBytesRead));
                        }

                        separatorByte = fileStream.ReadByte();
                        if (requireHash) {
                            if (separatorByte < 0) {
                                throw new Exception("Could not read file separator. (file too short)");
                            }

                            if (separatorByte != 10) {
                                throw new Exception("File separator is incorrect.");
                            }
                        }

                        while ((readByteCount = fileStream.Read(buffer, 0, buffer.Length)) > 0) {
                            stringBuilder.Append(Encoding.UTF8.GetString(buffer,0, readByteCount));
                        }
                    }

                    string payloadString = stringBuilder.ToString().Trim();

                    bool payloadIntegrityIntact = false;

                    if (separatorByte == 10 || requireHash) {
                        // there might be a hash, test it out

                        byte[] computedHash = HashAlgorithm.ComputeHash(payloadString.GetBytes(Encoding.UTF8));
                        byte[] readHash = hashStringBytes.FromHexStringBytes();

                        payloadIntegrityIntact = computedHash.SequenceEqual(readHash);
                    }

                    if (!payloadIntegrityIntact && requireHash) {
                        Debug.LogWarningFormat("File failed integrity check during load: {0}", fileName);
                    }

                    if (!payloadIntegrityIntact && (payloadString[0] != '{' || payloadString[payloadString.Length - 1] != '}')) {
                        // try combining all the bytes, maybe it is json without the hash header

                        payloadString = (Encoding.UTF8.GetString(hashStringBytes)
                                         + Encoding.UTF8.GetString(new []{(byte)separatorByte})
                                         + stringBuilder).Trim();
                    }

                    if (payloadString[0] != '{' || payloadString[payloadString.Length - 1] != '}') {
                        throw new Exception("File failed JSON smoke test.");
                    }

                    JsonDictionary payload = GenericJson.Deserialize(payloadString);

                    callback?.Invoke(payload, payloadIntegrityIntact);
                } catch (Exception e) {
                    Debug.LogException(e);
                }
            });
        }
    }
}


text:
package me.ferrybig.javacoding.teamspeakconnector.repository;

import java.util.HashMap;
import java.util.Map;
import me.ferrybig.javacoding.teamspeakconnector.TeamspeakConnection;
import me.ferrybig.javacoding.teamspeakconnector.entities.Channel;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.junit.Test;
import static org.mockito.Mockito.mock;

/**
 *
 * @author Fernando
 */
public class ChannelRepositoryTest {

	@Test
	public void testReadEntity() {
		Map<String, String> data = new HashMap<>();
		data.put("cid", "1");
		data.put("pid", "0");
		data.put("channel_name", "Default Channel");
		data.put("channel_topic", "Default Channel has no topic");
		data.put("channel_description", "This is the default channel");
		data.put("channel_password", "");
		data.put("channel_codec", "4");
		data.put("channel_codec_quality", "6");
		data.put("channel_maxclients", "-1");
		data.put("channel_maxfamilyclients", "-1");
		data.put("channel_order", "0");
		data.put("channel_flag_permanent", "1");
		data.put("channel_flag_semi_permanent", "0");
		data.put("channel_flag_default", "1");
		data.put("channel_flag_password", "0");
		data.put("channel_codec_latency_factor", "1");
		data.put("channel_codec_is_unencrypted", "1");
		data.put("channel_security_salt", "");
		data.put("channel_delete_delay", "0");
		data.put("channel_flag_maxclients_unlimited", "1");
		data.put("channel_flag_maxfamilyclients_unlimited", "1");
		data.put("channel_flag_maxfamilyclients_inherited", "0");
		data.put("channel_filepath", "files/virtualserver_1/channel_1");
		data.put("channel_needed_talk_power", "0");
		data.put("channel_forced_silence", "0");
		data.put("channel_name_phonetic", "");
		data.put("channel_icon_id", "0");
		data.put("channel_flag_private", "0");
		data.put("seconds_empty", "-1");
		TeamspeakConnection con = mock(TeamspeakConnection.class);
		ChannelRepository repo = new ChannelRepository(con);

		Channel channel = repo.readEntityChecked(data);

		assertNotNull(channel);
		assertEquals(1, channel.getId());
		assertEquals(Channel.Codec.getById(4), channel.getCodec());
		assertEquals(6, channel.getCodecQuality());
		assertEquals(0, channel.getIconId());
		assertEquals("Default Channel", channel.getName());
		assertEquals(-1, channel.getMaxClients());
		assertEquals(0, channel.getOrder());
		assertEquals(null, channel.getParent());
		assertEquals("Default Channel has no topic", channel.getTopic());
		assertEquals(0, channel.getTotalClients());
		assertEquals(true, channel.isDefaultChannel());
		assertEquals(false, channel.isPassword());
		assertEquals(true, channel.isPermanent());
		assertEquals(false, channel.isSemiPermanent());

	}

}


text:
using UnityEngine;
using System.Collections;

public class ActivateBlink : MonoBehaviour {

    public GameObject target;
    public float activeDuration;
    public float inactiveDuration;

    private float timer = 0;

    void Start() {
        timer = target.activeSelf ? activeDuration : inactiveDuration;
    }

	// Update is called once per frame
	void Update () {
        timer -= Time.deltaTime;

	    if(timer < 0) {
            target.SetActive(!target.activeSelf);
            timer = target.activeSelf ? activeDuration : inactiveDuration;
        }
	}
}


text:
<?php
namespace Chamilo\Libraries\Storage\Query\Condition;

/**
 * This type of aggregate condition negates a single condition, thus requiring that that condition not be met.
 *
 * @author Tim De Pauw
 * @author Hans De Bisschop
 * @package Chamilo\Libraries\Storage\Query\Condition
 */
class NotCondition extends AggregateCondition
{

    /**
     * The condition to negate
     *
     * @var \Chamilo\Libraries\Storage\Query\Condition\Condition
     */
    private $condition;

    /**
     * Constructor
     *
     * @param \Chamilo\Libraries\Storage\Query\Condition\Condition $condition
     */
    public function __construct(Condition $condition)
    {
        $this->condition = $condition;
    }

    /**
     * Gets the condition to negate
     *
     * @return \Chamilo\Libraries\Storage\Query\Condition\Condition
     */
    public function get_condition()
    {
        return $this->condition;
    }

    /**
     *
     * @see \Chamilo\Libraries\Storage\Query\ConditionPart::getHashParts()
     */
    public function getHashParts()
    {
        $hashParts = parent::getHashParts();

        $hashParts[] = $this->get_condition()->getHashParts();

        return $hashParts;
    }
}